Merge branch 'main' into flutter/n1-settings
This commit is contained in:
+5
-1
@@ -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/**
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
- Standard Material and Cupertino controls, including buttons/menus in custom graphs/diffs/chat. System typography, theme colors, light/dark, content-driven layout and text scaling. No fixed row/bubble/button dimensions, bespoke palette or CSS token port. Platform differences are intentional. Centralize necessary layout constraints; do not ban legitimate native default spacing or graph coordinates.
|
||||
- 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.
|
||||
|
||||
+173
-6
@@ -7,15 +7,48 @@ All work under app/. Existing applications remain running and unchanged.
|
||||
| Item | Scope | Source | Verification | Landing | Preview |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| F0 | Scaffold and gateway contract | 0e0ef54 | analyze + 1 scaffold test pass | main | not served |
|
||||
| F1 | Socket transport, endpoint rules, reconnect | run 29 / flutter/f1-transport | pipeline passed; manager expanded to 12 regressions and corrected races | pending | — |
|
||||
| F2 | Adaptive shell and standard platform controls | run 31 / flutter/f2-shell | pipeline passed; manager completing real browser evidence and native-default corrections | pending | pending |
|
||||
| F3 | Run models, live event fold, actions | run 32 / flutter/f3-runs | pipeline passed; manager correcting ignored source and parity gaps | pending | — |
|
||||
| F1 | Socket transport, endpoint rules, reconnect | run 29 + 1e4ecea | 12 regressions pass, analyze/web build pass | main cb1ea90, ancestry verified | — |
|
||||
| F2 | Adaptive shell and standard platform controls | run 31 + a561c45 | 6 widget tests; real Chrome navigation + inspected phone/desktop PNGs | main 2f60a0e, ancestry verified | served skeleton |
|
||||
| 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 / flutter/f5-preview | pipeline passed; manager checking actual websocket/auth/byte forwarding | pending | pending |
|
||||
| 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 | run 35 / flutter/f4-chat | running (Luna), includes adapter prerequisites | pending | pending |
|
||||
| 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 | run34 / flutter/p1-pipelines | UIReview found whole-word tab-label scaling defect; visit3 export waits on duplicated inline screenshot data | held for exact export recovery then review-directed fix | 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 +35a8aab | manager checked retained candidate and real browser captures | merged main; ancestry verified | built into8096 preview |
|
||||
| D1 | Recorded changes/diff viewer | run39 / flutter/d1-diff-viewer | visual-review audit now export-waiting; inline-payload correction staged | held for exact export recovery | 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 / commit51140cd | manager reran36 tests, checked native browser evidence + source; all pass | merged main, ancestry verified | standalone screen; shell wiring pending |
|
||||
| I1 | App-owned socket/session + live Runs shell registration | run50 timeout → manager finish /35a8aab |68 focused tests; integrated375 tests; clean analyze/build; normal-entry browser probe passed18 captures incl deep links/history/reconnect | merged main; ancestry verified |8096 bundle rebuilt, auth preserved; live authenticated smoke not verified |
|
||||
| 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 / commitebfa7f7 | manager reran29 tests/analyze and inspected2x phone PNG; browser-review advisory accepted | merged main, ancestry verified | standalone; navigation/editor 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 timeout → resume63 / commitff0f812 | preserved780 source lines; manager reran60 tests before/after resume, pass; URL security checked | merged main, ancestry verified | data only |
|
||||
| P2c | Edge routes and measured label geometry | run62 / commitb381290 | manager reran20 tests, checked geometry entrypoint/measured inputs, pass | merged main, ancestry verified | no renderer yet |
|
||||
|
||||
## Next ready work
|
||||
### Current execution target (user correction)
|
||||
Target approximately20 minutes END TO END per task, not per model stage. One
|
||||
independently testable behavior, focused regression, short handoff; concurrent
|
||||
small lanes, prompt integration. No multi-hour feature-sized runs or blind
|
||||
retry/review loops. When a slice overruns, inspect retained progress and split
|
||||
unfinished behavior or finish directly. This changes task selection/prompts,
|
||||
not pipeline definitions. Keep existing in-flight work intact.
|
||||
|
||||
Ready micro-slices after the necessary audit-fix service window:
|
||||
- Graph: native measured stage-node widget + selection callback ONLY.
|
||||
- Graph: edge/label painter over already-routed geometry ONLY (parallel node lane).
|
||||
- Artifacts: read-only visit-group list + selection callback ONLY (no viewer/share).
|
||||
- Schedules: editor input validation + unchanged revision payload tests ONLY (no UI).
|
||||
Keep each item separately reviewable; renderer composition, artifact preview and
|
||||
schedule save integration are later slices, not bundled into those tasks.
|
||||
|
||||
- P1 pipelines list/detail/source/version; P2 graph and stage/visit selection.
|
||||
- R1 runs list/detail/timeline; R2 decisions/run/retry/cancel/title and attention.
|
||||
- C1 chat list/group/search/star/rename/close/create; C2 transcript/markdown/reasoning/tools; C3 composer/attachments/queue/stop; C4 forms/permissions/models/metrics/shells.
|
||||
@@ -45,6 +78,135 @@ workspace/write scope, so could not correct this admission mistake. No policy
|
||||
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
|
||||
After Runs landing, integrated main:375 Flutter tests pass; analysis and normal
|
||||
web build pass. Manager reran browser probe against that normal bundle:18 PNGs,
|
||||
deep link/back/forward/drop/reconnect pass,5 subscriptions/5 lists/7 detail reads.
|
||||
Preview8096 serves the rebuilt build/web without any service restart. Rollback
|
||||
bundle retained in approved temp as preview-before-runs-1792600010. LAN/tailnet
|
||||
/runs reach the authenticated login correctly. Authenticated production data
|
||||
rendering not tested; fixture evidence is not a claim of live-data verification.
|
||||
|
||||
### Visual-audit export correction prepared (not installed over active work)
|
||||
Run34 UIReview3 native source is complete:71 messages,4,196,297 decoded bytes.
|
||||
Its projection duplicated47 inline screenshot URIs (3,752,634 bytes) already
|
||||
stored in complete native JSON, exceeding the unchanged8MiB HTML cap. Direct
|
||||
infrastructure correction c303756 on exact-running-b4627e2 base (main cherry-pick
|
||||
ceffd5d) summarizes ONLY data: URIs whose exact bytes are also present in the
|
||||
message's retained native record. Native JSON is unchanged and escaped; absent
|
||||
native copy falls back to full output. No limits raised and no partial evidence
|
||||
declared complete. New large-inline/fallback/security regressions, full Go suite,
|
||||
build/vet and focused race tests pass. Exact original visit scratch export now
|
||||
4,676,544 bytes/71 messages/untruncated. Staged binary is in approved temp as
|
||||
pipelines-server-inlinefix-c303756. Original production evidence untouched.
|
||||
Install and exact export-only repair34/3 automatically at a quiescent server
|
||||
window; do not interrupt active37/39/42/50/58 work. Review's rejection is legitimate:
|
||||
Summary/Source tab labels break mid-word under scaled text; once the audit gate
|
||||
is repaired, the same run follows its recorded Code edge to fix that actual defect.
|
||||
On schedule-list58 completion manager checked the safe window:37 Review,
|
||||
42 UIReview and50 Code still active;34/39 visual audits export-waiting. Therefore
|
||||
no restart was performed. Do not launch additional model stages ahead of this
|
||||
short necessary deployment window; finish/check current candidates meanwhile.
|
||||
|
||||
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
|
||||
preview process is running separately on loopback 8096, authenticating via the
|
||||
unchanged existing web proxy on 8095. Verified unauthenticated page redirects
|
||||
to login, JS denies with 401, and proxied login responds 200. The served app is
|
||||
currently a shell with explicit unimplemented bodies, NOT a feature-complete app.
|
||||
No Android/iOS build or device verification has occurred.
|
||||
|
||||
Network preview update: per user request, the preview now binds 0.0.0.0:8096,
|
||||
reachable at http://10.0.0.249:8096/ on the current LAN. Verified listener *:8096,
|
||||
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;
|
||||
@@ -58,6 +220,11 @@ Allowed pipeline models: Luna or DeepSeek V4.1 Flash; current runs use Luna.
|
||||
already started while corrections proceed.
|
||||
|
||||
## Completion loop
|
||||
Manager role: check evidence/diffs, verify, merge, update preview and start next
|
||||
ready items. Per latest user steering, substantial implementation and corrections
|
||||
belong to existing pipelines, not manager-written replacements. Already-running
|
||||
direct correction work is preserved; do not discard it or duplicate it.
|
||||
|
||||
Use pipelines wait for every started run. Inspect failure evidence before fixing,
|
||||
resuming or retrying; preserve partial work. On success inspect actual diff and
|
||||
checks, integrate, verify ancestry, then launch the next ready item. Do not
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../shell/adaptive_shell.dart';
|
||||
import '../shell/destination.dart';
|
||||
|
||||
/// The injectable application shell. Composition supplies the live feature
|
||||
/// bodies and, when it owns a route, the selected destination; widget tests
|
||||
/// can continue to pass a small map or no bodies at all.
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({
|
||||
super.key,
|
||||
this.destinationBodies = const {},
|
||||
this.cupertino,
|
||||
this.destination,
|
||||
this.onDestinationSelected,
|
||||
}) : routerConfig = null;
|
||||
|
||||
/// A host for a [Router]-owned location, so browser Back/Forward and deep
|
||||
/// links use Flutter's multi-entry web history instead of a second, competing
|
||||
/// history implementation.
|
||||
const MyApp.router({
|
||||
super.key,
|
||||
required RouterConfig<Object> this.routerConfig,
|
||||
this.cupertino,
|
||||
}) : destinationBodies = const {},
|
||||
destination = null,
|
||||
onDestinationSelected = null;
|
||||
|
||||
final Map<AppDestination, WidgetBuilder> destinationBodies;
|
||||
final bool? cupertino;
|
||||
final AppDestination? destination;
|
||||
final ValueChanged<AppDestination>? onDestinationSelected;
|
||||
final RouterConfig<Object>? routerConfig;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final router = routerConfig;
|
||||
if (cupertino ?? _platformIsCupertino) {
|
||||
if (router != null) {
|
||||
return CupertinoApp.router(title: 'Pipelines', routerConfig: router);
|
||||
}
|
||||
return CupertinoApp(
|
||||
title: 'Pipelines',
|
||||
home: AdaptiveShell(
|
||||
destinationBodies: destinationBodies,
|
||||
cupertino: true,
|
||||
destination: destination,
|
||||
onDestinationSelected: onDestinationSelected,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (router != null) {
|
||||
return MaterialApp.router(
|
||||
title: 'Pipelines',
|
||||
theme: ThemeData(),
|
||||
darkTheme: ThemeData(brightness: Brightness.dark),
|
||||
themeMode: ThemeMode.system,
|
||||
routerConfig: router,
|
||||
);
|
||||
}
|
||||
return MaterialApp(
|
||||
title: 'Pipelines',
|
||||
theme: ThemeData(),
|
||||
darkTheme: ThemeData(brightness: Brightness.dark),
|
||||
themeMode: ThemeMode.system,
|
||||
home: AdaptiveShell(
|
||||
destinationBodies: destinationBodies,
|
||||
destination: destination,
|
||||
onDestinationSelected: onDestinationSelected,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
bool get _platformIsCupertino =>
|
||||
defaultTargetPlatform == TargetPlatform.iOS ||
|
||||
defaultTargetPlatform == TargetPlatform.macOS;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/// The destinations the app has a URL for.
|
||||
///
|
||||
/// The set mirrors [AppDestination] but stays free of widget imports so the
|
||||
/// parser and serialiser can be exercised without a Flutter host.
|
||||
enum AppRouteKind { pipelines, runs, chat, settings }
|
||||
|
||||
/// One page route: a destination plus the run it opens, if any.
|
||||
///
|
||||
/// Parsing is total, like the web client's route model: an unknown or
|
||||
/// malformed path resolves to the default Pipelines list instead of throwing.
|
||||
/// The serialiser is its inverse for every route the app can produce.
|
||||
class AppRoute {
|
||||
const AppRoute(this.kind, {this.runId});
|
||||
|
||||
static const pipelines = AppRoute(AppRouteKind.pipelines);
|
||||
static const runs = AppRoute(AppRouteKind.runs);
|
||||
static const chat = AppRoute(AppRouteKind.chat);
|
||||
static const settings = AppRoute(AppRouteKind.settings);
|
||||
|
||||
static const run = _RunRouteFactory();
|
||||
|
||||
final AppRouteKind kind;
|
||||
|
||||
/// The run shown by the Runs destination, or null for the list.
|
||||
final int? runId;
|
||||
|
||||
/// The path the app writes into history for this route.
|
||||
String get path => switch (kind) {
|
||||
AppRouteKind.pipelines => '/pipelines',
|
||||
AppRouteKind.runs => runId == null ? '/runs' : '/runs/$runId',
|
||||
AppRouteKind.chat => '/chat',
|
||||
AppRouteKind.settings => '/settings',
|
||||
};
|
||||
|
||||
/// Parses a browser pathname (or a full URL) into a route.
|
||||
///
|
||||
/// `/runs/abc` and other malformed details are the default route, matching
|
||||
/// the web parser; `/pipelines/` and other trailing slashes are normalised.
|
||||
static AppRoute parse(String location) {
|
||||
var path = location.trim();
|
||||
if (path.isEmpty) return pipelines;
|
||||
if (path.contains('://')) {
|
||||
final uri = Uri.tryParse(path);
|
||||
if (uri == null) return pipelines;
|
||||
path = uri.path;
|
||||
}
|
||||
final hash = path.indexOf('#');
|
||||
if (hash != -1) path = path.substring(0, hash);
|
||||
final query = path.indexOf('?');
|
||||
if (query != -1) path = path.substring(0, query);
|
||||
|
||||
final segments = <String>[];
|
||||
for (final raw in path.split('/')) {
|
||||
if (raw.isEmpty) continue;
|
||||
try {
|
||||
segments.add(Uri.decodeComponent(raw));
|
||||
} on ArgumentError {
|
||||
return pipelines;
|
||||
}
|
||||
}
|
||||
if (segments.isEmpty) return pipelines;
|
||||
|
||||
return switch (segments.first) {
|
||||
'pipelines' when segments.length == 1 => pipelines,
|
||||
'runs' when segments.length == 1 => runs,
|
||||
'runs' when segments.length == 2 => _runRoute(segments[1]),
|
||||
'chat' when segments.length == 1 => chat,
|
||||
'settings' when segments.length == 1 => settings,
|
||||
_ => pipelines,
|
||||
};
|
||||
}
|
||||
|
||||
static AppRoute _runRoute(String value) {
|
||||
if (!RegExp(r'^[0-9]+$').hasMatch(value)) return pipelines;
|
||||
final id = int.tryParse(value);
|
||||
if (id == null || id <= 0) return pipelines;
|
||||
return AppRoute(AppRouteKind.runs, runId: id);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is AppRoute && other.kind == kind && other.runId == runId;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(kind, runId);
|
||||
|
||||
@override
|
||||
String toString() => path;
|
||||
}
|
||||
|
||||
/// `AppRoute.run(3)` reads better than a constructor named after a field.
|
||||
class _RunRouteFactory {
|
||||
const _RunRouteFactory();
|
||||
|
||||
AppRoute call(int id) => AppRoute(AppRouteKind.runs, runId: id);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'app_route.dart';
|
||||
|
||||
/// Parses the browser (or platform) location into the app's routes.
|
||||
class AppRouteParser extends RouteInformationParser<AppRoute> {
|
||||
const AppRouteParser();
|
||||
|
||||
@override
|
||||
Future<AppRoute> parseRouteInformation(
|
||||
RouteInformation routeInformation,
|
||||
) async => AppRoute.parse(routeInformation.uri.path);
|
||||
|
||||
@override
|
||||
RouteInformation restoreRouteInformation(AppRoute configuration) =>
|
||||
RouteInformation(uri: Uri(path: configuration.path));
|
||||
}
|
||||
|
||||
/// Owns the app's current route and builds the shell for it.
|
||||
///
|
||||
/// Route changes made by the operator go through [goTo]; the Router reports
|
||||
/// them as browser history entries. Browser Back/Forward and deep links arrive
|
||||
/// through [setNewRoutePath] and update the same route.
|
||||
class AppRouterDelegate extends RouterDelegate<AppRoute> with ChangeNotifier {
|
||||
AppRouterDelegate({
|
||||
required this.builder,
|
||||
required this.onPopToRuns,
|
||||
required this.cupertino,
|
||||
AppRoute initial = AppRoute.pipelines,
|
||||
}) : _route = initial;
|
||||
|
||||
final Widget Function(BuildContext context, AppRoute route) builder;
|
||||
|
||||
/// Called when a system Back belongs to the Runs detail, not the app stack.
|
||||
final VoidCallback onPopToRuns;
|
||||
|
||||
final bool cupertino;
|
||||
|
||||
final _navigatorKey = GlobalKey<NavigatorState>();
|
||||
static const _pageKey = ValueKey<String>('pipelines-shell');
|
||||
|
||||
AppRoute _route;
|
||||
|
||||
AppRoute get route => _route;
|
||||
|
||||
@override
|
||||
AppRoute get currentConfiguration => _route;
|
||||
|
||||
/// A single-page Navigator supplies the Overlay, overlay portals and route
|
||||
/// context that native controls (action sheets, tooltips) require. The page
|
||||
/// key is stable, so changing the route updates the shell in place instead of
|
||||
/// remounting it and losing the open run.
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final child = builder(context, _route);
|
||||
return Navigator(
|
||||
key: _navigatorKey,
|
||||
pages: [
|
||||
if (cupertino)
|
||||
CupertinoPage<void>(key: _pageKey, child: child)
|
||||
else
|
||||
MaterialPage<void>(key: _pageKey, child: child),
|
||||
],
|
||||
onDidRemovePage: (_) {},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setInitialRoutePath(AppRoute configuration) async {
|
||||
_route = configuration;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setNewRoutePath(AppRoute configuration) async {
|
||||
if (configuration == _route) return;
|
||||
_route = configuration;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> popRoute() async {
|
||||
if (_route.runId == null) return false;
|
||||
onPopToRuns();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Records a user move; the Router turns the new configuration into a
|
||||
/// history entry (or a replacement when it already matches the location).
|
||||
void goTo(AppRoute route) {
|
||||
if (route == _route) return;
|
||||
_route = route;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
/// The location a web launch starts at, or the Pipelines list elsewhere.
|
||||
///
|
||||
/// Only the path is meaningful to [AppRouteParser]; the origin stays out of
|
||||
/// route configuration so a serialised route is always app-relative.
|
||||
RouteInformation initialRouteInformation() {
|
||||
if (!kIsWeb) return RouteInformation(uri: Uri(path: '/pipelines'));
|
||||
final path = Uri.base.path;
|
||||
return RouteInformation(uri: Uri(path: path.isEmpty ? '/' : path));
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../core/api_gateway.dart';
|
||||
import '../core/transport/pipelines_client.dart';
|
||||
|
||||
/// Whether this connection's send-only `subscribe` was accepted.
|
||||
///
|
||||
/// A server that never acks leaves this [pending]; only an explicit refusal
|
||||
/// makes the session report that live updates are unavailable, so the UI never
|
||||
/// guesses "not live" from silence.
|
||||
enum RunSubscriptionState { pending, live, refused }
|
||||
|
||||
/// Owns the one app-wide Pipelines socket and its run-event watch.
|
||||
///
|
||||
/// The client reconnects on its own; this session re-sends the send-only
|
||||
/// `subscribe` on every connected transition because a new socket has no
|
||||
/// watch, and drops it deliberately with `unsubscribe` when the app stops.
|
||||
class AppSession extends ChangeNotifier {
|
||||
AppSession({required this.endpoint, PipelinesClient? client})
|
||||
: _client = client ?? PipelinesClient() {
|
||||
_states = _client.states.listen(_onState);
|
||||
_frames = _client.frames.listen(_onFrame);
|
||||
}
|
||||
|
||||
final Uri? endpoint;
|
||||
final PipelinesClient _client;
|
||||
late final StreamSubscription<ConnectionState> _states;
|
||||
late final StreamSubscription<JsonMap> _frames;
|
||||
ConnectionState _connection = const ConnectionState(ConnectionKind.idle);
|
||||
bool _subscribed = false, _disposed = false, _everConnected = false;
|
||||
int _connectionEpoch = 0;
|
||||
RunSubscriptionState _subscription = RunSubscriptionState.pending;
|
||||
String _subscriptionError = '';
|
||||
String? _subscribeRequest;
|
||||
|
||||
ApiGateway get gateway => _client;
|
||||
ConnectionState get connection => _connection;
|
||||
bool get connected => _connection.kind == ConnectionKind.connected;
|
||||
|
||||
/// True once any connection has succeeded. The Runs destination shows the
|
||||
/// full connection screen before this, then keeps the loaded screen mounted
|
||||
/// through later drops instead of discarding the operator's place.
|
||||
bool get everConnected => _everConnected;
|
||||
|
||||
RunSubscriptionState get subscription => _subscription;
|
||||
String get subscriptionError => _subscriptionError;
|
||||
|
||||
/// Advances on every connected transition. The Runs destination keys the
|
||||
/// screen's reload with this so a reconnect re-reads the list and the open
|
||||
/// detail without remounting the screen or losing its selection.
|
||||
int get connectionEpoch => _connectionEpoch;
|
||||
|
||||
/// Connects the shared socket. A missing endpoint is a configuration state,
|
||||
/// so this is a no-op rather than a guessed endpoint.
|
||||
Future<void> start() async {
|
||||
if (_disposed || endpoint == null) return;
|
||||
await _client.connect(endpoint!);
|
||||
}
|
||||
|
||||
/// Retries now: reopens a disconnected socket, or repeats a refused watch on
|
||||
/// a healthy one.
|
||||
Future<void> retry() async {
|
||||
if (connected) {
|
||||
resubscribe();
|
||||
return;
|
||||
}
|
||||
await start();
|
||||
}
|
||||
|
||||
/// Repeats the send-only watch on the current socket. Used when the server
|
||||
/// explicitly refused the previous `subscribe`.
|
||||
void resubscribe() {
|
||||
if (_disposed) return;
|
||||
_subscribed = false;
|
||||
_subscribeRequest = null;
|
||||
_subscription = RunSubscriptionState.pending;
|
||||
_subscriptionError = '';
|
||||
_subscribe();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Stops the watch and the socket without disposing the session, so a later
|
||||
/// [start] can open a fresh connection.
|
||||
Future<void> stop() async {
|
||||
if (_disposed) return;
|
||||
_sendUnsubscribe();
|
||||
await _client.disconnect();
|
||||
}
|
||||
|
||||
void _onState(ConnectionState state) {
|
||||
if (_disposed) return;
|
||||
final wasConnected = connected;
|
||||
_connection = state;
|
||||
if (state.kind == ConnectionKind.connected) {
|
||||
_everConnected = true;
|
||||
_connectionEpoch++;
|
||||
_subscription = RunSubscriptionState.pending;
|
||||
_subscriptionError = '';
|
||||
_subscribe();
|
||||
} else if (wasConnected) {
|
||||
_subscribed = false;
|
||||
_subscribeRequest = null;
|
||||
_subscription = RunSubscriptionState.pending;
|
||||
_subscriptionError = '';
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _onFrame(JsonMap frame) {
|
||||
if (_disposed) return;
|
||||
final id = frame['id'];
|
||||
if (id is! String || id != _subscribeRequest) return;
|
||||
switch (frame['type']) {
|
||||
case 'subscribe':
|
||||
_subscription = RunSubscriptionState.live;
|
||||
_subscriptionError = '';
|
||||
break;
|
||||
case 'error':
|
||||
_subscription = RunSubscriptionState.refused;
|
||||
final reason = '${frame['error'] ?? ''}'.trim();
|
||||
_subscriptionError = reason.isEmpty
|
||||
? 'Live run updates are unavailable.'
|
||||
: reason;
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _subscribe() {
|
||||
if (_subscribed || !connected) return;
|
||||
try {
|
||||
_subscribeRequest = _client.sendOnly('subscribe', const {
|
||||
'workspace': '',
|
||||
});
|
||||
_subscribed = true;
|
||||
} on NotConnectedError {
|
||||
// A close raced the connected state; the next connected transition
|
||||
// subscribes instead of leaving a half-registered watch.
|
||||
}
|
||||
}
|
||||
|
||||
void _sendUnsubscribe() {
|
||||
if (!_subscribed) return;
|
||||
_subscribed = false;
|
||||
_subscribeRequest = null;
|
||||
if (!connected) return;
|
||||
try {
|
||||
_client.sendOnly('unsubscribe');
|
||||
} on NotConnectedError {
|
||||
// The socket already closed, which drops the watch server-side.
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_sendUnsubscribe();
|
||||
unawaited(_states.cancel());
|
||||
unawaited(_frames.cancel());
|
||||
unawaited(_client.dispose());
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import 'app_url_strategy_stub.dart'
|
||||
if (dart.library.js_interop) 'app_url_strategy_web.dart'
|
||||
as platform;
|
||||
|
||||
/// Chooses the URL form the app's routes use.
|
||||
///
|
||||
/// Web serves real paths (`/runs/1`) so a route can be bookmarked, opened
|
||||
/// directly and handled by browser Back/Forward; other platforms keep their
|
||||
/// in-memory route state.
|
||||
void useAppUrlStrategy() => platform.useAppUrlStrategy();
|
||||
@@ -0,0 +1 @@
|
||||
void useAppUrlStrategy() {}
|
||||
@@ -0,0 +1,3 @@
|
||||
import 'package:flutter_web_plugins/url_strategy.dart';
|
||||
|
||||
void useAppUrlStrategy() => usePathUrlStrategy();
|
||||
@@ -0,0 +1,20 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import 'app_url_strategy.dart';
|
||||
import 'pipelines_app.dart';
|
||||
import 'server_endpoint.dart';
|
||||
|
||||
/// Native builds must supply their server explicitly; there is no baked host.
|
||||
const configuredServerUrl = String.fromEnvironment('PIPELINES_SERVER_URL');
|
||||
|
||||
/// Resolves the endpoint for this launch and starts the normal composition.
|
||||
void runPipelinesApp({Uri? base, String configured = configuredServerUrl}) {
|
||||
useAppUrlStrategy();
|
||||
final server = ServerEndpoint.resolve(
|
||||
base: base ?? Uri.base,
|
||||
web: kIsWeb,
|
||||
configured: configured,
|
||||
);
|
||||
runApp(PipelinesApp(server: server));
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../core/transport/pipelines_client.dart';
|
||||
import '../shell/adaptive_shell.dart';
|
||||
import '../shell/destination.dart';
|
||||
import 'app.dart';
|
||||
import 'app_route.dart';
|
||||
import 'app_router.dart';
|
||||
import 'app_session.dart';
|
||||
import 'runs_destination.dart';
|
||||
import 'server_endpoint.dart';
|
||||
|
||||
/// Composes the live application around one [AppSession] and one [Router].
|
||||
///
|
||||
/// Tests may inject the client and route-information provider; the session
|
||||
/// owns the socket either way, so there is never a second app-level connection.
|
||||
class PipelinesApp extends StatefulWidget {
|
||||
const PipelinesApp({
|
||||
super.key,
|
||||
required this.server,
|
||||
this.client,
|
||||
this.cupertino,
|
||||
this.routeInformationProvider,
|
||||
});
|
||||
|
||||
final ServerEndpoint server;
|
||||
final PipelinesClient? client;
|
||||
final bool? cupertino;
|
||||
|
||||
/// Test seam: the Router's initial and subsequent route information.
|
||||
final RouteInformationProvider? routeInformationProvider;
|
||||
|
||||
@override
|
||||
State<PipelinesApp> createState() => _PipelinesAppState();
|
||||
}
|
||||
|
||||
class _PipelinesAppState extends State<PipelinesApp> {
|
||||
late final AppSession _session;
|
||||
late final AppRouterDelegate _delegate;
|
||||
late final RouteInformationProvider _provider;
|
||||
late final bool _ownsProvider;
|
||||
late final RouterConfig<AppRoute> _config;
|
||||
late final bool _cupertino;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_session = AppSession(endpoint: widget.server.uri, client: widget.client);
|
||||
_ownsProvider = widget.routeInformationProvider == null;
|
||||
_provider =
|
||||
widget.routeInformationProvider ??
|
||||
PlatformRouteInformationProvider(
|
||||
initialRouteInformation: initialRouteInformation(),
|
||||
);
|
||||
// A malformed or unknown boot path renders Pipelines, so make the address
|
||||
// bar agree with the rendered destination instead of showing a dead link.
|
||||
final initial = AppRoute.parse(_provider.value.uri.path);
|
||||
if (_provider.value.uri.path != initial.path) {
|
||||
_provider.routerReportsNewRouteInformation(
|
||||
RouteInformation(uri: Uri(path: initial.path)),
|
||||
type: RouteInformationReportingType.neglect,
|
||||
);
|
||||
}
|
||||
_cupertino = widget.cupertino ?? _platformIsCupertino;
|
||||
_delegate = AppRouterDelegate(
|
||||
initial: initial,
|
||||
cupertino: _cupertino,
|
||||
onPopToRuns: () => _delegate.goTo(AppRoute.runs),
|
||||
builder: _buildShell,
|
||||
);
|
||||
_config = RouterConfig<AppRoute>(
|
||||
routeInformationParser: const AppRouteParser(),
|
||||
routerDelegate: _delegate,
|
||||
routeInformationProvider: _provider,
|
||||
);
|
||||
unawaited(_session.start());
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_delegate.dispose();
|
||||
if (_ownsProvider) {
|
||||
(_provider as PlatformRouteInformationProvider).dispose();
|
||||
}
|
||||
_session.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) =>
|
||||
MyApp.router(cupertino: _cupertino, routerConfig: _config);
|
||||
|
||||
Widget _buildShell(BuildContext context, AppRoute route) => AdaptiveShell(
|
||||
cupertino: _cupertino,
|
||||
destination: _destinationOf(route.kind),
|
||||
onDestinationSelected: (destination) =>
|
||||
_delegate.goTo(_routeOf(destination)),
|
||||
destinationBodies: {
|
||||
AppDestination.runs: (_) => RunsDestination(
|
||||
session: _session,
|
||||
server: widget.server,
|
||||
initialRunId: route.runId,
|
||||
onRunSelected: (id) => _delegate.goTo(AppRoute.run(id)),
|
||||
onBack: () => _delegate.goTo(AppRoute.runs),
|
||||
),
|
||||
},
|
||||
);
|
||||
|
||||
AppDestination _destinationOf(AppRouteKind kind) => switch (kind) {
|
||||
AppRouteKind.pipelines => AppDestination.pipelines,
|
||||
AppRouteKind.runs => AppDestination.runs,
|
||||
AppRouteKind.chat => AppDestination.chat,
|
||||
AppRouteKind.settings => AppDestination.settings,
|
||||
};
|
||||
|
||||
AppRoute _routeOf(AppDestination destination) => switch (destination) {
|
||||
AppDestination.pipelines => AppRoute.pipelines,
|
||||
AppDestination.runs => AppRoute.runs,
|
||||
AppDestination.chat => AppRoute.chat,
|
||||
AppDestination.settings => AppRoute.settings,
|
||||
};
|
||||
|
||||
bool get _platformIsCupertino =>
|
||||
defaultTargetPlatform == TargetPlatform.iOS ||
|
||||
defaultTargetPlatform == TargetPlatform.macOS;
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../core/transport/connection_state.dart';
|
||||
import '../features/runs/screen.dart';
|
||||
import '../ui/adaptive/host.dart';
|
||||
import 'app_session.dart';
|
||||
import 'server_endpoint.dart';
|
||||
|
||||
/// The Runs destination: the loaded screen plus an honest connection status.
|
||||
///
|
||||
/// Before the first successful connection there is nothing to show, so the
|
||||
/// destination is a full connection screen. After that the screen stays
|
||||
/// mounted through drops and reconnects: a status banner reports reconnecting
|
||||
/// or not live, and the screen reloads in place without losing the open run.
|
||||
class RunsDestination extends StatelessWidget {
|
||||
const RunsDestination({
|
||||
super.key,
|
||||
required this.session,
|
||||
required this.server,
|
||||
this.initialRunId,
|
||||
this.onRunSelected,
|
||||
this.onBack,
|
||||
});
|
||||
|
||||
final AppSession session;
|
||||
final ServerEndpoint server;
|
||||
final int? initialRunId;
|
||||
final ValueChanged<int>? onRunSelected;
|
||||
final VoidCallback? onBack;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => AnimatedBuilder(
|
||||
animation: session,
|
||||
builder: (context, _) {
|
||||
final cupertino = usesCupertinoHost(context);
|
||||
if (server.requiresConfiguration || server.error != null) {
|
||||
return _ConnectionScreen(
|
||||
session: session,
|
||||
server: server,
|
||||
cupertino: cupertino,
|
||||
);
|
||||
}
|
||||
if (!session.everConnected) {
|
||||
if (session.connected) return _runsScreen();
|
||||
return _ConnectionScreen(
|
||||
session: session,
|
||||
server: server,
|
||||
cupertino: cupertino,
|
||||
);
|
||||
}
|
||||
return Column(
|
||||
children: [
|
||||
if (!session.connected ||
|
||||
session.subscription == RunSubscriptionState.refused)
|
||||
_ConnectionBanner(session: session, cupertino: cupertino),
|
||||
Expanded(child: _runsScreen()),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
Widget _runsScreen() => RunsScreen(
|
||||
gateway: session.gateway,
|
||||
initialRunId: initialRunId,
|
||||
syncToken: session.connectionEpoch,
|
||||
onRunSelected: onRunSelected,
|
||||
onBack: onBack,
|
||||
);
|
||||
}
|
||||
|
||||
class _ConnectionScreen extends StatelessWidget {
|
||||
const _ConnectionScreen({
|
||||
required this.session,
|
||||
required this.server,
|
||||
required this.cupertino,
|
||||
});
|
||||
|
||||
final AppSession session;
|
||||
final ServerEndpoint server;
|
||||
final bool cupertino;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final state = session.connection;
|
||||
if (server.requiresConfiguration) {
|
||||
return _status(
|
||||
context,
|
||||
title: 'Server endpoint not configured',
|
||||
detail:
|
||||
'Build the native app with an explicit Pipelines endpoint, for '
|
||||
'example --dart-define=PIPELINES_SERVER_URL=ws://host:port/connect.',
|
||||
);
|
||||
}
|
||||
if (server.error != null) {
|
||||
return _status(context, title: server.error!, detail: '');
|
||||
}
|
||||
// Only the very first attempt is "connecting". A failed attempt keeps the
|
||||
// same honest unavailable state while the client retries behind it, so the
|
||||
// screen no longer flickers between unavailable and connecting.
|
||||
if (state.kind == ConnectionKind.connecting && state.attempt <= 1) {
|
||||
return _status(
|
||||
context,
|
||||
title: 'Connecting to Pipelines…',
|
||||
detail: '',
|
||||
progress: true,
|
||||
);
|
||||
}
|
||||
return _status(
|
||||
context,
|
||||
title: 'Pipelines server unavailable',
|
||||
detail: state.retrying
|
||||
? 'Retrying automatically. Check that the Pipelines server is running.'
|
||||
: 'Check that the Pipelines server is running, then try again.',
|
||||
onRetry: session.retry,
|
||||
);
|
||||
}
|
||||
|
||||
Widget _status(
|
||||
BuildContext context, {
|
||||
required String title,
|
||||
required String detail,
|
||||
bool progress = false,
|
||||
VoidCallback? onRetry,
|
||||
}) {
|
||||
final theme = Theme.of(context);
|
||||
return Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (progress)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
child: cupertino
|
||||
? const CupertinoActivityIndicator()
|
||||
: const CircularProgressIndicator(),
|
||||
),
|
||||
Semantics(
|
||||
liveRegion: true,
|
||||
child: Text(
|
||||
title,
|
||||
textAlign: TextAlign.center,
|
||||
style: cupertino
|
||||
? CupertinoTheme.of(context).textTheme.navTitleTextStyle
|
||||
: theme.textTheme.titleMedium,
|
||||
),
|
||||
),
|
||||
if (detail.isNotEmpty) ...[
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
detail,
|
||||
textAlign: TextAlign.center,
|
||||
style: cupertino ? null : theme.textTheme.bodyMedium,
|
||||
),
|
||||
],
|
||||
if (onRetry != null) ...[
|
||||
const SizedBox(height: 16),
|
||||
if (cupertino)
|
||||
CupertinoButton(onPressed: onRetry, child: const Text('Retry'))
|
||||
else
|
||||
FilledButton(onPressed: onRetry, child: const Text('Retry')),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A compact status bar above the retained Runs screen.
|
||||
class _ConnectionBanner extends StatelessWidget {
|
||||
const _ConnectionBanner({required this.session, required this.cupertino});
|
||||
|
||||
final AppSession session;
|
||||
final bool cupertino;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final state = session.connection;
|
||||
final refused = session.subscription == RunSubscriptionState.refused;
|
||||
final reconnecting =
|
||||
!session.connected &&
|
||||
(state.kind == ConnectionKind.connecting || state.retrying);
|
||||
final String title;
|
||||
final String detail;
|
||||
final VoidCallback onRetry;
|
||||
if (session.connected && refused) {
|
||||
title = 'Not live — run updates are unavailable.';
|
||||
detail = session.subscriptionError;
|
||||
onRetry = session.resubscribe;
|
||||
} else if (reconnecting) {
|
||||
title = 'Reconnecting to Pipelines…';
|
||||
detail = '';
|
||||
onRetry = session.retry;
|
||||
} else {
|
||||
title = 'Not live — Pipelines server unavailable.';
|
||||
detail = 'Check that the Pipelines server is running.';
|
||||
onRetry = session.retry;
|
||||
}
|
||||
final textStyle = cupertino
|
||||
? CupertinoTheme.of(context).textTheme.textStyle
|
||||
: Theme.of(context).textTheme.bodyMedium;
|
||||
return ColoredBox(
|
||||
color: cupertino
|
||||
? CupertinoDynamicColor.resolve(CupertinoColors.systemGrey5, context)
|
||||
: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
if (reconnecting) ...[
|
||||
cupertino
|
||||
? const CupertinoActivityIndicator(radius: 7)
|
||||
: const SizedBox(
|
||||
width: 14,
|
||||
height: 14,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
],
|
||||
Expanded(
|
||||
child: Semantics(
|
||||
liveRegion: true,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(title, style: textStyle),
|
||||
if (detail.isNotEmpty) Text(detail, style: textStyle),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
if (cupertino)
|
||||
CupertinoButton(
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: onRetry,
|
||||
child: const Text('Retry'),
|
||||
)
|
||||
else
|
||||
TextButton(onPressed: onRetry, child: const Text('Retry')),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import '../core/transport/server_url.dart';
|
||||
|
||||
/// The single endpoints decision for an app launch.
|
||||
///
|
||||
/// A web build is served by the Pipelines proxy itself, so its own page origin
|
||||
/// is the only endpoint it may use: the browser reaches the same host over
|
||||
/// ws(s) at `/connect`. A native build has no trustworthy origin and must be
|
||||
/// given an explicit endpoint at build time; there is no default host.
|
||||
class ServerEndpoint {
|
||||
const ServerEndpoint._({
|
||||
this.uri,
|
||||
this.error,
|
||||
this.requiresConfiguration = false,
|
||||
});
|
||||
|
||||
/// Validated websocket endpoint, or null when configuration is missing or
|
||||
/// invalid. Never a guessed fallback.
|
||||
final Uri? uri;
|
||||
|
||||
/// Why no endpoint could be resolved, shown verbatim by the connection gate.
|
||||
final String? error;
|
||||
|
||||
/// Native builds without an explicit endpoint. This is a configuration
|
||||
/// state, not a server error, so the gate can explain the required setting.
|
||||
final bool requiresConfiguration;
|
||||
|
||||
static ServerEndpoint resolve({
|
||||
required Uri base,
|
||||
required bool web,
|
||||
String configured = '',
|
||||
}) {
|
||||
if (web) {
|
||||
if ((base.scheme != 'http' && base.scheme != 'https') ||
|
||||
base.host.isEmpty) {
|
||||
return const ServerEndpoint._(
|
||||
error:
|
||||
'The Pipelines endpoint is inferred from the page URL, '
|
||||
'which is not HTTP(S).',
|
||||
);
|
||||
}
|
||||
final secure = base.scheme == 'https';
|
||||
final sameOrigin = Uri(
|
||||
scheme: secure ? 'wss' : 'ws',
|
||||
host: base.host,
|
||||
port: base.hasPort ? base.port : null,
|
||||
path: '/connect',
|
||||
);
|
||||
return _validated(sameOrigin);
|
||||
}
|
||||
final value = configured.trim();
|
||||
if (value.isEmpty) {
|
||||
return const ServerEndpoint._(requiresConfiguration: true);
|
||||
}
|
||||
return _validated(Uri.tryParse(value) ?? Uri());
|
||||
}
|
||||
|
||||
static ServerEndpoint _validated(Uri value) {
|
||||
try {
|
||||
final endpoint = ServerUrl.validate(value.toString());
|
||||
return ServerEndpoint._(uri: Uri.parse(endpoint.wsUrl));
|
||||
} on FormatException catch (error) {
|
||||
return ServerEndpoint._(error: error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'artifact_record.dart';
|
||||
|
||||
/// Whether a step actually carried an artifact list.
|
||||
///
|
||||
/// An absent (or null) field means the capture is unavailable: an older step, a
|
||||
/// running visit, or a reply that did not include the field. It must never be
|
||||
/// reported as an empty capture. An explicitly recorded empty list is a known,
|
||||
/// empty capture.
|
||||
enum ArtifactCaptureAvailability { unavailable, recorded }
|
||||
|
||||
/// The recorded capture facts of one step: availability, files, and how many
|
||||
/// files the bounded scan excluded or omitted. Pure: it reads the step and adds
|
||||
/// no server call.
|
||||
class ArtifactCapture {
|
||||
const ArtifactCapture._({
|
||||
required this.availability,
|
||||
required this.artifacts,
|
||||
required this.skipped,
|
||||
required this.truncated,
|
||||
});
|
||||
|
||||
factory ArtifactCapture.fromStep(JsonMap step) {
|
||||
final value = step['artifacts'];
|
||||
final available = step.containsKey('artifacts') && value is List;
|
||||
final artifacts = available
|
||||
? <ArtifactRecord>[
|
||||
for (final item in value)
|
||||
if (item is Map)
|
||||
ArtifactRecord.fromJson(Map<String, dynamic>.from(item)),
|
||||
]
|
||||
: const <ArtifactRecord>[];
|
||||
return ArtifactCapture._(
|
||||
availability: available
|
||||
? ArtifactCaptureAvailability.recorded
|
||||
: ArtifactCaptureAvailability.unavailable,
|
||||
artifacts: List<ArtifactRecord>.unmodifiable(artifacts),
|
||||
skipped: _countOf(step['artifacts_skipped']),
|
||||
truncated: _countOf(step['artifacts_truncated']),
|
||||
);
|
||||
}
|
||||
|
||||
final ArtifactCaptureAvailability availability;
|
||||
|
||||
/// Every recorded file, including utility and retired files.
|
||||
final List<ArtifactRecord> artifacts;
|
||||
|
||||
/// Files excluded from the bounded per-step scan.
|
||||
final int skipped;
|
||||
|
||||
/// Files omitted by the capture's total budget.
|
||||
final int truncated;
|
||||
|
||||
bool get isAvailable => availability == ArtifactCaptureAvailability.recorded;
|
||||
|
||||
bool get isPartial => skipped > 0 || truncated > 0;
|
||||
|
||||
static int _countOf(dynamic value) {
|
||||
if (value is num) return value.toInt();
|
||||
if (value is String) return int.tryParse(value.trim()) ?? 0;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../graph/domain/stage_visits.dart';
|
||||
import 'artifact_record.dart';
|
||||
import 'artifact_selection.dart';
|
||||
|
||||
/// One gallery group: the stage-produced artifacts of a recorded stage visit.
|
||||
class ArtifactGroup {
|
||||
const ArtifactGroup({
|
||||
required this.stageKey,
|
||||
required this.visit,
|
||||
required this.artifacts,
|
||||
});
|
||||
|
||||
final String stageKey;
|
||||
|
||||
/// The display visit number: `control.visit` when positive, else the position
|
||||
/// within the stage's ordered visits. Never a synthetic visit.
|
||||
final int visit;
|
||||
|
||||
final List<ArtifactRecord> artifacts;
|
||||
}
|
||||
|
||||
int _sequenceOf(JsonMap step) {
|
||||
final sequence = step['sequence'];
|
||||
return sequence is num ? sequence.toInt() : 0;
|
||||
}
|
||||
|
||||
/// Sequence order with recorded order as the tie-break, matching the web
|
||||
/// client's stable sort.
|
||||
List<JsonMap> _orderedBySequence(List<JsonMap> steps) {
|
||||
final indexed = <({int position, JsonMap step})>[
|
||||
for (var index = 0; index < steps.length; index += 1)
|
||||
(position: index, step: steps[index]),
|
||||
];
|
||||
indexed.sort((a, b) {
|
||||
final bySequence = _sequenceOf(a.step).compareTo(_sequenceOf(b.step));
|
||||
return bySequence != 0 ? bySequence : a.position.compareTo(b.position);
|
||||
});
|
||||
return <JsonMap>[for (final entry in indexed) entry.step];
|
||||
}
|
||||
|
||||
/// Groups a run's stage artifacts by stage and recorded visit.
|
||||
///
|
||||
/// Stages keep first-appearance order and each stage's visits are ordered by
|
||||
/// sequence. A shared `public/` file is attributed to the visit that first
|
||||
/// recorded it, because the server records the whole public directory on every
|
||||
/// model visit. Only visits with at least one presented stage artifact produce a
|
||||
/// group, so an unavailable or empty capture never yields an empty group. An
|
||||
/// artifact-less run yields an empty list rather than a fabricated stage.
|
||||
List<ArtifactGroup> artifactGroups(List<JsonMap> steps) {
|
||||
if (steps.isEmpty) return const <ArtifactGroup>[];
|
||||
|
||||
final attributed = <JsonMap, List<ArtifactRecord>>{};
|
||||
final seenPublic = <String>{};
|
||||
for (final recordedStep in _orderedBySequence(steps)) {
|
||||
final repairs = repairArtifactNames(recordedStep);
|
||||
final kept = <ArtifactRecord>[];
|
||||
for (final artifact in stageArtifactsFrom(
|
||||
artifactsOf(recordedStep),
|
||||
repairs: repairs,
|
||||
)) {
|
||||
if (artifact.isPublicName) {
|
||||
if (seenPublic.contains(artifact.name)) continue;
|
||||
seenPublic.add(artifact.name);
|
||||
}
|
||||
kept.add(artifact);
|
||||
}
|
||||
attributed[recordedStep] = List<ArtifactRecord>.unmodifiable(kept);
|
||||
}
|
||||
|
||||
final groups = <ArtifactGroup>[];
|
||||
for (final entry in visitsByStage(steps).entries) {
|
||||
final visits = entry.value;
|
||||
for (var index = 0; index < visits.length; index += 1) {
|
||||
final artifacts = attributed[visits[index]];
|
||||
if (artifacts == null || artifacts.isEmpty) continue;
|
||||
groups.add(
|
||||
ArtifactGroup(
|
||||
stageKey: entry.key,
|
||||
visit: displayVisit(visits[index], index),
|
||||
artifacts: artifacts,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
return List<ArtifactGroup>.unmodifiable(groups);
|
||||
}
|
||||
|
||||
/// One visit's stage artifacts, excluding shared public files that an earlier
|
||||
/// visit already recorded. A repeated non-public name in a later visit stays
|
||||
/// because it is a different recorded artifact, not the same shared file.
|
||||
List<ArtifactRecord> visitArtifacts(JsonMap step, List<JsonMap> runSteps) {
|
||||
final all = stageArtifacts(step);
|
||||
if (runSteps.isEmpty) return all;
|
||||
final seen = <String>{};
|
||||
for (final candidate in _orderedBySequence(runSteps)) {
|
||||
if (identical(candidate, step) ||
|
||||
_sequenceOf(candidate) == _sequenceOf(step)) {
|
||||
break;
|
||||
}
|
||||
for (final artifact in stageArtifacts(candidate)) {
|
||||
if (artifact.isPublicName) seen.add(artifact.name);
|
||||
}
|
||||
}
|
||||
return <ArtifactRecord>[
|
||||
for (final artifact in all)
|
||||
if (!artifact.isPublicName || !seen.contains(artifact.name)) artifact,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
/// What an artifact is from the gallery's point of view: the two media kinds it
|
||||
/// previews and the file kinds it labels with a type word. Mirrors the web
|
||||
/// client's `ArtifactKind` vocabulary.
|
||||
enum ArtifactKind {
|
||||
image,
|
||||
video,
|
||||
audio,
|
||||
pdf,
|
||||
json,
|
||||
archive,
|
||||
spreadsheet,
|
||||
log,
|
||||
code,
|
||||
document,
|
||||
other,
|
||||
}
|
||||
|
||||
const Set<String> _archiveExtensions = <String>{
|
||||
'zip',
|
||||
'tar',
|
||||
'gz',
|
||||
'tgz',
|
||||
'bz2',
|
||||
'xz',
|
||||
'rar',
|
||||
'7z',
|
||||
'jar',
|
||||
'war',
|
||||
};
|
||||
|
||||
const Set<String> _archiveMimes = <String>{
|
||||
'application/zip',
|
||||
'application/gzip',
|
||||
'application/x-tar',
|
||||
'application/x-7z-compressed',
|
||||
'application/x-rar-compressed',
|
||||
'application/java-archive',
|
||||
};
|
||||
|
||||
const Set<String> _spreadsheetExtensions = <String>{
|
||||
'csv',
|
||||
'tsv',
|
||||
'xls',
|
||||
'xlsx',
|
||||
'ods',
|
||||
};
|
||||
|
||||
const Set<String> _spreadsheetMimes = <String>{
|
||||
'text/csv',
|
||||
'text/tab-separated-values',
|
||||
'application/vnd.ms-excel',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
};
|
||||
|
||||
const Set<String> _codeExtensions = <String>{
|
||||
'kt',
|
||||
'kts',
|
||||
'java',
|
||||
'go',
|
||||
'py',
|
||||
'rb',
|
||||
'php',
|
||||
'rs',
|
||||
'c',
|
||||
'h',
|
||||
'cc',
|
||||
'cpp',
|
||||
'hpp',
|
||||
'cs',
|
||||
'js',
|
||||
'jsx',
|
||||
'ts',
|
||||
'tsx',
|
||||
'mjs',
|
||||
'cjs',
|
||||
'swift',
|
||||
'scala',
|
||||
'sh',
|
||||
'bash',
|
||||
'zsh',
|
||||
'fish',
|
||||
'ps1',
|
||||
'sql',
|
||||
'yaml',
|
||||
'yml',
|
||||
'toml',
|
||||
'ini',
|
||||
'xml',
|
||||
'gradle',
|
||||
'properties',
|
||||
'proto',
|
||||
};
|
||||
|
||||
const Set<String> _codeMimes = <String>{
|
||||
'application/xml',
|
||||
'application/x-yaml',
|
||||
'application/javascript',
|
||||
'text/javascript',
|
||||
'text/x-python',
|
||||
'text/x-java-source',
|
||||
'text/x-kotlin',
|
||||
'application/x-sh',
|
||||
'application/x-httpd-php',
|
||||
'application/sql',
|
||||
};
|
||||
|
||||
const Set<String> _documentExtensions = <String>{
|
||||
'txt',
|
||||
'md',
|
||||
'markdown',
|
||||
'rst',
|
||||
'doc',
|
||||
'docx',
|
||||
'odt',
|
||||
'rtf',
|
||||
'html',
|
||||
'htm',
|
||||
};
|
||||
|
||||
const Set<String> _markdownExtensions = <String>{'md', 'markdown', 'txt'};
|
||||
|
||||
const Set<String> _documentMimes = <String>{
|
||||
'application/msword',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'application/rtf',
|
||||
};
|
||||
|
||||
const Map<ArtifactKind, String> _kindLabels = <ArtifactKind, String>{
|
||||
ArtifactKind.image: 'Image',
|
||||
ArtifactKind.video: 'Video',
|
||||
ArtifactKind.audio: 'Audio',
|
||||
ArtifactKind.pdf: 'PDF',
|
||||
ArtifactKind.json: 'JSON',
|
||||
ArtifactKind.archive: 'Archive',
|
||||
ArtifactKind.spreadsheet: 'Spreadsheet',
|
||||
ArtifactKind.log: 'Log',
|
||||
ArtifactKind.code: 'Code',
|
||||
ArtifactKind.document: 'Document',
|
||||
ArtifactKind.other: 'File',
|
||||
};
|
||||
|
||||
/// Whether a recorded content type is an image the gallery previews.
|
||||
bool isImageContentType(String contentType) => contentType.startsWith('image/');
|
||||
|
||||
/// Whether a recorded content type is a video; videos get a poster tile and are
|
||||
/// never decoded inline or autoplayed.
|
||||
bool isVideoContentType(String contentType) => contentType.startsWith('video/');
|
||||
|
||||
/// The lowercased extension of [name], or '' when it carries none.
|
||||
String _extensionOf(String name) {
|
||||
final dot = name.lastIndexOf('.');
|
||||
return dot == -1 ? '' : name.substring(dot + 1).toLowerCase();
|
||||
}
|
||||
|
||||
/// The gallery kind for a recorded content type and name.
|
||||
///
|
||||
/// Image and video come straight from the content type; the other kinds match
|
||||
/// the normalised MIME first, then the name's extension. Pure and total: an
|
||||
/// unknown type is [ArtifactKind.other], never a guess that changes an action.
|
||||
ArtifactKind artifactKind(String contentType, String name) {
|
||||
if (isImageContentType(contentType)) return ArtifactKind.image;
|
||||
if (isVideoContentType(contentType)) return ArtifactKind.video;
|
||||
final mime = contentType.split(';').first.trim().toLowerCase();
|
||||
final ext = _extensionOf(name);
|
||||
if (mime.startsWith('audio/')) return ArtifactKind.audio;
|
||||
if (mime == 'application/pdf' || ext == 'pdf') return ArtifactKind.pdf;
|
||||
if (mime.contains('json') || ext == 'json') return ArtifactKind.json;
|
||||
if (_archiveMimes.contains(mime) || _archiveExtensions.contains(ext)) {
|
||||
return ArtifactKind.archive;
|
||||
}
|
||||
if (_spreadsheetMimes.contains(mime) ||
|
||||
_spreadsheetExtensions.contains(ext)) {
|
||||
return ArtifactKind.spreadsheet;
|
||||
}
|
||||
if (ext == 'log') return ArtifactKind.log;
|
||||
if (mime == 'text/html') return ArtifactKind.document;
|
||||
if (_codeMimes.contains(mime) || _codeExtensions.contains(ext)) {
|
||||
return ArtifactKind.code;
|
||||
}
|
||||
if (mime.startsWith('text/') ||
|
||||
_documentMimes.contains(mime) ||
|
||||
_documentExtensions.contains(ext)) {
|
||||
return ArtifactKind.document;
|
||||
}
|
||||
return ArtifactKind.other;
|
||||
}
|
||||
|
||||
/// The prose word naming [kind], so a type glyph never has to be read alone.
|
||||
String artifactKindLabel(ArtifactKind kind) => _kindLabels[kind] ?? 'File';
|
||||
|
||||
/// Whether an artifact is text the viewer can render as markdown: `text/markdown`
|
||||
/// or `text/plain` (parameters ignored), or an md/markdown/txt name.
|
||||
bool isMarkdownArtifact(String contentType, String name) {
|
||||
final mime = contentType.split(';').first.trim().toLowerCase();
|
||||
if (mime == 'text/markdown' || mime == 'text/plain') return true;
|
||||
return _markdownExtensions.contains(_extensionOf(name));
|
||||
}
|
||||
|
||||
/// Whether an artifact opens inside the full-screen viewer: images, videos, and
|
||||
/// markdown/text documents. A `text/plain` log, source file or spreadsheet stays
|
||||
/// an external file because those are evidence, not prose.
|
||||
bool isViewerArtifact(String contentType, String name) {
|
||||
if (isImageContentType(contentType) || isVideoContentType(contentType)) {
|
||||
return true;
|
||||
}
|
||||
return artifactKind(contentType, name) == ArtifactKind.document &&
|
||||
isMarkdownArtifact(contentType, name);
|
||||
}
|
||||
|
||||
/// Human-readable byte size, matching the web client: whole bytes under 1 KiB,
|
||||
/// otherwise one decimal with a binary unit (KiB/MiB/GiB/TiB/PiB/EiB).
|
||||
String humanBytes(num size) {
|
||||
final value = size.truncate();
|
||||
const unit = 1024;
|
||||
if (value < unit) return '$value B';
|
||||
var div = unit;
|
||||
var exp = 0;
|
||||
var scaled = value ~/ unit;
|
||||
while (scaled >= unit) {
|
||||
div *= unit;
|
||||
exp++;
|
||||
scaled ~/= unit;
|
||||
}
|
||||
return '${(value / div).toStringAsFixed(1)} ${'KMGTPE'[exp]}iB';
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
/// The retired markdown session export file name. Nothing writes it any more,
|
||||
/// but a run recorded before the HTML-only change still lists `session.md`: it
|
||||
/// is dated evidence that is never presented beside `session.html`.
|
||||
const String legacySessionMarkdownArtifact = 'session.md';
|
||||
|
||||
/// The files the turn protocol itself writes for every visit. They are audit
|
||||
/// evidence, not stage output, so the artifact gallery lists stage files first
|
||||
/// and keeps these for an audit/debug surface.
|
||||
const List<String> systemArtifactNames = <String>[
|
||||
'input.md',
|
||||
'memory.md',
|
||||
'output.md',
|
||||
'session.html',
|
||||
];
|
||||
|
||||
/// One recorded artifact of a stage visit.
|
||||
///
|
||||
/// The server is the authority: [name], [url], [contentType] and [sizeBytes]
|
||||
/// are read verbatim and every other field is kept in [raw]. A record is never
|
||||
/// inferred or completed locally; a missing url stays empty rather than being
|
||||
/// fabricated from the name. Two records with the same name stay distinct
|
||||
/// because only the recorded url identifies an artifact.
|
||||
class ArtifactRecord {
|
||||
const ArtifactRecord({
|
||||
required this.name,
|
||||
required this.url,
|
||||
required this.contentType,
|
||||
required this.sizeBytes,
|
||||
required this.raw,
|
||||
});
|
||||
|
||||
factory ArtifactRecord.fromJson(JsonMap json) {
|
||||
final raw = _frozenMap(json);
|
||||
return ArtifactRecord(
|
||||
name: _text(raw['name']),
|
||||
url: _text(raw['url']),
|
||||
contentType: _text(raw['content_type']),
|
||||
sizeBytes: _intOf(raw['size_bytes']),
|
||||
raw: raw,
|
||||
);
|
||||
}
|
||||
|
||||
/// The recorded file name, including any `public/` prefix.
|
||||
final String name;
|
||||
|
||||
/// The recorded artifact url exactly as the server sent it.
|
||||
final String url;
|
||||
|
||||
/// The server-sniffed content type, possibly with parameters.
|
||||
final String contentType;
|
||||
|
||||
/// The recorded byte size; 0 when the server recorded none.
|
||||
final int sizeBytes;
|
||||
|
||||
/// Every field the server sent, including fields this slice does not model.
|
||||
/// Deeply unmodifiable, so a view cannot mutate the server reply.
|
||||
final JsonMap raw;
|
||||
|
||||
bool get hasUrl => url.trim().isNotEmpty;
|
||||
bool get isLegacySessionMarkdown => name == legacySessionMarkdownArtifact;
|
||||
bool get isSystem => isSystemArtifactName(name);
|
||||
bool get isPublicName => name.startsWith('public/');
|
||||
|
||||
static String _text(dynamic value) => value == null ? '' : '$value';
|
||||
|
||||
static int _intOf(dynamic value) {
|
||||
if (value is num) return value.toInt();
|
||||
if (value is String) return int.tryParse(value.trim()) ?? 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static JsonMap _frozenMap(JsonMap json) => Map<String, dynamic>.unmodifiable(
|
||||
json.map((key, value) => MapEntry(key, _frozen(value))),
|
||||
);
|
||||
|
||||
static dynamic _frozen(dynamic value) {
|
||||
if (value is Map) return _frozenMap(Map<String, dynamic>.from(value));
|
||||
if (value is List) return List<dynamic>.unmodifiable(value.map(_frozen));
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
bool isSystemArtifactName(String name) => systemArtifactNames.contains(name);
|
||||
@@ -0,0 +1,67 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'artifact_record.dart';
|
||||
|
||||
/// Parses one step's recorded artifact list. An absent, null or malformed list
|
||||
/// yields no records; the capture state (and its unavailable wording) is
|
||||
/// reported by `artifact_capture.dart`, never treated as an empty capture here.
|
||||
List<ArtifactRecord> artifactsOf(JsonMap step) {
|
||||
final value = step['artifacts'];
|
||||
if (value is! List) return const <ArtifactRecord>[];
|
||||
return <ArtifactRecord>[
|
||||
for (final item in value)
|
||||
if (item is Map) ArtifactRecord.fromJson(Map<String, dynamic>.from(item)),
|
||||
];
|
||||
}
|
||||
|
||||
/// The html names a visit's session-export repairs produced.
|
||||
Set<String> repairArtifactNames(JsonMap step) {
|
||||
final value = step['session_export_repairs'];
|
||||
if (value is! List) return const <String>{};
|
||||
return <String>{
|
||||
for (final entry in value)
|
||||
if (entry is Map &&
|
||||
entry['html'] is String &&
|
||||
'${entry['html']}'.trim().isNotEmpty)
|
||||
'${entry['html']}',
|
||||
};
|
||||
}
|
||||
|
||||
/// The artifacts of one visit as presented: the recorded files with the retired
|
||||
/// markdown session export filtered out. Duplicate names are kept because an
|
||||
/// artifact's identity is its recorded url, not its name.
|
||||
List<ArtifactRecord> presentedArtifacts(Iterable<ArtifactRecord> artifacts) {
|
||||
return <ArtifactRecord>[
|
||||
for (final artifact in artifacts)
|
||||
if (!artifact.isLegacySessionMarkdown) artifact,
|
||||
];
|
||||
}
|
||||
|
||||
/// A visit's stage-produced artifacts: everything except the turn-owned files
|
||||
/// and repaired session exports. Order is preserved.
|
||||
List<ArtifactRecord> stageArtifactsFrom(
|
||||
Iterable<ArtifactRecord> artifacts, {
|
||||
Set<String> repairs = const <String>{},
|
||||
}) {
|
||||
return <ArtifactRecord>[
|
||||
for (final artifact in presentedArtifacts(artifacts))
|
||||
if (!artifact.isSystem && !repairs.contains(artifact.name)) artifact,
|
||||
];
|
||||
}
|
||||
|
||||
/// A visit's system files and repaired exports, in recorded order.
|
||||
List<ArtifactRecord> systemArtifactsFrom(
|
||||
Iterable<ArtifactRecord> artifacts, {
|
||||
Set<String> repairs = const <String>{},
|
||||
}) {
|
||||
return <ArtifactRecord>[
|
||||
for (final artifact in presentedArtifacts(artifacts))
|
||||
if (artifact.isSystem || repairs.contains(artifact.name)) artifact,
|
||||
];
|
||||
}
|
||||
|
||||
/// Convenience for callers holding a raw step rather than parsed records.
|
||||
List<ArtifactRecord> stageArtifacts(JsonMap step) =>
|
||||
stageArtifactsFrom(artifactsOf(step), repairs: repairArtifactNames(step));
|
||||
|
||||
List<ArtifactRecord> systemArtifacts(JsonMap step) =>
|
||||
systemArtifactsFrom(artifactsOf(step), repairs: repairArtifactNames(step));
|
||||
@@ -0,0 +1,78 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'artifact_capture.dart';
|
||||
import 'artifact_groups.dart';
|
||||
import 'artifact_selection.dart';
|
||||
|
||||
/// The "capture pending" wording shared by a running visit's summary and the
|
||||
/// run-level empty state, so the two never spell it differently.
|
||||
const String artifactCapturePending = 'capture pending';
|
||||
|
||||
/// The explicit message shown where the run's gallery would be when there are
|
||||
/// no recorded artifacts. A running run says capture pending; a finished run
|
||||
/// with available captures says plainly that nothing was recorded.
|
||||
String artifactsEmptyMessage(bool executing) => executing
|
||||
? 'Artifacts · $artifactCapturePending'
|
||||
: 'No artifacts recorded for this run.';
|
||||
|
||||
/// The run summary's Artifacts section header.
|
||||
///
|
||||
/// The recorded count is exactly the number of tiles [artifactGroups] yields;
|
||||
/// the title takes its singular form for one. A run whose capture is unavailable
|
||||
/// says so instead of claiming that nothing was recorded. Partial capture is
|
||||
/// flagged when any visit excluded or omitted files.
|
||||
String artifactsHeader(List<JsonMap> steps, {required bool executing}) {
|
||||
final recorded = artifactGroups(
|
||||
steps,
|
||||
).fold<int>(0, (sum, group) => sum + group.artifacts.length);
|
||||
if (recorded == 0) {
|
||||
if (executing) return artifactsEmptyMessage(true);
|
||||
final unavailable = steps.any(
|
||||
(step) => !ArtifactCapture.fromStep(step).isAvailable,
|
||||
);
|
||||
return unavailable
|
||||
? 'Artifacts · capture unavailable'
|
||||
: artifactsEmptyMessage(false);
|
||||
}
|
||||
final partial = steps.any((step) => ArtifactCapture.fromStep(step).isPartial);
|
||||
var label =
|
||||
'${recorded == 1 ? 'Artifact' : 'Artifacts'} · $recorded recorded';
|
||||
if (partial) label += ' · partial capture';
|
||||
return label;
|
||||
}
|
||||
|
||||
/// The per-visit artifacts label.
|
||||
///
|
||||
/// A running visit says capture pending. A finished visit whose capture field was
|
||||
/// absent says capture unavailable rather than "not recorded"; only an explicitly
|
||||
/// empty capture says "not recorded for this visit". Recorded counts exclude the
|
||||
/// turn-owned files and the retired session markdown, so the words match tiles.
|
||||
String artifactsSummary(JsonMap step, {int? count}) {
|
||||
final capture = ArtifactCapture.fromStep(step);
|
||||
final recorded = count ?? stageArtifacts(step).length;
|
||||
if (recorded == 0) {
|
||||
if (step['status'] == 'running') {
|
||||
return 'Artifacts · $artifactCapturePending';
|
||||
}
|
||||
if (!capture.isAvailable) return 'Artifacts · capture unavailable';
|
||||
return 'Artifacts · not recorded for this visit';
|
||||
}
|
||||
var label = 'Artifacts · $recorded recorded';
|
||||
if (capture.isPartial) label += ' · partial capture';
|
||||
return label;
|
||||
}
|
||||
|
||||
/// The partial-capture notes, one line per non-zero count and nothing when the
|
||||
/// capture was complete or had no presented files. An unavailable capture yields
|
||||
/// no notes because there is no evidence to quantify.
|
||||
List<String> artifactCaptureNotes(JsonMap step) {
|
||||
final notes = <String>[];
|
||||
if (presentedArtifacts(artifactsOf(step)).isEmpty) return notes;
|
||||
final capture = ArtifactCapture.fromStep(step);
|
||||
if (capture.skipped > 0) {
|
||||
notes.add('${capture.skipped} files excluded from artifact capture.');
|
||||
}
|
||||
if (capture.truncated > 0) {
|
||||
notes.add('${capture.truncated} files omitted by artifact capture limits.');
|
||||
}
|
||||
return notes;
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import '../../../core/transport/server_url.dart';
|
||||
|
||||
/// A validated artifact url plus whether it points outside the configured
|
||||
/// server origin.
|
||||
class ResolvedArtifactUrl {
|
||||
const ResolvedArtifactUrl({required this.uri, required this.external});
|
||||
|
||||
final Uri uri;
|
||||
|
||||
/// True when the url's origin differs from the configured server origin (or
|
||||
/// the configured origin is unusable). A future authenticated fetch must send
|
||||
/// no cookies, authorization header or other server credentials for an
|
||||
/// external url.
|
||||
final bool external;
|
||||
|
||||
String get url => uri.toString();
|
||||
}
|
||||
|
||||
const List<String> _unsafePrefixes = <String>['//', r'\\', r'\/', '/\\'];
|
||||
|
||||
/// Resolves a recorded artifact url for display and opening.
|
||||
///
|
||||
/// A server-relative path (`/artifacts/...`, or a path without the leading
|
||||
/// slash) resolves against the configured websocket endpoint's http(s) origin,
|
||||
/// dropping the endpoint path and query. An absolute http(s) url is preserved,
|
||||
/// including its encoded path and query. Output is always http(s): protocol-
|
||||
/// relative (`//host`), hostless, credentialed, malformed and non-http(s) urls
|
||||
/// are rejected with null. A blank or invalid configured endpoint resolves no
|
||||
/// relative path; it never invents a host.
|
||||
ResolvedArtifactUrl? resolveArtifactUrl(
|
||||
String configuredEndpoint,
|
||||
String artifactUrl,
|
||||
) {
|
||||
final raw = artifactUrl.trim();
|
||||
if (raw.isEmpty) return null;
|
||||
for (final prefix in _unsafePrefixes) {
|
||||
if (raw.startsWith(prefix)) return null;
|
||||
}
|
||||
final parsed = Uri.tryParse(raw);
|
||||
if (parsed == null) return null;
|
||||
|
||||
final configured = _httpOrigin(configuredEndpoint);
|
||||
if (parsed.hasScheme) {
|
||||
final scheme = parsed.scheme.toLowerCase();
|
||||
if (scheme != 'http' && scheme != 'https') return null;
|
||||
if (!parsed.hasAuthority || parsed.host.isEmpty) return null;
|
||||
if (parsed.userInfo.isNotEmpty) return null;
|
||||
return ResolvedArtifactUrl(
|
||||
uri: parsed,
|
||||
external: configured == null || parsed.origin != configured.origin,
|
||||
);
|
||||
}
|
||||
|
||||
if (configured == null) return null;
|
||||
final relative = raw.startsWith('/') ? raw : '/$raw';
|
||||
final resolved = Uri.tryParse('${configured.origin}$relative');
|
||||
if (resolved == null) return null;
|
||||
final scheme = resolved.scheme.toLowerCase();
|
||||
if (scheme != 'http' && scheme != 'https') return null;
|
||||
if (!resolved.hasAuthority || resolved.host.isEmpty) return null;
|
||||
if (resolved.userInfo.isNotEmpty) return null;
|
||||
return ResolvedArtifactUrl(uri: resolved, external: false);
|
||||
}
|
||||
|
||||
/// The http(s) origin of a configured websocket endpoint, or null when the
|
||||
/// endpoint is blank, malformed, or not a ws/wss url.
|
||||
Uri? _httpOrigin(String configuredEndpoint) {
|
||||
try {
|
||||
final endpoint = ServerUrl.validate(configuredEndpoint);
|
||||
final http = Uri.parse(endpoint.httpUrl);
|
||||
final scheme = http.scheme.toLowerCase();
|
||||
if (scheme != 'http' && scheme != 'https') return null;
|
||||
if (http.host.isEmpty) return null;
|
||||
return Uri.parse(http.origin);
|
||||
} on FormatException {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import 'artifact_groups.dart';
|
||||
import 'artifact_kind.dart';
|
||||
import 'artifact_record.dart';
|
||||
|
||||
/// One artifact in the viewer's filtered page list, with the stage visit it
|
||||
/// belongs to. [identity] is the recorded url when there is one; otherwise it is
|
||||
/// a visit-scoped key so two url-less records never collapse into one page.
|
||||
class PagedArtifact {
|
||||
const PagedArtifact({
|
||||
required this.stageKey,
|
||||
required this.visit,
|
||||
required this.artifact,
|
||||
required this.pageIndex,
|
||||
});
|
||||
|
||||
final String stageKey;
|
||||
final int visit;
|
||||
final ArtifactRecord artifact;
|
||||
|
||||
/// Position in the filtered page list.
|
||||
final int pageIndex;
|
||||
|
||||
String get identity => artifact.hasUrl
|
||||
? artifact.url
|
||||
: '$stageKey\u0000$visit\u0000$pageIndex\u0000${artifact.name}';
|
||||
}
|
||||
|
||||
/// The artifacts the viewer can page through, in gallery order: group by group,
|
||||
/// each group's images, videos and markdown/text documents in recorded order.
|
||||
/// Other artifacts open externally and are not part of this list. Pure: it only
|
||||
/// filters and orders records the gallery already holds.
|
||||
List<PagedArtifact> pagedArtifacts(List<ArtifactGroup> groups) {
|
||||
final pages = <PagedArtifact>[];
|
||||
for (final group in groups) {
|
||||
for (final artifact in group.artifacts) {
|
||||
if (!isViewerArtifact(artifact.contentType, artifact.name)) continue;
|
||||
pages.add(
|
||||
PagedArtifact(
|
||||
stageKey: group.stageKey,
|
||||
visit: group.visit,
|
||||
artifact: artifact,
|
||||
pageIndex: pages.length,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
return List<PagedArtifact>.unmodifiable(pages);
|
||||
}
|
||||
|
||||
/// Each page's recorded url mapped to its page index, so a tile and the viewer
|
||||
/// derive from the same ordered list. The first occurrence of a url wins. A
|
||||
/// record with no recorded url has no fetchable identity and is omitted.
|
||||
Map<String, int> viewerIndexByUrl(List<ArtifactGroup> groups) {
|
||||
final indices = <String, int>{};
|
||||
for (final page in pagedArtifacts(groups)) {
|
||||
if (!page.artifact.hasUrl) continue;
|
||||
indices.putIfAbsent(page.artifact.url, () => page.pageIndex);
|
||||
}
|
||||
return indices;
|
||||
}
|
||||
|
||||
/// Paging from [current] by [delta] within `count` pages, clamped at both ends
|
||||
/// so a page never wraps and an empty list is index 0.
|
||||
int pagedIndex(int current, int delta, int count) {
|
||||
if (count <= 0) return 0;
|
||||
final wanted = current + delta;
|
||||
if (wanted < 0) return 0;
|
||||
if (wanted >= count) return count - 1;
|
||||
return wanted;
|
||||
}
|
||||
|
||||
/// The viewer's position label, e.g. `2 of 5 · image/png`.
|
||||
String artifactViewerPositionLabel(int index, int count, String contentType) {
|
||||
final type = contentType.split(';').first.trim();
|
||||
return '${index + 1} of $count · ${type.isEmpty ? 'artifact' : type}';
|
||||
}
|
||||
@@ -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<String> stageOutcomes(dynamic stage) {
|
||||
final edges = stage is Map ? stage['edges'] : null;
|
||||
if (edges is! Map) return const <String>[];
|
||||
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<Map<String, dynamic>> _stages(dynamic graph) {
|
||||
if (graph is! Map) return const <Map<String, dynamic>>[];
|
||||
final stages = graph['stages'];
|
||||
if (stages is! List) return const <Map<String, dynamic>>[];
|
||||
return stages.whereType<Map>().map(Map<String, dynamic>.from).toList();
|
||||
}
|
||||
|
||||
String _stageKey(Map<String, dynamic> 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<GraphEdge> graphEdges(dynamic graph) {
|
||||
final stages = _stages(graph);
|
||||
final stageKeys = <String>{
|
||||
for (final stage in stages)
|
||||
if (_stageKey(stage).isNotEmpty) _stageKey(stage),
|
||||
};
|
||||
final result = <GraphEdge>[];
|
||||
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<GraphNode> graphNodes(dynamic graph) {
|
||||
final stages = _stages(graph);
|
||||
final seen = <String>{};
|
||||
final nodes = <GraphNode>[];
|
||||
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;
|
||||
}
|
||||
@@ -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 ?? '';
|
||||
}
|
||||
@@ -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<String> visitedStages,
|
||||
required List<String> 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<String> visitedStages;
|
||||
|
||||
/// Taken routes as `source\0outcome\0resolvedTarget`, in recorded order.
|
||||
final List<String> 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<Map<String, dynamic>> _steps(dynamic run) {
|
||||
if (run is! Map) return const <Map<String, dynamic>>[];
|
||||
final steps = run['steps'];
|
||||
if (steps is! List) return const <Map<String, dynamic>>[];
|
||||
return steps.whereType<Map>().map(Map<String, dynamic>.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 = <String>[];
|
||||
final seenStages = <String>{};
|
||||
final takenRoutes = <String>[];
|
||||
final seenRoutes = <String>{};
|
||||
|
||||
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,
|
||||
);
|
||||
}
|
||||
@@ -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<JsonMap> _ordered(List<JsonMap> 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<String, List<JsonMap>> visitsByStage(List<JsonMap> steps) {
|
||||
final grouped = <String, List<JsonMap>>{};
|
||||
for (final step in steps) {
|
||||
final stage = '${step['stage'] ?? ''}';
|
||||
grouped.putIfAbsent(stage, () => <JsonMap>[]).add(step);
|
||||
}
|
||||
return <String, List<JsonMap>>{
|
||||
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<JsonMap> 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<JsonMap> steps,
|
||||
String stageKey, {
|
||||
int? visitIndex,
|
||||
}) {
|
||||
final visits = visitsByStage(steps)[stageKey] ?? const <JsonMap>[];
|
||||
final wanted = visitIndex ?? (visits.isEmpty ? 0 : visits.length - 1);
|
||||
return StageVisitSelection(
|
||||
stageKey: stageKey,
|
||||
visits: visits,
|
||||
index: clampVisitIndex(wanted, visits.length),
|
||||
);
|
||||
}
|
||||
@@ -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<GraphNode> nodes,
|
||||
required List<GraphEdge> edges,
|
||||
required Map<String, NodeExtent> extents,
|
||||
required GraphLayoutConfig config,
|
||||
}) {
|
||||
_validateNodeKeys(nodes);
|
||||
final ranks = assignGraphRanks(nodes, edges);
|
||||
final measured = <String, NodeExtent>{};
|
||||
final missing = <String>[];
|
||||
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<List<GraphNode>>.generate(
|
||||
ranks.rankCount,
|
||||
(_) => <GraphNode>[],
|
||||
);
|
||||
for (final node in nodes) {
|
||||
columns[ranks.rankOf[node.key]!].add(node);
|
||||
}
|
||||
|
||||
final columnWidths = <double>[
|
||||
for (final column in columns)
|
||||
column.fold<double>(
|
||||
0,
|
||||
(width, node) => math.max(width, measured[node.key]!.width),
|
||||
),
|
||||
];
|
||||
final columnHeights = <double>[
|
||||
for (final column in columns)
|
||||
_columnHeight(column, measured, config.rowGap),
|
||||
];
|
||||
final columnX = <double>[];
|
||||
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 = <GraphNodeBox>[];
|
||||
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<double>(0, (sum, column) => sum + column) +
|
||||
config.columnGap * math.max(0, columns.length - 1);
|
||||
final height =
|
||||
config.padding * 2 +
|
||||
columnHeights.fold<double>(
|
||||
0,
|
||||
(tallest, column) => math.max(tallest, column),
|
||||
);
|
||||
|
||||
return GraphLayout(
|
||||
nodes: boxes,
|
||||
width: width,
|
||||
height: height,
|
||||
rankCount: ranks.rankCount,
|
||||
ranks: ranks.rankOf,
|
||||
);
|
||||
}
|
||||
|
||||
void _validateNodeKeys(List<GraphNode> nodes) {
|
||||
final seen = <String>{};
|
||||
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<GraphNode> column,
|
||||
Map<String, NodeExtent> 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);
|
||||
}
|
||||
@@ -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<String, int> rankOf,
|
||||
required this.rankCount,
|
||||
required List<List<String>> components,
|
||||
}) : rankOf = Map.unmodifiable(rankOf),
|
||||
components = List.unmodifiable(<List<String>>[
|
||||
for (final component in components) List.unmodifiable(component),
|
||||
]);
|
||||
|
||||
/// Every definition key's rank, in definition order.
|
||||
final Map<String, int> 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<List<String>> 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<GraphNode> nodes, List<GraphEdge> edges) {
|
||||
final indexOf = <String, int>{};
|
||||
for (var index = 0; index < nodes.length; index += 1) {
|
||||
indexOf[nodes[index].key] = index;
|
||||
}
|
||||
|
||||
final adjacency = List<List<int>>.generate(nodes.length, (_) => <int>[]);
|
||||
final seenPairs = <int>{};
|
||||
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<int>.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<Set<int>>.generate(components.length, (_) => <int>{});
|
||||
final indegree = List<int>.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<int>.filled(components.length, 0);
|
||||
final ready = ListQueue<int>();
|
||||
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 = <List<String>>[
|
||||
for (final component in components)
|
||||
<String>[for (final node in component) nodes[node].key],
|
||||
];
|
||||
final componentOrder = <int>[
|
||||
for (var component = 0; component < components.length; component += 1)
|
||||
component,
|
||||
]..sort((a, b) => components[a].first.compareTo(components[b].first));
|
||||
|
||||
final rankOf = <String, int>{};
|
||||
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: <List<String>>[
|
||||
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<List<int>> _components(List<List<int>> adjacency) {
|
||||
final discovery = List<int>.filled(adjacency.length, -1);
|
||||
final low = List<int>.filled(adjacency.length, 0);
|
||||
final onStack = List<bool>.filled(adjacency.length, false);
|
||||
final stack = <int>[];
|
||||
final components = <List<int>>[];
|
||||
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 = <int>[];
|
||||
while (stack.isNotEmpty) {
|
||||
final member = stack.removeLast();
|
||||
onStack[member] = false;
|
||||
component.add(member);
|
||||
if (member == node) break;
|
||||
}
|
||||
component.sort();
|
||||
components.add(component);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return components;
|
||||
}
|
||||
@@ -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<GraphNodeBox> nodes,
|
||||
required this.width,
|
||||
required this.height,
|
||||
required this.rankCount,
|
||||
required Map<String, int> ranks,
|
||||
}) : nodes = List.unmodifiable(nodes),
|
||||
ranks = Map.unmodifiable(ranks);
|
||||
|
||||
final List<GraphNodeBox> nodes;
|
||||
final Map<String, int> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import '../layout/layout_models.dart';
|
||||
import 'route_geometry.dart';
|
||||
import 'route_models.dart';
|
||||
|
||||
/// One vertical-corridor request from a wrapping route.
|
||||
///
|
||||
/// A route needs a track right of its source and a track beside its target;
|
||||
/// both gaps are 0-based column gaps (`rankCount` is the right free gap).
|
||||
class CorridorRequest {
|
||||
const CorridorRequest({
|
||||
required this.edgeId,
|
||||
required this.sourceGap,
|
||||
required this.targetGap,
|
||||
});
|
||||
|
||||
final int edgeId;
|
||||
final int sourceGap;
|
||||
final int targetGap;
|
||||
}
|
||||
|
||||
/// Assigned x coordinates for every wrapping route's two vertical tracks.
|
||||
class CorridorPlan {
|
||||
CorridorPlan({
|
||||
required Map<int, double> sourceX,
|
||||
required Map<int, double> targetX,
|
||||
}) : sourceX = Map.unmodifiable(sourceX),
|
||||
targetX = Map.unmodifiable(targetX);
|
||||
|
||||
final Map<int, double> sourceX;
|
||||
final Map<int, double> targetX;
|
||||
}
|
||||
|
||||
/// Spreads corridor requests across the free band of each column gap.
|
||||
///
|
||||
/// Requests keep edge-id order, so equal input yields equal coordinates. Tracks
|
||||
/// are distinct inside a gap; a narrow gap compresses the spacing instead of
|
||||
/// pushing a corridor into a node column.
|
||||
CorridorPlan planCorridors({
|
||||
required GraphLayout layout,
|
||||
required List<CorridorRequest> requests,
|
||||
required RoutingConfig config,
|
||||
}) {
|
||||
final ordered = <CorridorRequest>[...requests]
|
||||
..sort((a, b) => a.edgeId.compareTo(b.edgeId));
|
||||
final slots = <int, List<_Slot>>{};
|
||||
for (final request in ordered) {
|
||||
slots
|
||||
.putIfAbsent(request.sourceGap, () => <_Slot>[])
|
||||
.add(_Slot(request.edgeId, source: true));
|
||||
slots
|
||||
.putIfAbsent(request.targetGap, () => <_Slot>[])
|
||||
.add(_Slot(request.edgeId, source: false));
|
||||
}
|
||||
|
||||
final gaps = ColumnGaps(
|
||||
nodes: layout.nodes,
|
||||
rankCount: layout.rankCount,
|
||||
layoutWidth: layout.width,
|
||||
);
|
||||
final sourceX = <int, double>{};
|
||||
final targetX = <int, double>{};
|
||||
final gapKeys = slots.keys.toList()..sort();
|
||||
for (final gapKey in gapKeys) {
|
||||
final gapSlots = slots[gapKey]!;
|
||||
final band = gaps.band(gapKey, config.nodeClearance);
|
||||
final positions = _trackPositions(
|
||||
band,
|
||||
gapSlots.length,
|
||||
config.corridorSpacing,
|
||||
);
|
||||
for (var index = 0; index < gapSlots.length; index += 1) {
|
||||
if (gapSlots[index].source) {
|
||||
sourceX[gapSlots[index].edgeId] = positions[index];
|
||||
} else {
|
||||
targetX[gapSlots[index].edgeId] = positions[index];
|
||||
}
|
||||
}
|
||||
}
|
||||
return CorridorPlan(sourceX: sourceX, targetX: targetX);
|
||||
}
|
||||
|
||||
List<double> _trackPositions(GapBand band, int count, double spacing) {
|
||||
if (count == 0) return const <double>[];
|
||||
if (band.open) {
|
||||
return <double>[
|
||||
for (var index = 0; index < count; index += 1) band.lo + spacing * index,
|
||||
];
|
||||
}
|
||||
final width = band.hi - band.lo;
|
||||
if (count == 1) return <double>[(band.lo + band.hi) / 2];
|
||||
if (width <= 0) return List<double>.filled(count, band.lo);
|
||||
final step = math.min(spacing, width / (count - 1));
|
||||
return <double>[
|
||||
for (var index = 0; index < count; index += 1) band.lo + step * index,
|
||||
];
|
||||
}
|
||||
|
||||
class _Slot {
|
||||
const _Slot(this.edgeId, {required this.source});
|
||||
|
||||
final int edgeId;
|
||||
final bool source;
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import '../layout/layout_models.dart';
|
||||
import 'route_geometry.dart';
|
||||
import 'route_models.dart';
|
||||
|
||||
/// Places one measured edge label without overlapping a node or another label.
|
||||
///
|
||||
/// Candidates are tried in a deterministic order: the midpoint of each
|
||||
/// horizontal run (above, then below), then each vertical run (right, then
|
||||
/// left), sliding along the run before giving up. A run too narrow for the
|
||||
/// box pushes the label to a free shelf below the drawing, which expands the
|
||||
/// routing bounds instead of covering a node.
|
||||
EdgeLabelBox placeEdgeLabel({
|
||||
required EdgeRoute route,
|
||||
required LabelExtent extent,
|
||||
required List<GraphNodeBox> nodes,
|
||||
required List<EdgeLabelBox> placed,
|
||||
required RoutingConfig config,
|
||||
required double floorY,
|
||||
}) {
|
||||
final width = extent.width;
|
||||
final height = extent.height;
|
||||
for (final candidate in _candidates(route, width, height, config.labelGap)) {
|
||||
final box = EdgeLabelBox(
|
||||
edgeId: route.id,
|
||||
x: candidate.x,
|
||||
y: candidate.y,
|
||||
width: width,
|
||||
height: height,
|
||||
);
|
||||
if (_fits(box, nodes, placed, config)) return box;
|
||||
}
|
||||
|
||||
// The fallback shelf is below every route and every existing label, so it
|
||||
// cannot cover a node. Growing it down expands the returned bounds.
|
||||
var top = math.max(
|
||||
floorY,
|
||||
placed.fold<double>(0, (bottom, box) => math.max(bottom, box.bottom)),
|
||||
);
|
||||
top += config.labelGap;
|
||||
final centre = _routeCentreX(route);
|
||||
final step = math.max(height + config.labelGap, 1.0);
|
||||
for (var attempt = 0; attempt < 100000; attempt += 1) {
|
||||
final x = math.max(0.0, centre - width / 2);
|
||||
final box = EdgeLabelBox(
|
||||
edgeId: route.id,
|
||||
x: x,
|
||||
y: top,
|
||||
width: width,
|
||||
height: height,
|
||||
);
|
||||
if (_fits(box, nodes, placed, config)) return box;
|
||||
top += step;
|
||||
}
|
||||
// A zero-sized label cannot collide; this is unreachable for real extents.
|
||||
return EdgeLabelBox(
|
||||
edgeId: route.id,
|
||||
x: math.max(0.0, centre - width / 2),
|
||||
y: top,
|
||||
width: width,
|
||||
height: height,
|
||||
);
|
||||
}
|
||||
|
||||
bool _fits(
|
||||
EdgeLabelBox box,
|
||||
List<GraphNodeBox> nodes,
|
||||
List<EdgeLabelBox> placed,
|
||||
RoutingConfig config,
|
||||
) {
|
||||
if (box.x < 0 || box.y < 0) return false;
|
||||
for (final node in nodes) {
|
||||
if (boxIntersectsNode(
|
||||
x: box.x,
|
||||
y: box.y,
|
||||
width: box.width,
|
||||
height: box.height,
|
||||
node: node,
|
||||
gap: config.labelGap,
|
||||
)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for (final other in placed) {
|
||||
if (boxesOverlap(
|
||||
ax: box.x,
|
||||
ay: box.y,
|
||||
aw: box.width,
|
||||
ah: box.height,
|
||||
bx: other.x,
|
||||
by: other.y,
|
||||
bw: other.width,
|
||||
bh: other.height,
|
||||
gap: config.labelGap,
|
||||
)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
List<_LabelCandidate> _candidates(
|
||||
EdgeRoute route,
|
||||
double width,
|
||||
double height,
|
||||
double gap,
|
||||
) {
|
||||
const fractions = <double>[0.5, 0.35, 0.65, 0.2, 0.8, 0.08, 0.92];
|
||||
final horizontals = <_Run>[];
|
||||
final verticals = <_Run>[];
|
||||
for (var index = 1; index < route.points.length; index += 1) {
|
||||
final a = route.points[index - 1];
|
||||
final b = route.points[index];
|
||||
if (a.y == b.y) {
|
||||
horizontals.add(_Run(a, b, (b.x - a.x).abs(), index));
|
||||
} else if (a.x == b.x) {
|
||||
verticals.add(_Run(a, b, (b.y - a.y).abs(), index));
|
||||
}
|
||||
}
|
||||
horizontals.sort((a, b) {
|
||||
final length = b.length.compareTo(a.length);
|
||||
return length != 0 ? length : a.order.compareTo(b.order);
|
||||
});
|
||||
verticals.sort((a, b) {
|
||||
final length = b.length.compareTo(a.length);
|
||||
return length != 0 ? length : a.order.compareTo(b.order);
|
||||
});
|
||||
|
||||
final candidates = <_LabelCandidate>[];
|
||||
for (final run in horizontals) {
|
||||
for (final fraction in fractions) {
|
||||
final x = run.a.x + (run.b.x - run.a.x) * fraction;
|
||||
final left = x - width / 2;
|
||||
candidates.add(_LabelCandidate(left, run.a.y - gap - height));
|
||||
candidates.add(_LabelCandidate(left, run.a.y + gap));
|
||||
}
|
||||
}
|
||||
for (final run in verticals) {
|
||||
for (final fraction in fractions) {
|
||||
final y = run.a.y + (run.b.y - run.a.y) * fraction;
|
||||
final top = y - height / 2;
|
||||
candidates.add(_LabelCandidate(run.a.x + gap, top));
|
||||
candidates.add(_LabelCandidate(run.a.x - gap - width, top));
|
||||
}
|
||||
}
|
||||
return candidates;
|
||||
}
|
||||
|
||||
double _routeCentreX(EdgeRoute route) {
|
||||
if (route.points.isEmpty) return 0;
|
||||
var lo = route.points.first.x;
|
||||
var hi = lo;
|
||||
for (final point in route.points) {
|
||||
lo = math.min(lo, point.x);
|
||||
hi = math.max(hi, point.x);
|
||||
}
|
||||
return (lo + hi) / 2;
|
||||
}
|
||||
|
||||
class _Run {
|
||||
const _Run(this.a, this.b, this.length, this.order);
|
||||
|
||||
final RoutePoint a;
|
||||
final RoutePoint b;
|
||||
final double length;
|
||||
final int order;
|
||||
}
|
||||
|
||||
class _LabelCandidate {
|
||||
const _LabelCandidate(this.x, this.y);
|
||||
|
||||
final double x;
|
||||
final double y;
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import '../domain/graph_definition.dart';
|
||||
import '../layout/layout_models.dart';
|
||||
import 'corridor_plan.dart';
|
||||
import 'route_geometry.dart';
|
||||
import 'route_models.dart';
|
||||
|
||||
/// One routed edge before labels and bounds are assembled.
|
||||
///
|
||||
/// Internal to the routing library: callers receive the immutable public
|
||||
/// [EdgeRoute] instead.
|
||||
class PlannedEdgeRoute {
|
||||
PlannedEdgeRoute({
|
||||
required this.edge,
|
||||
required this.kind,
|
||||
required this.straight,
|
||||
required this.sourcePort,
|
||||
required this.targetPort,
|
||||
required List<RoutePoint> points,
|
||||
}) : points = List.unmodifiable(points);
|
||||
|
||||
final GraphEdge edge;
|
||||
final RouteKind kind;
|
||||
final bool straight;
|
||||
final RoutePort sourcePort;
|
||||
final RoutePort targetPort;
|
||||
final List<RoutePoint> points;
|
||||
|
||||
EdgeRoute toRoute() => EdgeRoute(
|
||||
id: edge.id,
|
||||
source: edge.source,
|
||||
outcome: edge.outcome,
|
||||
target: edge.target,
|
||||
label: edge.label,
|
||||
fallback: edge.fallback,
|
||||
kind: kind,
|
||||
straight: straight,
|
||||
sourcePort: sourcePort,
|
||||
targetPort: targetPort,
|
||||
points: points,
|
||||
);
|
||||
}
|
||||
|
||||
/// Plans orthogonal polylines for every edge whose endpoints have placed boxes.
|
||||
///
|
||||
/// [edges] must already be filtered to known endpoints and sorted by id. The
|
||||
/// plan is deterministic: forward one-rank routes take a straight horizontal
|
||||
/// run when the measured boxes and labels leave room, and every other route
|
||||
/// gets a unique lane below the node grid plus vertical corridors inside the
|
||||
/// column gaps. Corridors and lanes never enter a node column.
|
||||
///
|
||||
/// All horizontal stubs share one [AxisTrackAllocator], so two different edges
|
||||
/// cannot occupy the same run in a column gap even when they touch different
|
||||
/// nodes on the same row.
|
||||
List<PlannedEdgeRoute> planEdgeRoutes({
|
||||
required GraphLayout layout,
|
||||
required List<GraphEdge> edges,
|
||||
required double maxLabelHeight,
|
||||
required RoutingConfig config,
|
||||
}) {
|
||||
if (edges.isEmpty) return const <PlannedEdgeRoute>[];
|
||||
final nodes = <String, GraphNodeBox>{
|
||||
for (final node in layout.nodes) node.key: node,
|
||||
};
|
||||
final kinds = <int, RouteKind>{};
|
||||
for (final edge in edges) {
|
||||
final source = nodes[edge.source]!;
|
||||
final target = nodes[edge.target]!;
|
||||
kinds[edge.id] = _kindFor(edge, source, target, layout);
|
||||
}
|
||||
|
||||
final trackSpacing = math.max(
|
||||
config.portSpacing,
|
||||
maxLabelHeight + config.labelGap,
|
||||
);
|
||||
final runs = AxisTrackAllocator(trackSpacing);
|
||||
final straightY = <int, double>{};
|
||||
for (final edge in edges) {
|
||||
if (kinds[edge.id] != RouteKind.forward) continue;
|
||||
final source = nodes[edge.source]!;
|
||||
final target = nodes[edge.target]!;
|
||||
if (target.rank != source.rank + 1) continue;
|
||||
if (target.x <= source.right) continue;
|
||||
final sourceInset = portInset(source, config.portSpacing);
|
||||
final targetInset = portInset(target, config.portSpacing);
|
||||
final lo = math.max(source.y + sourceInset, target.y + targetInset);
|
||||
final hi = math.min(
|
||||
source.bottom - sourceInset,
|
||||
target.bottom - targetInset,
|
||||
);
|
||||
if (hi <= lo) continue;
|
||||
final y = runs.allocate(
|
||||
desired: (lo + hi) / 2,
|
||||
min: lo,
|
||||
max: hi,
|
||||
spanLo: source.right,
|
||||
spanHi: target.x,
|
||||
);
|
||||
if (y != null) straightY[edge.id] = y;
|
||||
}
|
||||
|
||||
final laneStep = math.max(
|
||||
config.laneSpacing,
|
||||
maxLabelHeight + config.labelGap,
|
||||
);
|
||||
final contentBottom = layout.nodes.fold<double>(
|
||||
0,
|
||||
(bottom, node) => math.max(bottom, node.bottom),
|
||||
);
|
||||
final wrapPlans = <_WrapPlan>[];
|
||||
final corridorRequests = <CorridorRequest>[];
|
||||
var laneIndex = 0;
|
||||
for (final edge in edges) {
|
||||
if (straightY.containsKey(edge.id)) continue;
|
||||
final source = nodes[edge.source]!;
|
||||
final target = nodes[edge.target]!;
|
||||
final kind = kinds[edge.id]!;
|
||||
final laneY =
|
||||
contentBottom + config.nodeClearance + laneStep * (laneIndex + 1);
|
||||
laneIndex += 1;
|
||||
final sourceGap = (source.rank + 1).clamp(0, layout.rankCount);
|
||||
final targetGap = kind == RouteKind.forward
|
||||
? target.rank.clamp(0, layout.rankCount)
|
||||
: (target.rank + 1).clamp(0, layout.rankCount);
|
||||
corridorRequests.add(
|
||||
CorridorRequest(
|
||||
edgeId: edge.id,
|
||||
sourceGap: sourceGap,
|
||||
targetGap: targetGap,
|
||||
),
|
||||
);
|
||||
wrapPlans.add(_WrapPlan(edge: edge, kind: kind, laneY: laneY));
|
||||
}
|
||||
|
||||
final corridors = planCorridors(
|
||||
layout: layout,
|
||||
requests: corridorRequests,
|
||||
config: config,
|
||||
);
|
||||
final sourceTrackX = corridors.sourceX;
|
||||
final targetTrackX = corridors.targetX;
|
||||
|
||||
final sourcePorts = <int, RoutePort>{};
|
||||
final targetPorts = <int, RoutePort>{};
|
||||
for (final edge in edges) {
|
||||
final y = straightY[edge.id];
|
||||
if (y == null) continue;
|
||||
final source = nodes[edge.source]!;
|
||||
final target = nodes[edge.target]!;
|
||||
sourcePorts[edge.id] = RoutePort(
|
||||
side: RoutePortSide.right,
|
||||
point: RoutePoint(source.right, y),
|
||||
);
|
||||
targetPorts[edge.id] = RoutePort(
|
||||
side: RoutePortSide.left,
|
||||
point: RoutePoint(target.x, y),
|
||||
);
|
||||
}
|
||||
for (final plan in wrapPlans) {
|
||||
final edge = plan.edge;
|
||||
final source = nodes[edge.source]!;
|
||||
final target = nodes[edge.target]!;
|
||||
final sourceTrack = sourceTrackX[edge.id]!;
|
||||
final targetTrack = targetTrackX[edge.id]!;
|
||||
final sourceInset = portInset(source, config.portSpacing);
|
||||
final targetInset = portInset(target, config.portSpacing);
|
||||
final sourceY = runs.allocate(
|
||||
desired: source.y + source.height / 2,
|
||||
min: source.y + sourceInset,
|
||||
max: source.bottom - sourceInset,
|
||||
spanLo: source.right,
|
||||
spanHi: sourceTrack,
|
||||
);
|
||||
final targetSide = plan.kind == RouteKind.forward
|
||||
? RoutePortSide.left
|
||||
: RoutePortSide.right;
|
||||
final targetBorder = targetSide == RoutePortSide.left
|
||||
? target.x
|
||||
: target.right;
|
||||
final targetY = runs.allocate(
|
||||
desired: target.y + target.height / 2,
|
||||
min: target.y + targetInset,
|
||||
max: target.bottom - targetInset,
|
||||
spanLo: math.min(targetBorder, targetTrack),
|
||||
spanHi: math.max(targetBorder, targetTrack),
|
||||
);
|
||||
sourcePorts[edge.id] = RoutePort(
|
||||
side: RoutePortSide.right,
|
||||
point: RoutePoint(source.right, sourceY ?? source.y + source.height / 2),
|
||||
);
|
||||
targetPorts[edge.id] = RoutePort(
|
||||
side: targetSide,
|
||||
point: RoutePoint(targetBorder, targetY ?? target.y + target.height / 2),
|
||||
);
|
||||
}
|
||||
|
||||
final planned = <int, PlannedEdgeRoute>{};
|
||||
for (final edge in edges) {
|
||||
final value = straightY[edge.id];
|
||||
if (value != null) {
|
||||
planned[edge.id] = PlannedEdgeRoute(
|
||||
edge: edge,
|
||||
kind: kinds[edge.id]!,
|
||||
straight: true,
|
||||
sourcePort: sourcePorts[edge.id]!,
|
||||
targetPort: targetPorts[edge.id]!,
|
||||
points: _collapse(<RoutePoint>[
|
||||
sourcePorts[edge.id]!.point,
|
||||
targetPorts[edge.id]!.point,
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
for (final plan in wrapPlans) {
|
||||
final sourceTrack = sourceTrackX[plan.edge.id]!;
|
||||
final targetTrack = targetTrackX[plan.edge.id]!;
|
||||
planned[plan.edge.id] = PlannedEdgeRoute(
|
||||
edge: plan.edge,
|
||||
kind: plan.kind,
|
||||
straight: false,
|
||||
sourcePort: sourcePorts[plan.edge.id]!,
|
||||
targetPort: targetPorts[plan.edge.id]!,
|
||||
points: _collapse(<RoutePoint>[
|
||||
sourcePorts[plan.edge.id]!.point,
|
||||
RoutePoint(sourceTrack, sourcePorts[plan.edge.id]!.point.y),
|
||||
RoutePoint(sourceTrack, plan.laneY),
|
||||
RoutePoint(targetTrack, plan.laneY),
|
||||
RoutePoint(targetTrack, targetPorts[plan.edge.id]!.point.y),
|
||||
targetPorts[plan.edge.id]!.point,
|
||||
]),
|
||||
);
|
||||
}
|
||||
return <PlannedEdgeRoute>[for (final edge in edges) planned[edge.id]!];
|
||||
}
|
||||
|
||||
RouteKind _kindFor(
|
||||
GraphEdge edge,
|
||||
GraphNodeBox source,
|
||||
GraphNodeBox target,
|
||||
GraphLayout layout,
|
||||
) {
|
||||
if (edge.source == edge.target) return RouteKind.selfLoop;
|
||||
final sourceRank = layout.ranks[edge.source] ?? source.rank;
|
||||
final targetRank = layout.ranks[edge.target] ?? target.rank;
|
||||
if (targetRank > sourceRank) return RouteKind.forward;
|
||||
if (targetRank < sourceRank) return RouteKind.back;
|
||||
return RouteKind.sameRank;
|
||||
}
|
||||
|
||||
List<RoutePoint> _collapse(List<RoutePoint> points) {
|
||||
final result = <RoutePoint>[];
|
||||
for (final point in points) {
|
||||
if (result.isEmpty || result.last != point) result.add(point);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
class _WrapPlan {
|
||||
_WrapPlan({required this.edge, required this.kind, required this.laneY});
|
||||
|
||||
final GraphEdge edge;
|
||||
final RouteKind kind;
|
||||
final double laneY;
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import '../domain/graph_definition.dart';
|
||||
import '../layout/layout_models.dart';
|
||||
import 'edge_label_placement.dart';
|
||||
import 'edge_route_planner.dart';
|
||||
import 'route_models.dart';
|
||||
|
||||
/// Routes every definition edge that has a placed source and target.
|
||||
///
|
||||
/// The node boxes and ranks come from the landed [GraphLayout]; this function
|
||||
/// never moves them, invents a node or assumes a node size. Callers supply one
|
||||
/// measured [LabelExtent] for every routed edge, plus the clearances and lane
|
||||
/// spacing in [RoutingConfig].
|
||||
///
|
||||
/// Edges with an unknown, empty or missing endpoint are returned in
|
||||
/// [GraphRouting.skipped] with their definition identity intact. A routed edge
|
||||
/// keeps its id, source, outcome, target, label and fallback flag. Results are
|
||||
/// ordered by definition edge id and are stable for repeated input.
|
||||
GraphRouting routeGraphEdges({
|
||||
required GraphLayout layout,
|
||||
required List<GraphEdge> edges,
|
||||
required Map<int, LabelExtent> labelExtents,
|
||||
required RoutingConfig config,
|
||||
}) {
|
||||
final ordered = <GraphEdge>[...edges]..sort((a, b) => a.id.compareTo(b.id));
|
||||
final seenIds = <int>{};
|
||||
for (final edge in ordered) {
|
||||
if (!seenIds.add(edge.id)) {
|
||||
throw ArgumentError.value(edge.id, 'edges', 'duplicate edge id');
|
||||
}
|
||||
}
|
||||
|
||||
final nodes = <String, GraphNodeBox>{
|
||||
for (final node in layout.nodes) node.key: node,
|
||||
};
|
||||
final routed = <GraphEdge>[];
|
||||
final skipped = <RouteDiagnostic>[];
|
||||
for (final edge in ordered) {
|
||||
if (!nodes.containsKey(edge.source)) {
|
||||
skipped.add(
|
||||
RouteDiagnostic(
|
||||
id: edge.id,
|
||||
source: edge.source,
|
||||
outcome: edge.outcome,
|
||||
target: edge.target,
|
||||
reason: RouteSkipReason.unknownSource,
|
||||
message: 'source "${edge.source}" has no placed node',
|
||||
),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (!edge.knownTarget || !nodes.containsKey(edge.target)) {
|
||||
skipped.add(
|
||||
RouteDiagnostic(
|
||||
id: edge.id,
|
||||
source: edge.source,
|
||||
outcome: edge.outcome,
|
||||
target: edge.target,
|
||||
reason: RouteSkipReason.unknownTarget,
|
||||
message: edge.target.isEmpty
|
||||
? 'edge target is empty'
|
||||
: 'target "${edge.target}" has no placed node',
|
||||
),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
routed.add(edge);
|
||||
}
|
||||
|
||||
final missing = <int>[
|
||||
for (final edge in routed)
|
||||
if (!labelExtents.containsKey(edge.id)) edge.id,
|
||||
];
|
||||
if (missing.isNotEmpty) {
|
||||
throw ArgumentError.value(
|
||||
missing,
|
||||
'labelExtents',
|
||||
'missing measured label extents for routed edges',
|
||||
);
|
||||
}
|
||||
|
||||
var maxLabelHeight = 0.0;
|
||||
for (final edge in routed) {
|
||||
maxLabelHeight = math.max(maxLabelHeight, labelExtents[edge.id]!.height);
|
||||
}
|
||||
final planned = planEdgeRoutes(
|
||||
layout: layout,
|
||||
edges: routed,
|
||||
maxLabelHeight: maxLabelHeight,
|
||||
config: config,
|
||||
);
|
||||
final routes = <EdgeRoute>[for (final plan in planned) plan.toRoute()];
|
||||
var floorY = layout.height;
|
||||
for (final route in routes) {
|
||||
for (final point in route.points) {
|
||||
floorY = math.max(floorY, point.y);
|
||||
}
|
||||
}
|
||||
|
||||
final labels = <EdgeLabelBox>[];
|
||||
for (var index = 0; index < routes.length; index += 1) {
|
||||
labels.add(
|
||||
placeEdgeLabel(
|
||||
route: routes[index],
|
||||
extent: labelExtents[routes[index].id]!,
|
||||
nodes: layout.nodes,
|
||||
placed: labels,
|
||||
config: config,
|
||||
floorY: floorY,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
var width = layout.width;
|
||||
var height = layout.height;
|
||||
for (final route in routes) {
|
||||
for (final point in route.points) {
|
||||
width = math.max(width, point.x);
|
||||
height = math.max(height, point.y);
|
||||
}
|
||||
}
|
||||
for (final label in labels) {
|
||||
width = math.max(width, label.right);
|
||||
height = math.max(height, label.bottom);
|
||||
}
|
||||
|
||||
return GraphRouting(
|
||||
routes: routes,
|
||||
labels: labels,
|
||||
skipped: skipped,
|
||||
width: width + config.boundsPadding,
|
||||
height: height + config.boundsPadding,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import '../layout/layout_models.dart';
|
||||
|
||||
/// Geometry helpers for deterministic orthogonal routing.
|
||||
///
|
||||
/// Everything here is plain numbers: no Flutter types, no drawing and no
|
||||
/// assumed metrics. The helpers are internal to the routing library.
|
||||
|
||||
/// Reserves horizontal or vertical tracks without collinear overlap.
|
||||
///
|
||||
/// A track is a position on [axis] plus the interval it spans on the other
|
||||
/// axis. Two tracks only conflict when both their positions and their spans
|
||||
/// overlap, so a long cross lane and a short stub may share a coordinate when
|
||||
/// their runs do not meet.
|
||||
class AxisTrackAllocator {
|
||||
AxisTrackAllocator(this.step);
|
||||
|
||||
final double step;
|
||||
final List<_Track> _placed = <_Track>[];
|
||||
|
||||
/// The nearest free position to [desired], or null when none is found.
|
||||
double? allocate({
|
||||
required double desired,
|
||||
required double min,
|
||||
required double max,
|
||||
required double spanLo,
|
||||
required double spanHi,
|
||||
}) {
|
||||
if (max < min) return null;
|
||||
final start = desired.clamp(min, max);
|
||||
var spacing = step;
|
||||
while (spacing > 0.0001) {
|
||||
for (var attempt = 0; attempt <= 512; attempt += 1) {
|
||||
final candidates = attempt == 0
|
||||
? <double>[start]
|
||||
: <double>[start + attempt * spacing, start - attempt * spacing];
|
||||
for (final candidate in candidates) {
|
||||
if (candidate < min || candidate > max) continue;
|
||||
if (_isFree(candidate, spanLo, spanHi, spacing)) {
|
||||
_placed.add(_Track(candidate, spanLo, spanHi));
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
spacing /= 2;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
bool _isFree(double position, double spanLo, double spanHi, double spacing) {
|
||||
for (final track in _placed) {
|
||||
if ((track.position - position).abs() >= spacing) continue;
|
||||
final overlaps = track.lo <= spanHi && spanLo <= track.hi;
|
||||
if (overlaps) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
class _Track {
|
||||
const _Track(this.position, this.lo, this.hi);
|
||||
|
||||
final double position;
|
||||
final double lo;
|
||||
final double hi;
|
||||
}
|
||||
|
||||
/// The x band available for vertical corridors in each column gap.
|
||||
///
|
||||
/// Gap `g` sits before rank `g`; gap `rankCount` is the free space right of the
|
||||
/// last column. Left/right bounds come from the placed boxes themselves, so a
|
||||
/// corridor never crosses a column, including heterogeneous node widths.
|
||||
class ColumnGaps {
|
||||
ColumnGaps({
|
||||
required List<GraphNodeBox> nodes,
|
||||
required this.rankCount,
|
||||
required this.layoutWidth,
|
||||
}) : _left = List<double>.filled(rankCount + 1, 0),
|
||||
_right = List<double>.filled(rankCount + 1, layoutWidth) {
|
||||
final rankRight = List<double>.filled(rankCount, 0);
|
||||
final rankLeft = List<double>.filled(rankCount, layoutWidth);
|
||||
for (final node in nodes) {
|
||||
if (node.rank < 0 || node.rank >= rankCount) continue;
|
||||
rankRight[node.rank] = math.max(rankRight[node.rank], node.right);
|
||||
rankLeft[node.rank] = math.min(rankLeft[node.rank], node.x);
|
||||
}
|
||||
var left = 0.0;
|
||||
for (var rank = 0; rank < rankCount; rank += 1) {
|
||||
_left[rank] = left;
|
||||
left = math.max(left, rankRight[rank]);
|
||||
}
|
||||
_left[rankCount] = left;
|
||||
var right = layoutWidth;
|
||||
_right[rankCount] = right;
|
||||
for (var rank = rankCount - 1; rank >= 0; rank -= 1) {
|
||||
right = math.min(right, rankLeft[rank]);
|
||||
_right[rank] = right;
|
||||
}
|
||||
}
|
||||
|
||||
final int rankCount;
|
||||
final double layoutWidth;
|
||||
final List<double> _left;
|
||||
final List<double> _right;
|
||||
|
||||
/// The usable band in gap [index], inset by at most [clearance].
|
||||
///
|
||||
/// The rightmost gap is open-ended because a loop may expand the canvas;
|
||||
/// every other gap is bounded by the neighbouring columns.
|
||||
GapBand band(int index, double clearance) {
|
||||
final gap = index.clamp(0, rankCount);
|
||||
final left = _left[gap];
|
||||
final right = _right[gap];
|
||||
if (gap == rankCount) {
|
||||
return GapBand(lo: left + clearance, hi: double.infinity, open: true);
|
||||
}
|
||||
if (gap == 0) {
|
||||
return GapBand(
|
||||
lo: double.negativeInfinity,
|
||||
hi: right - clearance,
|
||||
open: true,
|
||||
);
|
||||
}
|
||||
final width = math.max(0.0, right - left);
|
||||
final inset = math.min(clearance, width / 4);
|
||||
return GapBand(lo: left + inset, hi: right - inset, open: false);
|
||||
}
|
||||
}
|
||||
|
||||
/// One usable corridor band.
|
||||
class GapBand {
|
||||
const GapBand({required this.lo, required this.hi, required this.open});
|
||||
|
||||
final double lo;
|
||||
final double hi;
|
||||
final bool open;
|
||||
}
|
||||
|
||||
/// The inset a port keeps from a node corner.
|
||||
double portInset(GraphNodeBox node, double portSpacing) =>
|
||||
math.min(portSpacing / 2, node.height / 2);
|
||||
|
||||
/// True when an axis-aligned box overlaps [node], optionally inflated by [gap].
|
||||
bool boxIntersectsNode({
|
||||
required double x,
|
||||
required double y,
|
||||
required double width,
|
||||
required double height,
|
||||
required GraphNodeBox node,
|
||||
double gap = 0,
|
||||
}) {
|
||||
return x < node.right + gap &&
|
||||
x + width > node.x - gap &&
|
||||
y < node.bottom + gap &&
|
||||
y + height > node.y - gap;
|
||||
}
|
||||
|
||||
/// True when two label-sized boxes overlap, optionally inflated by [gap].
|
||||
bool boxesOverlap({
|
||||
required double ax,
|
||||
required double ay,
|
||||
required double aw,
|
||||
required double ah,
|
||||
required double bx,
|
||||
required double by,
|
||||
required double bw,
|
||||
required double bh,
|
||||
double gap = 0,
|
||||
}) {
|
||||
return ax < bx + bw + gap &&
|
||||
ax + aw + gap > bx &&
|
||||
ay < by + bh + gap &&
|
||||
ay + ah + gap > by;
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
/// Pure orthogonal geometry for a workflow graph's edges and labels.
|
||||
///
|
||||
/// The caller owns every measurement: node boxes come from the landed
|
||||
/// `GraphLayout`, label extents are measured after text layout, and clearances
|
||||
/// or spacings come from [RoutingConfig]. This library never assumes a font,
|
||||
/// widget style, device class or CSS value, and it has no Flutter imports.
|
||||
///
|
||||
/// The same result can be built into a painter, native widgets or a test
|
||||
/// fixture; no drawing decision lives here.
|
||||
library;
|
||||
|
||||
export 'routing_inputs.dart';
|
||||
|
||||
/// One point on an orthogonal route, in graph space.
|
||||
class RoutePoint {
|
||||
const RoutePoint(this.x, this.y);
|
||||
|
||||
final double x;
|
||||
final double y;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is RoutePoint && other.x == x && other.y == y;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(x, y);
|
||||
|
||||
@override
|
||||
String toString() => 'RoutePoint($x, $y)';
|
||||
}
|
||||
|
||||
/// The border an edge leaves or enters through.
|
||||
enum RoutePortSide { top, right, bottom, left }
|
||||
|
||||
/// A route endpoint on a node's border.
|
||||
///
|
||||
/// [side] is the edge's outward direction: a right port leaves to the right
|
||||
/// (or enters from the right), a left port leaves to the left, and so on.
|
||||
class RoutePort {
|
||||
const RoutePort({required this.side, required this.point});
|
||||
|
||||
final RoutePortSide side;
|
||||
final RoutePoint point;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is RoutePort && other.side == side && other.point == point;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(side, point);
|
||||
|
||||
@override
|
||||
String toString() => 'RoutePort($side, ${point.x}, ${point.y})';
|
||||
}
|
||||
|
||||
/// How an edge relates to the layer it comes from.
|
||||
enum RouteKind {
|
||||
/// The target is in a later rank.
|
||||
forward,
|
||||
|
||||
/// Both endpoints share a rank (a cycle or strongly connected component).
|
||||
sameRank,
|
||||
|
||||
/// The target is in an earlier rank. Ranks from `assignGraphRanks` only
|
||||
/// produce this for a caller-supplied layout; it is still routed honestly.
|
||||
back,
|
||||
|
||||
/// The source and target are the same node.
|
||||
selfLoop,
|
||||
}
|
||||
|
||||
/// Why an edge has no route.
|
||||
enum RouteSkipReason {
|
||||
/// The source key has no placed node.
|
||||
unknownSource,
|
||||
|
||||
/// The target key has no placed node, including an empty/unknown target.
|
||||
unknownTarget,
|
||||
}
|
||||
|
||||
/// One edge's deterministic orthogonal route.
|
||||
///
|
||||
/// [id], [source], [outcome], [target], [label] and [fallback] are copied from
|
||||
/// the definition edge unchanged. [points] starts at [sourcePort] and ends at
|
||||
/// [targetPort]; every consecutive pair shares one coordinate.
|
||||
class EdgeRoute {
|
||||
EdgeRoute({
|
||||
required this.id,
|
||||
required this.source,
|
||||
required this.outcome,
|
||||
required this.target,
|
||||
required this.label,
|
||||
required this.fallback,
|
||||
required this.kind,
|
||||
required this.straight,
|
||||
required this.sourcePort,
|
||||
required this.targetPort,
|
||||
required List<RoutePoint> points,
|
||||
}) : points = List.unmodifiable(points);
|
||||
|
||||
final int id;
|
||||
final String source;
|
||||
final String outcome;
|
||||
final String target;
|
||||
final String label;
|
||||
final bool fallback;
|
||||
final RouteKind kind;
|
||||
|
||||
/// True when the route is one straight horizontal segment.
|
||||
final bool straight;
|
||||
final RoutePort sourcePort;
|
||||
final RoutePort targetPort;
|
||||
final List<RoutePoint> points;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is EdgeRoute &&
|
||||
other.id == id &&
|
||||
other.source == source &&
|
||||
other.outcome == outcome &&
|
||||
other.target == target &&
|
||||
other.label == label &&
|
||||
other.fallback == fallback &&
|
||||
other.kind == kind &&
|
||||
other.straight == straight &&
|
||||
other.sourcePort == sourcePort &&
|
||||
other.targetPort == targetPort &&
|
||||
_samePoints(other.points, points);
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(
|
||||
id,
|
||||
source,
|
||||
outcome,
|
||||
target,
|
||||
label,
|
||||
fallback,
|
||||
kind,
|
||||
straight,
|
||||
sourcePort,
|
||||
targetPort,
|
||||
Object.hashAll(points),
|
||||
);
|
||||
}
|
||||
|
||||
/// One measured label box placed clear of node interiors.
|
||||
class EdgeLabelBox {
|
||||
const EdgeLabelBox({
|
||||
required this.edgeId,
|
||||
required this.x,
|
||||
required this.y,
|
||||
required this.width,
|
||||
required this.height,
|
||||
});
|
||||
|
||||
final int edgeId;
|
||||
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 EdgeLabelBox &&
|
||||
other.edgeId == edgeId &&
|
||||
other.x == x &&
|
||||
other.y == y &&
|
||||
other.width == width &&
|
||||
other.height == height;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(edgeId, x, y, width, height);
|
||||
}
|
||||
|
||||
/// An edge the router deliberately did not draw.
|
||||
///
|
||||
/// The definition identity is preserved so a caller can present a diagnostic
|
||||
/// instead of inventing a node, route or visit.
|
||||
class RouteDiagnostic {
|
||||
const RouteDiagnostic({
|
||||
required this.id,
|
||||
required this.source,
|
||||
required this.outcome,
|
||||
required this.target,
|
||||
required this.reason,
|
||||
required this.message,
|
||||
});
|
||||
|
||||
final int id;
|
||||
final String source;
|
||||
final String outcome;
|
||||
final String target;
|
||||
final RouteSkipReason reason;
|
||||
final String message;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is RouteDiagnostic &&
|
||||
other.id == id &&
|
||||
other.source == source &&
|
||||
other.outcome == outcome &&
|
||||
other.target == target &&
|
||||
other.reason == reason &&
|
||||
other.message == message;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(id, source, outcome, target, reason, message);
|
||||
}
|
||||
|
||||
/// The complete immutable routing result.
|
||||
///
|
||||
/// [width] and [height] include every route point and label box as well as the
|
||||
/// landed layout bounds, so a loop that leaves the node grid expands the
|
||||
/// returned box instead of being clipped. [routes] and [skipped] are ordered by
|
||||
/// definition edge id; [labels] follows the same order.
|
||||
class GraphRouting {
|
||||
GraphRouting({
|
||||
required List<EdgeRoute> routes,
|
||||
required List<EdgeLabelBox> labels,
|
||||
required List<RouteDiagnostic> skipped,
|
||||
required this.width,
|
||||
required this.height,
|
||||
}) : routes = List.unmodifiable(routes),
|
||||
labels = List.unmodifiable(labels),
|
||||
skipped = List.unmodifiable(skipped);
|
||||
|
||||
final List<EdgeRoute> routes;
|
||||
final List<EdgeLabelBox> labels;
|
||||
final List<RouteDiagnostic> skipped;
|
||||
final double width;
|
||||
final double height;
|
||||
|
||||
bool get isEmpty => routes.isEmpty;
|
||||
|
||||
/// The route for [id], or null when that edge was skipped.
|
||||
EdgeRoute? routeFor(int id) {
|
||||
for (final route in routes) {
|
||||
if (route.id == id) return route;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// The label box for [id], or null when the edge was skipped.
|
||||
EdgeLabelBox? labelFor(int id) {
|
||||
for (final label in labels) {
|
||||
if (label.edgeId == id) return label;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
bool _samePoints(List<RoutePoint> a, List<RoutePoint> b) {
|
||||
if (a.length != b.length) return false;
|
||||
for (var index = 0; index < a.length; index += 1) {
|
||||
if (a[index] != b[index]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/// Caller-supplied measurements and clearances for graph-edge routing.
|
||||
///
|
||||
/// No font, widget style, device class or CSS value is assumed: every size is
|
||||
/// measured or chosen by the caller.
|
||||
library;
|
||||
|
||||
void _requireFiniteNonNegative(String name, double value) {
|
||||
if (!value.isFinite || value < 0) {
|
||||
throw ArgumentError.value(value, name, 'must be finite and non-negative');
|
||||
}
|
||||
}
|
||||
|
||||
void _requireFinitePositive(String name, double value) {
|
||||
if (!value.isFinite || value <= 0) {
|
||||
throw ArgumentError.value(value, name, 'must be finite and positive');
|
||||
}
|
||||
}
|
||||
|
||||
/// A caller-measured edge label extent, in logical pixels.
|
||||
class LabelExtent {
|
||||
LabelExtent({required this.width, required this.height}) {
|
||||
_requireFiniteNonNegative('width', width);
|
||||
_requireFiniteNonNegative('height', height);
|
||||
}
|
||||
|
||||
final double width;
|
||||
final double height;
|
||||
}
|
||||
|
||||
/// Clearances and spacings a caller reserves for edge geometry.
|
||||
///
|
||||
/// [nodeClearance] is the distance a lane or corridor keeps from every node
|
||||
/// edge. [laneSpacing] separates the horizontal tracks used by wrapping
|
||||
/// routes, [corridorSpacing] separates vertical tracks inside one column gap,
|
||||
/// and [portSpacing] separates ports on a node side. [labelGap] keeps a label
|
||||
/// box off its wire; [boundsPadding] is added to the returned bounds.
|
||||
///
|
||||
/// The router may widen a lane step beyond [laneSpacing] when the measured
|
||||
/// label heights need the room. Inside a narrow column gap it compresses
|
||||
/// corridor or port spacing rather than routing a track into a node column.
|
||||
class RoutingConfig {
|
||||
RoutingConfig({
|
||||
required this.nodeClearance,
|
||||
required this.laneSpacing,
|
||||
required this.corridorSpacing,
|
||||
required this.portSpacing,
|
||||
required this.labelGap,
|
||||
this.boundsPadding = 0,
|
||||
}) {
|
||||
_requireFiniteNonNegative('nodeClearance', nodeClearance);
|
||||
_requireFinitePositive('laneSpacing', laneSpacing);
|
||||
_requireFinitePositive('corridorSpacing', corridorSpacing);
|
||||
_requireFinitePositive('portSpacing', portSpacing);
|
||||
_requireFiniteNonNegative('labelGap', labelGap);
|
||||
_requireFiniteNonNegative('boundsPadding', boundsPadding);
|
||||
}
|
||||
|
||||
final double nodeClearance;
|
||||
final double laneSpacing;
|
||||
final double corridorSpacing;
|
||||
final double portSpacing;
|
||||
final double labelGap;
|
||||
final double boundsPadding;
|
||||
}
|
||||
@@ -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<bool?>? 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.';
|
||||
@@ -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<ActionRefusal?> 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<void> 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<void>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (_) => prompt,
|
||||
);
|
||||
}
|
||||
return showDialog<void>(
|
||||
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<void> _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),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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<JsonMap> onRunChanged;
|
||||
|
||||
@override
|
||||
State<CancelRunAction> createState() => _CancelRunActionState();
|
||||
}
|
||||
|
||||
class _CancelRunActionState extends State<CancelRunAction> {
|
||||
bool _dialogOpen = false;
|
||||
Future<bool?>? _resync;
|
||||
|
||||
bool _usesCupertino(BuildContext context) {
|
||||
final material = Localizations.of<MaterialLocalizations>(
|
||||
context,
|
||||
MaterialLocalizations,
|
||||
);
|
||||
return material == null;
|
||||
}
|
||||
|
||||
Future<void> _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<ActionRefusal?> _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<bool?> _resyncRun(num id) {
|
||||
return _resync ??= _readRun(id);
|
||||
}
|
||||
|
||||
Future<bool?> _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),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<String>('cancel-run-action');
|
||||
const cancelKeepKey = ValueKey<String>('cancel-run-keep');
|
||||
const cancelConfirmKey = ValueKey<String>('cancel-run-confirm');
|
||||
const cancelErrorKey = ValueKey<String>('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;
|
||||
}
|
||||
@@ -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<JsonMap> onRunChanged;
|
||||
|
||||
/// Overrides the platform style; by default it follows the enclosing app.
|
||||
final bool? cupertino;
|
||||
|
||||
@override
|
||||
State<HumanDecisionAction> createState() => _HumanDecisionActionState();
|
||||
}
|
||||
|
||||
class _HumanDecisionActionState extends State<HumanDecisionAction> {
|
||||
PendingDecision? _pending;
|
||||
bool _dialogOpen = false;
|
||||
bool _sending = false;
|
||||
Future<bool?>? _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<MaterialLocalizations>(
|
||||
context,
|
||||
MaterialLocalizations,
|
||||
);
|
||||
return material == null;
|
||||
}
|
||||
|
||||
Future<void> _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<ActionRefusal?> _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<bool?> _resyncRun(PendingDecision decision) {
|
||||
return _resync ??= _readRun(decision);
|
||||
}
|
||||
|
||||
Future<bool?> _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;
|
||||
}
|
||||
@@ -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<ActionRefusal?> Function(DecisionDraft draft);
|
||||
|
||||
/// Opens the native decision prompt for [decision].
|
||||
Future<void> 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<void>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (_) => prompt,
|
||||
);
|
||||
}
|
||||
return showDialog<void>(
|
||||
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<void> _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<String>(
|
||||
groupValue: _draft.selected,
|
||||
onChanged: (value) {
|
||||
if (value != null) _select(value);
|
||||
},
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
for (final option in widget.decision.options)
|
||||
RadioListTile<String>(
|
||||
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<String>(
|
||||
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<String>(
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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<String>('human-decision-action');
|
||||
const decisionFeedbackKey = ValueKey<String>('human-decision-feedback');
|
||||
const decisionErrorKey = ValueKey<String>('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';
|
||||
@@ -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<JsonMap> onRunChanged;
|
||||
|
||||
@override
|
||||
State<RetryRunAction> createState() => _RetryRunActionState();
|
||||
}
|
||||
|
||||
class _RetryRunActionState extends State<RetryRunAction> {
|
||||
bool _dialogOpen = false;
|
||||
Future<bool?>? _resync;
|
||||
|
||||
bool _usesCupertino(BuildContext context) {
|
||||
final material = Localizations.of<MaterialLocalizations>(
|
||||
context,
|
||||
MaterialLocalizations,
|
||||
);
|
||||
return material == null;
|
||||
}
|
||||
|
||||
Future<void> _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<ActionRefusal?> _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<bool?> _resyncRun(num id) {
|
||||
return _resync ??= _readRun(id);
|
||||
}
|
||||
|
||||
Future<bool?> _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),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<ActionRefusal?> 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<void> 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<void>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (_) => prompt,
|
||||
);
|
||||
}
|
||||
return showDialog<void>(
|
||||
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<void> _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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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)}';
|
||||
}
|
||||
@@ -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<String>('retry-run-action');
|
||||
const retryKeepKey = ValueKey<String>('retry-run-keep');
|
||||
const retryConfirmKey = ValueKey<String>('retry-run-confirm');
|
||||
const retryRestartKey = ValueKey<String>('retry-run-restart');
|
||||
const retryErrorKey = ValueKey<String>('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;
|
||||
}
|
||||
@@ -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<JsonMap> onRunChanged;
|
||||
|
||||
@override
|
||||
State<RunTitleAction> createState() => _RunTitleActionState();
|
||||
}
|
||||
|
||||
class _RunTitleActionState extends State<RunTitleAction> {
|
||||
bool _dialogOpen = false;
|
||||
bool _saving = false;
|
||||
|
||||
bool _usesCupertino(BuildContext context) {
|
||||
final material = Localizations.of<MaterialLocalizations>(
|
||||
context,
|
||||
MaterialLocalizations,
|
||||
);
|
||||
return material == null;
|
||||
}
|
||||
|
||||
Future<void> _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<ActionRefusal?> _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';
|
||||
}
|
||||
@@ -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<ActionRefusal?> 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<void> 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<void>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (_) => prompt,
|
||||
);
|
||||
}
|
||||
return showDialog<void>(
|
||||
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<void> _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),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<String>('rename-run-action');
|
||||
const runTitleFieldKey = ValueKey<String>('rename-run-field');
|
||||
const runTitleSaveKey = ValueKey<String>('rename-run-save');
|
||||
const runTitleCancelKey = ValueKey<String>('rename-run-cancel');
|
||||
const runTitleErrorKey = ValueKey<String>('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;
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/run_models.dart';
|
||||
|
||||
/// Protocol failure kept separate from transport errors; server error envelopes
|
||||
/// are otherwise propagated unchanged by [ApiGateway].
|
||||
class RunsRepositoryException implements Exception {
|
||||
const RunsRepositoryException(this.message);
|
||||
final String message;
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
/// Run protocol requests over the application's shared gateway.
|
||||
class RunsRepository {
|
||||
RunsRepository(this._gateway);
|
||||
final ApiGateway _gateway;
|
||||
|
||||
Future<RunListResult> listRuns() async {
|
||||
final reply = await _gateway.call('list_runs');
|
||||
final runs = reply['runs'];
|
||||
return RunListResult(
|
||||
runs is List
|
||||
? runs
|
||||
.whereType<Map>()
|
||||
.map((r) => Map<String, dynamic>.from(r))
|
||||
.toList()
|
||||
: const [],
|
||||
reply['usage'] is Map
|
||||
? Map<String, dynamic>.from(reply['usage'] as Map)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
Future<JsonMap> getRun(num id) async =>
|
||||
_required(await _gateway.call('get_run', {'run_id': id}), 'run_detail');
|
||||
Future<JsonMap> cancelRun(num id) async => _required(
|
||||
await _gateway.call('cancel_run', {'run_id': id}),
|
||||
'run_detail',
|
||||
);
|
||||
|
||||
Future<JsonMap> retryRun(
|
||||
num id, {
|
||||
required String requestKey,
|
||||
String? mode,
|
||||
}) async {
|
||||
final fields = <String, dynamic>{'run_id': id, 'request_key': requestKey};
|
||||
if (mode == 'restart') fields['retry_mode'] = mode;
|
||||
return _required(await _gateway.call('retry_run', fields), 'run_detail');
|
||||
}
|
||||
|
||||
Future<JsonMap> decideRun(
|
||||
num id, {
|
||||
String? stage,
|
||||
required String option,
|
||||
String feedback = '',
|
||||
}) async {
|
||||
final selected = option.trim();
|
||||
if (selected.isEmpty) {
|
||||
throw const RunsRepositoryException(
|
||||
'Choose an option before continuing.',
|
||||
);
|
||||
}
|
||||
final fields = <String, dynamic>{'run_id': id, 'option': selected};
|
||||
if (stage != null && stage.trim().isNotEmpty) fields['stage'] = stage;
|
||||
if (feedback.trim().isNotEmpty) fields['feedback'] = feedback.trim();
|
||||
return _required(await _gateway.call('decide_run', fields), 'run_detail');
|
||||
}
|
||||
|
||||
Future<JsonMap> setRunTitle(num id, String title) async => _required(
|
||||
await _gateway.call('set_run_title', {'run_id': id, 'title': title}),
|
||||
'run_detail',
|
||||
);
|
||||
|
||||
Future<JsonMap> startRun({
|
||||
required num pipelineId,
|
||||
required num version,
|
||||
required String prompt,
|
||||
required String workspace,
|
||||
required String requestKey,
|
||||
String title = '',
|
||||
String outputFormat = '',
|
||||
String notifyMode = 'auto',
|
||||
}) async {
|
||||
final fields = <String, dynamic>{
|
||||
'pipeline_id': pipelineId,
|
||||
'version': version,
|
||||
'request_key': requestKey,
|
||||
'workspace': workspace.trim(),
|
||||
'input': {'prompt': prompt},
|
||||
};
|
||||
if (title.trim().isNotEmpty) fields['title'] = title.trim();
|
||||
if (outputFormat.isNotEmpty) fields['output_format'] = outputFormat;
|
||||
final mode = notifyMode.trim().toLowerCase();
|
||||
if (mode == 'on' || mode == 'off') fields['notify_mode'] = mode;
|
||||
return _required(await _gateway.call('run_pipeline', fields), 'run_detail');
|
||||
}
|
||||
|
||||
JsonMap _required(JsonMap reply, String key) {
|
||||
final value = reply[key];
|
||||
if (value is! Map) {
|
||||
throw RunsRepositoryException('The server returned no $key.');
|
||||
}
|
||||
return Map<String, dynamic>.from(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'run_models.dart';
|
||||
|
||||
class PendingDecision {
|
||||
const PendingDecision({
|
||||
required this.runId,
|
||||
required this.runLabel,
|
||||
required this.stageKey,
|
||||
required this.instructions,
|
||||
required this.options,
|
||||
});
|
||||
final num runId;
|
||||
final String runLabel;
|
||||
final String stageKey;
|
||||
final String instructions;
|
||||
final List<DecisionOption> options;
|
||||
}
|
||||
|
||||
JsonMap? lastWaitingStep(List<dynamic> steps) {
|
||||
for (final value in steps.reversed) {
|
||||
if (value is Map && value['status'] == 'waiting') {
|
||||
return Map<String, dynamic>.from(value);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
String waitingPrompt(dynamic output) =>
|
||||
output is Map && output['prompt'] is String
|
||||
? output['prompt'] as String
|
||||
: '';
|
||||
|
||||
List<String> waitingOptions(dynamic output) {
|
||||
final options = output is Map ? output['options'] : null;
|
||||
if (options is! List) return const [];
|
||||
return options
|
||||
.whereType<String>()
|
||||
.where((entry) => entry.trim().isNotEmpty)
|
||||
.toList();
|
||||
}
|
||||
|
||||
List<String> humanOptions(dynamic edges) {
|
||||
if (edges is! Map) return const [];
|
||||
return edges.keys.map((key) => '$key').where((key) => key != 'error').toList()
|
||||
..sort();
|
||||
}
|
||||
|
||||
PendingDecision? pendingDecision(JsonMap? run) {
|
||||
if (run == null ||
|
||||
run['status'] != 'waiting' ||
|
||||
_positive(run['export_pending_sequence'])) {
|
||||
return null;
|
||||
}
|
||||
final steps = run['steps'] is List ? run['steps'] as List : const [];
|
||||
final step = lastWaitingStep(steps);
|
||||
final stage = _string(step?['stage']).trim().isNotEmpty
|
||||
? _string(step?['stage'])
|
||||
: _string(run['current_stage']);
|
||||
if (stage.trim().isEmpty) return null;
|
||||
JsonMap? declaration;
|
||||
final graph = run['graph'];
|
||||
final graphStages = graph is Map ? graph['stages'] : null;
|
||||
if (graphStages is List) {
|
||||
for (final value in graphStages.whereType<Map>()) {
|
||||
if (value['key'] == stage) {
|
||||
declaration = Map<String, dynamic>.from(value);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (declaration?['type'] != null && declaration!['type'] != 'human') {
|
||||
return null;
|
||||
}
|
||||
final edges = declaration?['edges'];
|
||||
final options = waitingOptions(step?['output']);
|
||||
final keys = options.isNotEmpty ? options : humanOptions(edges);
|
||||
if (keys.isEmpty) return null;
|
||||
final instructions = waitingPrompt(step?['output']).trim().isNotEmpty
|
||||
? waitingPrompt(step?['output'])
|
||||
: _string(declaration?['prompt']);
|
||||
return PendingDecision(
|
||||
runId: run['id'] is num ? run['id'] as num : 0,
|
||||
runLabel: runIdentity(run['title'], run['name']).label,
|
||||
stageKey: stage,
|
||||
instructions: instructions,
|
||||
options: keys
|
||||
.map(
|
||||
(key) => DecisionOption(
|
||||
key,
|
||||
target: _targetLabel(key, edges is Map ? edges[key] : null),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
String _targetLabel(String option, dynamic target) {
|
||||
if (target == null || '$target'.trim().isEmpty) return '';
|
||||
final resolved = target == '#'
|
||||
? (option == 'error' ? '#failure' : '#success')
|
||||
: '$target';
|
||||
return switch (resolved) {
|
||||
'#success' => 'SUCCESS',
|
||||
'#failure' => 'FAILURE',
|
||||
_ => resolved,
|
||||
};
|
||||
}
|
||||
|
||||
bool _positive(dynamic value) => value is num && value > 0;
|
||||
String _string(dynamic value) => value == null ? '' : '$value';
|
||||
@@ -0,0 +1,226 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'run_step_evidence.dart';
|
||||
|
||||
const terminalRunStatuses = {'succeeded', 'failed', 'canceled', 'interrupted'};
|
||||
|
||||
bool isTerminalRunStatus(dynamic status) =>
|
||||
terminalRunStatuses.contains(_word(status));
|
||||
bool isWaitingRunStatus(dynamic status) => _word(status) == 'waiting';
|
||||
|
||||
int runLifecycleRank(dynamic status) => switch (_word(status)) {
|
||||
'queued' => 0,
|
||||
'running' || 'waiting' => 1,
|
||||
'succeeded' || 'failed' || 'canceled' || 'interrupted' => 2,
|
||||
_ => -1,
|
||||
};
|
||||
|
||||
int stepLifecycleRank(dynamic status) => switch (_word(status)) {
|
||||
'running' || 'waiting' => 1,
|
||||
'completed' || 'failed' || 'canceled' || 'interrupted' => 2,
|
||||
_ => -1,
|
||||
};
|
||||
|
||||
bool _stale(dynamic current, dynamic incoming, int Function(dynamic) rank) {
|
||||
if (_word(incoming).isEmpty) return false;
|
||||
final oldRank = rank(current);
|
||||
final newRank = rank(incoming);
|
||||
return oldRank >= 0 &&
|
||||
newRank >= 0 &&
|
||||
(newRank < oldRank ||
|
||||
(oldRank == 2 && newRank == 2 && incoming != current));
|
||||
}
|
||||
|
||||
String _advance(dynamic current, dynamic incoming, int Function(dynamic) rank) {
|
||||
if (_word(incoming).isEmpty || incoming == current) return '${current ?? ''}';
|
||||
final oldRank = rank(current);
|
||||
final newRank = rank(incoming);
|
||||
if (oldRank < 0) return '$incoming';
|
||||
if (newRank < 0 || (oldRank == 2 && newRank == 2) || newRank < oldRank) {
|
||||
return '${current ?? ''}';
|
||||
}
|
||||
return '$incoming';
|
||||
}
|
||||
|
||||
bool executingFor(dynamic status, bool current) => switch (_word(status)) {
|
||||
'queued' || 'running' => true,
|
||||
'waiting' || 'succeeded' || 'failed' || 'canceled' || 'interrupted' => false,
|
||||
_ => current,
|
||||
};
|
||||
|
||||
bool _blank(dynamic value) => '${value ?? ''}'.trim().isEmpty;
|
||||
|
||||
JsonMap _scheduleOrigin(JsonMap current, JsonMap frame) {
|
||||
final oldId = _positiveInt(current['schedule_id']);
|
||||
final newId = _positiveInt(frame['schedule_id']);
|
||||
final known =
|
||||
current.containsKey('scheduled') ||
|
||||
frame.containsKey('scheduled') ||
|
||||
oldId > 0 ||
|
||||
newId > 0;
|
||||
if (!known) return {};
|
||||
final id = oldId > 0 ? oldId : newId;
|
||||
final nameConflict = oldId > 0 && newId > 0 && oldId != newId;
|
||||
final name =
|
||||
'${current['schedule_name'] ?? (nameConflict ? '' : frame['schedule_name'] ?? '')}';
|
||||
return {
|
||||
'scheduled':
|
||||
current['scheduled'] == true || frame['scheduled'] == true || id > 0,
|
||||
if (id > 0) 'schedule_id': id,
|
||||
if (name.isNotEmpty) 'schedule_name': name,
|
||||
};
|
||||
}
|
||||
|
||||
int _positiveInt(dynamic value) =>
|
||||
value is num && value > 0 ? value.toInt() : 0;
|
||||
|
||||
JsonMap _mergeRunFields(JsonMap current, JsonMap frame) {
|
||||
if (_stale(current['status'], frame['status'], runLifecycleRank) &&
|
||||
frame['resource_wait_set'] != true) {
|
||||
return current;
|
||||
}
|
||||
final beforeStatus = '${current['status'] ?? ''}';
|
||||
final status =
|
||||
frame['resource_wait_set'] == true &&
|
||||
frame['status'] == 'queued' &&
|
||||
!isTerminalRunStatus(beforeStatus)
|
||||
? 'queued'
|
||||
: _advance(beforeStatus, frame['status'], runLifecycleRank);
|
||||
final merged = <String, dynamic>{
|
||||
...current,
|
||||
..._scheduleOrigin(current, frame),
|
||||
'status': status,
|
||||
'executing': executingFor(status, current['executing'] == true),
|
||||
'completed_steps': _maxInt(
|
||||
current['completed_steps'],
|
||||
frame['completed_steps'],
|
||||
),
|
||||
'resource_wait': isTerminalRunStatus(status)
|
||||
? null
|
||||
: frame['resource_wait_set'] == true
|
||||
? frame['resource_wait']
|
||||
: current['resource_wait'],
|
||||
'notify_mode': _blank(frame['notify_mode'])
|
||||
? current['notify_mode'] ?? 'auto'
|
||||
: frame['notify_mode'],
|
||||
'cancel_requested':
|
||||
current['cancel_requested'] == true ||
|
||||
frame['cancel_requested'] == true,
|
||||
'cleanup_unconfirmed':
|
||||
current['cleanup_unconfirmed'] == true ||
|
||||
frame['cleanup_unconfirmed'] == true,
|
||||
};
|
||||
for (final key in ['outcome', 'current_stage', 'created_at', 'finished_at']) {
|
||||
if (!_blank(frame[key])) merged[key] = frame[key];
|
||||
}
|
||||
final oldExport = _positiveInt(current['export_pending_sequence']);
|
||||
if (oldExport > 0 || frame.containsKey('export_pending_sequence')) {
|
||||
merged['export_pending_sequence'] = _blank(frame['status'])
|
||||
? oldExport
|
||||
: status == 'waiting'
|
||||
? _positiveInt(frame['export_pending_sequence'])
|
||||
: 0;
|
||||
}
|
||||
if (current['steps'] is! List) {
|
||||
final evidence = mergeGraphEvidence(
|
||||
current['graph_evidence'] as JsonMap?,
|
||||
frame,
|
||||
);
|
||||
if (evidence != null) merged['graph_evidence'] = evidence;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
int _maxInt(dynamic a, dynamic b) =>
|
||||
(a is num ? a.toInt() : 0).clamp(b is num ? b.toInt() : 0, 0x7fffffff);
|
||||
|
||||
/// A summary row can be built from a sufficiently identified push; otherwise
|
||||
/// the caller must resync from the server's authoritative list.
|
||||
JsonMap? newRunSummaryFromFrame(JsonMap frame) {
|
||||
final id = frame['run_id'];
|
||||
final pipelineId = frame['pipeline_id'];
|
||||
if (id is! num ||
|
||||
id <= 0 ||
|
||||
pipelineId is! num ||
|
||||
pipelineId <= 0 ||
|
||||
_blank(frame['name'])) {
|
||||
return null;
|
||||
}
|
||||
final row = <String, dynamic>{
|
||||
'id': id,
|
||||
'pipeline_id': pipelineId,
|
||||
'name': frame['name'],
|
||||
'title': _blank(frame['title']) ? null : frame['title'],
|
||||
'version': frame['version'] ?? 0,
|
||||
'notify_mode': frame['notify_mode'] ?? 'auto',
|
||||
'status': frame['status'] ?? '',
|
||||
'executing': executingFor(frame['status'], true),
|
||||
'completed_steps': _maxInt(0, frame['completed_steps']),
|
||||
'created_at': frame['created_at'] ?? '',
|
||||
'finished_at': frame['finished_at'] ?? '',
|
||||
'outcome': frame['outcome'] ?? '',
|
||||
'current_stage': frame['current_stage'] ?? '',
|
||||
'resource_wait': frame['resource_wait'],
|
||||
'cancel_requested': frame['cancel_requested'] == true,
|
||||
'cleanup_unconfirmed': frame['cleanup_unconfirmed'] == true,
|
||||
};
|
||||
row.addAll(_scheduleOrigin({}, frame));
|
||||
final sequence = _positiveInt(frame['export_pending_sequence']);
|
||||
if (sequence > 0) row['export_pending_sequence'] = sequence;
|
||||
final evidence = mergeGraphEvidence(null, frame);
|
||||
if (evidence != null) row['graph_evidence'] = evidence;
|
||||
return row;
|
||||
}
|
||||
|
||||
({List<JsonMap> runs, bool needsResync}) foldRunEvent(
|
||||
List<JsonMap> runs,
|
||||
JsonMap frame,
|
||||
) {
|
||||
final id = frame['run_id'];
|
||||
if (id is! num || id <= 0) return (runs: runs, needsResync: false);
|
||||
final index = runs.indexWhere((run) => run['id'] == id);
|
||||
if (index < 0) {
|
||||
final row = newRunSummaryFromFrame(frame);
|
||||
return row == null
|
||||
? (runs: runs, needsResync: true)
|
||||
: (runs: [row, ...runs], needsResync: false);
|
||||
}
|
||||
final updated = _mergeRunFields(runs[index], frame);
|
||||
if (identical(updated, runs[index])) return (runs: runs, needsResync: false);
|
||||
final next = [...runs];
|
||||
next[index] = updated;
|
||||
return (runs: next, needsResync: false);
|
||||
}
|
||||
|
||||
JsonMap? foldRunEventDetail(JsonMap? detail, JsonMap frame) {
|
||||
if (detail == null || detail['id'] != frame['run_id']) return detail;
|
||||
if (_stale(detail['status'], frame['status'], runLifecycleRank) &&
|
||||
frame['resource_wait_set'] != true) {
|
||||
return detail;
|
||||
}
|
||||
final merged = _mergeRunFields(detail, frame);
|
||||
final steps = frame['step'] is Map
|
||||
? upsertRunStep(
|
||||
detail['steps'] is List
|
||||
? (detail['steps'] as List)
|
||||
.whereType<Map>()
|
||||
.map((s) => Map<String, dynamic>.from(s))
|
||||
.toList()
|
||||
: [],
|
||||
Map<String, dynamic>.from(frame['step'] as Map),
|
||||
)
|
||||
: detail['steps'] ?? [];
|
||||
return {...merged, 'steps': steps};
|
||||
}
|
||||
|
||||
bool runDetailNeedsFullSync(JsonMap frame) {
|
||||
final step = frame['step'];
|
||||
final stepStatus = step is Map ? step['status'] : null;
|
||||
return isTerminalRunStatus(frame['status']) ||
|
||||
isWaitingRunStatus(frame['status']) ||
|
||||
frame['cancel_requested'] == true ||
|
||||
frame['cleanup_unconfirmed'] == true ||
|
||||
isWaitingRunStatus(stepStatus) ||
|
||||
stepLifecycleRank(stepStatus) == 2;
|
||||
}
|
||||
|
||||
String _word(dynamic value) => '${value ?? ''}'.trim().toLowerCase();
|
||||
@@ -0,0 +1,219 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
const runStates = [
|
||||
'queued',
|
||||
'running',
|
||||
'waiting',
|
||||
'succeeded',
|
||||
'failed',
|
||||
'canceled',
|
||||
'interrupted',
|
||||
];
|
||||
|
||||
/// The largest millisecond value [DateTime] supports, and also exactly
|
||||
/// representable by the web's JavaScript numbers. The previous
|
||||
/// `0x7fffffffffffffff` literals failed dart2js compilation.
|
||||
const int _maxMillis = 8640000000000000;
|
||||
|
||||
({String label, String? pipeline}) runIdentity(dynamic title, dynamic name) {
|
||||
final stored = '${title ?? ''}'.trim();
|
||||
return (
|
||||
label: stored.isNotEmpty ? stored : '${name ?? ''}',
|
||||
pipeline: stored.isNotEmpty ? '${name ?? ''}' : null,
|
||||
);
|
||||
}
|
||||
|
||||
String runStateOf(dynamic status) =>
|
||||
switch ('${status ?? ''}'.trim().toLowerCase()) {
|
||||
'queued' ||
|
||||
'running' ||
|
||||
'waiting' ||
|
||||
'active' ||
|
||||
'blocked' ||
|
||||
'skipped' => '${status ?? ''}'.trim().toLowerCase(),
|
||||
'succeeded' || 'success' || 'completed' || 'done' => 'succeeded',
|
||||
'failed' || 'error' => 'failed',
|
||||
'canceled' || 'cancelled' => 'canceled',
|
||||
'interrupted' => 'interrupted',
|
||||
_ => 'unknown',
|
||||
};
|
||||
|
||||
List<JsonMap> filterRuns(
|
||||
List<JsonMap> runs, {
|
||||
Set<String> statuses = const {},
|
||||
int? pipelineId,
|
||||
String timeRange = 'any_time',
|
||||
String scheduled = 'any',
|
||||
DateTime? today,
|
||||
}) => runs.where((run) {
|
||||
if (statuses.isNotEmpty && !statuses.contains(runStateOf(run['status']))) {
|
||||
return false;
|
||||
}
|
||||
if (pipelineId != null && run['pipeline_id'] != pipelineId) {
|
||||
return false;
|
||||
}
|
||||
if (scheduled == 'scheduled' && !_isScheduled(run)) {
|
||||
return false;
|
||||
}
|
||||
if (scheduled == 'unscheduled' &&
|
||||
(run['scheduled'] != false || _isScheduled(run))) {
|
||||
return false;
|
||||
}
|
||||
if (timeRange == 'any_time' || timeRange.isEmpty) {
|
||||
return true;
|
||||
}
|
||||
final created = DateTime.tryParse('${run['created_at'] ?? ''}')?.toLocal();
|
||||
if (created == null) {
|
||||
return false;
|
||||
}
|
||||
final now = today ?? DateTime.now();
|
||||
final start = DateTime(now.year, now.month, now.day);
|
||||
final date = DateTime(created.year, created.month, created.day);
|
||||
if (date.isAfter(start)) {
|
||||
return false;
|
||||
}
|
||||
final days = switch (timeRange) {
|
||||
'today' => 0,
|
||||
'last_7_days' => 6,
|
||||
'last_30_days' => 29,
|
||||
_ => null,
|
||||
};
|
||||
return days == null || !date.isBefore(start.subtract(Duration(days: days)));
|
||||
}).toList();
|
||||
|
||||
bool _isScheduled(JsonMap run) =>
|
||||
run['scheduled'] == true ||
|
||||
(run['schedule_id'] is num && (run['schedule_id'] as num) > 0);
|
||||
|
||||
String runStatusLabel(JsonMap run) {
|
||||
final status = '${run['status'] ?? ''}';
|
||||
if (!{'queued', 'running', 'waiting'}.contains(status)) {
|
||||
return status.isEmpty ? 'unknown' : status;
|
||||
}
|
||||
if (run['cleanup_unconfirmed'] == true) {
|
||||
return 'Cleanup unconfirmed — workspace reserved';
|
||||
}
|
||||
if (run['cancel_requested'] == true) {
|
||||
return 'Stopping — waiting for execution to stop';
|
||||
}
|
||||
if (status == 'waiting' &&
|
||||
(run['export_pending_sequence'] as num? ?? 0) > 0) {
|
||||
return 'Waiting for session export';
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
List<JsonMap> sortRuns(List<JsonMap> runs, {String sort = 'newest_first'}) {
|
||||
final result = [...runs];
|
||||
int? instant(dynamic value) =>
|
||||
DateTime.tryParse('${value ?? ''}')?.millisecondsSinceEpoch;
|
||||
int? duration(JsonMap run) {
|
||||
final from = instant(run['created_at']);
|
||||
final to = instant(run['finished_at']);
|
||||
if (from == null || to == null || to < from) return null;
|
||||
return (to - from) ~/ 1000;
|
||||
}
|
||||
|
||||
int cmp<T extends Comparable<Object>>(T a, T b) => a.compareTo(b);
|
||||
result.sort((a, b) {
|
||||
final at = instant(a['created_at']);
|
||||
final bt = instant(b['created_at']);
|
||||
int primary;
|
||||
switch (sort) {
|
||||
case 'oldest_first':
|
||||
primary = cmp(at ?? _maxMillis, bt ?? _maxMillis);
|
||||
break;
|
||||
case 'longest_duration':
|
||||
primary = cmp(duration(a) == null ? 1 : 0, duration(b) == null ? 1 : 0);
|
||||
if (primary == 0) primary = cmp(duration(b) ?? -1, duration(a) ?? -1);
|
||||
if (primary == 0) {
|
||||
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
|
||||
}
|
||||
break;
|
||||
case 'shortest_duration':
|
||||
primary = cmp(duration(a) == null ? 1 : 0, duration(b) == null ? 1 : 0);
|
||||
if (primary == 0) {
|
||||
primary = cmp(duration(a) ?? _maxMillis, duration(b) ?? _maxMillis);
|
||||
}
|
||||
if (primary == 0) {
|
||||
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
|
||||
}
|
||||
break;
|
||||
case 'pipeline_name':
|
||||
primary = '${a['name'] ?? ''}'.toLowerCase().compareTo(
|
||||
'${b['name'] ?? ''}'.toLowerCase(),
|
||||
);
|
||||
if (primary == 0) {
|
||||
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
|
||||
}
|
||||
break;
|
||||
case 'status':
|
||||
primary = '${a['status'] ?? ''}'.toLowerCase().compareTo(
|
||||
'${b['status'] ?? ''}'.toLowerCase(),
|
||||
);
|
||||
if (primary == 0) {
|
||||
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
|
||||
}
|
||||
return primary == 0
|
||||
? ((b['id'] as num?) ?? 0).compareTo((a['id'] as num?) ?? 0)
|
||||
: primary;
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Null usage means unsupported/unavailable, not zero.
|
||||
class RunListResult {
|
||||
const RunListResult(this.runs, this.usage);
|
||||
final List<JsonMap> runs;
|
||||
final JsonMap? usage;
|
||||
}
|
||||
|
||||
class DecisionOption {
|
||||
const DecisionOption(this.key, {this.target = ''});
|
||||
final String key;
|
||||
final String target;
|
||||
}
|
||||
|
||||
class DecisionDraft {
|
||||
const DecisionDraft({this.selected, this.feedback = ''});
|
||||
final String? selected;
|
||||
final String feedback;
|
||||
bool get canSubmit => selected != null && selected!.trim().isNotEmpty;
|
||||
DecisionDraft select(String option) =>
|
||||
DecisionDraft(selected: option, feedback: feedback);
|
||||
DecisionDraft withFeedback(String value) =>
|
||||
DecisionDraft(selected: selected, feedback: value);
|
||||
}
|
||||
|
||||
String attentionKey(num runId, String kind) => '$runId:$kind';
|
||||
|
||||
List<JsonMap> orderAttention(
|
||||
List<JsonMap> runs, {
|
||||
Set<String> dismissed = const {},
|
||||
}) {
|
||||
final result = runs.where((run) {
|
||||
final waiting = run['status'] == 'waiting';
|
||||
if (waiting && (run['export_pending_sequence'] as num? ?? 0) > 0) {
|
||||
return false;
|
||||
}
|
||||
final kind = waiting ? 'Decision' : 'Failed';
|
||||
return (waiting || run['status'] == 'failed') &&
|
||||
!dismissed.contains(attentionKey(run['id'] as num, kind));
|
||||
}).toList();
|
||||
String recency(JsonMap run) => '${run['finished_at'] ?? ''}'.trim().isNotEmpty
|
||||
? '${run['finished_at']}'
|
||||
: '${run['created_at'] ?? ''}';
|
||||
result.sort((a, b) {
|
||||
final rank = (a['status'] == 'waiting' ? 0 : 1).compareTo(
|
||||
b['status'] == 'waiting' ? 0 : 1,
|
||||
);
|
||||
if (rank != 0) return rank;
|
||||
final date = recency(b).compareTo(recency(a));
|
||||
return date != 0 ? date : (b['id'] as num).compareTo(a['id'] as num);
|
||||
});
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
/// Merge a visit by sequence without allowing stale status or blank sparse
|
||||
/// deltas to erase evidence already held by the detail cache.
|
||||
List<JsonMap> upsertRunStep(List<JsonMap> steps, JsonMap delta) {
|
||||
final sequence = delta['sequence'] is num
|
||||
? (delta['sequence'] as num).toInt()
|
||||
: 0;
|
||||
final index = steps.indexWhere((step) => step['sequence'] == sequence);
|
||||
if (index < 0) {
|
||||
final result = [...steps, _stepFields({}, delta, sequence)];
|
||||
result.sort(
|
||||
(a, b) => ((a['sequence'] as num?) ?? 0).compareTo(
|
||||
(b['sequence'] as num?) ?? 0,
|
||||
),
|
||||
);
|
||||
return result;
|
||||
}
|
||||
final old = steps[index];
|
||||
final incomingStatus = '${delta['status'] ?? ''}';
|
||||
final oldStatus = '${old['status'] ?? ''}';
|
||||
if (_stale(oldStatus, incomingStatus)) return steps;
|
||||
final merged = _stepFields(old, delta, sequence);
|
||||
if (_same(old, merged)) return steps;
|
||||
final result = [...steps];
|
||||
result[index] = merged;
|
||||
return result;
|
||||
}
|
||||
|
||||
JsonMap _stepFields(JsonMap old, JsonMap delta, int sequence) {
|
||||
final oldStatus = '${old['status'] ?? ''}';
|
||||
final incoming = '${delta['status'] ?? ''}';
|
||||
return {
|
||||
...old,
|
||||
'sequence': sequence,
|
||||
for (final key in ['stage', 'outcome', 'target', 'diagnostic'])
|
||||
key: _blank(delta[key]) ? old[key] ?? '' : delta[key],
|
||||
'status': _advance(oldStatus, incoming),
|
||||
};
|
||||
}
|
||||
|
||||
bool _stale(String old, String incoming) {
|
||||
if (_blank(incoming)) return false;
|
||||
final before = _rank(old);
|
||||
final after = _rank(incoming);
|
||||
return before >= 0 &&
|
||||
after >= 0 &&
|
||||
(after < before || (before == 2 && after == 2 && old != incoming));
|
||||
}
|
||||
|
||||
String _advance(String old, String incoming) {
|
||||
if (_blank(incoming)) return old;
|
||||
final before = _rank(old);
|
||||
final after = _rank(incoming);
|
||||
if (before < 0 || (after >= 0 && after > before && before < 2)) {
|
||||
return incoming;
|
||||
}
|
||||
if (before < 2 && after == before) return incoming;
|
||||
return old;
|
||||
}
|
||||
|
||||
int _rank(String status) => switch (status.trim().toLowerCase()) {
|
||||
'running' || 'waiting' => 1,
|
||||
'completed' || 'failed' || 'canceled' || 'interrupted' => 2,
|
||||
_ => -1,
|
||||
};
|
||||
|
||||
bool _same(JsonMap a, JsonMap b) =>
|
||||
a.length == b.length && a.entries.every((e) => b[e.key] == e.value);
|
||||
|
||||
/// Compact graph evidence is intentionally allowlisted. It retains latest
|
||||
/// visit-by-stage and distinct outcome routes, not arbitrary frame diagnostics.
|
||||
JsonMap? mergeGraphEvidence(JsonMap? current, JsonMap frame) {
|
||||
final incomingEvidence = frame['graph_evidence'];
|
||||
final graphVisits = frame['graph_visits'];
|
||||
final step = frame['step'];
|
||||
if (incomingEvidence is! Map && graphVisits is! List && step is! Map) {
|
||||
return current;
|
||||
}
|
||||
var visits = <JsonMap>[];
|
||||
final oldVisits = current?['visits'];
|
||||
if (oldVisits is List) {
|
||||
visits = oldVisits
|
||||
.whereType<Map>()
|
||||
.map((v) => Map<String, dynamic>.from(v))
|
||||
.toList();
|
||||
}
|
||||
final additions = <dynamic>[];
|
||||
if (incomingEvidence is Map && incomingEvidence['visits'] is List) {
|
||||
additions.addAll(incomingEvidence['visits'] as List);
|
||||
}
|
||||
if (graphVisits is List) additions.addAll(graphVisits);
|
||||
if (step is Map) additions.add(step);
|
||||
for (final item in additions.whereType<Map>()) {
|
||||
final delta = Map<String, dynamic>.from(item);
|
||||
visits = upsertRunStep(visits, {
|
||||
'sequence': delta['sequence'],
|
||||
'stage': delta['stage'],
|
||||
'status': delta['status'],
|
||||
'outcome': delta['outcome'],
|
||||
'target': delta['target'],
|
||||
});
|
||||
}
|
||||
final latestByStage = <String, int>{};
|
||||
final routeSequence = <String, int>{};
|
||||
for (final visit in visits) {
|
||||
final sequence = (visit['sequence'] as num?)?.toInt() ?? 0;
|
||||
final stage = '${visit['stage'] ?? ''}';
|
||||
latestByStage[stage] = sequence;
|
||||
if (!_blank(visit['outcome']) && !_blank(visit['target'])) {
|
||||
routeSequence['$stage\u0000${visit['outcome']}\u0000${visit['target']}'] =
|
||||
sequence;
|
||||
}
|
||||
}
|
||||
visits = visits
|
||||
.where((visit) {
|
||||
final sequence = (visit['sequence'] as num?)?.toInt() ?? 0;
|
||||
final stage = '${visit['stage'] ?? ''}';
|
||||
final route = '$stage\u0000${visit['outcome']}\u0000${visit['target']}';
|
||||
return latestByStage[stage] == sequence ||
|
||||
routeSequence[route] == sequence;
|
||||
})
|
||||
.map(
|
||||
(visit) => <String, dynamic>{
|
||||
for (final key in [
|
||||
'sequence',
|
||||
'stage',
|
||||
'status',
|
||||
'outcome',
|
||||
'target',
|
||||
])
|
||||
key: visit[key],
|
||||
},
|
||||
)
|
||||
.toList();
|
||||
final complete =
|
||||
current?['complete'] == true ||
|
||||
(incomingEvidence is Map && incomingEvidence['complete'] == true);
|
||||
return {'complete': complete, 'visits': visits};
|
||||
}
|
||||
|
||||
bool _blank(dynamic value) => '${value ?? ''}'.trim().isEmpty;
|
||||
@@ -0,0 +1,113 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../../core/api_gateway.dart';
|
||||
import 'data/runs_repository.dart';
|
||||
import 'ui/run_detail_view.dart';
|
||||
import 'ui/runs_controller.dart';
|
||||
import 'ui/runs_list.dart';
|
||||
|
||||
/// The runs destination's list/detail switch.
|
||||
///
|
||||
/// The controller's `selectedRunId` is the only selection source, so an
|
||||
/// initial run, a pending detail, a failed detail, Back and a route change all
|
||||
/// navigate the same way. The shell owns the app bar; this screen adds no
|
||||
/// second one.
|
||||
class RunsScreen extends StatefulWidget {
|
||||
const RunsScreen({
|
||||
super.key,
|
||||
required this.gateway,
|
||||
this.initialRunId,
|
||||
this.syncToken = 0,
|
||||
this.onRunSelected,
|
||||
this.onBack,
|
||||
});
|
||||
|
||||
final ApiGateway gateway;
|
||||
|
||||
/// The run the current route names, or null for the list.
|
||||
final int? initialRunId;
|
||||
|
||||
/// Advances when the shared socket is replaced. The loaded screen refreshes
|
||||
/// in place instead of being remounted, so its selection survives.
|
||||
final int syncToken;
|
||||
|
||||
final ValueChanged<int>? onRunSelected;
|
||||
final VoidCallback? onBack;
|
||||
|
||||
@override
|
||||
State<RunsScreen> createState() => _RunsScreenState();
|
||||
}
|
||||
|
||||
class _RunsScreenState extends State<RunsScreen> {
|
||||
late final RunsController controller;
|
||||
num? _shownRunId;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
controller = RunsController(RunsRepository(widget.gateway));
|
||||
controller.listen(widget.gateway.frames);
|
||||
controller.addListener(_selectionChanged);
|
||||
controller.load(widget.initialRunId);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant RunsScreen oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (widget.syncToken != oldWidget.syncToken) {
|
||||
controller.resync();
|
||||
}
|
||||
if (widget.initialRunId != oldWidget.initialRunId) {
|
||||
final id = widget.initialRunId;
|
||||
if (id == null) {
|
||||
if (controller.selectedRunId != null) controller.back();
|
||||
} else if (controller.selectedRunId != id) {
|
||||
controller.select(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuild the switch only when the selection changes. Detail progress and
|
||||
/// live updates are already watched by [RunDetailView] and [RunsList], so
|
||||
/// this avoids a second whole-detail rebuild per notification.
|
||||
void _selectionChanged() {
|
||||
final selected = controller.selectedRunId;
|
||||
if (selected == _shownRunId) return;
|
||||
_shownRunId = selected;
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
|
||||
void _select(num id) {
|
||||
controller.select(id);
|
||||
widget.onRunSelected?.call(id.toInt());
|
||||
}
|
||||
|
||||
void _back() {
|
||||
controller.back();
|
||||
widget.onBack?.call();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
controller.removeListener(_selectionChanged);
|
||||
controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final selected = controller.selectedRunId != null;
|
||||
return Stack(
|
||||
children: [
|
||||
AnimatedBuilder(
|
||||
animation: controller,
|
||||
builder: (context, _) => Offstage(
|
||||
offstage: selected,
|
||||
child: RunsList(controller: controller, onSelected: _select),
|
||||
),
|
||||
),
|
||||
if (selected) RunDetailView(controller: controller, onBack: _back),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/run_models.dart';
|
||||
|
||||
/// One labelled value in the run detail's metrics block.
|
||||
typedef DetailMetric = ({String label, String value});
|
||||
|
||||
/// One recorded visit in the run detail's timeline.
|
||||
typedef DetailVisit = ({String title, String subtitle});
|
||||
|
||||
/// The run's primary label: the stored title, else the pipeline name, and only
|
||||
/// then the numeric identity.
|
||||
String detailTitle(JsonMap run) {
|
||||
final identity = runIdentity(run['title'], run['name']);
|
||||
return identity.label.trim().isEmpty ? 'Run ${run['id']}' : identity.label;
|
||||
}
|
||||
|
||||
String detailPipeline(JsonMap run) {
|
||||
final name = '${run['name'] ?? ''}'.trim();
|
||||
return name.isEmpty ? 'unavailable' : name;
|
||||
}
|
||||
|
||||
/// The original prompt exactly as the server stored it; never trimmed or
|
||||
/// replaced by another field.
|
||||
String? detailPrompt(JsonMap run) {
|
||||
final input = run['input'];
|
||||
return input is Map && input['prompt'] is String
|
||||
? input['prompt'] as String
|
||||
: null;
|
||||
}
|
||||
|
||||
/// Nested input/output shown as formatted, selectable JSON.
|
||||
String detailJson(dynamic value) =>
|
||||
const JsonEncoder.withIndent(' ').convert(value);
|
||||
|
||||
bool detailEmpty(dynamic value) => value is! Map || value.isEmpty;
|
||||
|
||||
/// Reported run metrics. A present zero with a reporting stage count is a real
|
||||
/// zero; a zero without that evidence is unavailable, never a measured zero.
|
||||
List<DetailMetric> detailUsageMetrics(dynamic raw) {
|
||||
if (raw is! Map || raw.isEmpty) return const [];
|
||||
final usage = Map<String, dynamic>.from(raw);
|
||||
final stages = _int(usage['stages']);
|
||||
final tokenStages = _int(usage['tokens_known_stages']) ?? 0;
|
||||
final costStages = _int(usage['cost_known_stages']) ?? 0;
|
||||
final totalTokens = _int(usage['tokens_total']);
|
||||
final splitKnown = usage['split_known'] == true && tokenStages > 0;
|
||||
final rows = <DetailMetric>[
|
||||
if (stages != null) (label: 'Stages', value: '$stages'),
|
||||
(
|
||||
label: 'Total tokens',
|
||||
value: tokenStages == 0 || totalTokens == null
|
||||
? 'Unavailable'
|
||||
: '$totalTokens',
|
||||
),
|
||||
(
|
||||
label: 'Input tokens',
|
||||
value: splitKnown ? '${_int(usage['tokens_in']) ?? 0}' : 'Unavailable',
|
||||
),
|
||||
(
|
||||
label: 'Output tokens',
|
||||
value: splitKnown ? '${_int(usage['tokens_out']) ?? 0}' : 'Unavailable',
|
||||
),
|
||||
(
|
||||
label: 'Reported cost',
|
||||
// cost_usd is omitted by the server when zero, so a known stage count
|
||||
// makes an absent value a real $0.000000 rather than an unknown cost.
|
||||
value: costStages == 0
|
||||
? 'Unavailable'
|
||||
: '\$${((usage['cost_usd'] as num?) ?? 0).toStringAsFixed(6)}',
|
||||
),
|
||||
];
|
||||
if (stages != null && tokenStages < stages) {
|
||||
rows.add((
|
||||
label: 'Token reporting',
|
||||
value: '$tokenStages of $stages stages',
|
||||
));
|
||||
}
|
||||
if (stages != null && costStages < stages) {
|
||||
rows.add((label: 'Cost reporting', value: '$costStages of $stages stages'));
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/// Every recorded visit with its server sequence, in recorded order.
|
||||
List<DetailVisit> detailTimeline(dynamic steps) {
|
||||
if (steps is! List) return const [];
|
||||
return [
|
||||
for (final step in steps.whereType<Map>())
|
||||
(
|
||||
title:
|
||||
'${_text(step['stage'], 'Stage unavailable')} · visit '
|
||||
'${step['sequence'] is num ? (step['sequence'] as num).toInt() : 'unavailable'}',
|
||||
subtitle: _visitSubtitle(step),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
String _visitSubtitle(Map step) {
|
||||
final status = _text(step['status'], 'Status unavailable');
|
||||
final outcome = '${step['outcome'] ?? ''}'.trim();
|
||||
final target = '${step['target'] ?? ''}'.trim();
|
||||
return [
|
||||
status,
|
||||
if (outcome.isNotEmpty) outcome,
|
||||
if (target.isNotEmpty) '→ $target',
|
||||
].join(' · ');
|
||||
}
|
||||
|
||||
String _text(dynamic value, String fallback) {
|
||||
final text = '${value ?? ''}'.trim();
|
||||
return text.isEmpty ? fallback : text;
|
||||
}
|
||||
|
||||
int? _int(dynamic value) => value is num ? value.toInt() : null;
|
||||
@@ -0,0 +1,203 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/run_models.dart';
|
||||
import 'run_detail_content.dart';
|
||||
|
||||
/// The runs detail with standard Cupertino controls. It has no Material
|
||||
/// ancestor: sections use native Cupertino expansion tiles and grouped list
|
||||
/// sections, and copy feedback is an inline live-region status.
|
||||
Widget buildCupertinoRunDetail({
|
||||
required BuildContext context,
|
||||
required JsonMap run,
|
||||
required bool detailLoading,
|
||||
required String? error,
|
||||
required bool copying,
|
||||
required String? copyStatus,
|
||||
required VoidCallback onBack,
|
||||
required VoidCallback onCopy,
|
||||
}) {
|
||||
final theme = CupertinoTheme.of(context);
|
||||
final prompt = detailPrompt(run);
|
||||
final visits = detailTimeline(run['steps']);
|
||||
final metrics = detailUsageMetrics(run['usage']);
|
||||
return ListView(
|
||||
key: ValueKey<String>('run-detail-${run['id']}'),
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0),
|
||||
child: Row(
|
||||
children: [
|
||||
CupertinoButton(
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: onBack,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(CupertinoIcons.back),
|
||||
const SizedBox(width: 4),
|
||||
const Text('Back'),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
if (copying) const CupertinoActivityIndicator(),
|
||||
],
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
detailTitle(run),
|
||||
style: theme.textTheme.navLargeTitleTextStyle,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(runStatusLabel(run)),
|
||||
Text('Run ${run['id']} · Pipeline ${detailPipeline(run)}'),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (detailLoading) const _CupertinoNotice('Refreshing run details…'),
|
||||
if (error != null) _CupertinoNotice(error),
|
||||
if (prompt != null)
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 16, 16, 0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Wrap(
|
||||
alignment: WrapAlignment.spaceBetween,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
spacing: 8,
|
||||
runSpacing: 4,
|
||||
children: [
|
||||
Text(
|
||||
'Original prompt',
|
||||
style: theme.textTheme.navTitleTextStyle,
|
||||
),
|
||||
CupertinoButton(
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: copying ? null : onCopy,
|
||||
child: const Text('Copy prompt'),
|
||||
),
|
||||
],
|
||||
),
|
||||
_CupertinoSelectableText(prompt),
|
||||
if (copyStatus != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Semantics(liveRegion: true, child: Text(copyStatus)),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
_fieldSection('Input', run['input'], 'No input recorded.'),
|
||||
_fieldSection('Output', run['output'], 'No output recorded.'),
|
||||
CupertinoListSection.insetGrouped(
|
||||
header: const Text('Timeline'),
|
||||
children: [
|
||||
if (visits.isEmpty)
|
||||
const CupertinoListTile(title: Text('No visits recorded.'))
|
||||
else
|
||||
for (final visit in visits)
|
||||
CupertinoListTile(
|
||||
leading: const Icon(CupertinoIcons.circle),
|
||||
title: Text(visit.title),
|
||||
subtitle: Text(visit.subtitle),
|
||||
),
|
||||
],
|
||||
),
|
||||
CupertinoListSection.insetGrouped(
|
||||
children: [
|
||||
CupertinoExpansionTile(
|
||||
title: const Text('Metrics'),
|
||||
child: Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (metrics.isEmpty)
|
||||
const Text('No reported usage.')
|
||||
else
|
||||
for (final metric in metrics)
|
||||
CupertinoListTile(
|
||||
title: Text(metric.label),
|
||||
subtitle: Text(metric.value),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _fieldSection(String title, dynamic value, String empty) {
|
||||
final text = detailEmpty(value) ? empty : detailJson(value);
|
||||
return CupertinoListSection.insetGrouped(
|
||||
children: [
|
||||
CupertinoExpansionTile(
|
||||
title: Text(title),
|
||||
child: Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 16),
|
||||
child: _CupertinoSelectableText(text),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
class _CupertinoNotice extends StatelessWidget {
|
||||
const _CupertinoNotice(this.text);
|
||||
final String text;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0),
|
||||
child: Semantics(liveRegion: true, child: Text(text)),
|
||||
);
|
||||
}
|
||||
|
||||
/// A read-only Cupertino text control: plain, selectable text without a
|
||||
/// Material dependency, while keeping native selection and copy affordances.
|
||||
class _CupertinoSelectableText extends StatefulWidget {
|
||||
const _CupertinoSelectableText(this.text);
|
||||
final String text;
|
||||
|
||||
@override
|
||||
State<_CupertinoSelectableText> createState() =>
|
||||
_CupertinoSelectableTextState();
|
||||
}
|
||||
|
||||
class _CupertinoSelectableTextState extends State<_CupertinoSelectableText> {
|
||||
late final TextEditingController _controller = TextEditingController(
|
||||
text: widget.text,
|
||||
);
|
||||
|
||||
@override
|
||||
void didUpdateWidget(_CupertinoSelectableText oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (widget.text != oldWidget.text) _controller.text = widget.text;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => CupertinoTextField(
|
||||
controller: _controller,
|
||||
readOnly: true,
|
||||
maxLines: null,
|
||||
padding: EdgeInsets.zero,
|
||||
decoration: const BoxDecoration(),
|
||||
style: CupertinoTheme.of(context).textTheme.textStyle,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/run_models.dart';
|
||||
import 'run_detail_content.dart';
|
||||
|
||||
/// The runs detail with standard Material controls.
|
||||
Widget buildMaterialRunDetail({
|
||||
required BuildContext context,
|
||||
required JsonMap run,
|
||||
required bool detailLoading,
|
||||
required String? error,
|
||||
required bool copying,
|
||||
required String? copyStatus,
|
||||
required VoidCallback onBack,
|
||||
required VoidCallback onCopy,
|
||||
}) {
|
||||
final theme = Theme.of(context);
|
||||
final prompt = detailPrompt(run);
|
||||
final visits = detailTimeline(run['steps']);
|
||||
final metrics = detailUsageMetrics(run['usage']);
|
||||
return ListView(
|
||||
key: ValueKey<String>('run-detail-${run['id']}'),
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: TextButton.icon(
|
||||
onPressed: onBack,
|
||||
icon: const Icon(Icons.arrow_back),
|
||||
label: const Text('Back to list'),
|
||||
),
|
||||
),
|
||||
Text(detailTitle(run), style: theme.textTheme.headlineSmall),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 4,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
Chip(label: Text(runStatusLabel(run))),
|
||||
Text('Run ${run['id']}'),
|
||||
Text('Pipeline ${detailPipeline(run)}'),
|
||||
],
|
||||
),
|
||||
if (detailLoading) const _Notice('Refreshing run details…'),
|
||||
if (error != null) _Notice(error),
|
||||
if (prompt != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Original prompt',
|
||||
style: theme.textTheme.titleMedium,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: 'Copy prompt',
|
||||
onPressed: copying ? null : onCopy,
|
||||
icon: const Icon(Icons.copy),
|
||||
),
|
||||
],
|
||||
),
|
||||
SelectableText(prompt),
|
||||
if (copyStatus != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Semantics(liveRegion: true, child: Text(copyStatus)),
|
||||
),
|
||||
],
|
||||
_fieldSection('Input', run['input'], 'No input recorded.'),
|
||||
_fieldSection('Output', run['output'], 'No output recorded.'),
|
||||
Text('Timeline', style: theme.textTheme.titleLarge),
|
||||
if (visits.isEmpty)
|
||||
const Text('No visits recorded.')
|
||||
else
|
||||
...visits.map(
|
||||
(visit) => ListTile(
|
||||
leading: const Icon(Icons.circle_outlined),
|
||||
title: Text(visit.title),
|
||||
subtitle: Text(visit.subtitle),
|
||||
),
|
||||
),
|
||||
ExpansionTile(
|
||||
title: const Text('Metrics'),
|
||||
children: [
|
||||
if (metrics.isEmpty)
|
||||
const Padding(
|
||||
padding: EdgeInsets.all(16),
|
||||
child: Text('No reported usage.'),
|
||||
)
|
||||
else
|
||||
...metrics.map(
|
||||
(metric) => ListTile(
|
||||
title: Text(metric.label),
|
||||
subtitle: Text(metric.value),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _fieldSection(String title, dynamic value, String empty) {
|
||||
final text = detailEmpty(value) ? empty : detailJson(value);
|
||||
return ExpansionTile(
|
||||
title: Text(title),
|
||||
children: [
|
||||
Padding(padding: const EdgeInsets.all(16), child: SelectableText(text)),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
class _Notice extends StatelessWidget {
|
||||
const _Notice(this.text);
|
||||
final String text;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Semantics(liveRegion: true, child: Text(text)),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import 'run_detail_content.dart';
|
||||
import 'run_detail_cupertino.dart';
|
||||
import 'run_detail_material.dart';
|
||||
import 'runs_controller.dart';
|
||||
|
||||
class RunDetailView extends StatefulWidget {
|
||||
const RunDetailView({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.onBack,
|
||||
});
|
||||
|
||||
final RunsController controller;
|
||||
final VoidCallback onBack;
|
||||
|
||||
@override
|
||||
State<RunDetailView> createState() => _RunDetailViewState();
|
||||
}
|
||||
|
||||
class _RunDetailViewState extends State<RunDetailView> {
|
||||
bool _copying = false;
|
||||
String? _copyStatus;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => AnimatedBuilder(
|
||||
animation: widget.controller,
|
||||
builder: (context, _) {
|
||||
final cupertino = usesCupertinoHost(context);
|
||||
final run = widget.controller.detail;
|
||||
if (run == null) return _placeholder(context, cupertino: cupertino);
|
||||
final prompt = detailPrompt(run);
|
||||
return cupertino
|
||||
? buildCupertinoRunDetail(
|
||||
context: context,
|
||||
run: run,
|
||||
detailLoading: widget.controller.detailLoading,
|
||||
error: widget.controller.error,
|
||||
copying: _copying,
|
||||
copyStatus: _copyStatus,
|
||||
onBack: widget.onBack,
|
||||
onCopy: () => _copyPrompt(prompt ?? '', cupertino: true),
|
||||
)
|
||||
: buildMaterialRunDetail(
|
||||
context: context,
|
||||
run: run,
|
||||
detailLoading: widget.controller.detailLoading,
|
||||
error: widget.controller.error,
|
||||
copying: _copying,
|
||||
copyStatus: _copyStatus,
|
||||
onBack: widget.onBack,
|
||||
onCopy: () => _copyPrompt(prompt ?? '', cupertino: false),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
Widget _placeholder(BuildContext context, {required bool cupertino}) {
|
||||
final loading = widget.controller.detailLoading;
|
||||
final message = loading
|
||||
? 'Loading run details…'
|
||||
: widget.controller.error ?? 'Run details unavailable.';
|
||||
// Back stays available while the detail is pending as well as after a
|
||||
// failure, so a slow or refused request can never trap the destination.
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (loading) ...[
|
||||
if (cupertino)
|
||||
const CupertinoActivityIndicator()
|
||||
else
|
||||
const CircularProgressIndicator(),
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24),
|
||||
child: Text(message, textAlign: TextAlign.center),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
if (cupertino)
|
||||
CupertinoButton(
|
||||
onPressed: widget.onBack,
|
||||
child: const Text('Back to list'),
|
||||
)
|
||||
else
|
||||
FilledButton(
|
||||
onPressed: widget.onBack,
|
||||
child: const Text('Back to list'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Copies the stored prompt byte-for-byte. A refusal is surfaced, never
|
||||
/// replaced by copying a title or the formatted detail.
|
||||
Future<void> _copyPrompt(String prompt, {required bool cupertino}) async {
|
||||
if (_copying) return;
|
||||
setState(() => _copying = true);
|
||||
String message;
|
||||
try {
|
||||
await Clipboard.setData(ClipboardData(text: prompt));
|
||||
message = 'Prompt copied to clipboard.';
|
||||
} catch (_) {
|
||||
message = 'Could not copy prompt to clipboard.';
|
||||
}
|
||||
if (!mounted) return;
|
||||
final scaffold = cupertino ? null : Scaffold.maybeOf(context);
|
||||
final inline = cupertino || scaffold == null;
|
||||
setState(() {
|
||||
_copying = false;
|
||||
_copyStatus = inline ? message : null;
|
||||
});
|
||||
if (!cupertino && scaffold != null) {
|
||||
ScaffoldMessenger.maybeOf(
|
||||
context,
|
||||
)?.showSnackBar(SnackBar(content: Text(message)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../data/runs_repository.dart';
|
||||
import '../domain/run_events.dart';
|
||||
import '../domain/run_models.dart';
|
||||
|
||||
class RunsController extends ChangeNotifier {
|
||||
RunsController(this.repository);
|
||||
final RunsRepository repository;
|
||||
StreamSubscription<JsonMap>? _subscription;
|
||||
List<JsonMap> runs = [];
|
||||
JsonMap? detail, usage;
|
||||
String? error;
|
||||
bool loading = false, detailLoading = false;
|
||||
String query = '',
|
||||
sort = 'newest_first',
|
||||
scheduled = 'any',
|
||||
timeRange = 'any_time';
|
||||
final Set<String> statuses = {};
|
||||
int? pipelineId;
|
||||
// List and detail requests advance independent generations so neither can
|
||||
// make the other's in-flight reply stale.
|
||||
int _listGeneration = 0, _detailGeneration = 0;
|
||||
num? _selectedId;
|
||||
Timer? _detailRefresh;
|
||||
bool _listResyncing = false, _listAgain = false;
|
||||
bool _detailRefreshing = false, _detailAgain = false;
|
||||
bool _disposed = false;
|
||||
|
||||
num? get selectedRunId => _selectedId;
|
||||
|
||||
void listen(Stream<JsonMap> frames) {
|
||||
_subscription?.cancel();
|
||||
_subscription = frames
|
||||
.where((f) => f['type'] == 'run_event')
|
||||
.listen(_event);
|
||||
}
|
||||
|
||||
Future<void> load([int? initialId]) async {
|
||||
final token = ++_listGeneration;
|
||||
_listAgain = false;
|
||||
loading = true;
|
||||
error = null;
|
||||
notifyListeners();
|
||||
try {
|
||||
final result = await repository.listRuns();
|
||||
if (!_listOwned(token)) return;
|
||||
runs = result.runs;
|
||||
usage = result.usage;
|
||||
} catch (e) {
|
||||
if (!_listOwned(token)) return;
|
||||
error = '$e';
|
||||
}
|
||||
if (!_listOwned(token)) return;
|
||||
loading = false;
|
||||
notifyListeners();
|
||||
// A run event may have arrived while the list request was in flight; one
|
||||
// resync after it keeps the pushed state without dropping the event.
|
||||
_resyncAgainIfNeeded();
|
||||
if (initialId != null) await select(initialId);
|
||||
}
|
||||
|
||||
/// Re-reads the list and the open detail after the socket was replaced.
|
||||
///
|
||||
/// The selection is kept, so a reconnect refreshes in place instead of
|
||||
/// discarding the detail the operator had open.
|
||||
Future<void> resync() async {
|
||||
final selected = _selectedId;
|
||||
await load();
|
||||
if (selected != null && _selectedId == selected) await select(selected);
|
||||
}
|
||||
|
||||
Future<void> select(num id) async {
|
||||
final token = ++_detailGeneration;
|
||||
_cancelDetailRefresh();
|
||||
// Keep a same-run detail while it refreshes, but never present the previous
|
||||
// run as if it were the newly selected one.
|
||||
if (_selectedId != id) detail = null;
|
||||
_selectedId = id;
|
||||
detailLoading = true;
|
||||
error = null;
|
||||
notifyListeners();
|
||||
try {
|
||||
final value = await repository.getRun(id);
|
||||
if (!_detailOwned(id, token)) return;
|
||||
detail = value;
|
||||
} catch (e) {
|
||||
if (!_detailOwned(id, token)) return;
|
||||
error = '$e';
|
||||
}
|
||||
if (!_detailOwned(id, token)) return;
|
||||
detailLoading = false;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void back() {
|
||||
++_detailGeneration;
|
||||
_cancelDetailRefresh();
|
||||
_selectedId = null;
|
||||
detail = null;
|
||||
detailLoading = false;
|
||||
error = null;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void setQuery(String value) {
|
||||
query = value;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void setStatus(String? value) {
|
||||
if (value == null) {
|
||||
statuses.clear();
|
||||
} else if (!statuses.add(value)) {
|
||||
statuses.remove(value);
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void setPipeline(int? value) {
|
||||
pipelineId = value;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void setScheduled(String value) {
|
||||
scheduled = value;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void setSort(String value) {
|
||||
sort = value;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _event(JsonMap frame) {
|
||||
final folded = foldRunEvent(runs, frame);
|
||||
runs = folded.runs;
|
||||
if (detail?['id'] == frame['run_id']) {
|
||||
detail = foldRunEventDetail(detail, frame);
|
||||
}
|
||||
if (frame['run_id'] == null || folded.needsResync) {
|
||||
_scheduleListRefresh();
|
||||
}
|
||||
final selected = _selectedId;
|
||||
if (selected != null &&
|
||||
frame['run_id'] == selected &&
|
||||
(folded.needsResync || runDetailNeedsFullSync(frame))) {
|
||||
_scheduleDetailRefresh(selected);
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _scheduleListRefresh() {
|
||||
if (_disposed) return;
|
||||
if (_listResyncing || loading) {
|
||||
_listAgain = true;
|
||||
return;
|
||||
}
|
||||
_listResyncing = true;
|
||||
loading = true;
|
||||
notifyListeners();
|
||||
unawaited(_reloadList());
|
||||
}
|
||||
|
||||
Future<void> _reloadList() async {
|
||||
final token = ++_listGeneration;
|
||||
_listAgain = false;
|
||||
try {
|
||||
final result = await repository.listRuns();
|
||||
if (!_listOwned(token)) return;
|
||||
runs = result.runs;
|
||||
usage = result.usage;
|
||||
error = null;
|
||||
} catch (e) {
|
||||
if (_listOwned(token)) error = '$e';
|
||||
} finally {
|
||||
_listResyncing = false;
|
||||
if (_listOwned(token)) {
|
||||
loading = false;
|
||||
notifyListeners();
|
||||
}
|
||||
// A followup may have been requested while this (possibly superseded)
|
||||
// request was still the one marked in flight.
|
||||
_resyncAgainIfNeeded();
|
||||
}
|
||||
}
|
||||
|
||||
void _resyncAgainIfNeeded() {
|
||||
if (_disposed || !_listAgain) return;
|
||||
_listAgain = false;
|
||||
_scheduleListRefresh();
|
||||
}
|
||||
|
||||
void _scheduleDetailRefresh(num id) {
|
||||
if (_disposed || _selectedId != id) return;
|
||||
if (_detailRefreshing) {
|
||||
_detailAgain = true;
|
||||
return;
|
||||
}
|
||||
_detailRefresh?.cancel();
|
||||
_detailRefresh = Timer(
|
||||
const Duration(milliseconds: 150),
|
||||
() => _refreshDetail(id, _detailGeneration),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _refreshDetail(num id, int token) async {
|
||||
_detailRefresh = null;
|
||||
if (!_detailOwned(id, token)) return;
|
||||
_detailRefreshing = true;
|
||||
try {
|
||||
final value = await repository.getRun(id);
|
||||
if (_detailOwned(id, token)) {
|
||||
detail = value;
|
||||
notifyListeners();
|
||||
}
|
||||
} catch (e) {
|
||||
if (_detailOwned(id, token)) {
|
||||
error = '$e';
|
||||
notifyListeners();
|
||||
}
|
||||
} finally {
|
||||
if (_detailOwned(id, token)) {
|
||||
_detailRefreshing = false;
|
||||
if (_detailAgain) {
|
||||
_detailAgain = false;
|
||||
unawaited(_refreshDetail(id, token));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _cancelDetailRefresh() {
|
||||
_detailRefresh?.cancel();
|
||||
_detailRefresh = null;
|
||||
_detailAgain = false;
|
||||
_detailRefreshing = false;
|
||||
}
|
||||
|
||||
bool _listOwned(int token) => !_disposed && token == _listGeneration;
|
||||
|
||||
bool _detailOwned(num id, int token) =>
|
||||
!_disposed && token == _detailGeneration && _selectedId == id;
|
||||
|
||||
List<JsonMap> get visibleRuns => sortRuns(
|
||||
filterRuns(
|
||||
runs,
|
||||
statuses: statuses,
|
||||
pipelineId: pipelineId,
|
||||
scheduled: scheduled,
|
||||
timeRange: timeRange,
|
||||
)
|
||||
.where(
|
||||
(r) => '${r['title'] ?? r['name'] ?? ''}'.toLowerCase().contains(
|
||||
query.toLowerCase(),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
sort: sort,
|
||||
);
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
_subscription?.cancel();
|
||||
_detailRefresh?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import '../domain/run_models.dart';
|
||||
import 'runs_controller.dart';
|
||||
|
||||
class RunsList extends StatelessWidget {
|
||||
const RunsList({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.onSelected,
|
||||
});
|
||||
|
||||
final RunsController controller;
|
||||
final ValueChanged<num> onSelected;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (controller.loading && controller.runs.isEmpty) {
|
||||
return Center(
|
||||
child: usesCupertinoHost(context)
|
||||
? const CupertinoActivityIndicator()
|
||||
: const CircularProgressIndicator(),
|
||||
);
|
||||
}
|
||||
if (controller.error != null && controller.runs.isEmpty) {
|
||||
return _emptyError(context);
|
||||
}
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (controller.usage != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: Text('Usage: ${controller.usage}'),
|
||||
),
|
||||
if (controller.error != null) _inlineError(context),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: usesCupertinoHost(context)
|
||||
? CupertinoSearchTextField(
|
||||
placeholder: 'Filter runs',
|
||||
onChanged: controller.setQuery,
|
||||
)
|
||||
: TextField(
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Filter runs',
|
||||
prefixIcon: Icon(Icons.search),
|
||||
),
|
||||
onChanged: controller.setQuery,
|
||||
),
|
||||
),
|
||||
_selectors(context),
|
||||
Expanded(
|
||||
child: controller.visibleRuns.isEmpty
|
||||
? const Center(child: Text('No runs found.'))
|
||||
: ListView.builder(
|
||||
itemCount: controller.visibleRuns.length,
|
||||
itemBuilder: (context, index) =>
|
||||
_runTile(context, controller.visibleRuns[index]),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _emptyError(BuildContext context) => Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(controller.error!),
|
||||
const SizedBox(height: 8),
|
||||
usesCupertinoHost(context)
|
||||
? CupertinoButton(
|
||||
onPressed: controller.load,
|
||||
child: const Text('Retry'),
|
||||
)
|
||||
: FilledButton(
|
||||
onPressed: controller.load,
|
||||
child: const Text('Retry'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
Widget _inlineError(BuildContext context) => Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(child: Text(controller.error!)),
|
||||
if (usesCupertinoHost(context))
|
||||
CupertinoButton(
|
||||
onPressed: controller.load,
|
||||
child: const Text('Retry'),
|
||||
)
|
||||
else
|
||||
TextButton(onPressed: controller.load, child: const Text('Retry')),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
Widget _selectors(BuildContext context) {
|
||||
if (usesCupertinoHost(context)) {
|
||||
return Wrap(
|
||||
spacing: 8,
|
||||
children: [
|
||||
CupertinoButton(
|
||||
onPressed: () => _choose(
|
||||
context,
|
||||
'Sort runs',
|
||||
_sorts,
|
||||
controller.sort,
|
||||
controller.setSort,
|
||||
),
|
||||
child: Text('Sort: ${_sortLabel(controller.sort)}'),
|
||||
),
|
||||
CupertinoButton(
|
||||
onPressed: () => _choose(
|
||||
context,
|
||||
'Schedule',
|
||||
_schedules,
|
||||
controller.scheduled,
|
||||
controller.setScheduled,
|
||||
),
|
||||
child: Text('Schedule: ${_scheduleLabel(controller.scheduled)}'),
|
||||
),
|
||||
for (final status in _statuses)
|
||||
CupertinoButton(
|
||||
onPressed: () => controller.setStatus(status),
|
||||
child: Text(
|
||||
'${controller.statuses.contains(status) ? '✓ ' : ''}${_title(status)}',
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return Wrap(
|
||||
spacing: 8,
|
||||
children: [
|
||||
DropdownButton<String>(
|
||||
value: controller.sort,
|
||||
isExpanded: true,
|
||||
onChanged: (v) {
|
||||
if (v != null) controller.setSort(v);
|
||||
},
|
||||
items: _sorts
|
||||
.map((e) => DropdownMenuItem(value: e.$1, child: Text(e.$2)))
|
||||
.toList(),
|
||||
),
|
||||
DropdownButton<String>(
|
||||
value: controller.scheduled,
|
||||
isExpanded: true,
|
||||
onChanged: (v) {
|
||||
if (v != null) controller.setScheduled(v);
|
||||
},
|
||||
items: _schedules
|
||||
.map((e) => DropdownMenuItem(value: e.$1, child: Text(e.$2)))
|
||||
.toList(),
|
||||
),
|
||||
for (final status in _statuses)
|
||||
FilterChip(
|
||||
label: Text(_title(status)),
|
||||
selected: controller.statuses.contains(status),
|
||||
onSelected: (_) => controller.setStatus(status),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _choose(
|
||||
BuildContext context,
|
||||
String title,
|
||||
List<(String, String)> values,
|
||||
String selected,
|
||||
ValueChanged<String> onSelected,
|
||||
) async {
|
||||
final value = await showCupertinoModalPopup<String>(
|
||||
context: context,
|
||||
builder: (context) => CupertinoActionSheet(
|
||||
title: Text(title),
|
||||
actions: [
|
||||
for (final option in values)
|
||||
CupertinoActionSheetAction(
|
||||
onPressed: () => Navigator.pop(context, option.$1),
|
||||
child: Text(option.$2),
|
||||
),
|
||||
],
|
||||
cancelButton: CupertinoActionSheetAction(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (value != null && value != selected) onSelected(value);
|
||||
}
|
||||
|
||||
Widget _runTile(BuildContext context, JsonMap run) {
|
||||
final identity = runIdentity(run['title'], run['name']);
|
||||
final id = run['id'];
|
||||
final title = identity.label.isEmpty ? 'Run $id' : identity.label;
|
||||
final subtitle =
|
||||
'${run['name'] ?? 'Pipeline unavailable'} · ${run['created_at'] ?? 'Time unavailable'}${run['scheduled'] == true ? ' · Scheduled' : ''}';
|
||||
if (usesCupertinoHost(context)) {
|
||||
return CupertinoListTile(
|
||||
title: Text(title),
|
||||
subtitle: Text(subtitle),
|
||||
additionalInfo: Text(runStatusLabel(run)),
|
||||
trailing: const CupertinoListTileChevron(),
|
||||
onTap: id is num ? () => onSelected(id) : null,
|
||||
);
|
||||
}
|
||||
return ListTile(
|
||||
title: Text(title),
|
||||
subtitle: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [Text(subtitle), Text(runStatusLabel(run))],
|
||||
),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: id is num ? () => onSelected(id) : null,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const _sorts = [
|
||||
('newest_first', 'Newest'),
|
||||
('oldest_first', 'Oldest'),
|
||||
('pipeline_name', 'Pipeline'),
|
||||
('status', 'Status'),
|
||||
];
|
||||
const _schedules = [
|
||||
('any', 'Any schedule'),
|
||||
('scheduled', 'Scheduled'),
|
||||
('unscheduled', 'Unscheduled'),
|
||||
];
|
||||
const _statuses = ['queued', 'running', 'waiting', 'succeeded', 'failed'];
|
||||
String _sortLabel(String value) =>
|
||||
_sorts.firstWhere((e) => e.$1 == value, orElse: () => _sorts.first).$2;
|
||||
String _scheduleLabel(String value) => _schedules
|
||||
.firstWhere((e) => e.$1 == value, orElse: () => _schedules.first)
|
||||
.$2;
|
||||
String _title(String value) => '${value[0].toUpperCase()}${value.substring(1)}';
|
||||
@@ -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<List<SavedSchedule>> listSchedules({int? pipelineId}) async {
|
||||
final fields = <String, dynamic>{};
|
||||
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<String, dynamic>.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<SavedSchedule> 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 = <String, dynamic>{'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<String, dynamic>.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<void> 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;
|
||||
@@ -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<String> get writePaths => _texts(raw['write_paths']);
|
||||
bool get allowTools => raw['allow_tools'] == true;
|
||||
String get model => _text(raw['model']);
|
||||
Map<String, String> 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 <String, dynamic>{};
|
||||
return <String, dynamic>{
|
||||
for (final entry in value.entries)
|
||||
'${entry.key}': cloneJsonValue(entry.value),
|
||||
};
|
||||
}
|
||||
|
||||
List<String> _texts(dynamic value) => value is List
|
||||
? [
|
||||
for (final item in value)
|
||||
if (item is String) item,
|
||||
]
|
||||
: const [];
|
||||
@@ -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 <String, dynamic>{
|
||||
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<String, dynamic>.from(cloneJsonValue(value) as Map);
|
||||
@@ -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<String> get times => _texts(raw['times']);
|
||||
|
||||
/// Empty means every day (written as absent on the wire).
|
||||
List<String> 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<String> _texts(dynamic value) => value is List
|
||||
? [
|
||||
for (final item in value)
|
||||
if (item is String) item,
|
||||
]
|
||||
: const [];
|
||||
@@ -0,0 +1,94 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/api_gateway.dart';
|
||||
import 'data/schedules_repository.dart';
|
||||
import 'domain/saved_schedule.dart';
|
||||
import 'ui/list/schedule_list_controller.dart';
|
||||
import 'ui/list/schedule_list_view.dart';
|
||||
|
||||
/// The saved-schedules list body.
|
||||
///
|
||||
/// The shell supplies navigation chrome. Selecting a row reports the exact
|
||||
/// [SavedSchedule] the server returned; this screen does not create, edit,
|
||||
/// delete, pause or enable anything.
|
||||
class SchedulesScreen extends StatefulWidget {
|
||||
const SchedulesScreen({
|
||||
super.key,
|
||||
required this.gateway,
|
||||
required this.onOpen,
|
||||
this.pipelineId,
|
||||
});
|
||||
|
||||
final ApiGateway gateway;
|
||||
final ValueChanged<SavedSchedule> onOpen;
|
||||
final int? pipelineId;
|
||||
|
||||
@override
|
||||
State<SchedulesScreen> createState() => _SchedulesScreenState();
|
||||
}
|
||||
|
||||
class _SchedulesScreenState extends State<SchedulesScreen> {
|
||||
late SchedulesController _controller;
|
||||
late final TextEditingController _searchController;
|
||||
final ScrollController _scrollController = ScrollController();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller = _createController();
|
||||
_searchController = TextEditingController(text: _controller.query);
|
||||
unawaited(_controller.refresh());
|
||||
}
|
||||
|
||||
SchedulesController _createController() => SchedulesController(
|
||||
repository: SchedulesRepository(widget.gateway),
|
||||
pipelineId: widget.pipelineId,
|
||||
);
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant SchedulesScreen oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (identical(oldWidget.gateway, widget.gateway) &&
|
||||
oldWidget.pipelineId == widget.pipelineId) {
|
||||
return;
|
||||
}
|
||||
final query = _controller.query;
|
||||
final filter = _controller.filter;
|
||||
_controller.dispose();
|
||||
_controller = _createController();
|
||||
_controller.setQuery(query);
|
||||
_controller.setFilter(filter);
|
||||
unawaited(_controller.refresh());
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
_searchController.dispose();
|
||||
_scrollController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final cupertino =
|
||||
Localizations.of<MaterialLocalizations>(
|
||||
context,
|
||||
MaterialLocalizations,
|
||||
) ==
|
||||
null;
|
||||
return AnimatedBuilder(
|
||||
animation: _controller,
|
||||
builder: (context, _) => SchedulesListView(
|
||||
controller: _controller,
|
||||
searchController: _searchController,
|
||||
scrollController: _scrollController,
|
||||
cupertino: cupertino,
|
||||
onOpen: widget.onOpen,
|
||||
onRefresh: () => unawaited(_controller.refresh()),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../data/schedules_repository.dart';
|
||||
import '../../domain/saved_schedule.dart';
|
||||
import 'schedule_list_format.dart';
|
||||
|
||||
enum ScheduleListFilter { all, enabled }
|
||||
|
||||
extension ScheduleListFilterLabel on ScheduleListFilter {
|
||||
String get label => switch (this) {
|
||||
ScheduleListFilter.all => 'All',
|
||||
ScheduleListFilter.enabled => 'Enabled',
|
||||
};
|
||||
}
|
||||
|
||||
/// A list refresh failure, kept apart from a valid empty result.
|
||||
class ScheduleListFailure {
|
||||
const ScheduleListFailure(this.message, {this.unsupported = false});
|
||||
|
||||
factory ScheduleListFailure.from(Object error) {
|
||||
final text = error is SchedulesRepositoryException
|
||||
? error.message
|
||||
: '$error';
|
||||
if (text == _unsupportedReply || _unsupportedPattern.hasMatch(text)) {
|
||||
return ScheduleListFailure(
|
||||
'This server does not support saved schedules. '
|
||||
'Upgrade the server to use schedules. ($text)',
|
||||
unsupported: true,
|
||||
);
|
||||
}
|
||||
return ScheduleListFailure(text);
|
||||
}
|
||||
|
||||
final String message;
|
||||
final bool unsupported;
|
||||
|
||||
/// The repository's exact report for a reply without `type: schedules`.
|
||||
static const _unsupportedReply = 'The server returned no schedules response.';
|
||||
|
||||
/// Matches the web client's older-server detection, so a server that refuses
|
||||
/// the command with its own `unknown request`/`unsupported` wording gets the
|
||||
/// same upgrade guidance instead of only the raw error.
|
||||
static final _unsupportedPattern = RegExp(
|
||||
r'unknown (message|request|command)|unsupported.*schedule',
|
||||
caseSensitive: false,
|
||||
);
|
||||
}
|
||||
|
||||
/// Loads saved run configurations with search and enabled filtering.
|
||||
///
|
||||
/// This controller is read-only: it only calls `list_schedules`. It never saves,
|
||||
/// deletes, pauses or enables a schedule, and it never treats schedules as
|
||||
/// pipeline definitions.
|
||||
class SchedulesController extends ChangeNotifier {
|
||||
SchedulesController({required this.repository, this.pipelineId});
|
||||
|
||||
final SchedulesRepository repository;
|
||||
final int? pipelineId;
|
||||
|
||||
List<SavedSchedule> _schedules = const [];
|
||||
List<SavedSchedule>? _visibleSchedules;
|
||||
bool _loading = false;
|
||||
bool _loaded = false;
|
||||
ScheduleListFailure? _failure;
|
||||
String _query = '';
|
||||
ScheduleListFilter _filter = ScheduleListFilter.all;
|
||||
int _generation = 0;
|
||||
bool _disposed = false;
|
||||
|
||||
List<SavedSchedule> get schedules => _schedules;
|
||||
bool get isLoading => _loading;
|
||||
bool get hasLoaded => _loaded;
|
||||
ScheduleListFailure? get failure => _failure;
|
||||
String get query => _query;
|
||||
ScheduleListFilter get filter => _filter;
|
||||
|
||||
/// Cached until the list, query or filter changes; the view, count label and
|
||||
/// toolbar all read it during one build.
|
||||
List<SavedSchedule> get visibleSchedules =>
|
||||
_visibleSchedules ??= _filterSchedules();
|
||||
|
||||
List<SavedSchedule> _filterSchedules() {
|
||||
final needle = _query.trim().toLowerCase();
|
||||
return List.unmodifiable([
|
||||
for (final schedule in _schedules)
|
||||
if ((_filter == ScheduleListFilter.all || schedule.enabled) &&
|
||||
(needle.isEmpty || _matches(schedule, needle)))
|
||||
schedule,
|
||||
]);
|
||||
}
|
||||
|
||||
void _invalidateVisibility() => _visibleSchedules = null;
|
||||
|
||||
bool get isInitialLoading => _loading && !_loaded;
|
||||
|
||||
/// Empty-state wording that names the actual reason when the search box is
|
||||
/// empty and only the enabled filter hides every row.
|
||||
String get emptyMessage => _query.trim().isNotEmpty
|
||||
? 'No schedules match this search.'
|
||||
: 'No enabled schedules.';
|
||||
|
||||
String get countLabel =>
|
||||
scheduleCountLabel(visibleSchedules.length, _schedules.length);
|
||||
|
||||
bool _matches(SavedSchedule schedule, String needle) {
|
||||
final haystack = [
|
||||
scheduleDisplayName(schedule),
|
||||
schedule.prompt,
|
||||
if (schedule.pipelineId != null) 'Pipeline ${schedule.pipelineId}',
|
||||
].join('\n').toLowerCase();
|
||||
return haystack.contains(needle);
|
||||
}
|
||||
|
||||
void setQuery(String value) {
|
||||
if (value == _query) return;
|
||||
_query = value;
|
||||
_invalidateVisibility();
|
||||
_notify();
|
||||
}
|
||||
|
||||
void setFilter(ScheduleListFilter value) {
|
||||
if (value == _filter) return;
|
||||
_filter = value;
|
||||
_invalidateVisibility();
|
||||
_notify();
|
||||
}
|
||||
|
||||
void clearQuery() => setQuery('');
|
||||
|
||||
/// Reloads the list without recreating the screen, so the search field and
|
||||
/// the list's scroll position survive a refresh.
|
||||
///
|
||||
/// Only the newest request may publish. A slower, older reply is ignored,
|
||||
/// including one that completes after this controller was disposed.
|
||||
Future<void> refresh() async {
|
||||
final generation = ++_generation;
|
||||
_loading = true;
|
||||
_failure = null;
|
||||
_notify();
|
||||
try {
|
||||
final schedules = await repository.listSchedules(pipelineId: pipelineId);
|
||||
if (!_owns(generation)) return;
|
||||
_schedules = List.unmodifiable(schedules);
|
||||
_invalidateVisibility();
|
||||
_loaded = true;
|
||||
} catch (error) {
|
||||
if (!_owns(generation)) return;
|
||||
_failure = ScheduleListFailure.from(error);
|
||||
} finally {
|
||||
if (_owns(generation)) {
|
||||
_loading = false;
|
||||
_notify();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool _owns(int generation) => !_disposed && generation == _generation;
|
||||
|
||||
void _notify() {
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import '../../domain/saved_schedule.dart';
|
||||
|
||||
/// User-facing values for one saved schedule row.
|
||||
///
|
||||
/// Every accessor reports what the server sent. A missing field keeps a
|
||||
/// distinct "unavailable"/"not scheduled" value instead of being invented.
|
||||
|
||||
String scheduleDisplayName(SavedSchedule schedule) {
|
||||
final name = schedule.name.trim();
|
||||
return name.isEmpty ? 'Unnamed schedule' : name;
|
||||
}
|
||||
|
||||
String scheduleStatusLabel(SavedSchedule schedule) =>
|
||||
schedule.enabled ? 'Enabled' : 'Paused';
|
||||
|
||||
String schedulePipelineVersionValue(SavedSchedule schedule) {
|
||||
final pipeline = schedule.pipelineId == null
|
||||
? 'Pipeline unavailable'
|
||||
: 'Pipeline ${schedule.pipelineId}';
|
||||
final version = schedule.version == null
|
||||
? 'Version unavailable'
|
||||
: 'v${schedule.version}';
|
||||
return '$pipeline · $version';
|
||||
}
|
||||
|
||||
String scheduleWorkspaceValue(SavedSchedule schedule) {
|
||||
final workspace = schedule.workspace.trim();
|
||||
return workspace.isEmpty ? 'Workspace unavailable' : workspace;
|
||||
}
|
||||
|
||||
String scheduleTimerValue(SavedSchedule schedule) {
|
||||
final rule = schedule.rule;
|
||||
final repeat = rule.every.isNotEmpty
|
||||
? 'Every ${rule.every}'
|
||||
: rule.times.isNotEmpty
|
||||
? rule.times.join(', ')
|
||||
: '';
|
||||
if (repeat.isEmpty) return 'Timer unavailable';
|
||||
return rule.days.isEmpty ? repeat : '$repeat · ${rule.days.join(', ')}';
|
||||
}
|
||||
|
||||
/// Matches the web client: an empty or `Local` rule timezone means the server
|
||||
/// applies its own timezone, which is not an absent value.
|
||||
String scheduleTimezoneValue(SavedSchedule schedule) {
|
||||
final timezone = schedule.rule.timezone.trim();
|
||||
return timezone.isEmpty || timezone == 'Local' ? 'Server timezone' : timezone;
|
||||
}
|
||||
|
||||
/// Paused schedules show the pause state, as in the current web client; enabled
|
||||
/// schedules show the server's `next_due` or an honest unavailable value.
|
||||
String scheduleNextDueValue(SavedSchedule schedule) {
|
||||
if (!schedule.enabled) return 'Paused';
|
||||
return scheduleDueValue(schedule.nextDue);
|
||||
}
|
||||
|
||||
String scheduleDueValue(String value) {
|
||||
if (value.isEmpty) return 'Not scheduled';
|
||||
final date = DateTime.tryParse(value);
|
||||
if (date == null) return 'Next time unavailable';
|
||||
final local = date.toLocal();
|
||||
String two(int part) => part.toString().padLeft(2, '0');
|
||||
return '${local.year.toString().padLeft(4, '0')}-${two(local.month)}-'
|
||||
'${two(local.day)} ${two(local.hour)}:${two(local.minute)} '
|
||||
'(your local time)';
|
||||
}
|
||||
|
||||
String scheduleCountLabel(int visible, int total) {
|
||||
if (visible != total) return '$visible of $total schedules';
|
||||
return total == 1 ? '1 schedule' : '$total schedules';
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../domain/saved_schedule.dart';
|
||||
import 'schedule_list_format.dart';
|
||||
|
||||
/// One tappable saved-schedule row with the server's actual values.
|
||||
class ScheduleListRow extends StatelessWidget {
|
||||
const ScheduleListRow({
|
||||
super.key,
|
||||
required this.schedule,
|
||||
required this.cupertino,
|
||||
required this.onOpen,
|
||||
});
|
||||
|
||||
final SavedSchedule schedule;
|
||||
final bool cupertino;
|
||||
final VoidCallback onOpen;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final content = Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(child: _details(context)),
|
||||
const SizedBox(width: 8),
|
||||
Icon(
|
||||
cupertino ? CupertinoIcons.chevron_right : Icons.chevron_right,
|
||||
color: _secondaryColor(context),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (cupertino) {
|
||||
return CupertinoButton(
|
||||
padding: EdgeInsets.zero,
|
||||
alignment: Alignment.centerLeft,
|
||||
onPressed: onOpen,
|
||||
child: content,
|
||||
);
|
||||
}
|
||||
return InkWell(onTap: onOpen, child: content);
|
||||
}
|
||||
|
||||
Widget _details(BuildContext context) {
|
||||
final prompt = schedule.prompt;
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
scheduleDisplayName(schedule),
|
||||
style: _titleStyle(context),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(scheduleStatusLabel(schedule), style: _statusStyle(context)),
|
||||
],
|
||||
),
|
||||
if (prompt.isNotEmpty) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(prompt, style: _bodyStyle(context)),
|
||||
],
|
||||
const SizedBox(height: 6),
|
||||
_meta(context, schedulePipelineVersionValue(schedule)),
|
||||
_meta(context, 'Workspace: ${scheduleWorkspaceValue(schedule)}'),
|
||||
_meta(context, 'Timer: ${scheduleTimerValue(schedule)}'),
|
||||
_meta(context, 'Timezone: ${scheduleTimezoneValue(schedule)}'),
|
||||
_meta(context, 'Next due: ${scheduleNextDueValue(schedule)}'),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _meta(BuildContext context, String value) =>
|
||||
Text(value, style: _metaStyle(context));
|
||||
|
||||
TextStyle? _titleStyle(BuildContext context) => cupertino
|
||||
? CupertinoTheme.of(
|
||||
context,
|
||||
).textTheme.textStyle.copyWith(fontWeight: FontWeight.w600)
|
||||
: Theme.of(
|
||||
context,
|
||||
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w600);
|
||||
|
||||
TextStyle? _bodyStyle(BuildContext context) =>
|
||||
cupertino ? CupertinoTheme.of(context).textTheme.textStyle : null;
|
||||
|
||||
TextStyle? _metaStyle(BuildContext context) => cupertino
|
||||
? CupertinoTheme.of(context).textTheme.textStyle.copyWith(
|
||||
fontSize: 14,
|
||||
color: _secondaryColor(context),
|
||||
)
|
||||
: Theme.of(
|
||||
context,
|
||||
).textTheme.bodySmall?.copyWith(color: _secondaryColor(context));
|
||||
|
||||
TextStyle? _statusStyle(BuildContext context) => _metaStyle(
|
||||
context,
|
||||
)?.copyWith(color: _statusColor(context), fontWeight: FontWeight.w600);
|
||||
|
||||
Color _secondaryColor(BuildContext context) => cupertino
|
||||
? CupertinoColors.secondaryLabel.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.onSurfaceVariant;
|
||||
|
||||
Color _statusColor(BuildContext context) => schedule.enabled
|
||||
? (cupertino
|
||||
? CupertinoTheme.of(context).primaryColor
|
||||
: Theme.of(context).colorScheme.primary)
|
||||
: _secondaryColor(context);
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'schedule_list_controller.dart';
|
||||
|
||||
const scheduleSearchFieldKey = ValueKey<String>('schedule-search-field');
|
||||
const scheduleFilterKey = ValueKey<String>('schedule-filter');
|
||||
const scheduleRefreshKey = ValueKey<String>('schedule-refresh');
|
||||
|
||||
/// Search, enabled filter and the read-only refresh control.
|
||||
class ScheduleListToolbar extends StatelessWidget {
|
||||
const ScheduleListToolbar({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.searchController,
|
||||
required this.cupertino,
|
||||
required this.onRefresh,
|
||||
});
|
||||
|
||||
final SchedulesController controller;
|
||||
final TextEditingController searchController;
|
||||
final bool cupertino;
|
||||
final VoidCallback onRefresh;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
|
||||
child: _search(context),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 480),
|
||||
child: _filter(context),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
_refresh(context),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (controller.hasLoaded)
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 4),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(controller.countLabel, style: _metaStyle(context)),
|
||||
Text(
|
||||
'Saved run configurations, not pipeline definitions.',
|
||||
style: _metaStyle(context),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _search(BuildContext context) {
|
||||
if (cupertino) {
|
||||
return CupertinoSearchTextField(
|
||||
key: scheduleSearchFieldKey,
|
||||
controller: searchController,
|
||||
placeholder: 'Search schedules',
|
||||
onChanged: controller.setQuery,
|
||||
onSuffixTap: () {
|
||||
searchController.clear();
|
||||
controller.clearQuery();
|
||||
},
|
||||
);
|
||||
}
|
||||
return TextField(
|
||||
key: scheduleSearchFieldKey,
|
||||
controller: searchController,
|
||||
onChanged: controller.setQuery,
|
||||
textInputAction: TextInputAction.search,
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Search schedules',
|
||||
prefixIcon: const Icon(Icons.search),
|
||||
suffixIcon: controller.query.isEmpty
|
||||
? null
|
||||
: IconButton(
|
||||
tooltip: 'Clear search',
|
||||
icon: const Icon(Icons.clear),
|
||||
onPressed: () {
|
||||
searchController.clear();
|
||||
controller.clearQuery();
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _filter(BuildContext context) {
|
||||
if (cupertino) {
|
||||
return CupertinoSlidingSegmentedControl<ScheduleListFilter>(
|
||||
key: scheduleFilterKey,
|
||||
groupValue: controller.filter,
|
||||
onValueChanged: (value) {
|
||||
if (value != null) controller.setFilter(value);
|
||||
},
|
||||
children: {
|
||||
for (final filter in ScheduleListFilter.values)
|
||||
filter: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
|
||||
child: Text(filter.label),
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
return SegmentedButton<ScheduleListFilter>(
|
||||
key: scheduleFilterKey,
|
||||
segments: [
|
||||
for (final filter in ScheduleListFilter.values)
|
||||
ButtonSegment<ScheduleListFilter>(
|
||||
value: filter,
|
||||
label: Text(filter.label),
|
||||
),
|
||||
],
|
||||
selected: {controller.filter},
|
||||
showSelectedIcon: false,
|
||||
onSelectionChanged: (selection) {
|
||||
if (selection.isNotEmpty) controller.setFilter(selection.first);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _refresh(BuildContext context) {
|
||||
if (controller.isLoading) {
|
||||
return Semantics(
|
||||
label: 'Refreshing schedules',
|
||||
liveRegion: true,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: cupertino
|
||||
? const CupertinoActivityIndicator()
|
||||
: const CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (cupertino) {
|
||||
return Semantics(
|
||||
label: 'Refresh schedules',
|
||||
child: CupertinoButton(
|
||||
key: scheduleRefreshKey,
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: onRefresh,
|
||||
child: const Icon(CupertinoIcons.refresh),
|
||||
),
|
||||
);
|
||||
}
|
||||
return IconButton(
|
||||
key: scheduleRefreshKey,
|
||||
tooltip: 'Refresh schedules',
|
||||
onPressed: onRefresh,
|
||||
icon: const Icon(Icons.refresh),
|
||||
);
|
||||
}
|
||||
|
||||
TextStyle? _metaStyle(BuildContext context) => cupertino
|
||||
? CupertinoTheme.of(context).textTheme.textStyle.copyWith(
|
||||
fontSize: 14,
|
||||
color: CupertinoColors.secondaryLabel.resolveFrom(context),
|
||||
)
|
||||
: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../domain/saved_schedule.dart';
|
||||
import 'schedule_list_controller.dart';
|
||||
import 'schedule_list_row.dart';
|
||||
import 'schedule_list_toolbar.dart';
|
||||
|
||||
const scheduleListKey = ValueKey<String>('schedule-list');
|
||||
const scheduleRetryKey = ValueKey<String>('schedule-retry');
|
||||
|
||||
/// Platform-adaptive list body. It owns no navigation chrome; the shell frames
|
||||
/// it as the Schedules destination.
|
||||
class SchedulesListView extends StatelessWidget {
|
||||
const SchedulesListView({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.searchController,
|
||||
required this.scrollController,
|
||||
required this.cupertino,
|
||||
required this.onOpen,
|
||||
required this.onRefresh,
|
||||
});
|
||||
|
||||
final SchedulesController controller;
|
||||
final TextEditingController searchController;
|
||||
final ScrollController scrollController;
|
||||
final bool cupertino;
|
||||
final ValueChanged<SavedSchedule> onOpen;
|
||||
final VoidCallback onRefresh;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
children: [
|
||||
ScheduleListToolbar(
|
||||
controller: controller,
|
||||
searchController: searchController,
|
||||
cupertino: cupertino,
|
||||
onRefresh: onRefresh,
|
||||
),
|
||||
Expanded(child: _body(context)),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _body(BuildContext context) {
|
||||
final failure = controller.failure;
|
||||
if (failure != null && controller.schedules.isEmpty) {
|
||||
return _failureState(context, failure);
|
||||
}
|
||||
if (controller.isInitialLoading) return _loadingState(context);
|
||||
if (controller.schedules.isEmpty) {
|
||||
return _emptyState('No schedules yet.');
|
||||
}
|
||||
final content = controller.visibleSchedules.isEmpty
|
||||
? _emptyState(controller.emptyMessage)
|
||||
: _list(context);
|
||||
// The banner slot is always present so a failed or recovered refresh does
|
||||
// not change the list's ancestors. Replacing the ListView would rebuild the
|
||||
// Scrollable and drop the user's scroll offset.
|
||||
return Column(
|
||||
children: [
|
||||
if (failure != null)
|
||||
_failureBanner(context, failure)
|
||||
else
|
||||
const SizedBox.shrink(),
|
||||
Expanded(child: content),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _list(BuildContext context) {
|
||||
final schedules = controller.visibleSchedules;
|
||||
return ListView.separated(
|
||||
key: scheduleListKey,
|
||||
controller: scrollController,
|
||||
padding: const EdgeInsets.only(top: 4, bottom: 24),
|
||||
itemCount: schedules.length,
|
||||
separatorBuilder: (context, index) =>
|
||||
cupertino ? _cupertinoSeparator(context) : const Divider(height: 1),
|
||||
itemBuilder: (context, index) {
|
||||
final schedule = schedules[index];
|
||||
return ScheduleListRow(
|
||||
key: ValueKey<String>(
|
||||
'schedule-row-$index-${schedule.id ?? 'unknown'}',
|
||||
),
|
||||
schedule: schedule,
|
||||
cupertino: cupertino,
|
||||
onOpen: () => onOpen(schedule),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _cupertinoSeparator(BuildContext context) => Container(
|
||||
height: 1 / MediaQuery.devicePixelRatioOf(context),
|
||||
color: CupertinoColors.separator.resolveFrom(context),
|
||||
);
|
||||
|
||||
Widget _loadingState(BuildContext context) {
|
||||
return Center(
|
||||
child: Semantics(
|
||||
liveRegion: true,
|
||||
label: 'Loading schedules',
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
cupertino
|
||||
? const CupertinoActivityIndicator()
|
||||
: const CircularProgressIndicator(),
|
||||
const SizedBox(height: 12),
|
||||
const Text('Loading schedules…'),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _emptyState(String message) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Text(message, textAlign: TextAlign.center),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _failureState(BuildContext context, ScheduleListFailure failure) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
_failureText(context, failure),
|
||||
const SizedBox(height: 16),
|
||||
_retryButton(),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _failureBanner(BuildContext context, ScheduleListFailure failure) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(child: _failureText(context, failure)),
|
||||
const SizedBox(width: 8),
|
||||
_retryButton(),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _failureText(BuildContext context, ScheduleListFailure failure) {
|
||||
final color = cupertino
|
||||
? CupertinoColors.systemRed.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.error;
|
||||
return Semantics(
|
||||
liveRegion: true,
|
||||
child: Text(
|
||||
failure.message,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(color: color),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _retryButton() {
|
||||
if (cupertino) {
|
||||
return CupertinoButton(
|
||||
key: scheduleRetryKey,
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: onRefresh,
|
||||
child: const Text('Retry'),
|
||||
);
|
||||
}
|
||||
return TextButton(
|
||||
key: scheduleRetryKey,
|
||||
onPressed: onRefresh,
|
||||
child: const Text('Retry'),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/search_models.dart';
|
||||
|
||||
/// Search protocol requests over the application's shared gateway.
|
||||
///
|
||||
/// The request body is exactly `SearchRequest{query, kind, limit}` with
|
||||
/// `limit: 0`, so the server applies its own default cap (`SearchDefaultLimit`,
|
||||
/// 50) instead of the client choosing a larger one.
|
||||
class SearchRepository {
|
||||
SearchRepository(this._gateway);
|
||||
|
||||
final ApiGateway _gateway;
|
||||
|
||||
/// Returns the bounded `search_results` body, or null when an older server
|
||||
/// answered without it (its default `pong`) so the caller can report the
|
||||
/// "cannot search" sentence rather than showing a false empty success.
|
||||
Future<SearchResponse?> search({
|
||||
required String query,
|
||||
required SearchKind kind,
|
||||
}) async {
|
||||
final reply = await _gateway.call('search', {
|
||||
'search': {'query': query, 'kind': kind.wire, 'limit': 0},
|
||||
});
|
||||
final results = reply['search_results'];
|
||||
if (results is! Map) return null;
|
||||
return SearchResponse.fromJson(Map<String, dynamic>.from(results));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../data/search_repository.dart';
|
||||
import 'search_models.dart';
|
||||
import 'search_query.dart';
|
||||
import 'search_row.dart';
|
||||
|
||||
/// The body the results area shows, in the browser's precedence order: an error
|
||||
/// takes precedence over retained results, a refresh keeps results on screen,
|
||||
/// and a first load shows the searching row.
|
||||
enum SearchBodyKind { idle, searching, results, empty, error }
|
||||
|
||||
/// Debounced, stale-safe omni-search state. It owns no widgets and no socket:
|
||||
/// the screen listens to it and the repository talks to the shared gateway.
|
||||
class OmniSearchController extends ChangeNotifier {
|
||||
OmniSearchController({
|
||||
required this.repository,
|
||||
this.debounce = const Duration(milliseconds: 250),
|
||||
});
|
||||
|
||||
final SearchRepository repository;
|
||||
final Duration debounce;
|
||||
final SearchSequencer _sequencer = SearchSequencer();
|
||||
|
||||
Timer? _timer;
|
||||
bool _disposed = false;
|
||||
|
||||
String _query = '';
|
||||
SearchKind _selectedKind = SearchKind.all;
|
||||
List<JsonMap> _results = const [];
|
||||
bool _loading = false;
|
||||
bool _loaded = false;
|
||||
bool _truncated = false;
|
||||
int _scannedSteps = 0;
|
||||
int _scannedBytes = 0;
|
||||
int _cap = 0;
|
||||
int _scanBoundBytes = 0;
|
||||
String? _error;
|
||||
|
||||
String get query => _query;
|
||||
SearchKind get selectedKind => _selectedKind;
|
||||
ParsedSearchQuery get parsed => parseSearchQuery(_query, _selectedKind);
|
||||
List<JsonMap> get results => _results;
|
||||
bool get loading => _loading;
|
||||
bool get loaded => _loaded;
|
||||
bool get truncated => _truncated;
|
||||
int get scannedSteps => _scannedSteps;
|
||||
int get scannedBytes => _scannedBytes;
|
||||
int get cap => _cap;
|
||||
int get scanBoundBytes => _scanBoundBytes;
|
||||
String? get error => _error;
|
||||
|
||||
/// The results already in hand, re-narrowed to the effective kind so the list
|
||||
/// always matches the control while a narrowed request loads.
|
||||
List<JsonMap> get shownResults {
|
||||
final kind = parsed.kind;
|
||||
if (kind == SearchKind.all) return _results;
|
||||
return _results
|
||||
.where((hit) => hit['kind'] == kind.wire)
|
||||
.toList(growable: false);
|
||||
}
|
||||
|
||||
SearchBodyKind get bodyKind {
|
||||
if (_error != null) return SearchBodyKind.error;
|
||||
if (shownResults.isNotEmpty) return SearchBodyKind.results;
|
||||
if (_loading && _results.isEmpty) return SearchBodyKind.searching;
|
||||
if (emptyMessage != null) return SearchBodyKind.empty;
|
||||
return SearchBodyKind.idle;
|
||||
}
|
||||
|
||||
/// A thin progress report above retained results while a newer query loads.
|
||||
bool get showProgress => _loading && _results.isNotEmpty;
|
||||
|
||||
String? get emptyMessage {
|
||||
if (_error != null || _loading || shownResults.isNotEmpty) return null;
|
||||
final effective = parsed;
|
||||
if (effective.query.trim().isEmpty) {
|
||||
if (!_loaded || effective.kind == SearchKind.all) return null;
|
||||
final label = effective.kind.label.toLowerCase();
|
||||
return _truncated
|
||||
? "No $label found within the server's scan limit."
|
||||
: 'No $label yet.';
|
||||
}
|
||||
final bounded = _truncated ? " within the server's scan limit" : '';
|
||||
if (effective.kind == SearchKind.all) {
|
||||
return 'No matches for "${effective.query}"$bounded.';
|
||||
}
|
||||
return 'No ${effective.kind.label.toLowerCase()} match '
|
||||
'"${effective.query}"$bounded.';
|
||||
}
|
||||
|
||||
/// The server's own result/scan bounds, so a capped answer is not presented as
|
||||
/// a complete one. A truncated reply keeps its warning even with no rows;
|
||||
/// before any loaded reply there is nothing to report.
|
||||
String? get boundsText {
|
||||
if (!_loaded) return null;
|
||||
// A new first load has no current result set yet, so do not carry the
|
||||
// previous reply's warning while the searching state is on screen.
|
||||
if (_loading && _results.isEmpty) return null;
|
||||
if (_results.isEmpty && !_truncated) return null;
|
||||
final count = _results.length;
|
||||
final parts = <String>[];
|
||||
if (_truncated) {
|
||||
parts.add("Results truncated by the server's result or scan limit.");
|
||||
}
|
||||
parts.add('$count ${count == 1 ? 'result' : 'results'}');
|
||||
if (_cap > 0) parts.add('cap $_cap');
|
||||
parts.add('scanned $_scannedSteps steps');
|
||||
parts.add('${humanBytes(_scannedBytes)} scanned');
|
||||
if (_scanBoundBytes > 0) {
|
||||
parts.add('scan limit ${humanBytes(_scanBoundBytes)}');
|
||||
}
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
/// Record a keystroke. Blank text with no kind clears locally and sends
|
||||
/// nothing; valid kind-only browsing is sendable like the browser's search.
|
||||
void updateQuery(String value) {
|
||||
_query = value;
|
||||
_error = null;
|
||||
_cancelTimer();
|
||||
final effective = parsed;
|
||||
if (!searchQuerySendable(effective.query, effective.kind)) {
|
||||
_sequencer.edit('');
|
||||
_clearResults();
|
||||
_notify();
|
||||
return;
|
||||
}
|
||||
_loading = true;
|
||||
final edit = _sequencer.edit(value);
|
||||
_notify();
|
||||
_timer = Timer(debounce, () {
|
||||
_timer = null;
|
||||
final sent = _sequencer.begin(edit);
|
||||
if (sent != null) unawaited(_send(sent));
|
||||
});
|
||||
}
|
||||
|
||||
/// A kind change removes recognised type tokens from the visible text and
|
||||
/// sends at once, matching the browser's selector behaviour.
|
||||
void selectKind(SearchKind kind) {
|
||||
_query = parseSearchQuery(_query, _selectedKind).query;
|
||||
_selectedKind = kind;
|
||||
_error = null;
|
||||
_notify();
|
||||
unawaited(sendNow());
|
||||
}
|
||||
|
||||
/// Enter: send the current query immediately, skipping the debounce.
|
||||
Future<void> submit() => sendNow();
|
||||
|
||||
/// Retry the current query after a failure.
|
||||
Future<void> retry() => sendNow();
|
||||
|
||||
Future<void> sendNow() async {
|
||||
_cancelTimer();
|
||||
final effective = parseSearchQuery(_query, _selectedKind);
|
||||
if (!searchQuerySendable(effective.query, effective.kind)) {
|
||||
_sequencer.edit('');
|
||||
_clearResults();
|
||||
_notify();
|
||||
return;
|
||||
}
|
||||
final sent = _sequencer.begin(_sequencer.edit(_query));
|
||||
if (sent == null) return;
|
||||
await _send(sent);
|
||||
}
|
||||
|
||||
Future<void> _send(SearchEdit sent) async {
|
||||
final effective = parseSearchQuery(sent.query, _selectedKind);
|
||||
_loading = true;
|
||||
_error = null;
|
||||
_notify();
|
||||
try {
|
||||
final response = await repository.search(
|
||||
query: effective.query.trim(),
|
||||
kind: effective.kind,
|
||||
);
|
||||
if (!_sequencer.accepts(sent.token) || _disposed) return;
|
||||
if (response == null) {
|
||||
_loading = false;
|
||||
_loaded = true;
|
||||
_error = unsupportedSearchCopy;
|
||||
_notify();
|
||||
return;
|
||||
}
|
||||
_results = response.results;
|
||||
_truncated = response.truncated;
|
||||
_scannedSteps = response.scannedSteps;
|
||||
_scannedBytes = response.scannedBytes;
|
||||
_cap = response.cap;
|
||||
_scanBoundBytes = response.scanBoundBytes;
|
||||
_loading = false;
|
||||
_loaded = true;
|
||||
_error = null;
|
||||
_notify();
|
||||
} catch (error) {
|
||||
if (!_sequencer.accepts(sent.token) || _disposed) return;
|
||||
_loading = false;
|
||||
_loaded = true;
|
||||
_error = searchFailureText(error);
|
||||
_notify();
|
||||
}
|
||||
}
|
||||
|
||||
void _clearResults() {
|
||||
_results = const [];
|
||||
_truncated = false;
|
||||
_scannedSteps = 0;
|
||||
_scannedBytes = 0;
|
||||
_cap = 0;
|
||||
_scanBoundBytes = 0;
|
||||
_loading = false;
|
||||
_loaded = false;
|
||||
_error = null;
|
||||
}
|
||||
|
||||
void _cancelTimer() {
|
||||
_timer?.cancel();
|
||||
_timer = null;
|
||||
}
|
||||
|
||||
void _notify() {
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
_cancelTimer();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/// Human bytes with the shared binary units (`2.0 KiB`), matching the browser.
|
||||
String humanBytes(int size) {
|
||||
const unit = 1024;
|
||||
if (size < unit) return '$size B';
|
||||
var divisor = unit;
|
||||
var exponent = 0;
|
||||
var scaled = size ~/ unit;
|
||||
while (scaled >= unit && exponent < 5) {
|
||||
divisor *= unit;
|
||||
exponent++;
|
||||
scaled ~/= unit;
|
||||
}
|
||||
return '${(size / divisor).toStringAsFixed(1)} ${'KMGTPE'[exponent]}iB';
|
||||
}
|
||||
|
||||
const _months = [
|
||||
'Jan',
|
||||
'Feb',
|
||||
'Mar',
|
||||
'Apr',
|
||||
'May',
|
||||
'Jun',
|
||||
'Jul',
|
||||
'Aug',
|
||||
'Sep',
|
||||
'Oct',
|
||||
'Nov',
|
||||
'Dec',
|
||||
];
|
||||
|
||||
/// An RFC3339 timestamp as the app's one human local rendering (`20 Oct 12:00`),
|
||||
/// or null when blank/unparseable so the caller omits the value rather than
|
||||
/// printing a blank.
|
||||
String? formatSearchTimestamp(String value) {
|
||||
final text = value.trim();
|
||||
if (text.isEmpty) return null;
|
||||
final instant = DateTime.tryParse(text);
|
||||
if (instant == null) return null;
|
||||
final local = instant.toLocal();
|
||||
final hour = local.hour.toString().padLeft(2, '0');
|
||||
final minute = local.minute.toString().padLeft(2, '0');
|
||||
return '${local.day} ${_months[local.month - 1]} $hour:$minute';
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
/// The server's search narrowing vocabulary (`internal/protocol/search.go`),
|
||||
/// in the control's display order. The empty [wire] value means every kind.
|
||||
enum SearchKind {
|
||||
all('', 'All kinds'),
|
||||
pipeline('pipeline', 'Pipelines'),
|
||||
run('run', 'Runs'),
|
||||
step('step', 'Steps'),
|
||||
field('field', 'Fields'),
|
||||
artifact('artifact', 'Artifacts'),
|
||||
version('version', 'Versions');
|
||||
|
||||
const SearchKind(this.wire, this.label);
|
||||
|
||||
final String wire;
|
||||
final String label;
|
||||
|
||||
/// A stale or unknown value falls back to [SearchKind.all] rather than
|
||||
/// inventing an option the server does not accept.
|
||||
static SearchKind fromWire(String? wire) {
|
||||
for (final kind in values) {
|
||||
if (kind.wire == wire) return kind;
|
||||
}
|
||||
return SearchKind.all;
|
||||
}
|
||||
}
|
||||
|
||||
/// A query after `t:`/`type:` tokens have been recognised. [query] is the text
|
||||
/// the server should match; [kind] is the effective narrowing.
|
||||
class ParsedSearchQuery {
|
||||
const ParsedSearchQuery(this.query, this.kind, this.hasType);
|
||||
|
||||
final String query;
|
||||
final SearchKind kind;
|
||||
final bool hasType;
|
||||
}
|
||||
|
||||
/// The bounded `search_results` body from the server. Every bound the server
|
||||
/// reports is kept, so the screen can show a truncation/scan indicator instead
|
||||
/// of pretending a capped reply was complete.
|
||||
class SearchResponse {
|
||||
const SearchResponse({
|
||||
this.query = '',
|
||||
this.kind = SearchKind.all,
|
||||
this.results = const [],
|
||||
this.truncated = false,
|
||||
this.scannedSteps = 0,
|
||||
this.scannedBytes = 0,
|
||||
this.cap = 0,
|
||||
this.scanBoundBytes = 0,
|
||||
});
|
||||
|
||||
factory SearchResponse.fromJson(JsonMap json) {
|
||||
final rows = json['results'];
|
||||
return SearchResponse(
|
||||
query: '${json['query'] ?? ''}',
|
||||
kind: SearchKind.fromWire('${json['kind'] ?? ''}'),
|
||||
results: rows is List
|
||||
? rows
|
||||
.whereType<Map>()
|
||||
.map((row) => Map<String, dynamic>.from(row))
|
||||
.toList(growable: false)
|
||||
: const [],
|
||||
truncated: json['truncated'] == true,
|
||||
scannedSteps: _integer(json['scanned_steps']),
|
||||
scannedBytes: _integer(json['scanned_bytes']),
|
||||
cap: _integer(json['cap']),
|
||||
scanBoundBytes: _integer(json['scan_bound_bytes']),
|
||||
);
|
||||
}
|
||||
|
||||
final String query;
|
||||
final SearchKind kind;
|
||||
final List<JsonMap> results;
|
||||
final bool truncated;
|
||||
final int scannedSteps;
|
||||
final int scannedBytes;
|
||||
final int cap;
|
||||
final int scanBoundBytes;
|
||||
}
|
||||
|
||||
int _integer(Object? value) {
|
||||
if (value is int) return value;
|
||||
if (value is num) return value.toInt();
|
||||
return int.tryParse('$value') ?? 0;
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import 'search_models.dart';
|
||||
|
||||
/// Wording for a server that cannot answer `search`: an explicit rejection
|
||||
/// naming an unknown/unsupported command, or a reply without
|
||||
/// `search_results`. Kept verbatim from the web client's AppViewModel copy.
|
||||
const unsupportedSearchCopy =
|
||||
'This server does not support search. Update the Pipelines server, then try again.';
|
||||
|
||||
/// Unquoted, whitespace-delimited `t:`/`type:` tokens; the last supported token
|
||||
/// wins. Unknown tokens and quoted text stay literal, including their whitespace.
|
||||
/// The selector is a fallback; explicitly changing it removes tokens in the view.
|
||||
///
|
||||
/// This is the same token grammar as `web/src/search.js`, so `"t:run"`,
|
||||
/// `t:unknown`, `prefix"t:run"` and `\t:run` all remain searchable text.
|
||||
ParsedSearchQuery parseSearchQuery(
|
||||
String value, [
|
||||
SearchKind selectedKind = SearchKind.all,
|
||||
]) {
|
||||
var kind = selectedKind;
|
||||
var hasType = false;
|
||||
final query = value.replaceAllMapped(_tokenPattern, (match) {
|
||||
final token = match[0] ?? '';
|
||||
final type = _typePattern.firstMatch(token);
|
||||
if (type == null) return token;
|
||||
final candidate = SearchKind.fromWire(type.group(1)!.toLowerCase());
|
||||
if (candidate == SearchKind.all) return token;
|
||||
kind = candidate;
|
||||
hasType = true;
|
||||
return '';
|
||||
});
|
||||
return ParsedSearchQuery(query, kind, hasType);
|
||||
}
|
||||
|
||||
final _tokenPattern = RegExp(
|
||||
r'''(?:[^\s"'\\]|\\[\s\S]|"(?:[^"\\]|\\[\s\S])*(?:"|$)|'(?:[^'\\]|\\[\s\S])*(?:'|$))+''',
|
||||
);
|
||||
final _typePattern = RegExp(r'^(?:t|type):([a-z]+)$', caseSensitive: false);
|
||||
|
||||
/// Text searches and valid kind-only browsing are sendable. Empty text with no
|
||||
/// supported kind clears locally, without an all-kind scan.
|
||||
bool searchQuerySendable(String query, SearchKind kind) =>
|
||||
query.trim().isNotEmpty || kind != SearchKind.all;
|
||||
|
||||
/// The message for a failed search: the unsupported sentence for a missing
|
||||
/// payload or an unknown-command rejection, otherwise the server's own text.
|
||||
String searchFailureText(Object? error) {
|
||||
if (error == null) return unsupportedSearchCopy;
|
||||
final message = error.toString().trim();
|
||||
if (message.isEmpty) return unsupportedSearchCopy;
|
||||
if (_unsupportedCommand.hasMatch(message)) return unsupportedSearchCopy;
|
||||
return message;
|
||||
}
|
||||
|
||||
final _unsupportedCommand = RegExp(
|
||||
r'\b(unknown|unsupported|unrecognised|unrecognized)\b[\s\S]*\bcommand\b',
|
||||
caseSensitive: false,
|
||||
);
|
||||
|
||||
/// One recorded edit being debounced.
|
||||
class SearchEdit {
|
||||
const SearchEdit(this.token, this.query);
|
||||
|
||||
final int token;
|
||||
final String query;
|
||||
}
|
||||
|
||||
/// Query sequencing: a burst of keystrokes collapses into one request, and a
|
||||
/// reply is accepted only for the newest recorded edit, so a stale reply can
|
||||
/// never overwrite a newer one. Recording an edit (a keystroke, or an empty
|
||||
/// edit when the field clears) is enough to invalidate an in-flight reply.
|
||||
class SearchSequencer {
|
||||
int _newest = 0;
|
||||
|
||||
SearchEdit edit(String query) => SearchEdit(++_newest, query);
|
||||
|
||||
SearchEdit? begin(SearchEdit? edit) {
|
||||
if (edit == null || edit.token != _newest) return null;
|
||||
return edit;
|
||||
}
|
||||
|
||||
bool accepts(int token) => token == _newest;
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'search_format.dart';
|
||||
|
||||
export 'search_format.dart' show humanBytes, formatSearchTimestamp;
|
||||
|
||||
/// One run of a field snippet, split so the first case-insensitive occurrence of
|
||||
/// the query can be emphasised without colour or markup.
|
||||
class SearchSnippetSpan {
|
||||
const SearchSnippetSpan(this.text, {required this.matched});
|
||||
|
||||
final String text;
|
||||
final bool matched;
|
||||
}
|
||||
|
||||
/// A render-ready search row. [target] is the server's own stable target token;
|
||||
/// it is null for an unknown/absent payload or a reply without a target, and
|
||||
/// such a row is read-only — the client never guesses a route.
|
||||
class SearchRowView {
|
||||
const SearchRowView({
|
||||
required this.title,
|
||||
required this.secondary,
|
||||
required this.kindLabel,
|
||||
required this.snippetSpans,
|
||||
required this.target,
|
||||
this.snippet,
|
||||
this.recency,
|
||||
});
|
||||
|
||||
final String title;
|
||||
final String secondary;
|
||||
final String kindLabel;
|
||||
final String? snippet;
|
||||
final List<SearchSnippetSpan> snippetSpans;
|
||||
final String? recency;
|
||||
final String? target;
|
||||
|
||||
bool get openable => target != null;
|
||||
}
|
||||
|
||||
/// One rendered search row, mirroring the browser's per-kind row text. Every
|
||||
/// server-provided string is only ever compared or rendered as text.
|
||||
SearchRowView searchRowView(JsonMap hit, String query) {
|
||||
final pipeline = _map(hit['pipeline']);
|
||||
final version = _map(hit['version']);
|
||||
final run = _map(hit['run']);
|
||||
final step = _map(hit['step']);
|
||||
final field = _map(hit['field']);
|
||||
final artifact = _map(hit['artifact']);
|
||||
|
||||
final recency = formatSearchTimestamp('${hit['recency'] ?? ''}');
|
||||
final target = _serverTarget(hit);
|
||||
|
||||
if (pipeline != null) {
|
||||
return SearchRowView(
|
||||
title: _nonBlank(pipeline['name']) ?? 'pipeline ${_num(pipeline['id'])}',
|
||||
secondary:
|
||||
'pipeline ${_num(pipeline['id'])} · v${_num(pipeline['version'])}'
|
||||
' · ${_stageCount(pipeline['stages'])}',
|
||||
kindLabel: 'Pipeline',
|
||||
snippetSpans: const [],
|
||||
recency: recency,
|
||||
target: target,
|
||||
);
|
||||
}
|
||||
if (version != null) {
|
||||
final hash = _nonBlank(version['content_hash']);
|
||||
return SearchRowView(
|
||||
title:
|
||||
'pipeline ${_num(version['pipeline_id'])}'
|
||||
' · v${_num(version['version'])}',
|
||||
secondary: _join([
|
||||
hash == null ? null : 'content $hash',
|
||||
formatSearchTimestamp('${version['created_at'] ?? ''}'),
|
||||
]),
|
||||
kindLabel: 'Pipeline version',
|
||||
snippetSpans: const [],
|
||||
recency: recency,
|
||||
target: target,
|
||||
);
|
||||
}
|
||||
if (run != null) {
|
||||
final name = _nonBlank(run['pipeline_name']);
|
||||
return SearchRowView(
|
||||
title: 'run #${_num(run['id'])}${name == null ? '' : ' · $name'}',
|
||||
secondary: _join([
|
||||
_nonBlank(run['status']),
|
||||
_nonBlank(run['workspace']),
|
||||
formatSearchTimestamp('${run['created_at'] ?? ''}'),
|
||||
]),
|
||||
kindLabel: 'Run',
|
||||
snippetSpans: const [],
|
||||
recency: recency,
|
||||
target: target,
|
||||
);
|
||||
}
|
||||
if (step != null) {
|
||||
final stage = _nonBlank(step['stage']) ?? 'step';
|
||||
return SearchRowView(
|
||||
title:
|
||||
'run #${_num(step['run_id'])} · $stage'
|
||||
' visit ${_num(step['visit'])}',
|
||||
secondary: _stepSecondary(step),
|
||||
kindLabel: 'Step',
|
||||
snippetSpans: const [],
|
||||
recency: recency,
|
||||
target: target,
|
||||
);
|
||||
}
|
||||
if (field != null) {
|
||||
final snippet = '${field['snippet'] ?? ''}';
|
||||
return SearchRowView(
|
||||
title:
|
||||
'run #${_num(field['run_id'])} · step ${_num(field['sequence'])}'
|
||||
' · ${_nonBlank(field['field']) ?? 'field'}',
|
||||
secondary: snippet,
|
||||
kindLabel: 'Field',
|
||||
snippet: snippet,
|
||||
snippetSpans: snippetSpans(snippet, query),
|
||||
recency: recency,
|
||||
target: target,
|
||||
);
|
||||
}
|
||||
if (artifact != null) {
|
||||
return SearchRowView(
|
||||
title: _nonBlank(artifact['name']) ?? 'artifact',
|
||||
secondary: _join([
|
||||
'run #${_num(artifact['run_id'])}',
|
||||
'step ${_num(artifact['sequence'])}',
|
||||
_nonBlank(artifact['content_type']),
|
||||
humanBytes(_num(artifact['size_bytes'])),
|
||||
]),
|
||||
kindLabel: 'Artifact',
|
||||
snippetSpans: const [],
|
||||
recency: recency,
|
||||
target: target,
|
||||
);
|
||||
}
|
||||
final kind = _nonBlank(hit['kind']);
|
||||
return SearchRowView(
|
||||
title: _nonBlank(hit['target']) ?? 'Unrecognised result',
|
||||
secondary: kind == null ? 'read-only' : 'kind "$kind" · read-only',
|
||||
kindLabel: 'Unrecognised result',
|
||||
snippetSpans: const [],
|
||||
recency: recency,
|
||||
target: target,
|
||||
);
|
||||
}
|
||||
|
||||
/// Splits [snippet] so the first case-insensitive occurrence of [query] is a
|
||||
/// distinct matched span. A blank query or absent match leaves the whole
|
||||
/// snippet unmatched, so no text is ever dropped.
|
||||
List<SearchSnippetSpan> snippetSpans(String snippet, String query) {
|
||||
if (snippet.isEmpty) return const [];
|
||||
final needle = query.trim();
|
||||
if (needle.isEmpty) {
|
||||
return [SearchSnippetSpan(snippet, matched: false)];
|
||||
}
|
||||
final index = snippet.toLowerCase().indexOf(needle.toLowerCase());
|
||||
if (index < 0) return [SearchSnippetSpan(snippet, matched: false)];
|
||||
final end = index + needle.length;
|
||||
return [
|
||||
if (index > 0)
|
||||
SearchSnippetSpan(snippet.substring(0, index), matched: false),
|
||||
SearchSnippetSpan(snippet.substring(index, end), matched: true),
|
||||
if (end < snippet.length)
|
||||
SearchSnippetSpan(snippet.substring(end), matched: false),
|
||||
];
|
||||
}
|
||||
|
||||
String _stepSecondary(JsonMap step) {
|
||||
final diagnostic = '${step['diagnostic'] ?? ''}';
|
||||
String? line;
|
||||
for (final candidate in diagnostic.split(RegExp(r'\r?\n'))) {
|
||||
if (candidate.trim().isNotEmpty) {
|
||||
line = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
final target = _nonBlank(step['target']);
|
||||
final joined = _join([
|
||||
_nonBlank(step['outcome']),
|
||||
target == null ? null : '→ $target',
|
||||
line?.trim(),
|
||||
]);
|
||||
return joined.isEmpty ? 'step ${_num(step['sequence'])}' : joined;
|
||||
}
|
||||
|
||||
/// The server's own target token, never a target the client invents. A known
|
||||
/// payload is not enough: an absent token makes the row read-only.
|
||||
String? _serverTarget(JsonMap hit) {
|
||||
final target = _nonBlank(hit['target']);
|
||||
if (target == null) return null;
|
||||
final known = [
|
||||
'pipeline',
|
||||
'version',
|
||||
'run',
|
||||
'step',
|
||||
'field',
|
||||
'artifact',
|
||||
].any((key) => _map(hit[key]) != null);
|
||||
return known ? target : null;
|
||||
}
|
||||
|
||||
String _stageCount(Object? count) {
|
||||
final n = _num(count);
|
||||
return '$n ${n == 1 ? 'stage' : 'stages'}';
|
||||
}
|
||||
|
||||
Map<String, dynamic>? _map(Object? value) {
|
||||
if (value is! Map) return null;
|
||||
return Map<String, dynamic>.from(value);
|
||||
}
|
||||
|
||||
String? _nonBlank(Object? value) {
|
||||
final text = '${value ?? ''}';
|
||||
return text.trim().isEmpty ? null : text;
|
||||
}
|
||||
|
||||
int _num(Object? value) {
|
||||
if (value is int) return value;
|
||||
if (value is num) return value.toInt();
|
||||
return int.tryParse('${value ?? ''}') ?? 0;
|
||||
}
|
||||
|
||||
String _join(List<String?> parts) =>
|
||||
parts.whereType<String>().where((part) => part.isNotEmpty).join(' · ');
|
||||
@@ -0,0 +1,228 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/api_gateway.dart';
|
||||
import 'data/search_repository.dart';
|
||||
import 'domain/search_controller.dart';
|
||||
import 'domain/search_models.dart';
|
||||
import 'ui/cupertino_search_body.dart';
|
||||
import 'ui/material_search_body.dart';
|
||||
|
||||
/// Native omni-search over the Pipelines server: a standard search field, an
|
||||
/// explicit kind selector, and a flat result list whose rows open the server's
|
||||
/// own target through [onOpen]. The screen never mutates server state and never
|
||||
/// guesses a route for an unknown or targetless hit.
|
||||
class SearchScreen extends StatefulWidget {
|
||||
const SearchScreen({
|
||||
super.key,
|
||||
required this.gateway,
|
||||
required this.onOpen,
|
||||
this.cupertino,
|
||||
});
|
||||
|
||||
final ApiGateway gateway;
|
||||
final ValueChanged<JsonMap> onOpen;
|
||||
|
||||
/// Lets the shell state the surface it composed. When omitted, iOS/macOS use
|
||||
/// Cupertino controls and every other platform uses Material.
|
||||
final bool? cupertino;
|
||||
|
||||
@override
|
||||
State<SearchScreen> createState() => _SearchScreenState();
|
||||
}
|
||||
|
||||
class _SearchScreenState extends State<SearchScreen> {
|
||||
late final OmniSearchController _controller;
|
||||
late final TextEditingController _text;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller = OmniSearchController(
|
||||
repository: SearchRepository(widget.gateway),
|
||||
);
|
||||
_text = TextEditingController();
|
||||
_controller.addListener(_onState);
|
||||
}
|
||||
|
||||
void _onState() {
|
||||
final query = _controller.query;
|
||||
if (_text.text != query) {
|
||||
_text.value = TextEditingValue(
|
||||
text: query,
|
||||
selection: TextSelection.collapsed(offset: query.length),
|
||||
);
|
||||
}
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
|
||||
void _clear() {
|
||||
_text.clear();
|
||||
_controller.updateQuery('');
|
||||
}
|
||||
|
||||
void _selectKind(SearchKind kind) => _controller.selectKind(kind);
|
||||
|
||||
bool get _showHint {
|
||||
final body = _controller.bodyKind;
|
||||
return body == SearchBodyKind.idle || body == SearchBodyKind.empty;
|
||||
}
|
||||
|
||||
Future<void> _pickKind(BuildContext context) async {
|
||||
final selected = await showCupertinoModalPopup<SearchKind>(
|
||||
context: context,
|
||||
builder: (context) => CupertinoActionSheet(
|
||||
title: const Text('Kind'),
|
||||
actions: [
|
||||
for (final kind in SearchKind.values)
|
||||
CupertinoActionSheetAction(
|
||||
onPressed: () => Navigator.pop(context, kind),
|
||||
isDefaultAction: kind == _controller.parsed.kind,
|
||||
child: Text(kind.label),
|
||||
),
|
||||
],
|
||||
cancelButton: CupertinoActionSheetAction(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (selected != null) _selectKind(selected);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.removeListener(_onState);
|
||||
_controller.dispose();
|
||||
_text.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final cupertino =
|
||||
widget.cupertino ??
|
||||
switch (Theme.of(context).platform) {
|
||||
TargetPlatform.iOS || TargetPlatform.macOS => true,
|
||||
_ => false,
|
||||
};
|
||||
return cupertino ? _cupertinoScreen() : _materialScreen();
|
||||
}
|
||||
|
||||
Widget _materialScreen() => Scaffold(
|
||||
appBar: AppBar(title: const Text('Search')),
|
||||
body: SafeArea(
|
||||
child: MaterialSearchBody(
|
||||
controller: _controller,
|
||||
query: _controller.parsed.query,
|
||||
onOpen: widget.onOpen,
|
||||
header: _materialHeader(),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
Widget _materialHeader() => Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
spacing: 8,
|
||||
children: [
|
||||
SearchBar(
|
||||
key: const ValueKey('search.field'),
|
||||
controller: _text,
|
||||
autoFocus: true,
|
||||
hintText: 'Search pipelines, runs and artifacts',
|
||||
leading: const Icon(Icons.search),
|
||||
trailing: [
|
||||
if (_text.text.isNotEmpty)
|
||||
IconButton(
|
||||
key: const ValueKey('search.clear'),
|
||||
onPressed: _clear,
|
||||
tooltip: 'Clear search',
|
||||
icon: const Icon(Icons.close),
|
||||
),
|
||||
],
|
||||
textInputAction: TextInputAction.search,
|
||||
onChanged: _controller.updateQuery,
|
||||
onSubmitted: (_) => _controller.submit(),
|
||||
),
|
||||
InputDecorator(
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Kind',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
child: DropdownButtonHideUnderline(
|
||||
child: DropdownButton<SearchKind>(
|
||||
key: const ValueKey('search.kind'),
|
||||
value: _controller.parsed.kind,
|
||||
isExpanded: true,
|
||||
onChanged: (kind) {
|
||||
if (kind != null) _selectKind(kind);
|
||||
},
|
||||
items: [
|
||||
for (final kind in SearchKind.values)
|
||||
DropdownMenuItem(value: kind, child: Text(kind.label)),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
if (_showHint) const Text(_tokenHint),
|
||||
if (_controller.boundsText case final bounds?) Text(bounds),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
Widget _cupertinoScreen() => CupertinoPageScaffold(
|
||||
navigationBar: const CupertinoNavigationBar(middle: Text('Search')),
|
||||
child: SafeArea(
|
||||
child: CupertinoSearchBody(
|
||||
controller: _controller,
|
||||
query: _controller.parsed.query,
|
||||
onOpen: widget.onOpen,
|
||||
header: _cupertinoHeader(context),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
Widget _cupertinoHeader(BuildContext context) => Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
spacing: 8,
|
||||
children: [
|
||||
CupertinoSearchTextField(
|
||||
key: const ValueKey('search.field'),
|
||||
controller: _text,
|
||||
autofocus: true,
|
||||
placeholder: 'Search pipelines, runs and artifacts',
|
||||
onChanged: _controller.updateQuery,
|
||||
onSubmitted: (_) => _controller.submit(),
|
||||
onSuffixTap: _clear,
|
||||
),
|
||||
Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: CupertinoButton(
|
||||
key: const ValueKey('search.kind'),
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: () => _pickKind(context),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.max,
|
||||
spacing: 6,
|
||||
children: [
|
||||
Expanded(child: Text('Kind: ${_controller.parsed.kind.label}')),
|
||||
const Icon(CupertinoIcons.chevron_down),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
if (_showHint) const Text(_tokenHint),
|
||||
if (_controller.boundsText case final bounds?) Text(bounds),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const _tokenHint =
|
||||
'Filter with t:pipeline or type:artifact (pipeline, run, step, field, '
|
||||
'artifact, version). Last type wins; choosing Kind replaces it. Quote '
|
||||
'tokens to search literally.';
|
||||
@@ -0,0 +1,174 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/search_controller.dart';
|
||||
import '../domain/search_row.dart';
|
||||
import 'search_result_view.dart';
|
||||
|
||||
/// The Cupertino search view: native search/kind controls and grouped list rows
|
||||
/// in one scroll view, with standard activity and retry controls.
|
||||
class CupertinoSearchBody extends StatelessWidget {
|
||||
const CupertinoSearchBody({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.query,
|
||||
required this.onOpen,
|
||||
required this.header,
|
||||
});
|
||||
|
||||
final OmniSearchController controller;
|
||||
final String query;
|
||||
final ValueChanged<JsonMap> onOpen;
|
||||
final Widget header;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CustomScrollView(
|
||||
slivers: [
|
||||
SliverToBoxAdapter(child: header),
|
||||
if (controller.showProgress)
|
||||
const SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.symmetric(vertical: 8),
|
||||
child: CupertinoActivityIndicator(),
|
||||
),
|
||||
),
|
||||
..._content(context),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
List<Widget> _content(BuildContext context) {
|
||||
switch (controller.bodyKind) {
|
||||
case SearchBodyKind.error:
|
||||
return [
|
||||
SliverFillRemaining(
|
||||
hasScrollBody: false,
|
||||
child: _CupertinoError(
|
||||
message: controller.error!,
|
||||
onRetry: controller.retry,
|
||||
),
|
||||
),
|
||||
];
|
||||
case SearchBodyKind.searching:
|
||||
return const [
|
||||
SliverFillRemaining(
|
||||
hasScrollBody: false,
|
||||
child: _CupertinoSearching(),
|
||||
),
|
||||
];
|
||||
case SearchBodyKind.results:
|
||||
return [
|
||||
SliverToBoxAdapter(
|
||||
child: CupertinoListSection.insetGrouped(
|
||||
children: [
|
||||
for (final hit in controller.shownResults)
|
||||
_CupertinoResult(hit: hit, query: query, onOpen: onOpen),
|
||||
],
|
||||
),
|
||||
),
|
||||
];
|
||||
case SearchBodyKind.empty:
|
||||
return [
|
||||
SliverFillRemaining(
|
||||
hasScrollBody: false,
|
||||
child: _CupertinoMessage(message: controller.emptyMessage!),
|
||||
),
|
||||
];
|
||||
case SearchBodyKind.idle:
|
||||
return const [
|
||||
SliverFillRemaining(
|
||||
hasScrollBody: false,
|
||||
child: _CupertinoMessage(
|
||||
message: 'Search pipelines, runs and artifacts.',
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _CupertinoResult extends StatelessWidget {
|
||||
const _CupertinoResult({
|
||||
required this.hit,
|
||||
required this.query,
|
||||
required this.onOpen,
|
||||
});
|
||||
|
||||
final JsonMap hit;
|
||||
final String query;
|
||||
final ValueChanged<JsonMap> onOpen;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final row = searchRowView(hit, query);
|
||||
return CupertinoListTile(
|
||||
key: ValueKey('search.result.${hit['target']}'),
|
||||
leading: Icon(searchCupertinoIcon('${hit['kind'] ?? ''}')),
|
||||
title: Text(row.title),
|
||||
subtitle: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
spacing: 2,
|
||||
children: [searchRowMeta(row), searchRowSnippet(context, row)],
|
||||
),
|
||||
onTap: row.openable ? () => onOpen(hit) : null,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CupertinoSearching extends StatelessWidget {
|
||||
const _CupertinoSearching();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => const Center(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
spacing: 12,
|
||||
children: [CupertinoActivityIndicator(), Text('Searching…')],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _CupertinoMessage extends StatelessWidget {
|
||||
const _CupertinoMessage({required this.message});
|
||||
|
||||
final String message;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Text(message, textAlign: TextAlign.center),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _CupertinoError extends StatelessWidget {
|
||||
const _CupertinoError({required this.message, required this.onRetry});
|
||||
|
||||
final String message;
|
||||
final Future<void> Function() onRetry;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
spacing: 12,
|
||||
children: [
|
||||
Text(message, textAlign: TextAlign.center),
|
||||
CupertinoButton.filled(
|
||||
key: const ValueKey('search.retry'),
|
||||
onPressed: onRetry,
|
||||
child: const Text('Retry'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/search_controller.dart';
|
||||
import '../domain/search_row.dart';
|
||||
import 'search_result_view.dart';
|
||||
|
||||
/// The Material search view: the controls header and a flat native result list
|
||||
/// in one scroll view, so text scaling can never clip the controls or a row.
|
||||
class MaterialSearchBody extends StatelessWidget {
|
||||
const MaterialSearchBody({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.query,
|
||||
required this.onOpen,
|
||||
required this.header,
|
||||
});
|
||||
|
||||
final OmniSearchController controller;
|
||||
final String query;
|
||||
final ValueChanged<JsonMap> onOpen;
|
||||
final Widget header;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CustomScrollView(
|
||||
slivers: [
|
||||
SliverToBoxAdapter(child: header),
|
||||
if (controller.showProgress)
|
||||
const SliverToBoxAdapter(child: LinearProgressIndicator()),
|
||||
..._content(context),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
List<Widget> _content(BuildContext context) {
|
||||
switch (controller.bodyKind) {
|
||||
case SearchBodyKind.error:
|
||||
return [
|
||||
SliverFillRemaining(
|
||||
hasScrollBody: false,
|
||||
child: _SearchError(
|
||||
message: controller.error!,
|
||||
onRetry: controller.retry,
|
||||
),
|
||||
),
|
||||
];
|
||||
case SearchBodyKind.searching:
|
||||
return const [
|
||||
SliverFillRemaining(hasScrollBody: false, child: _Searching()),
|
||||
];
|
||||
case SearchBodyKind.results:
|
||||
return [
|
||||
SliverList.builder(
|
||||
itemCount: controller.shownResults.length,
|
||||
itemBuilder: (context, index) {
|
||||
final hit = controller.shownResults[index];
|
||||
return _MaterialResult(hit: hit, query: query, onOpen: onOpen);
|
||||
},
|
||||
),
|
||||
];
|
||||
case SearchBodyKind.empty:
|
||||
return [
|
||||
SliverFillRemaining(
|
||||
hasScrollBody: false,
|
||||
child: _SearchMessage(message: controller.emptyMessage!),
|
||||
),
|
||||
];
|
||||
case SearchBodyKind.idle:
|
||||
return const [
|
||||
SliverFillRemaining(
|
||||
hasScrollBody: false,
|
||||
child: _SearchMessage(
|
||||
message: 'Search pipelines, runs and artifacts.',
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _MaterialResult extends StatelessWidget {
|
||||
const _MaterialResult({
|
||||
required this.hit,
|
||||
required this.query,
|
||||
required this.onOpen,
|
||||
});
|
||||
|
||||
final JsonMap hit;
|
||||
final String query;
|
||||
final ValueChanged<JsonMap> onOpen;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final row = searchRowView(hit, query);
|
||||
return ListTile(
|
||||
key: ValueKey('search.result.${hit['target']}'),
|
||||
leading: Icon(searchMaterialIcon('${hit['kind'] ?? ''}')),
|
||||
title: Text(row.title),
|
||||
subtitle: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
spacing: 2,
|
||||
children: [searchRowMeta(row), searchRowSnippet(context, row)],
|
||||
),
|
||||
onTap: row.openable ? () => onOpen(hit) : null,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Searching extends StatelessWidget {
|
||||
const _Searching();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => const Center(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
spacing: 12,
|
||||
children: [CircularProgressIndicator(), Text('Searching…')],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _SearchMessage extends StatelessWidget {
|
||||
const _SearchMessage({required this.message});
|
||||
|
||||
final String message;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Text(message, textAlign: TextAlign.center),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _SearchError extends StatelessWidget {
|
||||
const _SearchError({required this.message, required this.onRetry});
|
||||
|
||||
final String message;
|
||||
final Future<void> Function() onRetry;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
spacing: 12,
|
||||
children: [
|
||||
Text(message, textAlign: TextAlign.center),
|
||||
FilledButton.tonalIcon(
|
||||
key: const ValueKey('search.retry'),
|
||||
onPressed: onRetry,
|
||||
icon: const Icon(Icons.refresh),
|
||||
label: const Text('Retry'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../domain/search_row.dart';
|
||||
|
||||
/// Kind, recency and read-only affordance for one row. Deliberately unstyled
|
||||
/// beyond weight so Material and Cupertino inherit their own system typography
|
||||
/// and colours, including dark mode and text scaling.
|
||||
Widget searchRowMeta(SearchRowView row) {
|
||||
final parts = [row.kindLabel, if (row.recency != null) row.recency!];
|
||||
return Text(
|
||||
parts.join(' · '),
|
||||
style: const TextStyle(fontWeight: FontWeight.w600),
|
||||
);
|
||||
}
|
||||
|
||||
/// The snippet with the first query occurrence emphasised by weight, never by
|
||||
/// parsing server text as markup or by a bespoke colour.
|
||||
Widget searchRowSnippet(BuildContext context, SearchRowView row) {
|
||||
final snippet = row.snippet;
|
||||
if (snippet == null) {
|
||||
return row.secondary.isEmpty
|
||||
? const SizedBox.shrink()
|
||||
: Text(row.secondary);
|
||||
}
|
||||
return Text.rich(
|
||||
TextSpan(
|
||||
children: [
|
||||
for (final span in row.snippetSpans)
|
||||
TextSpan(
|
||||
text: span.text,
|
||||
style: span.matched
|
||||
? const TextStyle(fontWeight: FontWeight.bold)
|
||||
: null,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
IconData searchMaterialIcon(String kind) => switch (kind) {
|
||||
'pipeline' => Icons.account_tree_outlined,
|
||||
'version' => Icons.layers_outlined,
|
||||
'run' => Icons.play_circle_outline,
|
||||
'step' => Icons.arrow_forward,
|
||||
'field' => Icons.notes,
|
||||
'artifact' => Icons.attach_file,
|
||||
_ => Icons.help_outline,
|
||||
};
|
||||
|
||||
IconData searchCupertinoIcon(String kind) => switch (kind) {
|
||||
'pipeline' => CupertinoIcons.arrow_branch,
|
||||
'version' => CupertinoIcons.square_stack_3d_up,
|
||||
'run' => CupertinoIcons.play_circle,
|
||||
'step' => CupertinoIcons.arrow_right,
|
||||
'field' => CupertinoIcons.doc_text,
|
||||
'artifact' => CupertinoIcons.paperclip,
|
||||
_ => CupertinoIcons.question_circle,
|
||||
};
|
||||
@@ -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<List<TemplateEntry>> 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<String, dynamic>.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<JsonMap> 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<String, dynamic>.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<JsonMap> 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<String, dynamic>.from(detail);
|
||||
}
|
||||
}
|
||||
@@ -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<String, dynamic> json) =>
|
||||
Map<String, dynamic>.unmodifiable(
|
||||
json.map((key, value) => MapEntry(key, _frozen(value))),
|
||||
);
|
||||
|
||||
static dynamic _frozen(dynamic value) {
|
||||
if (value is Map) {
|
||||
return _frozenMap(Map<String, dynamic>.from(value));
|
||||
}
|
||||
if (value is List) {
|
||||
return List<dynamic>.unmodifiable(value.map(_frozen));
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
+5
-120
@@ -1,122 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'application/bootstrap.dart';
|
||||
|
||||
void main() {
|
||||
runApp(const MyApp());
|
||||
}
|
||||
export 'application/app.dart' show MyApp;
|
||||
export 'shell/adaptive_shell.dart';
|
||||
export 'shell/destination.dart';
|
||||
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
|
||||
// This widget is the root of your application.
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
title: 'Flutter Demo',
|
||||
theme: ThemeData(
|
||||
// This is the theme of your application.
|
||||
//
|
||||
// TRY THIS: Try running your application with "flutter run". You'll see
|
||||
// the application has a purple toolbar. Then, without quitting the app,
|
||||
// try changing the seedColor in the colorScheme below to Colors.green
|
||||
// and then invoke "hot reload" (save your changes or press the "hot
|
||||
// reload" button in a Flutter-supported IDE, or press "r" if you used
|
||||
// the command line to start the app).
|
||||
//
|
||||
// Notice that the counter didn't reset back to zero; the application
|
||||
// state is not lost during the reload. To reset the state, use hot
|
||||
// restart instead.
|
||||
//
|
||||
// This works for code too, not just values: Most code changes can be
|
||||
// tested with just a hot reload.
|
||||
colorScheme: .fromSeed(seedColor: Colors.deepPurple),
|
||||
),
|
||||
home: const MyHomePage(title: 'Flutter Demo Home Page'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class MyHomePage extends StatefulWidget {
|
||||
const MyHomePage({super.key, required this.title});
|
||||
|
||||
// This widget is the home page of your application. It is stateful, meaning
|
||||
// that it has a State object (defined below) that contains fields that affect
|
||||
// how it looks.
|
||||
|
||||
// This class is the configuration for the state. It holds the values (in this
|
||||
// case the title) provided by the parent (in this case the App widget) and
|
||||
// used by the build method of the State. Fields in a Widget subclass are
|
||||
// always marked "final".
|
||||
|
||||
final String title;
|
||||
|
||||
@override
|
||||
State<MyHomePage> createState() => _MyHomePageState();
|
||||
}
|
||||
|
||||
class _MyHomePageState extends State<MyHomePage> {
|
||||
int _counter = 0;
|
||||
|
||||
void _incrementCounter() {
|
||||
setState(() {
|
||||
// This call to setState tells the Flutter framework that something has
|
||||
// changed in this State, which causes it to rerun the build method below
|
||||
// so that the display can reflect the updated values. If we changed
|
||||
// _counter without calling setState(), then the build method would not be
|
||||
// called again, and so nothing would appear to happen.
|
||||
_counter++;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// This method is rerun every time setState is called, for instance as done
|
||||
// by the _incrementCounter method above.
|
||||
//
|
||||
// The Flutter framework has been optimized to make rerunning build methods
|
||||
// fast, so that you can just rebuild anything that needs updating rather
|
||||
// than having to individually change instances of widgets.
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
// TRY THIS: Try changing the color here to a specific color (to
|
||||
// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
|
||||
// change color while the other colors stay the same.
|
||||
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
|
||||
// Here we take the value from the MyHomePage object that was created by
|
||||
// the App.build method, and use it to set our appbar title.
|
||||
title: Text(widget.title),
|
||||
),
|
||||
body: Center(
|
||||
// Center is a layout widget. It takes a single child and positions it
|
||||
// in the middle of the parent.
|
||||
child: Column(
|
||||
// Column is also a layout widget. It takes a list of children and
|
||||
// arranges them vertically. By default, it sizes itself to fit its
|
||||
// children horizontally, and tries to be as tall as its parent.
|
||||
//
|
||||
// Column has various properties to control how it sizes itself and
|
||||
// how it positions its children. Here we use mainAxisAlignment to
|
||||
// center the children vertically; the main axis here is the vertical
|
||||
// axis because Columns are vertical (the cross axis would be
|
||||
// horizontal).
|
||||
//
|
||||
// TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
|
||||
// action in the IDE, or press "p" in the console), to see the
|
||||
// wireframe for each widget.
|
||||
mainAxisAlignment: .center,
|
||||
children: [
|
||||
const Text('You have pushed the button this many times:'),
|
||||
Text(
|
||||
'$_counter',
|
||||
style: Theme.of(context).textTheme.headlineMedium,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
floatingActionButton: FloatingActionButton(
|
||||
onPressed: _incrementCounter,
|
||||
tooltip: 'Increment',
|
||||
child: const Icon(Icons.add),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
void main() => runPipelinesApp();
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'destination.dart';
|
||||
|
||||
class AdaptiveShell extends StatefulWidget {
|
||||
const AdaptiveShell({
|
||||
super.key,
|
||||
this.destinationBodies = const {},
|
||||
this.cupertino = false,
|
||||
this.destination,
|
||||
this.onDestinationSelected,
|
||||
});
|
||||
|
||||
final Map<AppDestination, WidgetBuilder> destinationBodies;
|
||||
final bool cupertino;
|
||||
|
||||
/// The destination a route owner selected. When null the shell keeps its own
|
||||
/// selection, which preserves the plain-shell tests and native composition.
|
||||
final AppDestination? destination;
|
||||
final ValueChanged<AppDestination>? onDestinationSelected;
|
||||
|
||||
@override
|
||||
State<AdaptiveShell> createState() => _AdaptiveShellState();
|
||||
}
|
||||
|
||||
class _AdaptiveShellState extends State<AdaptiveShell> {
|
||||
late AppDestination _selected;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_selected = widget.destination ?? AppDestination.pipelines;
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant AdaptiveShell oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
final destination = widget.destination;
|
||||
if (destination != null) _selected = destination;
|
||||
}
|
||||
|
||||
void _select(AppDestination destination) {
|
||||
final callback = widget.onDestinationSelected;
|
||||
if (callback != null) {
|
||||
callback(destination);
|
||||
return;
|
||||
}
|
||||
setState(() => _selected = destination);
|
||||
}
|
||||
|
||||
List<T> _items<T>(T Function(AppDestination) build) =>
|
||||
AppDestination.values.map(build).toList();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final index = AppDestination.values.indexOf(_selected);
|
||||
final details = destinationDetails(_selected);
|
||||
final contents = AppDestination.values.map((destination) {
|
||||
final item = destinationDetails(destination);
|
||||
return KeyedSubtree(
|
||||
key: ValueKey(destination),
|
||||
child:
|
||||
widget.destinationBodies[destination]?.call(context) ??
|
||||
Center(child: Text('${item.label} — Not implemented')),
|
||||
);
|
||||
}).toList();
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final wide = constraints.maxWidth >= 600;
|
||||
if (widget.cupertino) {
|
||||
return CupertinoPageScaffold(
|
||||
navigationBar: CupertinoNavigationBar(middle: Text(details.label)),
|
||||
child: SafeArea(
|
||||
child: Column(
|
||||
children: [
|
||||
Expanded(child: _destinationStack(contents, index)),
|
||||
CupertinoTabBar(
|
||||
currentIndex: index,
|
||||
onTap: (value) => _select(AppDestination.values[value]),
|
||||
items: _items((destination) {
|
||||
final item = destinationDetails(destination);
|
||||
return BottomNavigationBarItem(
|
||||
icon: Icon(item.cupertinoIcon),
|
||||
label: item.label,
|
||||
);
|
||||
}),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: Text(details.label)),
|
||||
body: Row(
|
||||
children: [
|
||||
if (wide)
|
||||
NavigationRail(
|
||||
selectedIndex: index,
|
||||
onDestinationSelected: (value) =>
|
||||
_select(AppDestination.values[value]),
|
||||
labelType: NavigationRailLabelType.all,
|
||||
destinations: _items((destination) {
|
||||
final item = destinationDetails(destination);
|
||||
return NavigationRailDestination(
|
||||
icon: Icon(item.icon),
|
||||
label: Text(item.label),
|
||||
);
|
||||
}),
|
||||
),
|
||||
Expanded(child: _destinationStack(contents, index)),
|
||||
],
|
||||
),
|
||||
bottomNavigationBar: wide
|
||||
? null
|
||||
: NavigationBar(
|
||||
selectedIndex: index,
|
||||
onDestinationSelected: (value) =>
|
||||
_select(AppDestination.values[value]),
|
||||
destinations: _items((destination) {
|
||||
final item = destinationDetails(destination);
|
||||
return NavigationDestination(
|
||||
icon: Icon(item.icon),
|
||||
label: item.label,
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _destinationStack(List<Widget> contents, int index) =>
|
||||
IndexedStack(index: index, children: contents);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
|
||||
enum AppDestination { pipelines, runs, chat, settings }
|
||||
|
||||
({String label, IconData icon, IconData cupertinoIcon}) destinationDetails(
|
||||
AppDestination value,
|
||||
) => switch (value) {
|
||||
AppDestination.pipelines => (
|
||||
label: 'Pipelines',
|
||||
icon: Icons.account_tree_outlined,
|
||||
cupertinoIcon: CupertinoIcons.arrow_branch,
|
||||
),
|
||||
AppDestination.runs => (
|
||||
label: 'Runs',
|
||||
icon: Icons.play_circle_outline,
|
||||
cupertinoIcon: CupertinoIcons.play_circle,
|
||||
),
|
||||
AppDestination.chat => (
|
||||
label: 'Chat',
|
||||
icon: Icons.chat_bubble_outline,
|
||||
cupertinoIcon: CupertinoIcons.chat_bubble_2,
|
||||
),
|
||||
AppDestination.settings => (
|
||||
label: 'Settings',
|
||||
icon: Icons.settings_outlined,
|
||||
cupertinoIcon: CupertinoIcons.gear,
|
||||
),
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Whether the nearest app host is a Cupertino one.
|
||||
///
|
||||
/// A `CupertinoApp` supplies Cupertino localizations only, while `MaterialApp`
|
||||
/// supplies [MaterialLocalizations]. Checking the host avoids guessing from a
|
||||
/// desktop browser's target platform and keeps one answer for every control.
|
||||
bool usesCupertinoHost(BuildContext context) =>
|
||||
Localizations.of<MaterialLocalizations>(context, MaterialLocalizations) ==
|
||||
null;
|
||||
@@ -0,0 +1,101 @@
|
||||
# A1a — artifact records, capture facts, grouping, kinds and safe urls
|
||||
|
||||
## What changed
|
||||
|
||||
New nonvisual `artifacts` domain slice. Every file is new; no existing file was
|
||||
edited. Nothing under `lib/main.dart`, `lib/shell/`, another feature, `pubspec.*`,
|
||||
`web/`, the Go server or `android/` was touched. No dependency was added and no
|
||||
network/transport code was written.
|
||||
|
||||
| File | Lines | Responsibility |
|
||||
| --- | --- | --- |
|
||||
| `lib/features/artifacts/domain/artifact_record.dart` | 85 | One recorded artifact: name, url, content type, size and deeply read-only `raw`; retired `session.md` and system names |
|
||||
| `lib/features/artifacts/domain/artifact_capture.dart` | 63 | Per-step capture availability (`unavailable`/`recorded`), recorded files, skipped and truncated counts |
|
||||
| `lib/features/artifacts/domain/artifact_selection.dart` | 67 | Record parsing, retired/system/repair filtering (`presented`, `stage`, `system`) |
|
||||
| `lib/features/artifacts/domain/artifact_groups.dart` | 109 | Group stage artifacts by stage and recorded visit; shared `public/` attribution; per-visit list |
|
||||
| `lib/features/artifacts/domain/artifact_kind.dart` | 225 | MIME/extension kind vocabulary, labels, markdown/viewer predicates, `humanBytes` |
|
||||
| `lib/features/artifacts/domain/artifact_summary.dart` | 78 | Run/visit summary and empty wording, partial-capture flag and notes |
|
||||
| `lib/features/artifacts/domain/gallery_navigation.dart` | 76 | Filtered viewer page order, stable identities, previous/next clamp, position label |
|
||||
| `lib/features/artifacts/domain/artifact_url.dart` | 78 | Safe http(s) resolution against the configured endpoint and cross-origin marking |
|
||||
| `test/features/artifacts/domain/artifact_fixtures.dart` | 44 | Local step/artifact fixtures; no fake gateway or socket |
|
||||
| `test/features/artifacts/domain/artifact_capture_test.dart` | 241 | Unavailable/null/empty/partial capture facts and exact wording |
|
||||
| `test/features/artifacts/domain/artifact_groups_test.dart` | 308 | Visits, identity, retired/utility files, public attribution, empty states |
|
||||
| `test/features/artifacts/domain/artifact_selection_test.dart` | 154 | Field preservation, deep immutability, filtering, duplicates |
|
||||
| `test/features/artifacts/domain/artifact_kind_test.dart` | 110 | Known/unknown MIME and extension classification, markdown/viewer gates, bytes |
|
||||
| `test/features/artifacts/domain/gallery_navigation_test.dart` | 197 | Filtered order, duplicate urls/names, url-less identities, paging clamp, label |
|
||||
| `test/features/artifacts/domain/artifact_url_test.dart` | 148 | Relative/absolute urls, wss/https, IPv6, encoded path/query, schemes, credentials, cross-origin |
|
||||
|
||||
## Behaviour (from `web/src/artifacts.js` and `artifactNavigation.js`)
|
||||
|
||||
- **Record facts are verbatim.** `ArtifactRecord.fromJson` reads `name`, `url`,
|
||||
`content_type`, `size_bytes` and keeps every other server field in a deep
|
||||
unmodifiable `raw`. A missing url stays `''`; nothing is derived from the name.
|
||||
Two records with the same name stay distinct because identity is the recorded
|
||||
url (or a visit-scoped fallback in the viewer).
|
||||
- **Capture availability is a recorded fact.** An absent, null or non-list
|
||||
`artifacts` field is `unavailable`; an explicit empty list is a recorded empty
|
||||
capture. `artifacts_skipped`/`artifacts_truncated` are preserved as counts and
|
||||
mark a partial capture. Unavailable capture never degrades to "no artifacts"
|
||||
or "not recorded": the run header says `Artifacts · capture unavailable`
|
||||
instead of `No artifacts recorded for this run.`, which is the task's explicit
|
||||
requirement and the one deliberate wording extension beyond the web client.
|
||||
- **Grouping and identity.** `artifactGroups` keeps first-appearance stage order,
|
||||
orders each stage's visits by sequence (recorded order on ties), and uses
|
||||
`displayVisit` from the existing graph domain (`control.visit` when positive,
|
||||
else position + 1). A step with no presented stage artifact yields no group, so
|
||||
unavailable/empty captures and utility-only visits never fabricate a visit.
|
||||
Shared `public/` files are attributed to the first recorded visit; repeated
|
||||
non-public names in later visits remain separate artifacts.
|
||||
- **Retired and utility files.** `session.md` is hidden everywhere; `session.html`,
|
||||
`input.md`, `memory.md`, `output.md` remain system evidence and are excluded
|
||||
from stage output. Repaired session exports named by `session_export_repairs`
|
||||
are system evidence too.
|
||||
- **Kinds.** Image/video come from the content type; audio, PDF, JSON, archive,
|
||||
spreadsheet, log, code, document then match normalised MIME or extension;
|
||||
unknown values are `other`/`File`. `isMarkdownArtifact`/`isViewerArtifact` keep
|
||||
logs, source, CSV and HTML out of the in-app viewer while images, videos and
|
||||
md/markdown/txt pages enter it.
|
||||
- **Navigation.** `pagedArtifacts` filters group by group in recorded order;
|
||||
`viewerIndexByUrl` maps the first occurrence of each url; url-less pages use a
|
||||
visit-scoped identity; `pagedIndex` clamps with no wrap; the position label
|
||||
trims content-type parameters and falls back to `artifact`.
|
||||
- **Safe urls.** Server-relative paths resolve against the configured endpoint's
|
||||
http(s) origin (endpoint path/query dropped, `wss` → `https`, IPv6 brackets and
|
||||
percent-encoding kept). Absolute http(s) urls are preserved. Output is always
|
||||
http(s): blank, protocol-relative, backslash-relative, hostless, credentialed,
|
||||
malformed and non-http(s) urls return null. A url whose origin differs from the
|
||||
configured origin is marked `external`, so a future authenticated fetch can
|
||||
refuse to send cookies or headers; a same-origin url stays internal.
|
||||
|
||||
## Review and quality fixes in this visit
|
||||
|
||||
- `flutter analyze` reported four infos in this slice; all fixed: block braces in
|
||||
`artifact_summary.dart` and null-aware map entries (`'key': ?value`) in the
|
||||
test fixtures. Analyze is now clean for the whole app.
|
||||
- `dart format` found one unformatted test file; all 15 files are now formatted.
|
||||
- Semantics were re-read against `web/src/artifacts.js` (`presentedArtifacts`,
|
||||
`stageArtifacts`, `systemArtifacts`, `artifactKind`, `pagedArtifacts`,
|
||||
`viewerIndexByUrl`, `pagedIndex`, `displayVisit`) and `artifactNavigation.js`.
|
||||
No other concrete deviation was found, so no behaviour was rewritten.
|
||||
|
||||
## Checks actually run
|
||||
|
||||
```
|
||||
flutter test test/features/artifacts/domain # 60 passed
|
||||
flutter test test/features/graph/domain # 41 passed (stage_visits reuse)
|
||||
flutter analyze # No issues found! (0.9s)
|
||||
dart format lib/features/artifacts test/features/artifacts # clean, 15 files
|
||||
grep trailing whitespace # none
|
||||
```
|
||||
|
||||
## Honest limits
|
||||
|
||||
- No gallery screen, viewer, sharing, fetching or transport helper exists in this
|
||||
slice, so there is no rendered change and no browser capture. The gallery and
|
||||
viewer are separate future slices.
|
||||
- No live server, socket, artifact download or real run data was used; tests are
|
||||
local fixtures and pure functions only.
|
||||
- Mobile is unverified: no Android/iOS build, emulator, ADB or device was used.
|
||||
- **Committed by the Land stage** as `ff0f812` on `flutter/a1-data` and merged
|
||||
with `main` in `a303368`; the checks above were re-run on the merged candidate.
|
||||
This stage did not merge into `main`, push or deploy.
|
||||
@@ -0,0 +1,33 @@
|
||||
# F2 — Adaptive shell
|
||||
|
||||
## Manager browser acceptance
|
||||
The initial capture attempt failed because the fixture served its index with
|
||||
binary MIME. Corrected the fixture MIME and navigation assertions; the real
|
||||
Chrome run now passes actual Pipelines → Runs → Chat → Settings → Pipelines
|
||||
navigation, checking the selected destination body (not only navigation labels).
|
||||
Captured and inspected at 390×844 and 1280×800:
|
||||
`/private/var/folders/jp/q0qvjyg54fl_c5vhhk1ylz2m0000gn/T/opencode/f2-shell-{phone,phone-runs,phone-settings,desktop}.png`.
|
||||
These show the native Cupertino shell on a macOS browser with explicitly labelled
|
||||
unimplemented feature bodies. They do not prove feature parity or mobile behavior.
|
||||
Reproduce from app/ using `OPENCODE_ARTIFACT_DIR=<directory> node tool/shell_probe.mjs`
|
||||
after `flutter build web`. Earlier missing-capture statements below are historical.
|
||||
|
||||
Implemented standard adaptive navigation for Pipelines, Runs, Chat and Settings.
|
||||
Material uses a bottom `NavigationBar` below 600 logical pixels and a labeled
|
||||
`NavigationRail` at wider widths. Cupertino uses the native navigation bar and
|
||||
tab bar. `MyApp` chooses Cupertino on iOS/macOS, leaves Material system light/dark
|
||||
themes active elsewhere, and accepts injectable `WidgetBuilder` bodies through
|
||||
`AdaptiveShell`; unregistered destinations are explicitly marked Not implemented.
|
||||
|
||||
## Verification
|
||||
|
||||
- `flutter test test/widget_test.dart`: passed (narrow/wide, 2x text scale,
|
||||
Cupertino controls and injected destination body).
|
||||
- `flutter analyze`: passed, no issues.
|
||||
- Follow-up verification: widget tests now cover state retention across tab
|
||||
switches and Cupertino safe-area insets. `flutter build web` succeeds.
|
||||
- Browser interaction/capture remains unverified: the local Chrome DevTools
|
||||
probe did not complete, so no rendered evidence is claimed. Mobile targets
|
||||
are unverified.
|
||||
|
||||
No API capabilities are asserted or mocked. No dependencies were added.
|
||||
@@ -0,0 +1,22 @@
|
||||
# F3 run foundation
|
||||
|
||||
Public API: `run_models.dart` provides run identity/state/filter/sort helpers,
|
||||
status wording, `RunListResult`, decision draft/option values, and attention
|
||||
ordering/identity. `run_decisions.dart` resolves recorded human options and
|
||||
prompt evidence with graph fallback. `run_events.dart` and
|
||||
`run_step_evidence.dart` provide monotonic list/detail folds, immutable schedule
|
||||
origin, graph evidence, and `runDetailNeedsFullSync`. `data/runs_repository.dart`
|
||||
provides list/get/cancel/retry/decide/title/start calls through the shared gateway.
|
||||
|
||||
Focused tests cover stale and terminal lifecycle deltas, resource-wait clearing,
|
||||
sparse step preservation, sticky cancel/cleanup flags, schedule provenance,
|
||||
export gating, pending-decision evidence, list/detail agreement, filters/sorts,
|
||||
exact request fields and server refusals. The repository file is deliberately
|
||||
tracked despite the repository's `data/` ignore rule. This is a nonvisual
|
||||
foundation; browser UI captures were not applicable. Mobile targets are
|
||||
unverified.
|
||||
|
||||
This is not total web parity: date filtering uses Dart local-time conversion
|
||||
rather than web's explicit IANA-zone/locale helpers; the complete attention
|
||||
dismissal/persistence surface, retry key generation, and repository methods for
|
||||
export repair/request-key reconciliation are not included in this foundation.
|
||||
@@ -0,0 +1,26 @@
|
||||
# F5 preview server candidate review
|
||||
|
||||
Manager reran all 6 fixture tests and added an idle-websocket regression past the
|
||||
five-second establishment deadline. Healthy idle sockets now keep their session;
|
||||
auth-check listeners are removed when finished. Default preview port is 8096,
|
||||
separate from the raw API at 8080. HTTPS certificate paths remain untested.
|
||||
|
||||
Candidate `e3a82b0`'s static preview route was retained, with stricter decoded
|
||||
path validation and canonical-path checks for files and SPA fallback. The proxy
|
||||
now uses `http.request` / `https.request` streams so Range, HEAD, content-encoding,
|
||||
and exact response bytes are preserved. Authentication checks fail closed after
|
||||
five seconds and discard their response bodies. Unauthenticated document GETs
|
||||
are redirected to the authenticated proxy's `/login?next=...`; assets remain
|
||||
401. Login, logout, and artifact proxying still use the browser's upstream cookie.
|
||||
|
||||
WebSocket upgrades validate `/connect` and a same-origin browser Origin before
|
||||
authentication or upstream connection. After authentication, both Host and
|
||||
Origin map to the configured HTTP(S) upstream origin; cookies and upgrade headers
|
||||
are retained. Upgraded sockets are tracked and destroyed during `close()`. HTTPS
|
||||
uses Node TLS verification (no certificate bypass). Bind to loopback by default.
|
||||
|
||||
Verification: `node --test test/tool/preview.test.mjs`, `node --check` on server
|
||||
and test, and `git diff --check`. Tests use only local fixtures and cover login
|
||||
redirect, denied auth, exact compressed Range/HEAD bytes, origin rejection,
|
||||
authenticated bidirectional WebSocket bytes, timeout, shutdown, and traversal / symlink
|
||||
protection. No browser run, Flutter build, production access, or deployment was done.
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
# I1 — live Runs destination, routes and resilient connection
|
||||
|
||||
## Change
|
||||
|
||||
- `lib/application/` composes the real app separately from `main.dart`:
|
||||
`bootstrap.dart` resolves the endpoint and starts the composition,
|
||||
`pipelines_app.dart` owns one `AppSession` and one `Router`,
|
||||
`runs_destination.dart` frames the Runs destination, and `app.dart` keeps the
|
||||
injectable `MyApp` shell for existing widget tests. `main.dart` exports `MyApp`
|
||||
and calls `runPipelinesApp()`.
|
||||
- Web endpoint: the page origin from `Uri.base` over `ws(s)` at `/connect`, so
|
||||
the same server that served the bundle is the live server. Native builds use
|
||||
only the explicit `--dart-define=PIPELINES_SERVER_URL=ws://host:port/connect`
|
||||
value; there is no baked host or fallback endpoint.
|
||||
- **Routes/deep links (I1's second half):** the app now uses Flutter's `Router`
|
||||
with a total `AppRoute` parser (`/pipelines`, `/runs`, `/runs/:id`, `/chat`,
|
||||
`/settings`) and the path URL strategy (`flutter_web_plugins` declared as a
|
||||
direct dependency). `/runs/1` opens that run directly, tab and run selection
|
||||
push browser history, Back/Forward move between them, and a malformed or
|
||||
unknown path renders Pipelines and is corrected to `/pipelines`. Non-web
|
||||
platforms keep the same routes through the Router without an address bar.
|
||||
A single-page `Navigator` inside the Router delegate supplies the Overlay
|
||||
native controls need while keeping the shell state across route changes.
|
||||
- **Reconnects keep the destination:** before the first successful connection
|
||||
the destination is a full connection screen. After that the loaded Runs screen
|
||||
stays mounted through drops: a compact status banner reports `Reconnecting to
|
||||
Pipelines…` or `Not live — Pipelines server unavailable.` with a Retry action,
|
||||
and `connectionEpoch` triggers an in-place list/detail refresh. The open run,
|
||||
its scroll position and Back all survive the reconnect; the screen is not
|
||||
remounted and the selection is not reset.
|
||||
- **Honest connection copy:** the full gate no longer prints a raw transport
|
||||
exception. A failed first attempt stays `Pipelines server unavailable` with
|
||||
`Retrying automatically…` while the client retries instead of flickering to
|
||||
`Connecting…` on every attempt. Only the first attempt shows `Connecting to
|
||||
Pipelines…`.
|
||||
- **Live-watch status:** `AppSession` now observes the send-only `subscribe`
|
||||
ack/error. A server refusal is reported as `Not live — run updates are
|
||||
unavailable.` with the server's own refusal reason and a Retry that repeats the
|
||||
watch; silence (servers that never ack, like the fixture) is left pending
|
||||
rather than guessed as "not live".
|
||||
- `AppSession` owns the single shared `PipelinesClient` and its state stream. It
|
||||
sends `subscribe` with `{workspace: ''}` on every connected transition and
|
||||
`unsubscribe` on stop/dispose.
|
||||
- `RunsScreen` consumes `controller.selectedRunId` as the only selection source;
|
||||
a route change, an initial run, a pending/failed detail and Back all navigate
|
||||
the same path. Removed the nested `CupertinoPageScaffold`/`CupertinoNavigationBar`;
|
||||
the shell owns the single native bar.
|
||||
- `RunDetailView` keeps Back available while the detail is pending as well as on
|
||||
failure. The detail's back row and the pending/error action now read
|
||||
`Back to list` (Cupertino's compact row reads `Back`), matching web's
|
||||
accessible name instead of the ambiguous `Runs`.
|
||||
- Cupertino-host detection is centralized in `lib/ui/adaptive/host.dart` and used
|
||||
by the destination, detail and runs list instead of three different checks.
|
||||
- Inherited web build defect: `run_models.dart` used `0x7fffffffffffffff`
|
||||
sentinels, which dart2js cannot represent. Replaced them with the `DateTime`
|
||||
maximum millisecond value (`8640000000000000`), also an exact JavaScript
|
||||
number; sort behavior is unchanged.
|
||||
|
||||
## Checks
|
||||
|
||||
- `flutter test`: **86 passed** (12 new since the previous visit; the prior suite
|
||||
plus route, reconnect-retention, subscribe-status and composition coverage).
|
||||
- `flutter analyze`: **no issues**.
|
||||
- `flutter build web` (normal `lib/main.dart`): **succeeded**.
|
||||
- `dart format --output=none --set-exit-if-changed lib test tool`: clean.
|
||||
- `git diff --check`: clean.
|
||||
|
||||
## Browser acceptance
|
||||
|
||||
`tool/runs_probe.mjs` ran real headless Chrome against the isolated loopback
|
||||
fixture (`tool/runs_probe_server.mjs`) with a same-origin `/connect` WebSocket.
|
||||
HTML MIME is checked before launch; body assertions use Flutter semantics and
|
||||
Tesseract OCR of canvas-rendered text. The probe now also drives:
|
||||
|
||||
- `Runs` tab → URL `/runs`; run row → `/runs/1`; browser Back → list at
|
||||
`/runs`; browser Forward → detail at `/runs/1`.
|
||||
- a direct `/runs/1` load opens the detail and leaves the address bar there.
|
||||
- `/fixture/refuse` drops the socket and rejects upgrades: the open detail stays
|
||||
visible, the banner reads `Reconnecting to Pipelines…`, no raw
|
||||
`WebSocketException`/`Failed to connect` text is rendered, and the URL stays
|
||||
`/runs/1`.
|
||||
- accepting again plus Retry restores the same detail without a remount
|
||||
(`subscribed`, `listRuns` and `getRun` all increase on the fixture).
|
||||
- a fresh load while upgrades are refused shows the friendly
|
||||
`Pipelines server unavailable` gate with no raw exception and does not flicker
|
||||
back to `Connecting…`; Retry recovers the list.
|
||||
|
||||
Probe result: `ok: true`, `subscribed: 4`, `listRuns: 5`, `getRun: 7`,
|
||||
`dropped: 2`, `live: true`. Captures are in
|
||||
`/Users/alan/.local/share/pipelines/data/artifacts/50/public/i1-fixes/`
|
||||
(18 PNGs), including:
|
||||
|
||||
- `i1-runs-phone-browser-back-list.png`
|
||||
- `i1-runs-phone-browser-forward-detail.png`
|
||||
- `i1-deeplink-run-1-phone.png`
|
||||
- `i1-reconnect-detail-retained-phone.png`
|
||||
- `i1-reconnect-detail-restored-phone.png`
|
||||
- `i1-gate-unavailable-friendly-phone.png`
|
||||
- `i1-gate-recovered-list-phone.png`
|
||||
- `i1-material-deeplink-run-1-phone.png` — a Linux user-agent override selects
|
||||
the Material host; the same deep link renders Material controls with the
|
||||
`Back to list` action.
|
||||
|
||||
The existing list/detail/pending/error/input/output/metrics captures were also
|
||||
regenerated. No page exceptions were logged in the final probe run.
|
||||
|
||||
## Limits
|
||||
|
||||
- Read-only live authenticated smoke through the manager preview was not
|
||||
performed: `http://127.0.0.1:8096/` requires auth. No credentials were
|
||||
available without reading secrets. The preview was not restarted or replaced.
|
||||
- Mobile builds/devices were not run; mobile is unverified. The shared Router
|
||||
and single-page Navigator are used on all targets but only web was exercised.
|
||||
- The fixture does not ack `subscribe` (by design), so the "live" ack path is
|
||||
covered by widget tests; the refusal banner is covered by tests and the gate
|
||||
by browser evidence.
|
||||
- No real run was modified. No commit, push or deployment was made.
|
||||
- Adding `flutter_web_plugins` to `pubspec.yaml` is the one dependency change;
|
||||
it is required for path-style routes on web.
|
||||
@@ -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.
|
||||
@@ -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<GraphNode> nodes, List<GraphEdge> edges);
|
||||
|
||||
GraphLayout layoutGraphNodes({
|
||||
required List<GraphNode> nodes,
|
||||
required List<GraphEdge> edges,
|
||||
required Map<String, NodeExtent> 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.
|
||||
@@ -0,0 +1,116 @@
|
||||
# P2c — deterministic orthogonal edge and label routing
|
||||
|
||||
## What changed
|
||||
|
||||
New app-only, pure-Dart files. No existing file, server, web client, legacy
|
||||
client, shell, `main.dart`, pubspec, domain, layout, other feature or platform
|
||||
source was edited.
|
||||
|
||||
| File | Lines | Responsibility |
|
||||
| --- | --- | --- |
|
||||
| `lib/features/graph/routing/route_models.dart` | 261 | public route, port, label, diagnostic and bounds types |
|
||||
| `lib/features/graph/routing/routing_inputs.dart` | 64 | measured label extents and caller clearances |
|
||||
| `lib/features/graph/routing/route_geometry.dart` | 175 | axis track allocator and column-gap bands |
|
||||
| `lib/features/graph/routing/corridor_plan.dart` | 105 | vertical corridor allocation per column gap |
|
||||
| `lib/features/graph/routing/edge_route_planner.dart` | 265 | forward/back/same-rank/self-loop polyline planning |
|
||||
| `lib/features/graph/routing/edge_label_placement.dart` | 175 | measured label boxes clear of nodes and other labels |
|
||||
| `lib/features/graph/routing/graph_edge_routing.dart` | 135 | validation, skipped diagnostics, labels, total bounds |
|
||||
| `test/features/graph/routing/routing_fixtures.dart` | 143 | chain/diamond/parallel/cycle/self-loop/disconnected fixtures |
|
||||
| `test/features/graph/routing/routing_assertions.dart` | 215 | orthogonality, borders, node interiors, corridors, labels, bounds |
|
||||
| `test/features/graph/routing/graph_edge_routing_test.dart` | 191 | chain, diamond, parallel, cycle, loop, disconnected, expanded text, unknown targets |
|
||||
| `test/features/graph/routing/graph_routing_geometry_test.dart` | 161 | wide labels, tight gaps, 3-stage SCC, backward layout, loop + forwards |
|
||||
| `test/features/graph/routing/graph_routing_validation_test.dart` | 222 | empty input, missing measurements, duplicate ids, invalid config, determinism/immutability |
|
||||
|
||||
No painting, widgets, styling, shell wiring or font/CSS/device constants were
|
||||
added.
|
||||
|
||||
## Public API
|
||||
|
||||
```dart
|
||||
GraphRouting routeGraphEdges({
|
||||
required GraphLayout layout,
|
||||
required List<GraphEdge> edges,
|
||||
required Map<int, LabelExtent> labelExtents,
|
||||
required RoutingConfig config,
|
||||
});
|
||||
```
|
||||
|
||||
`RoutingConfig` takes `nodeClearance`, `laneSpacing`, `corridorSpacing`,
|
||||
`portSpacing`, `labelGap` and optional `boundsPadding`. `LabelExtent` is the
|
||||
caller's measured label width/height. The node boxes and ranks are the landed
|
||||
`GraphLayout` values; the router never moves or resizes a node.
|
||||
|
||||
`GraphRouting` exposes unmodifiable `routes`, `labels`, `skipped`, `width` and
|
||||
`height`, plus `routeFor(id)` / `labelFor(id)`. Each `EdgeRoute` keeps the
|
||||
definition `id`, `source`, `outcome`, `target`, `label` and `fallback` flag, and
|
||||
returns `sourcePort`, `targetPort`, a `RouteKind` and an orthogonal `points`
|
||||
list. Each `EdgeLabelBox` carries the measured box for its edge id.
|
||||
|
||||
## Deterministic guarantees (and what is not claimed)
|
||||
|
||||
- **Identity:** routed edges copy the definition identity unchanged; skipped
|
||||
edges keep it in `RouteDiagnostic` with `unknownSource`/`unknownTarget`. No
|
||||
node, route or visit is invented for an empty, missing or unknown target.
|
||||
- **Order and stability:** routes, labels and diagnostics are ordered by edge id
|
||||
regardless of input order. Equal input produces equal, immutable results.
|
||||
- **Orthogonality and ports:** every consecutive point pair shares one
|
||||
coordinate. Endpoints are exactly on the source/target border with the
|
||||
recorded side: forward routes leave right and enter left; same-rank, backward
|
||||
and self-loop routes leave/enter the right side.
|
||||
- **Node avoidance:** a forward one-rank route is a straight horizontal run only
|
||||
when the boxes share a port band and leave room for label-aware track spacing.
|
||||
Every other route drops into a unique horizontal lane below the node grid,
|
||||
travels vertically only inside column gaps (or the free space right of the
|
||||
last column), and returns to a port through its own stub. Vertical corridors
|
||||
and lanes never enter a node column, and every horizontal stub stays on a row
|
||||
that is clear of unrelated node boxes.
|
||||
- **Distinguishable runs:** vertical tracks are spread across each gap, one
|
||||
slot per corridor request; horizontal stubs and straight routes share one
|
||||
interval-aware allocator; every wrapping route owns its own lane. Two edges
|
||||
cannot share a collinear run in the tested fixtures.
|
||||
- **Labels:** each routed edge needs a measured `LabelExtent`; a missing one is
|
||||
an `ArgumentError`. The box is placed at a deterministic route run, clear of
|
||||
node interiors and earlier labels. If a run is too narrow (for example a wide
|
||||
label between close columns), the label moves to a free shelf below the
|
||||
drawing and the returned bounds grow instead of covering a node.
|
||||
- **Bounds:** `width`/`height` include the landed node layout, all route points
|
||||
and all label boxes, plus `boundsPadding`. A self loop or an edge into the
|
||||
right-free gap expands the box; nothing is clipped.
|
||||
- **Not claimed:** perfect general crossing minimization or minimal bend
|
||||
counts. Corridors and lanes are deterministic and locally separated, not a
|
||||
globally optimal routing.
|
||||
|
||||
## Checks actually run
|
||||
|
||||
```
|
||||
flutter pub get
|
||||
dart format lib/features/graph/routing test/features/graph/routing # 0 changed
|
||||
flutter test test/features/graph/routing # 20 passed
|
||||
flutter analyze # No issues found!
|
||||
flutter test # 193 passed
|
||||
```
|
||||
|
||||
Focused coverage includes chain, diamond fan-out/fan-in, three outcomes to one
|
||||
target, a two-stage and a three-stage SCC, a self loop alone and beside forward
|
||||
routes, disconnected stages, heterogeneous widths, 2.6x expanded text, tight
|
||||
gaps, wide labels, a caller-supplied backward rank, missing/empty/unknown
|
||||
targets, immutability, stable ordering and finite bounds.
|
||||
|
||||
## Honest limits
|
||||
|
||||
- **No rendering.** This is a nonvisual geometry slice: no painter, widgets,
|
||||
native controls, screenshots or browser behavior. Rendered parity belongs to
|
||||
the next renderer task.
|
||||
- **Layout is an input.** The router does not widen columns for labels or move
|
||||
nodes. Very wide labels may sit on the free shelf below the drawing; callers
|
||||
that want labels beside an edge should reserve enough column gap when laying
|
||||
out nodes. A zero-width column gap leaves no space for distinct vertical
|
||||
corridors, so callers should supply a positive gap (the landed layout keeps
|
||||
whatever gap it is given).
|
||||
- **No general crossing optimum.** Only deterministic corridor/lane separation
|
||||
is guaranteed, as described above.
|
||||
- **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.
|
||||
@@ -0,0 +1,7 @@
|
||||
# R1a — runs controller correctness
|
||||
|
||||
Implemented in `runs_controller.dart`: selection requests now retain prior detail while loading and ignore stale/disposed replies; list and detail loading indicators are independent; Back invalidates selection and cancels scheduled refresh; selected-run refreshes use captured ID/generation and preserve detail until the reply; identity-less or unresolvable run events trigger list resynchronization.
|
||||
|
||||
Added six fake-gateway regression tests in `test/features/runs/ui/runs_controller_test.dart` for stale selection, pending futures after disposal, Back cancellation, unrelated events, identity-less list resync, and full-refresh detail retention.
|
||||
|
||||
Verification: `flutter test test/features/runs/ui` passed (6 tests), `flutter analyze` passed with no issues, and `flutter build web` passed. Cupertino UI/browser evidence is outside this R1a slice and remains incomplete for the overall R1 task; mobile is unverified.
|
||||
@@ -0,0 +1,55 @@
|
||||
# R1b — runs controller request independence
|
||||
|
||||
Focused correctness fix on retained candidate `6b8d5ea`. Files:
|
||||
`lib/features/runs/ui/runs_controller.dart`,
|
||||
`test/features/runs/ui/runs_controller_test.dart`.
|
||||
|
||||
## Fixes
|
||||
|
||||
- List and detail requests now use independent generations (`_listGeneration`,
|
||||
`_detailGeneration`). `load(initialId)` no longer bumps the detail generation
|
||||
that `select(initialId)` also advances, so both `loading` and `detailLoading`
|
||||
clear when the requests resolve. Manual list loads also no longer invalidate
|
||||
valid detail refreshes.
|
||||
- List resyncs (`_reloadList`) capture and check a list generation, so a stale
|
||||
reply cannot overwrite a newer `load()`. Concurrent resync requests are
|
||||
coalesced into exactly one followup; a resync requested during a manual load
|
||||
runs after that load instead of being dropped.
|
||||
- Detail refreshes capture the current detail generation and selected run.
|
||||
Same-id refreshes keep the existing detail and are coalesced (in-flight plus
|
||||
one followup). Selecting a different run clears the previous detail instead of
|
||||
presenting it as the new run. Back/dispose invalidate pending replies, and
|
||||
stale requests cannot clear another generation's loading flags.
|
||||
- Added `num? get selectedRunId` for the native UI lane. All existing public
|
||||
methods and fields are preserved.
|
||||
|
||||
The existing 150 ms event debounce is retained; no polling or extra timers were
|
||||
introduced. File is 260 lines; the fix stays within the controller responsibility
|
||||
rather than fragmenting it.
|
||||
|
||||
## Tests
|
||||
|
||||
Extended `test/features/runs/ui/runs_controller_test.dart` with regressions for:
|
||||
|
||||
- `load(initialId)` resolves with `loading == false` and `detailLoading == false`.
|
||||
- Overlapping list loads with reversed completion order: newer reply wins.
|
||||
- List resync leaves the selected detail request valid.
|
||||
- Manual `load()` does not invalidate an in-flight detail refresh.
|
||||
- Sparse unknown run events coalesce into one followup resync.
|
||||
- A followup requested while a superseded resync is still marked in flight
|
||||
starts once that stale reply arrives instead of being stranded.
|
||||
- Selected refresh coalescing (in-flight plus followup) and Back ignoring the
|
||||
pending reply.
|
||||
- Choosing another run does not display the previous run's detail.
|
||||
- Pending detail refresh is safe after dispose.
|
||||
|
||||
Existing six regression tests remain and pass.
|
||||
|
||||
## Verification
|
||||
|
||||
- `/Users/alan/development/flutter/bin/flutter test test/features/runs/ui` — 15 tests passed.
|
||||
- `/Users/alan/development/flutter/bin/flutter test test/features/runs` — 26 tests passed.
|
||||
- `/Users/alan/development/flutter/bin/flutter analyze` — no issues found.
|
||||
- `flutter build web` not run in this NONVISUAL controller slice; manager
|
||||
integration/UI review owns rendered and build acceptance.
|
||||
- Mobile remains unverified; no device or browser tools used.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user