diff --git a/app/.gitignore b/app/.gitignore index 9f91cbac..ffe0bc2c 100644 --- a/app/.gitignore +++ b/app/.gitignore @@ -45,6 +45,10 @@ app.*.map.json /android/app/release # The repository ignores runtime data/ directories. Feature repository source -# is code, not runtime data, and must be included in fresh checkouts. +# and its mirroring tests are code, not runtime data, and must be included in +# fresh checkouts. The test negation is required too: without it every +# `test/**/data/` directory is silently dropped from the candidate. !/lib/**/data/ !/lib/**/data/** +!/test/**/data/ +!/test/**/data/** diff --git a/app/AGENTS.md b/app/AGENTS.md index a6c9d870..bee8f407 100644 --- a/app/AGENTS.md +++ b/app/AGENTS.md @@ -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. diff --git a/app/WORK.md b/app/WORK.md index 300c7588..514143b7 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -7,13 +7,53 @@ 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 | running | pending | — | -| F2 | Adaptive shell and standard platform controls | run 31 / flutter/f2-shell | running | pending | pending | -| F3 | Run models, live event fold, actions | run 32 / flutter/f3-runs | running | pending | — | -| F4 | Chat models, history/live fold, request facade | run 33 / flutter/f4-chat | running | pending | — | -| F5 | Isolated authenticated web preview tooling | run 30 / flutter/f5-preview | running | pending | 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 + 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 | exact visit3 audit repaired complete; original evidence preserved | resumed Code for tab-label scaling defect | pending | +| C1 | Chat session browser and management | 35 →36 →42 /41d30a4 | manager reran33 chat tests, inspected fixed native empty-state capture;448 integrated tests + analyze pass | merged main; ancestry verified | shell registration/transcript pending | +| N1 | Connection settings/preferences | run37 /abd696b + manager d05aa0c | native shell/shared-client/endpoint Retry wiring; actual dark Cupertino defect caught and fixed;516 integrated tests +20 browser captures pass | merged main | published8096 Settings+Runs; auth kept; live authenticated interaction not tested | +| 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 /15cca17 + manager32e1cac | manager rejected bundled font/fixed palette; corrected to host typography/native semantic colors,47 tests + fresh18 browser captures pass | merged main; ancestry verified | run-detail wiring 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 | +| P2-node | One native content-sized stage-node button | run64 /e63b0115 | manager inspected126-line native control + final PNG;13 focused tests pass;61min MISSED20min target | merged main; ancestry verified | graph composition pending | +| P2-edge | Passive routed-edge paint layer ONLY | run66 /835f16c | manager inspected160-line source + actual light PNG, reran38 painting/routing tests, pass; actual48min MISSED20min target | merged main; ancestry verified | graph composition pending | +| A1-list | One read-only artifact visit-group list | run65 /596365d9 | manager inspected231-line source + dark Cupertino PNG;11 focused tests pass;59min MISSED20min target | merged main; ancestry verified | run-detail wiring/preview pending | +| D1-wire | Open existing ChangesViewer from run detail | run67 /flutter/d1-wire | Task v6 Flash; one native button/recorded-steps route, no viewer rewrite | running | pending | +| R2-title-wire | Existing Rename action into detail/controller | run68 /flutter/r2-title-wire | Task v6 Flash; one exact accepted-server-reply update path, no dialog rewrite | running parallel | pending | ## 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. @@ -43,7 +83,207 @@ 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 +Integrated main after Settings wiring/node/artifact landings:540 tests pass; +analyzer clean. Settings integration d05aa0c built normal entry, ran extended +real-browser fixture20 captures including both actual native hosts and single +shared-socket assertions. Widget test reproduced dark Cupertino labels incorrectly +using Material fallback black before native-theme fix. Final dark screenshot +inspected: readable native label/secondary roles, no custom font/palette. +Published verified Settings/Runs bundle to build/web via directory rename, without +any service restart. Rollback build/web-before-settings-1792605369 retained. +Published main.dart.js sha256244bb0a561b7283dec5aa6a2fc53b82fc100e45d31a6c479a7a5d68e260ca212. +LAN/tailnet /settings routes correctly reach login200; unauthenticated JS401. +Native builds/device behavior and authenticated production-data interactions +remain unverified. Preview source is d05aa0c; later node/artifact components are +landed source only. Existing67 Changes wiring and new68 Rename wiring run in +parallel; small overlapping detail-body inserts are integration work, not a lock. + +After diff/edge landings, integrated main513 tests pass; analysis clean. Source +changes include22 diff files/+4511 lines after native-default correction and6 +edge files/+932 lines. Diff pipeline's request for custom fonts/palette conflicted +with user intent; manager reproduced native-style assertions failing, removed +font assets/pubspec registration/fixed colors, retained exact patch/capture facts, +and rebuilt/reran real browser fixture:18 captures including both native phone2x +views inspected. No fontFamily/fontSize/FontWeight/literalColor override remains +under changes/. No new preview build or shell registration claimed. + +After chat landing, manager reran integrated suite:448 tests pass; analysis clean. +Chat/settings are source landings, not visible preview registrations. Preview +continues to serve the previously verified live Runs bundle. + +Settings37 landed after manager source/evidence check and39 focused tests. A +separate small manager correction starts the already-connected client's ping +before preference loading rather than rendering false build/time unavailability +on the first frame. New delayed-store regression failed on the original and +passes with fix; also checks one ping only and stale pong ignored on disconnect. +Integrated main now415 tests pass; analysis clean. No new browser capture for +the first-frame correction; shell registration still needs native-host framing +and shared-client wiring, so Settings is not yet claimed delivered in preview. + +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) +**Installed/recovered after37 and42 finished:** confirmed zero active/queued runs +and zero recorded active agents; backed up SQLite with backup API, binary/plist +and exact34/39 records under ~/.local/share/pipelines/backups/inlinefix-c303756. +Atomically installed staged c303756 binary; restarted ONLY +gui/501/net.awan.pipelines.server. Ping verified clean exact commit +c30375626f6dcd100d33054687b79f5d8ba58336; binary SHA256 +c281c400d5fa0ffcc6326694e373fc08914f5b43ec03f0c0cd9350e6d3c2da0b. +Repair34/3 complete71 messages/4,676,625 bytes;39/5 complete56 messages/5,375,192 +bytes. Neither truncated. Compared all original step session IDs/outputs against +before backup: unchanged. Both cleared export waits and resumed recorded Code +edges. Restart-induced wait EOFs were expected; reattached individual34/39 waits +using new matching private CLI pipelines-cli-inlinefix-c303756 in approved temp. +No web/preview/OpenCode/ntfy restart, database edits or evidence overwrites. +With service window complete admitted micro-runs64/65/66 concurrently. No pipeline +definition or version was created/changed. + +Historical preparation details: +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; + candidate branch has it merged. Source is preserved, awaiting corrective + commit and expanded lifecycle/decision regression tests before landing. +- F2 UIReview was auto-skipped despite rendered shell changes (existing server + classifies workspace-relative lib/ paths as nonvisual). Do not change server; + manager obtains browser evidence directly and keeps rendered acceptance open. +- Direct Luna correction agents are scoped to the idle F2/F3 worktrees. No + recovery workflow or pipeline version was created. P1 is independent and + 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 diff --git a/app/lib/application/app.dart b/app/lib/application/app.dart new file mode 100644 index 00000000..311a4a8c --- /dev/null +++ b/app/lib/application/app.dart @@ -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 this.routerConfig, + this.cupertino, + }) : destinationBodies = const {}, + destination = null, + onDestinationSelected = null; + + final Map destinationBodies; + final bool? cupertino; + final AppDestination? destination; + final ValueChanged? onDestinationSelected; + final RouterConfig? 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; +} diff --git a/app/lib/application/app_route.dart b/app/lib/application/app_route.dart new file mode 100644 index 00000000..889f04f5 --- /dev/null +++ b/app/lib/application/app_route.dart @@ -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 = []; + 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); +} diff --git a/app/lib/application/app_router.dart b/app/lib/application/app_router.dart new file mode 100644 index 00000000..44c87efb --- /dev/null +++ b/app/lib/application/app_router.dart @@ -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 { + const AppRouteParser(); + + @override + Future 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 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(); + static const _pageKey = ValueKey('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(key: _pageKey, child: child) + else + MaterialPage(key: _pageKey, child: child), + ], + onDidRemovePage: (_) {}, + ); + } + + @override + Future setInitialRoutePath(AppRoute configuration) async { + _route = configuration; + } + + @override + Future setNewRoutePath(AppRoute configuration) async { + if (configuration == _route) return; + _route = configuration; + notifyListeners(); + } + + @override + Future 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)); +} diff --git a/app/lib/application/app_session.dart b/app/lib/application/app_session.dart new file mode 100644 index 00000000..39a48df8 --- /dev/null +++ b/app/lib/application/app_session.dart @@ -0,0 +1,173 @@ +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 Uri? endpoint, PipelinesClient? client}) + : _initialEndpoint = endpoint, + _client = client ?? PipelinesClient() { + _states = _client.states.listen(_onState); + _frames = _client.frames.listen(_onFrame); + } + + final Uri? _initialEndpoint; + final PipelinesClient _client; + late final StreamSubscription _states; + late final StreamSubscription _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; + + /// Settings controls the same transport; it must never create another socket. + PipelinesClient get client => _client; + Uri? get endpoint => _client.endpoint ?? _initialEndpoint; + 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 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 retry() async { + if (_client.state.kind == ConnectionKind.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 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(); + } +} diff --git a/app/lib/application/app_url_strategy.dart b/app/lib/application/app_url_strategy.dart new file mode 100644 index 00000000..db9fd768 --- /dev/null +++ b/app/lib/application/app_url_strategy.dart @@ -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(); diff --git a/app/lib/application/app_url_strategy_stub.dart b/app/lib/application/app_url_strategy_stub.dart new file mode 100644 index 00000000..04f5e160 --- /dev/null +++ b/app/lib/application/app_url_strategy_stub.dart @@ -0,0 +1 @@ +void useAppUrlStrategy() {} diff --git a/app/lib/application/app_url_strategy_web.dart b/app/lib/application/app_url_strategy_web.dart new file mode 100644 index 00000000..3d682e7a --- /dev/null +++ b/app/lib/application/app_url_strategy_web.dart @@ -0,0 +1,3 @@ +import 'package:flutter_web_plugins/url_strategy.dart'; + +void useAppUrlStrategy() => usePathUrlStrategy(); diff --git a/app/lib/application/bootstrap.dart b/app/lib/application/bootstrap.dart new file mode 100644 index 00000000..85accfc4 --- /dev/null +++ b/app/lib/application/bootstrap.dart @@ -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)); +} diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart new file mode 100644 index 00000000..f9c02e35 --- /dev/null +++ b/app/lib/application/pipelines_app.dart @@ -0,0 +1,135 @@ +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 '../features/settings/settings_screen.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 createState() => _PipelinesAppState(); +} + +class _PipelinesAppState extends State { + late final AppSession _session; + late final AppRouterDelegate _delegate; + late final RouteInformationProvider _provider; + late final bool _ownsProvider; + late final RouterConfig _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( + 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.settings: (_) => SettingsScreen( + client: _session.client, + initialEndpoint: _session.endpoint, + embedded: true, + ), + }, + ); + + 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; +} diff --git a/app/lib/application/runs_destination.dart b/app/lib/application/runs_destination.dart new file mode 100644 index 00000000..ca4e5481 --- /dev/null +++ b/app/lib/application/runs_destination.dart @@ -0,0 +1,250 @@ +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? onRunSelected; + final VoidCallback? onBack; + + @override + Widget build(BuildContext context) => AnimatedBuilder( + animation: session, + builder: (context, _) { + final cupertino = usesCupertinoHost(context); + if ((server.requiresConfiguration || server.error != null) && + session.endpoint == 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')), + ], + ), + ), + ); + } +} diff --git a/app/lib/application/server_endpoint.dart b/app/lib/application/server_endpoint.dart new file mode 100644 index 00000000..84b1c3e8 --- /dev/null +++ b/app/lib/application/server_endpoint.dart @@ -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); + } + } +} diff --git a/app/lib/core/transport/connection_state.dart b/app/lib/core/transport/connection_state.dart new file mode 100644 index 00000000..f8d6d32f --- /dev/null +++ b/app/lib/core/transport/connection_state.dart @@ -0,0 +1,27 @@ +enum ConnectionKind { idle, connecting, connected, disconnected } + +class ConnectionState { + const ConnectionState( + this.kind, { + this.attempt = 0, + this.reason = '', + this.retrying = false, + }); + final ConnectionKind kind; + final int attempt; + final String reason; + final bool retrying; +} + +class ProtocolError implements Exception { + const ProtocolError(this.message); + final String message; + @override + String toString() => message; +} + +class NotConnectedError implements Exception { + const NotConnectedError(); + @override + String toString() => 'Not connected to the Pipelines server'; +} diff --git a/app/lib/core/transport/pipelines_client.dart b/app/lib/core/transport/pipelines_client.dart new file mode 100644 index 00000000..2560a238 --- /dev/null +++ b/app/lib/core/transport/pipelines_client.dart @@ -0,0 +1,249 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:web_socket_channel/web_socket_channel.dart'; + +import '../api_gateway.dart'; +import 'connection_state.dart'; +import 'server_url.dart'; + +export 'connection_state.dart'; + +typedef ChannelFactory = WebSocketChannel Function(Uri uri); + +/// One correlated websocket transport shared by all feature gateways. +class PipelinesClient implements ApiGateway { + PipelinesClient({ + ChannelFactory? channelFactory, + this.requestTimeout = const Duration(seconds: 30), + this.backoffBase = const Duration(seconds: 1), + this.backoffMax = const Duration(seconds: 30), + }) : _factory = channelFactory ?? WebSocketChannel.connect; + + final ChannelFactory _factory; + final Duration requestTimeout, backoffBase, backoffMax; + final _frames = StreamController.broadcast(); + final _states = StreamController.broadcast(); + final Map> _pending = {}; + WebSocketChannel? _channel; + StreamSubscription? _subscription; + Uri? _endpoint; + Timer? _reconnect; + int _generation = 0, _sequence = 0, _attempt = 0; + bool _manual = true, _disposed = false; + ConnectionState _state = const ConnectionState(ConnectionKind.idle); + Future _queue = Future.value(); + + @override + Stream get frames => _frames.stream; + Stream get states => _states.stream; + ConnectionState get state => _state; + + /// Last validated endpoint, including changes made through native Settings. + Uri? get endpoint => _endpoint; + + Future connect(Uri uri) async { + if (_disposed) throw StateError('Client has been disposed'); + final endpoint = ServerUrl.validate(uri.toString()); + _endpoint = Uri.parse(endpoint.wsUrl); + _manual = false; + _attempt = 0; + _reconnect?.cancel(); + await _open(); + } + + Future _open() async { + final endpoint = _endpoint; + if (endpoint == null || _disposed) return; + final generation = ++_generation; + _setState(ConnectionState(ConnectionKind.connecting, attempt: ++_attempt)); + final old = _channel; + _channel = null; + _failPending('Connection replaced'); + if (old != null) unawaited(old.sink.close()); + final subscription = _subscription; + _subscription = null; + await subscription?.cancel(); + if (generation != _generation || _manual || _disposed) return; + try { + final channel = _factory(endpoint); + _channel = channel; + _subscription = channel.stream.listen( + (data) { + if (generation == _generation) _onMessage(data); + }, + onError: (Object error) { + if (generation == _generation) _closed(error.toString()); + }, + onDone: () { + if (generation == _generation) _closed('Connection closed'); + }, + ); + await channel.ready; + if (generation != _generation) return; + _attempt = 0; + _setState(const ConnectionState(ConnectionKind.connected)); + } catch (error) { + if (generation == _generation) _closed(error.toString()); + } + } + + void _setState(ConnectionState value) { + _state = value; + if (!_states.isClosed) _states.add(value); + } + + @override + Future call(String type, [JsonMap fields = const {}]) { + final completer = Completer(); + final generation = _generation; + final snapshot = Map.of(fields); + final run = _queue.then( + (_) => _sendCall(type, snapshot, completer, generation), + ); + _queue = run.catchError((_) {}); + return completer.future; + } + + Future _sendCall( + String type, + JsonMap fields, + Completer result, + int generation, + ) async { + if (generation != _generation) { + result.completeError(StateError('Connection replaced')); + return; + } + final channel = _channel; + if (channel == null || _state.kind != ConnectionKind.connected) { + result.completeError(const NotConnectedError()); + return; + } + final id = 'flutter-${++_sequence}'; + _pending[id] = result; + final timer = Timer(requestTimeout, () { + if (_pending.remove(id) != null) { + result.completeError( + TimeoutException( + 'request timed out after ${requestTimeout.inMilliseconds}ms', + ), + ); + } + }); + result.future.then( + (_) => timer.cancel(), + onError: (Object error, StackTrace stack) => timer.cancel(), + ); + try { + channel.sink.add(jsonEncode({...fields, 'type': type, 'id': id})); + } catch (error) { + timer.cancel(); + if (_pending.remove(id) != null) result.completeError(error); + } + // Match the existing client's serialized request semantics, even on errors. + try { + await result.future; + } catch (_) { + /* The caller receives the error. */ + } + } + + String sendOnly(String type, [JsonMap fields = const {}]) { + final channel = _channel; + if (channel == null || _state.kind != ConnectionKind.connected) { + throw const NotConnectedError(); + } + final id = 'flutter-${++_sequence}'; + channel.sink.add(jsonEncode({...fields, 'type': type, 'id': id})); + return id; + } + + void _onMessage(dynamic data) { + if (data is! String) return; + final Object? decoded; + try { + decoded = jsonDecode(data); + } on FormatException { + return; + } + if (decoded is! Map) return; + final message = decoded; + final id = message['id']; + final pending = id is String ? _pending.remove(id) : null; + if (pending != null) { + if (message['type'] == 'error') { + final reason = '${message['error'] ?? ''}'.trim(); + pending.completeError( + ProtocolError(reason.isEmpty ? 'server error' : reason), + ); + } else { + pending.complete(message); + } + } else if (!_frames.isClosed) { + _frames.add(message); + } + } + + void _failPending(String reason) { + final values = _pending.values.toList(); + _pending.clear(); + for (final item in values) { + if (!item.isCompleted) item.completeError(StateError(reason)); + } + } + + void _closed(String reason) { + _generation++; + final channel = _channel; + final subscription = _subscription; + _channel = null; + _subscription = null; + if (subscription != null) unawaited(subscription.cancel()); + if (channel != null) unawaited(channel.sink.close().catchError((_) {})); + _failPending(reason); + if (_manual || _disposed) { + _setState(const ConnectionState(ConnectionKind.idle)); + return; + } + _setState( + ConnectionState( + ConnectionKind.disconnected, + attempt: _attempt, + reason: reason, + retrying: true, + ), + ); + final shift = (_attempt - 1).clamp(0, 6); + final delay = backoffBase * (1 << shift); + _reconnect?.cancel(); + _reconnect = Timer( + delay > backoffMax ? backoffMax : delay, + () => unawaited(_open()), + ); + } + + Future disconnect() async { + _manual = true; + _reconnect?.cancel(); + final generation = ++_generation; + final channel = _channel; + _channel = null; + final subscription = _subscription; + _subscription = null; + _failPending('Disconnected'); + await subscription?.cancel(); + if (channel != null) await channel.sink.close(); + if (generation == _generation) { + _setState(const ConnectionState(ConnectionKind.idle)); + } + } + + Future dispose() async { + if (_disposed) return; + _disposed = true; + await disconnect(); + await _frames.close(); + await _states.close(); + } +} diff --git a/app/lib/core/transport/server_url.dart b/app/lib/core/transport/server_url.dart new file mode 100644 index 00000000..b08a10ac --- /dev/null +++ b/app/lib/core/transport/server_url.dart @@ -0,0 +1,90 @@ +/// Validation result for a configured Pipelines websocket endpoint. +class ServerUrl { + const ServerUrl._({ + required this.wsUrl, + required this.httpUrl, + required this.host, + required this.port, + required this.secure, + }); + + final String wsUrl; + final String httpUrl; + final String host; + final int port; + final bool secure; + + static ServerUrl validate(String raw) { + final value = raw.trim(); + if (value.isEmpty) { + throw const FormatException( + 'Enter the Pipelines server URL, for example ws://192.168.1.20:8081/connect', + ); + } + final uri = Uri.tryParse(value); + if (uri == null || !uri.hasScheme) { + throw const FormatException('That is not a valid URL.'); + } + final scheme = uri.scheme.toLowerCase(); + if (scheme != 'ws' && scheme != 'wss') { + throw FormatException( + 'Unsupported scheme "$scheme"; use ws:// (trusted LAN/VPN) or wss://', + ); + } + if (uri.userInfo.isNotEmpty) { + throw const FormatException( + 'Credentials are not supported; the server has no authentication. Remove userinfo from the URL', + ); + } + if (uri.hasFragment) { + throw const FormatException( + 'Remove the # fragment; it is not part of the server endpoint', + ); + } + if (uri.host.isEmpty) { + throw const FormatException( + 'The URL is missing a host, for example ws://192.168.1.20:8081/connect', + ); + } + if (!uri.hasAuthority || + (uri.hasPort && (uri.port < 1 || uri.port > 65535))) { + throw const FormatException( + 'That is not a valid server authority or port.', + ); + } + final secure = scheme == 'wss'; + final port = uri.hasPort + ? uri.port + : secure + ? 443 + : 80; + final path = uri.path.isEmpty || uri.path == '/' ? '/connect' : uri.path; + final normalized = uri.replace(scheme: scheme, path: path); + return ServerUrl._( + wsUrl: normalized.toString(), + httpUrl: normalized.replace(scheme: secure ? 'https' : 'http').toString(), + host: uri.host, + port: port, + secure: secure, + ); + } + + static Uri? resolveArtifactUrl(String configured, String artifactUrl) { + final path = artifactUrl.trim(); + if (path.isEmpty) return null; + final parsed = Uri.tryParse(path); + if (parsed != null && + (parsed.scheme == 'http' || parsed.scheme == 'https')) { + return parsed; + } + try { + final endpoint = validate(configured); + final origin = Uri.parse( + endpoint.httpUrl, + ).replace(path: '/', query: null); + return origin.resolve(path.replaceFirst(RegExp(r'^/+'), '')); + } on FormatException { + return null; + } + } +} diff --git a/app/lib/features/artifacts/domain/artifact_capture.dart b/app/lib/features/artifacts/domain/artifact_capture.dart new file mode 100644 index 00000000..6f081d16 --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_capture.dart @@ -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 + ? [ + for (final item in value) + if (item is Map) + ArtifactRecord.fromJson(Map.from(item)), + ] + : const []; + return ArtifactCapture._( + availability: available + ? ArtifactCaptureAvailability.recorded + : ArtifactCaptureAvailability.unavailable, + artifacts: List.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 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; + } +} diff --git a/app/lib/features/artifacts/domain/artifact_groups.dart b/app/lib/features/artifacts/domain/artifact_groups.dart new file mode 100644 index 00000000..bfa0707e --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_groups.dart @@ -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 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 _orderedBySequence(List 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 [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 artifactGroups(List steps) { + if (steps.isEmpty) return const []; + + final attributed = >{}; + final seenPublic = {}; + for (final recordedStep in _orderedBySequence(steps)) { + final repairs = repairArtifactNames(recordedStep); + final kept = []; + 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.unmodifiable(kept); + } + + final groups = []; + 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.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 visitArtifacts(JsonMap step, List runSteps) { + final all = stageArtifacts(step); + if (runSteps.isEmpty) return all; + final seen = {}; + 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 [ + for (final artifact in all) + if (!artifact.isPublicName || !seen.contains(artifact.name)) artifact, + ]; +} diff --git a/app/lib/features/artifacts/domain/artifact_kind.dart b/app/lib/features/artifacts/domain/artifact_kind.dart new file mode 100644 index 00000000..7bac7708 --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_kind.dart @@ -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 _archiveExtensions = { + 'zip', + 'tar', + 'gz', + 'tgz', + 'bz2', + 'xz', + 'rar', + '7z', + 'jar', + 'war', +}; + +const Set _archiveMimes = { + 'application/zip', + 'application/gzip', + 'application/x-tar', + 'application/x-7z-compressed', + 'application/x-rar-compressed', + 'application/java-archive', +}; + +const Set _spreadsheetExtensions = { + 'csv', + 'tsv', + 'xls', + 'xlsx', + 'ods', +}; + +const Set _spreadsheetMimes = { + 'text/csv', + 'text/tab-separated-values', + 'application/vnd.ms-excel', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', +}; + +const Set _codeExtensions = { + '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 _codeMimes = { + '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 _documentExtensions = { + 'txt', + 'md', + 'markdown', + 'rst', + 'doc', + 'docx', + 'odt', + 'rtf', + 'html', + 'htm', +}; + +const Set _markdownExtensions = {'md', 'markdown', 'txt'}; + +const Set _documentMimes = { + 'application/msword', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'application/rtf', +}; + +const Map _kindLabels = { + 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'; +} diff --git a/app/lib/features/artifacts/domain/artifact_record.dart b/app/lib/features/artifacts/domain/artifact_record.dart new file mode 100644 index 00000000..6c6bc845 --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_record.dart @@ -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 systemArtifactNames = [ + '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.unmodifiable( + json.map((key, value) => MapEntry(key, _frozen(value))), + ); + + static dynamic _frozen(dynamic value) { + if (value is Map) return _frozenMap(Map.from(value)); + if (value is List) return List.unmodifiable(value.map(_frozen)); + return value; + } +} + +bool isSystemArtifactName(String name) => systemArtifactNames.contains(name); diff --git a/app/lib/features/artifacts/domain/artifact_selection.dart b/app/lib/features/artifacts/domain/artifact_selection.dart new file mode 100644 index 00000000..4f976473 --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_selection.dart @@ -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 artifactsOf(JsonMap step) { + final value = step['artifacts']; + if (value is! List) return const []; + return [ + for (final item in value) + if (item is Map) ArtifactRecord.fromJson(Map.from(item)), + ]; +} + +/// The html names a visit's session-export repairs produced. +Set repairArtifactNames(JsonMap step) { + final value = step['session_export_repairs']; + if (value is! List) return const {}; + return { + 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 presentedArtifacts(Iterable artifacts) { + return [ + 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 stageArtifactsFrom( + Iterable artifacts, { + Set repairs = const {}, +}) { + return [ + 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 systemArtifactsFrom( + Iterable artifacts, { + Set repairs = const {}, +}) { + return [ + 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 stageArtifacts(JsonMap step) => + stageArtifactsFrom(artifactsOf(step), repairs: repairArtifactNames(step)); + +List systemArtifacts(JsonMap step) => + systemArtifactsFrom(artifactsOf(step), repairs: repairArtifactNames(step)); diff --git a/app/lib/features/artifacts/domain/artifact_summary.dart b/app/lib/features/artifacts/domain/artifact_summary.dart new file mode 100644 index 00000000..44161a86 --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_summary.dart @@ -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 steps, {required bool executing}) { + final recorded = artifactGroups( + steps, + ).fold(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 artifactCaptureNotes(JsonMap step) { + final notes = []; + 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; +} diff --git a/app/lib/features/artifacts/domain/artifact_url.dart b/app/lib/features/artifacts/domain/artifact_url.dart new file mode 100644 index 00000000..ea16d505 --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_url.dart @@ -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 _unsafePrefixes = ['//', 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; + } +} diff --git a/app/lib/features/artifacts/domain/gallery_navigation.dart b/app/lib/features/artifacts/domain/gallery_navigation.dart new file mode 100644 index 00000000..ca115a73 --- /dev/null +++ b/app/lib/features/artifacts/domain/gallery_navigation.dart @@ -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 pagedArtifacts(List groups) { + final pages = []; + 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.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 viewerIndexByUrl(List groups) { + final indices = {}; + 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}'; +} diff --git a/app/lib/features/artifacts/ui/artifact_visit_list.dart b/app/lib/features/artifacts/ui/artifact_visit_list.dart new file mode 100644 index 00000000..82cf0aa8 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_visit_list.dart @@ -0,0 +1,231 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; +import '../domain/artifact_groups.dart'; +import '../domain/artifact_kind.dart'; +import '../domain/artifact_record.dart'; + +/// A selection callback carrying the recorded group and the exact record the +/// operator chose, so the visit is never lost when two groups share a name. +typedef ArtifactSelected = + void Function(ArtifactGroup group, ArtifactRecord artifact); + +/// The identity of [artifact] inside [group], for +/// [ArtifactVisitList.selectedIdentity]. +/// +/// The recorded stage visit is part of the key, so two visits that both +/// recorded `result.csv` stay distinct even when their urls are identical. +/// A filename alone is never an identity. +String artifactVisitIdentity(ArtifactGroup group, ArtifactRecord artifact) { + final recorded = artifact.hasUrl ? artifact.url : artifact.name; + return '${group.stageKey}\u0000${group.visit}\u0000$recorded'; +} + +/// A read-only, selectable list of recorded artifact groups. +/// +/// Each group shows its recorded stage and visit, and each row its recorded +/// filename, content type and size. Rendering uses the host's own controls: +/// Material list tiles under [MaterialApp] and grouped Cupertino list sections +/// under [CupertinoApp]. It never resolves a url, opens a preview, downloads, +/// shares or filters; the only action is [onSelected]. +class ArtifactVisitList extends StatelessWidget { + const ArtifactVisitList({ + super.key, + required this.groups, + this.selectedIdentity, + this.onSelected, + }); + + final List groups; + + /// [artifactVisitIdentity] of the selected artifact, or null for none. + final String? selectedIdentity; + + final ArtifactSelected? onSelected; + + @override + Widget build(BuildContext context) { + if (groups.isEmpty) { + return const _NoArtifacts(); + } + if (usesCupertinoHost(context)) { + return ListView( + children: [ + for (final group in groups) + CupertinoListSection.insetGrouped( + // `container` keeps the heading a separate semantics node. Without + // it the heading merges into the neighbouring row button, so it is + // not navigable as a heading and activating it selects the row. + header: Semantics( + container: true, + header: true, + child: Text(_groupLabel(group)), + ), + hasLeading: false, + children: [ + for (var index = 0; index < group.artifacts.length; index += 1) + _CupertinoRow( + key: _rowKey(group, group.artifacts[index], index), + group: group, + artifact: group.artifacts[index], + selected: _isSelected(group, group.artifacts[index]), + onSelected: onSelected, + ), + ], + ), + ], + ); + } + return ListView( + children: [ + for (final group in groups) ...[ + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 16, 16, 4), + child: Semantics( + container: true, + header: true, + child: Text(_groupLabel(group)), + ), + ), + for (var index = 0; index < group.artifacts.length; index += 1) + _MaterialRow( + key: _rowKey(group, group.artifacts[index], index), + group: group, + artifact: group.artifacts[index], + selected: _isSelected(group, group.artifacts[index]), + onSelected: onSelected, + ), + ], + ], + ); + } + + bool _isSelected(ArtifactGroup group, ArtifactRecord artifact) => + selectedIdentity == artifactVisitIdentity(group, artifact); + + static Key _rowKey(ArtifactGroup group, ArtifactRecord artifact, int index) => + ValueKey('${artifactVisitIdentity(group, artifact)}\u0000$index'); +} + +/// The recorded group heading, matching the web client's group vocabulary. +String _groupLabel(ArtifactGroup group) => + '${group.stageKey} · visit ${group.visit}'; + +/// The displayed artifact name: a missing server name stays explicit. +String _displayName(ArtifactRecord artifact) => + artifact.name.isEmpty ? '(unnamed artifact)' : artifact.name; + +/// The recorded MIME and byte size, never inferred from the name. +/// +/// The value and its unit are joined by a non-breaking space so a narrow row +/// never wraps `120.6` away from `KiB`. +String _facts(ArtifactRecord artifact) { + final type = artifact.contentType.split(';').first.trim(); + final mime = type.isEmpty ? 'type not recorded' : type; + final size = humanBytes(artifact.sizeBytes).replaceFirst(' ', '\u00a0'); + return '$mime · $size'; +} + +class _MaterialRow extends StatelessWidget { + const _MaterialRow({ + super.key, + required this.group, + required this.artifact, + required this.selected, + required this.onSelected, + }); + + final ArtifactGroup group; + final ArtifactRecord artifact; + final bool selected; + final ArtifactSelected? onSelected; + + @override + Widget build(BuildContext context) { + return ListTile( + selected: selected, + title: Text(_displayName(artifact)), + subtitle: Text(_facts(artifact)), + trailing: selected ? const Icon(Icons.check) : null, + onTap: onSelected == null ? null : () => onSelected!(group, artifact), + ); + } +} + +class _CupertinoRow extends StatelessWidget { + const _CupertinoRow({ + super.key, + required this.group, + required this.artifact, + required this.selected, + required this.onSelected, + }); + + final ArtifactGroup group; + final ArtifactRecord artifact; + final bool selected; + final ArtifactSelected? onSelected; + + @override + Widget build(BuildContext context) { + final textTheme = CupertinoTheme.of(context).textTheme; + final factsStyle = textTheme.textStyle.copyWith( + color: CupertinoColors.secondaryLabel.resolveFrom(context), + ); + final content = DefaultTextStyle.merge( + style: textTheme.textStyle, + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(_displayName(artifact)), + Text(_facts(artifact), style: factsStyle), + ], + ), + ), + if (selected) const Icon(CupertinoIcons.check_mark), + ], + ), + ); + // `container` makes this row its own semantics node, so the section + // heading stays a separate header node and never covers the row. + return Semantics( + container: true, + selected: selected, + child: SizedBox( + width: double.infinity, + // A read-only row is not a button: a disabled CupertinoButton would + // still expose a button role to assistive technology. + child: onSelected == null + ? Padding( + padding: kCupertinoButtonPadding[CupertinoButtonSize.large]!, + child: content, + ) + : CupertinoButton( + alignment: AlignmentDirectional.centerStart, + onPressed: () => onSelected!(group, artifact), + child: content, + ), + ), + ); + } +} + +class _NoArtifacts extends StatelessWidget { + const _NoArtifacts(); + + @override + Widget build(BuildContext context) { + return ListView( + children: const [ + Padding( + padding: EdgeInsets.all(16), + child: Text('No stage artifacts recorded.'), + ), + ], + ); + } +} diff --git a/app/lib/features/changes/changes.dart b/app/lib/features/changes/changes.dart new file mode 100644 index 00000000..ac7e0e4d --- /dev/null +++ b/app/lib/features/changes/changes.dart @@ -0,0 +1,17 @@ +/// Public API for the run Changes feature. Integration imports this barrel: +/// +/// * [ChangesViewer] - the whole run, from `run detail['steps']`. +/// * [FileDiffViewer] and [showFileDiffViewer] - one recorded file. +/// * The pure domain models/parsers/wording for tests and other surfaces. +library; + +export 'domain/change_capture.dart'; +export 'domain/change_kind.dart'; +export 'domain/change_wording.dart'; +export 'domain/file_change.dart'; +export 'domain/run_changes.dart'; +export 'domain/unified_patch.dart'; +export 'widgets/change_style.dart' show DiffForm, usesCupertino; +export 'widgets/changes_viewer.dart'; +export 'widgets/file_diff_viewer.dart'; +export 'widgets/patch_view.dart'; diff --git a/app/lib/features/changes/domain/change_capture.dart b/app/lib/features/changes/domain/change_capture.dart new file mode 100644 index 00000000..0986de37 --- /dev/null +++ b/app/lib/features/changes/domain/change_capture.dart @@ -0,0 +1,145 @@ +import '../../../core/api_gateway.dart'; +import 'file_change.dart'; + +/// One step's recorded `file_changes` capture. A null capture on a +/// [StageCapture] means the step recorded no capture at all - it must never be +/// read as "the workspace was unchanged". +class ChangeCapture { + ChangeCapture({ + required this.status, + this.scope = '', + required this.files, + this.skipped = 0, + this.omitted = 0, + this.diagnostic = '', + }); + + final String status; + final String scope; + final List files; + final int skipped; + final int omitted; + final String diagnostic; + + String get _state => status.trim().toLowerCase(); + bool get unavailable => _state == 'unavailable'; + bool get partial => _state == 'partial'; + bool get complete => _state == 'complete' || _state.isEmpty; + bool get hasFiles => files.isNotEmpty; + + factory ChangeCapture.fromJson(JsonMap json) { + final rawFiles = json['files']; + final files = []; + if (rawFiles is List) { + for (final value in rawFiles) { + final file = FileChange.tryParse(value); + if (file != null) files.add(file); + } + } + return ChangeCapture( + status: '${json['status'] ?? ''}'.trim(), + scope: '${json['scope'] ?? ''}'.trim(), + files: List.unmodifiable(files), + skipped: _count(json['skipped']), + omitted: _count(json['omitted']), + diagnostic: '${json['diagnostic'] ?? ''}'.trim(), + ); + } +} + +/// The honest wording for a `file_changes` value that exists but is not an +/// object. Such a record is unreadable evidence, not an observed no-change. +const malformedCaptureDetail = + 'The recorded change capture could not be read, so no changes can be ' + 'shown. This does not mean the workspace was unchanged.'; + +/// One stage visit and the capture it recorded, in run order. `capture == null` +/// is missing evidence, not an observed no-change. +class StageCapture { + const StageCapture({ + required this.sequence, + required this.visit, + required this.stage, + required this.stepStatus, + required this.capture, + }); + + /// The run-wide step ordinal, used for ordering and widget keys. + final int sequence; + + /// The display visit number within [stage]: the recorded `control.visit` when + /// positive, otherwise the visit's 1-based position in its stage. Mirrors the + /// web client's `displayVisit`; [sequence] is not the visit number. + final int visit; + final String stage; + final String stepStatus; + final ChangeCapture? capture; + + bool get missing => capture == null; + + /// Parses one step. [position] is the step's 1-based position among the + /// steps of its own stage, used when the step recorded no `control.visit`. + factory StageCapture.fromStep(JsonMap step, {int position = 1}) { + final raw = step['file_changes']; + return StageCapture( + sequence: _count(step['sequence']), + visit: _displayVisit(step, position), + stage: _stageName(step), + stepStatus: '${step['status'] ?? ''}'.trim(), + // A non-null but malformed value still records that a capture existed; + // only null is missing evidence. A value we cannot read is unavailable, + // never a fabricated empty capture that would claim "no changes". + capture: raw == null + ? null + : raw is Map + ? ChangeCapture.fromJson(Map.from(raw)) + : ChangeCapture( + status: 'unavailable', + files: const [], + diagnostic: malformedCaptureDetail, + ), + ); + } +} + +/// Groups a run's steps into stage/visit captures ordered by numeric sequence, +/// stable for ties. A step with a null `file_changes` still appears so its +/// missing evidence is visible next to the captures that did record. +List stageCaptures(List steps) { + final indexed = <({JsonMap step, int index})>[]; + for (var i = 0; i < steps.length; i++) { + indexed.add((step: steps[i], index: i)); + } + indexed.sort((a, b) { + final bySequence = _count( + a.step['sequence'], + ).compareTo(_count(b.step['sequence'])); + return bySequence != 0 ? bySequence : a.index.compareTo(b.index); + }); + // The visit position is per stage, in the same sequence order (the web + // client's displayVisit), not the run-wide step ordinal. + final positions = {}; + final captures = []; + for (final entry in indexed) { + final stage = _stageName(entry.step); + final position = (positions[stage] ?? 0) + 1; + positions[stage] = position; + captures.add(StageCapture.fromStep(entry.step, position: position)); + } + return captures; +} + +/// The recorded `control.visit` when positive, else the stage position. +int _displayVisit(JsonMap step, int position) { + final control = step['control']; + final recorded = control is Map ? control['visit'] : null; + if (recorded is num && recorded > 0) return recorded.toInt(); + return position < 1 ? 1 : position; +} + +String _stageName(JsonMap step) { + final name = '${step['stage'] ?? ''}'.trim(); + return name.isEmpty ? 'stage' : name; +} + +int _count(dynamic value) => value is num ? value.toInt() : 0; diff --git a/app/lib/features/changes/domain/change_kind.dart b/app/lib/features/changes/domain/change_kind.dart new file mode 100644 index 00000000..8a9ff730 --- /dev/null +++ b/app/lib/features/changes/domain/change_kind.dart @@ -0,0 +1,30 @@ +/// The three recorded file-change kinds plus a safe fallback for future server +/// values. Ported from `web/src/changes.js` (and the Android client's +/// `ui/changes/RunChanges.kt`) so the Flutter client says the same words. +enum ChangeKind { added, modified, deleted, other } + +/// Maps a server kind token to a [ChangeKind]. The token is trimmed and +/// lowercased; an unknown or blank token stays [ChangeKind.other] rather than +/// being guessed, so a future server value is shown read-only instead of +/// mislabelled. +ChangeKind changeKind(dynamic kind) => + switch ('${kind ?? ''}'.trim().toLowerCase()) { + 'added' => ChangeKind.added, + 'modified' => ChangeKind.modified, + 'deleted' => ChangeKind.deleted, + _ => ChangeKind.other, + }; + +/// The word a file's kind is named by in the list and the diff header. +String changeKindLabel(ChangeKind kind) => switch (kind) { + ChangeKind.added => 'added', + ChangeKind.modified => 'modified', + ChangeKind.deleted => 'deleted', + ChangeKind.other => 'changed', +}; + +/// The kind word as the viewer header shows it, first letter capitalised. +String changeKindTitle(ChangeKind kind) { + final label = changeKindLabel(kind); + return label.isEmpty ? label : label[0].toUpperCase() + label.substring(1); +} diff --git a/app/lib/features/changes/domain/change_wording.dart b/app/lib/features/changes/domain/change_wording.dart new file mode 100644 index 00000000..0d844b60 --- /dev/null +++ b/app/lib/features/changes/domain/change_wording.dart @@ -0,0 +1,184 @@ +import 'change_capture.dart'; +import 'file_change.dart'; +import 'run_changes.dart'; +import 'unified_patch.dart'; + +/// The honest messages the viewer and its tests share. Spelled once, matching +/// the web client's `web/src/changes.js`. +const binaryDiffMessage = + 'This is a binary file: the server recorded the change but has no textual ' + 'diff to show.'; +const truncatedPatchNote = + 'The server truncated this patch at its capture limit; the raw text is the ' + 'whole record.'; +const noLineChangesMessage = 'no line changes recorded'; + +/// A step with no capture recorded no evidence; it does not prove the workspace +/// was unchanged. +const missingCaptureDetail = + 'This visit recorded no change capture (a historical step, or a stage that ' + 'does not capture). That does not mean the workspace was unchanged.'; +const pendingCaptureDetail = + 'The capture runs after the stage finishes; nothing is recorded yet.'; +const unavailableCaptureDetail = + 'The workspace snapshot could not be compared, so no changes can be shown.'; +const emptyCaptureDetail = + 'The captured snapshots were identical: the workspace was unchanged.'; +const partialCaptureDetail = 'Partial capture: some changes may be missing.'; + +/// The Changes section header's one-line summary: the observed file count, the +/// total `+N -M`, and the honest capture caveats. +String runChangesHeader(RunChanges changes) { + if (changes.unavailable) return 'Changes · capture unavailable'; + if (changes.files.isEmpty) { + if (changes.pending) return 'Changes · capture pending'; + if (changes.partial) return 'Changes · partial capture'; + if (changes.stepsWithChanges == 0) { + return 'Changes · not recorded for this run'; + } + if (changes.missingCaptures > 0) return 'Changes · capture incomplete'; + return 'Changes · no changes observed'; + } + final stat = changeStat(changes.added, changes.removed); + final count = changes.files.length; + final label = stat.isEmpty + ? '$count ${count == 1 ? 'file' : 'files'} changed' + : '$count ${count == 1 ? 'file' : 'files'} changed · $stat'; + if (changes.partial) return '$label · partial capture'; + if (changes.missingCaptures > 0) return '$label · capture incomplete'; + return label; +} + +/// The honest one-line note under the header for a capture that is not +/// complete, or "" when it was. +String runChangesNote(RunChanges changes) { + if (changes.unavailable) { + return changes.diagnostic.isNotEmpty + ? changes.diagnostic + : 'The workspace snapshot could not be compared; the changes below may ' + 'be incomplete.'; + } + var out = ''; + if (changes.partial) { + out = partialCaptureDetail; + final caveats = []; + if (changes.skipped > 0) caveats.add('${changes.skipped} files skipped'); + if (changes.omitted > 0) caveats.add('${changes.omitted} omitted'); + final truncated = changes.files.where((file) => file.truncated).length; + if (truncated > 0) caveats.add('$truncated truncated'); + if (caveats.isNotEmpty) out += ' (${caveats.join(', ')})'; + if (changes.diagnostic.isNotEmpty) out += ' ${changes.diagnostic}'; + } + if (changes.missingCaptures > 0) { + if (out.isNotEmpty) out += ' '; + out += + 'Missing capture: ${changes.missingCaptures} ' + '${changes.missingCaptures == 1 ? 'stage did' : 'stages did'} not ' + 'record changes.'; + } + return out.trim(); +} + +/// The file list's own summary line. +String changesListSummary(RunChanges changes) { + final count = + '${changes.files.length} ' + '${changes.files.length == 1 ? 'file' : 'files'} changed'; + final stat = changeStat(changes.added, changes.removed); + return stat.isEmpty ? count : '$count · $stat'; +} + +/// Why no change is listed: a pending capture, an unavailable one, a missing +/// capture or a recorded none. +String noChangeDetail(RunChanges changes) { + if (changes.pending) return pendingCaptureDetail; + if (changes.unavailable) return unavailableCaptureDetail; + if (changes.stepsWithChanges == 0) { + return 'This run recorded no change capture (a historical step, or a stage ' + 'that does not capture).'; + } + return emptyCaptureDetail; +} + +/// Why a file has no patch to render, in the entry's own recorded terms. +String patchUnavailableReason(FileChange file) { + if (file.truncated) { + return "The server truncated this file's patch at its capture limit; no " + 'diff text was recorded.'; + } + if (file.otherModeChange) { + return "Only the file's mode changed (${file.beforeMode ?? ''}→" + '${file.afterMode ?? ''}); the server recorded no text diff.'; + } + return 'The server recorded this change without a patch.'; +} + +/// The tags shown beside a file row: traits that change how the entry must be +/// read, never a fabricated diff. +List changeEntryTags(FileChange file) => file.tags; + +/// The row's secondary line for an aggregated entry: which stage(s) changed it +/// and how to read it. +String changeRowMeta(FileChange file) { + var out = file.steps.isEmpty ? '' : 'changed by ${file.steps.join(' → ')}'; + for (final tag in changeEntryTags(file)) { + out += '${out.isEmpty ? '' : ' · '}$tag'; + } + if (file.modeChanged && !file.binary) { + out += + '${out.isEmpty ? '' : ' · '}mode ${file.beforeMode ?? ''}→' + '${file.afterMode ?? ''}'; + } + return out; +} + +/// A compact per-entry line for a file row: stat, tags and mode, or the honest +/// no-line-change note. Content-driven; no fixed cell widths. +String changeFileMeta(FileChange file) { + final parts = []; + final stat = changeStat(file.added, file.removed); + if (stat.isNotEmpty) parts.add(stat); + parts.addAll(file.tags); + if (file.modeChanged && !file.binary) { + parts.add('mode ${file.beforeMode ?? ''}→${file.afterMode ?? ''}'); + } + return parts.isEmpty ? noLineChangesMessage : parts.join(' · '); +} + +/// A compact capture summary, e.g. +/// `partial (2 files), 1 skipped, 3 omitted · Excluded protected files.`. +/// Blank parts are omitted; an entirely blank capture renders as "". +String fileChangesSummary(ChangeCapture capture) { + var text = capture.status; + if (capture.files.isNotEmpty) { + if (text.isNotEmpty) text += ' '; + text += '(${capture.files.length} files)'; + } + if (capture.skipped > 0) { + if (text.isNotEmpty) text += ', '; + text += '${capture.skipped} skipped'; + } + if (capture.omitted > 0) { + if (text.isNotEmpty) text += ', '; + text += '${capture.omitted} omitted'; + } + if (capture.diagnostic.isNotEmpty) { + if (text.isNotEmpty) text += ' · '; + text += capture.diagnostic; + } + return text; +} + +/// Filters changed filenames by a case-insensitive substring, preserving the +/// recorded order. A blank query keeps every file. +List filterFileChanges(Iterable files, String query) { + final needle = query.trim().toLowerCase(); + final all = files.toList(growable: false); + if (needle.isEmpty) return all; + return all + .where((file) => file.path.toLowerCase().contains(needle)) + .toList(growable: false); +} + +/// The `N of M` position label a viewer can show for its open file. +String changePositionLabel(int index, int count) => '${index + 1} of $count'; diff --git a/app/lib/features/changes/domain/file_change.dart b/app/lib/features/changes/domain/file_change.dart new file mode 100644 index 00000000..0f8ccdcf --- /dev/null +++ b/app/lib/features/changes/domain/file_change.dart @@ -0,0 +1,117 @@ +import '../../../core/api_gateway.dart'; +import 'change_kind.dart'; +import 'unified_patch.dart'; + +/// One recorded file change, as the server's `file_changes.files[]` entry +/// describes it. A null/blank [patch] is a recorded fact (binary, truncated or +/// no text diff), never an invented empty diff. +class FileChange { + FileChange({ + required this.path, + required this.kind, + String? patch, + this.binary = false, + this.truncated = false, + String? beforeMode, + String? afterMode, + this.steps = const [], + ParsedPatch? parsedPatch, + }) : patch = _nonBlank(patch), + beforeMode = _nonBlank(beforeMode), + afterMode = _nonBlank(afterMode), + // Aggregate copies pass their already-parsed patch through instead of + // re-parsing the same recorded bytes for every stage that touched a path. + parsedPatch = parsedPatch ?? parseUnifiedPatch(patch); + + final String path; + final ChangeKind kind; + + /// The server's unified patch verbatim, or null when it recorded none. This + /// exact string is what Copy patch puts on the clipboard, including any + /// trailing newline or truncated final line. + final String? patch; + final bool binary; + final bool truncated; + final String? beforeMode; + final String? afterMode; + + /// Stage names that recorded a change to this path, in run order and deduped. + /// Empty for a single recorded entry; filled by [runChanges] aggregation. + final List steps; + + final ParsedPatch parsedPatch; + + int get added => parsedPatch.added; + int get removed => parsedPatch.removed; + + /// True when a patch the operator can read is present. + bool get hasPatch => !binary && patch != null; + + /// True when the recorded permissions differ. + bool get modeChanged => + beforeMode != null && afterMode != null && beforeMode != afterMode; + + /// True when the recorded permissions differ and no content change explains + /// it. The server records no text diff for a mode-only change. + bool get otherModeChange => + modeChanged && !binary && added == 0 && removed == 0; + + List get tags => [ + if (binary) 'binary', + if (truncated) 'truncated', + if (otherModeChange) 'mode change', + ]; + + FileChange withSteps(List value) => FileChange( + path: path, + kind: kind, + patch: patch, + binary: binary, + truncated: truncated, + beforeMode: beforeMode, + afterMode: afterMode, + steps: List.unmodifiable(value), + parsedPatch: parsedPatch, + ); + + /// Parses one server file entry; null when it has no usable path. The + /// capture owns the decision to skip such an entry, so it is never rendered + /// as an anonymous row. + static FileChange? tryParse(dynamic value) { + if (value is! Map) return null; + final json = Map.from(value); + final path = _text(json['path']); + if (path.trim().isEmpty) return null; + return FileChange( + path: path, + kind: changeKind(json['kind']), + patch: json['patch'] is String ? json['patch'] as String : null, + binary: json['binary'] == true, + truncated: json['truncated'] == true, + beforeMode: _textOrNull(json['before_mode']), + afterMode: _textOrNull(json['after_mode']), + ); + } + + /// Parses a required file entry. Integration code normally receives files + /// from [ChangeCapture] or [runChanges]; this constructor is for a viewer + /// opened directly with one recorded entry. + factory FileChange.fromJson(JsonMap json) { + final file = tryParse(json); + if (file == null) { + throw const FormatException('A recorded file change needs a path.'); + } + return file; + } +} + +/// A value kept as itself when present, else null (`?:` over nullable fields). +String? _textOrNull(dynamic value) => value == null ? null : '$value'; + +String _text(dynamic value) => '${value ?? ''}'; + +/// A string kept only when it has non-whitespace content. +String? _nonBlank(String? value) { + if (value == null) return null; + return value.trim().isEmpty ? null : value; +} diff --git a/app/lib/features/changes/domain/patch_models.dart b/app/lib/features/changes/domain/patch_models.dart new file mode 100644 index 00000000..123fdf12 --- /dev/null +++ b/app/lib/features/changes/domain/patch_models.dart @@ -0,0 +1,59 @@ +/// Patch value objects produced by the unified-patch parser. Kept separate from +/// the parser so widgets import the smallest model they need. +library; + +enum ChangeLineKind { context, add, remove } + +class PatchLine { + const PatchLine({ + required this.kind, + required this.text, + required this.oldLine, + required this.newLine, + this.noNewlineMarker = false, + }); + + final ChangeLineKind kind; + final String text; + final int oldLine; + final int newLine; + + /// A `\ No newline at end of file` marker: shown verbatim, never numbered. + final bool noNewlineMarker; +} + +class PatchHunk { + const PatchHunk({ + required this.header, + required this.oldStart, + required this.oldCount, + required this.newStart, + required this.newCount, + required this.lines, + }); + + final String header; + final int oldStart; + final int oldCount; + final int newStart; + final int newCount; + final List lines; +} + +class ParsedPatch { + const ParsedPatch({ + required this.raw, + required this.headerLines, + required this.hunks, + required this.added, + required this.removed, + }); + + final String raw; + final List headerLines; + final List hunks; + final int added; + final int removed; + + bool get isEmpty => hunks.isEmpty; +} diff --git a/app/lib/features/changes/domain/run_changes.dart b/app/lib/features/changes/domain/run_changes.dart new file mode 100644 index 00000000..b7708eeb --- /dev/null +++ b/app/lib/features/changes/domain/run_changes.dart @@ -0,0 +1,102 @@ +import '../../../core/api_gateway.dart'; +import 'change_capture.dart'; +import 'file_change.dart'; + +/// The run-level final-state aggregate of recorded file captures. Ported from +/// `web/src/changes.js` `runChanges`: +/// +/// * a null `file_changes` is missing evidence (pending while the step is +/// running/waiting), never "no changes"; +/// * a present capture with no files is a real, observed no-change; +/// * a path recorded by several visits is one entry, in first-seen order, whose +/// per-file facts come from the last recorded visit (the run's final state); +/// * capture counters and caveats describe every contributing step. +class RunChanges { + const RunChanges({ + required this.files, + required this.stepsWithChanges, + required this.stepsPending, + required this.added, + required this.removed, + required this.partial, + required this.unavailable, + required this.pending, + required this.missingCaptures, + required this.skipped, + required this.omitted, + required this.diagnostic, + }); + + final List files; + final int stepsWithChanges; + final int stepsPending; + final int added; + final int removed; + final bool partial; + final bool unavailable; + final bool pending; + final int missingCaptures; + final int skipped; + final int omitted; + final String diagnostic; +} + +RunChanges runChanges(List steps) => + runChangesFor(stageCaptures(steps)); + +/// The same aggregate over already-derived [stageCaptures], so a caller that +/// shows both the summary and the sections parses each capture only once. +RunChanges runChangesFor(List visits) { + final entries = {}; + var stepsWithChanges = 0; + var stepsPending = 0; + var partial = false; + var unavailable = false; + var missingCaptures = 0; + var skipped = 0; + var omitted = 0; + var truncatedSeen = false; + final diagnostics = {}; + + for (final visit in visits) { + final capture = visit.capture; + if (capture == null) { + final status = visit.stepStatus.trim().toLowerCase(); + if (status == 'running' || status == 'waiting') { + stepsPending++; + } else { + missingCaptures++; + } + continue; + } + stepsWithChanges++; + if (capture.unavailable) unavailable = true; + if (capture.partial) partial = true; + if (capture.diagnostic.isNotEmpty) diagnostics.add(capture.diagnostic); + skipped += capture.skipped; + omitted += capture.omitted; + for (final file in capture.files) { + if (file.truncated) truncatedSeen = true; + final existing = entries[file.path]; + final names = existing == null ? [] : [...existing.steps]; + if (!names.contains(visit.stage)) names.add(visit.stage); + entries[file.path] = file.withSteps(names); + } + } + + final files = entries.values.toList(growable: false); + return RunChanges( + files: List.unmodifiable(files), + stepsWithChanges: stepsWithChanges, + stepsPending: stepsPending, + added: files.fold(0, (sum, file) => sum + file.added), + removed: files.fold(0, (sum, file) => sum + file.removed), + partial: partial || truncatedSeen || omitted > 0, + unavailable: unavailable, + pending: stepsWithChanges == 0 && stepsPending > 0, + missingCaptures: missingCaptures, + skipped: skipped, + omitted: omitted, + diagnostic: diagnostics.join(' '), + ); +} diff --git a/app/lib/features/changes/domain/unified_patch.dart b/app/lib/features/changes/domain/unified_patch.dart new file mode 100644 index 00000000..18f550cd --- /dev/null +++ b/app/lib/features/changes/domain/unified_patch.dart @@ -0,0 +1,239 @@ +/// Parses a server-recorded unified patch into hunks, lines and the true +/// `+N -M` stat. Ported from `web/src/changes.js` so the Flutter viewer numbers +/// and groups lines exactly like the browser and Android clients. +/// +/// The server builds these patches with the Go `internal/filediff` writer: a +/// standard `---`/`+++` header, optional metadata, `@@ -a,b +c,d @@` hunk +/// headers and a ` `/`+`/`-` body. Anything unrecognised before the first hunk +/// is carried verbatim in [ParsedPatch.headerLines]; a truncated tail or exotic +/// marker inside a hunk stays an unnumbered context line. The raw patch is +/// always retained byte-for-byte so Copy patch never rewrites the record. +library; + +export 'patch_models.dart'; + +import 'patch_models.dart'; + +const _emptyPatch = ParsedPatch( + raw: '', + headerLines: [], + hunks: [], + added: 0, + removed: 0, +); + +/// Parses a patch with the same total behaviour as the browser: a blank or +/// absent patch is an empty result, never a fabricated diff. +ParsedPatch parseUnifiedPatch(dynamic patch) { + final text = patch == null ? '' : '$patch'; + if (text.trim().isEmpty) return _emptyPatch; + + final headers = []; + final hunks = []; + _HunkBuilder? current; + + for (final line in text.split('\n')) { + final start = _parseHunkHeader(line); + if (start != null) { + if (current != null) hunks.add(current.build()); + current = _HunkBuilder(line, start); + } else if (line.startsWith('--- ') || line.startsWith('+++ ')) { + // An aggregated entry can contain one complete patch per contributing + // stage. A new file header closes the preceding hunk instead of becoming + // an unnumbered context line inside it. + if (current != null) { + hunks.add(current.build()); + current = null; + } + headers.add(line); + } else if (current == null) { + headers.add(line); + } else { + current.lines.add(current.parseBody(line)); + } + } + if (current != null) hunks.add(current.build()); + + var added = 0; + var removed = 0; + for (final hunk in hunks) { + for (final line in hunk.lines) { + if (line.kind == ChangeLineKind.add) { + added++; + } else if (line.kind == ChangeLineKind.remove) { + removed++; + } + } + } + return ParsedPatch( + raw: text, + headerLines: headers, + hunks: hunks, + added: added, + removed: removed, + ); +} + +/// Mutable accumulator carrying the running old/new counters so each body line +/// is numbered in one pass. +class _HunkBuilder { + _HunkBuilder(this.header, _HunkStart start) + : oldStart = start.oldStart, + oldCount = start.oldCount, + newStart = start.newStart, + newCount = start.newCount, + oldLine = start.oldStart, + newLine = start.newStart; + + final String header; + final int oldStart; + final int oldCount; + final int newStart; + final int newCount; + final List lines = []; + int oldLine; + int newLine; + + PatchHunk build() => PatchHunk( + header: header, + oldStart: oldStart, + oldCount: oldCount, + newStart: newStart, + newCount: newCount, + lines: List.unmodifiable(lines), + ); + + PatchLine parseBody(String line) { + if (line.startsWith('+')) { + return PatchLine( + kind: ChangeLineKind.add, + text: line.substring(1), + oldLine: 0, + newLine: newLine++, + ); + } + if (line.startsWith('-')) { + return PatchLine( + kind: ChangeLineKind.remove, + text: line.substring(1), + oldLine: oldLine++, + newLine: 0, + ); + } + if (line.startsWith('\\')) { + return PatchLine( + kind: ChangeLineKind.context, + text: line, + oldLine: 0, + newLine: 0, + noNewlineMarker: true, + ); + } + if (line.startsWith(' ')) { + return PatchLine( + kind: ChangeLineKind.context, + text: line.substring(1), + oldLine: oldLine++, + newLine: newLine++, + ); + } + if (line.isEmpty) { + return PatchLine( + kind: ChangeLineKind.context, + text: '', + oldLine: oldLine++, + newLine: newLine++, + ); + } + // A truncated tail or an unexpected marker: keep the text, do not number it. + return PatchLine( + kind: ChangeLineKind.context, + text: line, + oldLine: 0, + newLine: 0, + ); + } +} + +class _HunkStart { + const _HunkStart(this.oldStart, this.oldCount, this.newStart, this.newCount); + + final int oldStart; + final int oldCount; + final int newStart; + final int newCount; +} + +_HunkStart? _parseHunkHeader(String line) { + if (!line.startsWith('@@')) return null; + final end = line.indexOf('@@', 2); + if (end < 0) return null; + final ranges = _tokenizeRanges(line.substring(2, end)); + return ranges == null + ? null + : _HunkStart(ranges[0], ranges[1], ranges[2], ranges[3]); +} + +List? _tokenizeRanges(String body) { + final plus = body.indexOf('+'); + final old = plus == -1 ? body : body.substring(0, plus); + final next = plus == -1 ? '' : body.substring(plus + 1); + if (old.isEmpty || next.isEmpty) return null; + final oldRange = _parseRange(old); + if (oldRange == null) return null; + final newRange = _parseRange(next); + if (newRange == null) return null; + return [oldRange[0], oldRange[1], newRange[0], newRange[1]]; +} + +List? _parseRange(String text) { + var trimmed = text.trim(); + if (trimmed.startsWith('-') || trimmed.startsWith('+')) { + trimmed = trimmed.substring(1); + } + if (trimmed.isEmpty) return null; + final comma = trimmed.indexOf(','); + final startText = (comma == -1 ? trimmed : trimmed.substring(0, comma)) + .trim(); + final start = _intOrNull(startText); + if (start == null) return null; + final countText = (comma == -1 ? '' : trimmed.substring(comma + 1)).trim(); + final count = countText.isEmpty ? 1 : _intOrNull(countText); + if (count == null) return null; + return [start, count]; +} + +int? _intOrNull(String text) => + RegExp(r'^[+-]?\d+$').hasMatch(text) ? int.tryParse(text) : null; + +/// The widest line number in a hunk, so its gutter lines up across every row. +int gutterWidth(PatchHunk hunk) { + var widest = 0; + for (final line in hunk.lines) { + if (line.oldLine > widest) widest = line.oldLine; + if (line.newLine > widest) widest = line.newLine; + } + return '${widest < 1 ? 1 : widest}'.length; +} + +/// One gutter number padded to [width]; 0 means no number on that side. +String gutterText(int value, int width) => + value > 0 ? '$value'.padLeft(width) : ' ' * width; + +/// The gutter symbol one line kind is drawn with (`+`/`-`/space). +String diffLineSymbol(ChangeLineKind kind) => switch (kind) { + ChangeLineKind.add => '+', + ChangeLineKind.remove => '-', + ChangeLineKind.context => ' ', +}; + +/// The `+N -M` stat, or "" when both counts are zero. Shared by every renderer. +String changeStat(int added, int removed) { + var out = ''; + if (added > 0) out += '+$added'; + if (removed > 0) { + if (out.isNotEmpty) out += ' '; + out += '-$removed'; + } + return out; +} diff --git a/app/lib/features/changes/widgets/capture_section.dart b/app/lib/features/changes/widgets/capture_section.dart new file mode 100644 index 00000000..f82d2988 --- /dev/null +++ b/app/lib/features/changes/widgets/capture_section.dart @@ -0,0 +1,238 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../domain/change_capture.dart'; +import '../domain/change_kind.dart'; +import '../domain/change_wording.dart'; +import '../domain/file_change.dart'; +import 'change_style.dart'; + +/// One stage/visit capture: its honest status, scope, counters and diagnostic, +/// followed by the recorded file rows. Missing and unavailable captures are +/// shown as evidence gaps, never as an observed no-change. +class StageCaptureSection extends StatelessWidget { + const StageCaptureSection({ + super.key, + required this.stage, + required this.query, + required this.onOpen, + }); + + final StageCapture stage; + final String query; + final ValueChanged onOpen; + + @override + Widget build(BuildContext context) { + final capture = stage.capture; + final filtered = capture == null + ? const [] + : filterFileChanges(capture.files, query); + // The aggregate trims and lowercases the status before testing it; do the + // same here so the section and the run header always agree. + final status = stage.stepStatus.trim().toLowerCase(); + final pending = + capture == null && (status == 'running' || status == 'waiting'); + final meta = [ + 'Visit ${stage.visit}', + if (stage.stepStatus.isNotEmpty) stage.stepStatus, + ].join(' · '); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(stage.stage, style: Theme.of(context).textTheme.titleMedium), + Text(meta, style: Theme.of(context).textTheme.bodySmall), + if (capture != null) ...[ + Text( + fileChangesSummary(capture), + style: Theme.of(context).textTheme.bodySmall, + ), + if (capture.scope.isNotEmpty) + Text( + 'Scope: ${capture.scope}', + style: Theme.of(context).textTheme.bodySmall, + ), + ], + ], + ), + ), + const Divider(height: 1), + if (capture == null) + _CaptureNote( + icon: _noteIcon( + context, + pending ? _NoteKind.pending : _NoteKind.missing, + ), + title: pending ? 'Capture pending' : 'Capture unavailable', + detail: pending ? pendingCaptureDetail : missingCaptureDetail, + ) + else if (capture.unavailable) + _CaptureNote( + icon: _noteIcon(context, _NoteKind.unavailable), + title: 'Capture unavailable', + detail: capture.diagnostic.isEmpty + ? unavailableCaptureDetail + : capture.diagnostic, + ) + else if (capture.files.isEmpty) + _CaptureNote( + icon: _noteIcon( + context, + capture.partial ? _NoteKind.partial : _NoteKind.empty, + ), + title: capture.partial ? 'Partial capture' : 'No changes observed', + detail: capture.partial ? partialCaptureDetail : emptyCaptureDetail, + ) + else if (filtered.isEmpty) + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 16), + child: Text('No changed filenames match "$query".'), + ) + else + for (final file in filtered) + _FileRow( + key: ValueKey('change-${stage.sequence}-${file.path}'), + file: file, + onOpen: onOpen, + ), + ], + ); + } +} + +class _FileRow extends StatelessWidget { + const _FileRow({super.key, required this.file, required this.onOpen}); + + final FileChange file; + final ValueChanged onOpen; + + @override + Widget build(BuildContext context) { + final mono = nativeDiffText(DefaultTextStyle.of(context).style); + final cupertino = usesCupertino(context); + final leading = Icon(_kindIcon(context, file.kind)); + final title = Text(file.path, style: mono); + final subtitle = Text(changeFileMeta(file)); + final trailing = cupertino + ? const CupertinoListTileChevron() + : const Icon(Icons.chevron_right); + return Semantics( + container: true, + button: true, + // Announce the visible kind and meta too; the row's icon and subtitle are + // excluded from the semantic tree by [excludeSemantics]. + label: + 'Open diff for ${file.path}. ' + '${changeKindTitle(file.kind)} · ${changeFileMeta(file)}', + excludeSemantics: true, + onTap: () => onOpen(file), + child: cupertino + ? CupertinoListTile( + leading: leading, + // A recorded path is the row's identity, so it wraps instead of + // being ellipsized to one line. + title: _unclampedText(title), + subtitle: _unclampedText(subtitle), + trailing: trailing, + onTap: () => onOpen(file), + ) + : ListTile( + leading: leading, + title: title, + subtitle: subtitle, + trailing: trailing, + onTap: () => onOpen(file), + ), + ); + } +} + +/// CupertinoListTile caps its title and subtitle at one ellipsized line through +/// the inherited [DefaultTextStyle]. Re-establish the ambient style without that +/// cap so a long recorded path stays readable; the tile keeps its native +/// padding, pressed state and chevron. +Widget _unclampedText(Widget child) { + return Builder( + builder: (context) { + final inherited = DefaultTextStyle.of(context); + return DefaultTextStyle( + style: inherited.style, + softWrap: true, + overflow: TextOverflow.visible, + textAlign: inherited.textAlign, + textWidthBasis: inherited.textWidthBasis, + textHeightBehavior: inherited.textHeightBehavior, + child: child, + ); + }, + ); +} + +class _CaptureNote extends StatelessWidget { + const _CaptureNote({ + required this.icon, + required this.title, + required this.detail, + }); + + final IconData icon; + final String title; + final String detail; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 16), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(icon), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(title, style: Theme.of(context).textTheme.titleSmall), + const SizedBox(height: 4), + Text(detail), + ], + ), + ), + ], + ), + ); + } +} + +enum _NoteKind { missing, unavailable, empty, partial, pending } + +IconData _noteIcon(BuildContext context, _NoteKind kind) { + final cupertino = usesCupertino(context); + return switch (kind) { + _NoteKind.missing || _NoteKind.unavailable => + cupertino ? CupertinoIcons.exclamationmark_triangle : Icons.warning_amber, + _NoteKind.empty => + cupertino ? CupertinoIcons.checkmark_circle : Icons.check_circle_outline, + _NoteKind.partial => cupertino ? CupertinoIcons.info : Icons.info_outline, + _NoteKind.pending => cupertino ? CupertinoIcons.clock : Icons.schedule, + }; +} + +IconData _kindIcon(BuildContext context, ChangeKind kind) { + final cupertino = usesCupertino(context); + return switch (kind) { + ChangeKind.added => + cupertino ? CupertinoIcons.add_circled : Icons.add_circle_outline, + ChangeKind.deleted => + cupertino ? CupertinoIcons.trash : Icons.delete_outline, + ChangeKind.modified => + cupertino ? CupertinoIcons.pencil : Icons.edit_outlined, + ChangeKind.other => + cupertino ? CupertinoIcons.doc : Icons.description_outlined, + }; +} diff --git a/app/lib/features/changes/widgets/change_style.dart b/app/lib/features/changes/widgets/change_style.dart new file mode 100644 index 00000000..a3f12ffd --- /dev/null +++ b/app/lib/features/changes/widgets/change_style.dart @@ -0,0 +1,151 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../domain/unified_patch.dart'; + +/// Which form of a recorded patch the viewer is showing. +enum DiffForm { rendered, raw } + +/// The app's established platform switch: Material for Android/desktop/web, +/// Cupertino for iOS and macOS. Feature widgets stay portable across all three +/// targets instead of hard-coding one control set. +bool usesCupertino(BuildContext context) { + final platform = Theme.of(context).platform; + return platform == TargetPlatform.iOS || platform == TargetPlatform.macOS; +} + +/// Patch text inherits the host's typography, including its font and scaler. +/// A diff is not an exception to the native-defaults requirement. +TextStyle nativeDiffText(TextStyle base) => base; + +/// Native semantic colours, never a bespoke diff palette. The recorded +/- +/// markers carry meaning independently of colour. No background tint is added. +({Color text, Color? background}) diffLineColors( + BuildContext context, + ChangeLineKind kind, +) { + return switch (kind) { + ChangeLineKind.add => ( + text: usesCupertino(context) + ? CupertinoColors.systemGreen.resolveFrom(context) + : Theme.of(context).colorScheme.primary, + background: null, + ), + ChangeLineKind.remove => ( + text: usesCupertino(context) + ? CupertinoColors.destructiveRed.resolveFrom(context) + : Theme.of(context).colorScheme.error, + background: null, + ), + ChangeLineKind.context => (text: labelColor(context), background: null), + }; +} + +/// The plain body/label colour for non-diff text inside the viewer. +Color labelColor(BuildContext context) => usesCupertino(context) + ? CupertinoColors.label.resolveFrom(context) + : Theme.of(context).colorScheme.onSurface; + +/// The muted colour for gutters, notes and secondary metadata. +Color mutedColor(BuildContext context) => usesCupertino(context) + ? CupertinoColors.secondaryLabel.resolveFrom(context) + : Theme.of(context).colorScheme.onSurfaceVariant; + +/// The hunk header's fill. +Color hunkHeaderColor(BuildContext context) => usesCupertino(context) + ? CupertinoColors.tertiarySystemFill.resolveFrom(context) + : Theme.of(context).colorScheme.surfaceContainerHighest; + +/// The viewer's shared Rendered/Raw control: a native segmented control on each +/// platform, with the same two words the browser uses. +Widget diffFormControl( + BuildContext context, { + required DiffForm form, + required ValueChanged onChanged, +}) { + if (usesCupertino(context)) { + return CupertinoSlidingSegmentedControl( + groupValue: form, + onValueChanged: (value) { + if (value != null) onChanged(value); + }, + children: const { + DiffForm.rendered: _SegmentLabel('Rendered'), + DiffForm.raw: _SegmentLabel('Raw patch'), + }, + ); + } + return SegmentedButton( + segments: const [ + ButtonSegment(value: DiffForm.rendered, label: Text('Rendered')), + ButtonSegment(value: DiffForm.raw, label: Text('Raw patch')), + ], + selected: {form}, + showSelectedIcon: false, + onSelectionChanged: (selection) { + if (selection.isNotEmpty) onChanged(selection.first); + }, + ); +} + +class _SegmentLabel extends StatelessWidget { + const _SegmentLabel(this.label); + + final String label; + + @override + Widget build(BuildContext context) => + Padding(padding: const EdgeInsets.all(6), child: Text(label)); +} + +/// Copy the server's raw patch exactly as recorded. Disabled when the entry has +/// no readable patch, so the action never copies a fabricated empty diff. +Widget copyPatchControl( + BuildContext context, { + required bool enabled, + required bool copied, + required VoidCallback onPressed, +}) { + final label = copied ? 'Copied' : 'Copy patch'; + if (usesCupertino(context)) { + return CupertinoButton( + padding: EdgeInsets.zero, + onPressed: enabled ? onPressed : null, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(CupertinoIcons.doc_on_doc), + const SizedBox(width: 8), + Text(label), + ], + ), + ); + } + return TextButton.icon( + onPressed: enabled ? onPressed : null, + icon: const Icon(Icons.copy_all_outlined), + label: Text(label), + ); +} + +/// The standard close action, labelled exactly on both platforms. +Widget closeDiffControl(BuildContext context, VoidCallback onClose) { + if (usesCupertino(context)) { + return Semantics( + label: 'Close diff', + button: true, + excludeSemantics: true, + onTap: onClose, + child: CupertinoButton( + padding: EdgeInsets.zero, + onPressed: onClose, + child: const Icon(CupertinoIcons.xmark), + ), + ); + } + return IconButton( + tooltip: 'Close diff', + onPressed: onClose, + icon: const Icon(Icons.close), + ); +} diff --git a/app/lib/features/changes/widgets/changes_viewer.dart b/app/lib/features/changes/widgets/changes_viewer.dart new file mode 100644 index 00000000..a58d91b7 --- /dev/null +++ b/app/lib/features/changes/widgets/changes_viewer.dart @@ -0,0 +1,189 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../domain/change_capture.dart'; +import '../domain/change_wording.dart'; +import '../domain/run_changes.dart'; +import 'capture_section.dart'; +import 'change_style.dart'; +import 'file_diff_viewer.dart'; + +/// The run's Changes surface: an honest final-state summary followed by one +/// section per stage/visit capture, with changed-filename filtering and the +/// reusable single-file diff viewer. +/// +/// The viewer fills the available height, so give it a bounded parent (a +/// Scaffold body, tab body or Expanded child). It never opens its own socket or +/// requests data; the caller passes the run detail's `steps`. +class ChangesViewer extends StatefulWidget { + const ChangesViewer({super.key, required this.steps}); + + /// The run detail's steps exactly as the server returned them. Each step's + /// `file_changes` may be null (no capture), a complete/partial/unavailable + /// capture, or a capture with zero files (a recorded no-change). + /// + /// Pass a stable list: the same instance until the server reply changes. The + /// captures and the summary are derived from it rather than on every rebuild. + final List steps; + + @override + State createState() => _ChangesViewerState(); +} + +class _ChangesViewerState extends State { + final _filter = TextEditingController(); + late List _captures; + late RunChanges _run; + + @override + void initState() { + super.initState(); + _derive(); + } + + @override + void didUpdateWidget(ChangesViewer oldWidget) { + super.didUpdateWidget(oldWidget); + // Filter keystrokes rebuild this widget with the same steps list; only a + // new server reply re-derives the captures and the aggregate. + if (!identical(oldWidget.steps, widget.steps)) _derive(); + } + + void _derive() { + _captures = stageCaptures(widget.steps); + _run = runChangesFor(_captures); + } + + @override + void dispose() { + _filter.dispose(); + super.dispose(); + } + + String get _query => _filter.text; + + @override + Widget build(BuildContext context) { + final run = _run; + final captures = _captures; + final hasFiles = captures.any( + (visit) => visit.capture?.files.isNotEmpty ?? false, + ); + final note = runChangesNote(run); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + runChangesHeader(run), + style: Theme.of(context).textTheme.titleMedium, + ), + if (note.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text( + note, + style: Theme.of(context).textTheme.bodySmall, + ), + ), + if (hasFiles) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text( + 'The summary counts each path once, as the last recorded ' + 'visit left it. Each stage/visit below lists what its own ' + 'capture recorded.', + style: Theme.of(context).textTheme.bodySmall, + ), + ), + ], + ), + ), + if (hasFiles) + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), + child: _filterField(context, run), + ), + const Divider(height: 1), + Expanded( + child: captures.isEmpty + ? SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Text(noChangeDetail(run)), + ) + : ListView.builder( + itemCount: captures.length, + itemBuilder: (context, index) { + final visit = captures[index]; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + StageCaptureSection( + stage: visit, + query: _query, + onOpen: (file) => showFileDiffViewer(context, file), + ), + const Divider(height: 1), + ], + ); + }, + ), + ), + ], + ); + } + + Widget _filterField(BuildContext context, RunChanges run) { + final query = _query; + final matched = query.trim().isEmpty + ? run.files.length + : filterFileChanges(run.files, query).length; + // The summary counts paths while the sections below list one row per stage + // visit, so the counter names what it actually counts. + final counter = query.trim().isEmpty + ? '' + : '$matched of ${run.files.length} changed ' + '${run.files.length == 1 ? 'path' : 'paths'} match'; + final field = usesCupertino(context) + ? CupertinoSearchTextField( + controller: _filter, + placeholder: 'Filter changed files', + onChanged: (_) => setState(() {}), + ) + : TextField( + controller: _filter, + decoration: InputDecoration( + labelText: 'Filter changed files', + hintText: 'Filename contains…', + prefixIcon: const Icon(Icons.search), + suffixIcon: query.isEmpty + ? null + : IconButton( + tooltip: 'Clear filter', + onPressed: () { + _filter.clear(); + setState(() {}); + }, + icon: const Icon(Icons.clear), + ), + ), + onChanged: (_) => setState(() {}), + ); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + field, + if (counter.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text(counter, style: Theme.of(context).textTheme.bodySmall), + ), + ], + ); + } +} diff --git a/app/lib/features/changes/widgets/file_diff_viewer.dart b/app/lib/features/changes/widgets/file_diff_viewer.dart new file mode 100644 index 00000000..1e05c54e --- /dev/null +++ b/app/lib/features/changes/widgets/file_diff_viewer.dart @@ -0,0 +1,254 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../domain/change_kind.dart'; +import '../domain/change_wording.dart'; +import '../domain/file_change.dart'; +import '../domain/unified_patch.dart'; +import 'change_style.dart'; +import 'patch_view.dart'; + +/// The reusable viewer for one recorded file change: its kind, path, stat, +/// tags, the rendered or raw unified patch, Copy patch (the server's exact +/// bytes) and Close. Binary/truncated/mode-only/no-patch entries show an honest +/// reason instead of a fabricated diff. +class FileDiffViewer extends StatefulWidget { + const FileDiffViewer({super.key, required this.file, this.onClose}); + + final FileChange file; + + /// Called by the Close control. Defaults to popping the enclosing route. + final VoidCallback? onClose; + + @override + State createState() => _FileDiffViewerState(); +} + +class _FileDiffViewerState extends State { + DiffForm _form = DiffForm.rendered; + bool _copied = false; + Timer? _copyTimer; + + @override + void dispose() { + _copyTimer?.cancel(); + super.dispose(); + } + + void _close() { + final close = widget.onClose; + if (close != null) { + close(); + } else { + Navigator.of(context).maybePop(); + } + } + + Future _copy() async { + final patch = widget.file.patch; + if (patch == null) return; + await Clipboard.setData(ClipboardData(text: patch)); + if (!mounted) return; + setState(() => _copied = true); + _copyTimer?.cancel(); + _copyTimer = Timer(const Duration(seconds: 2), () { + if (mounted) setState(() => _copied = false); + }); + } + + @override + Widget build(BuildContext context) { + final file = widget.file; + final cupertino = usesCupertino(context); + final base = DefaultTextStyle.of(context).style; + final mono = nativeDiffText(base); + final stat = changeStat(file.added, file.removed); + final tags = changeEntryTags(file); + return ConstrainedBox( + key: const ValueKey('file-diff-viewer'), + constraints: BoxConstraints( + maxWidth: 900, + maxHeight: MediaQuery.sizeOf(context).height * 0.85, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 8, 8), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Semantics( + container: true, + header: true, + excludeSemantics: true, + label: [ + changeKindTitle(file.kind), + if (stat.isNotEmpty) stat, + if (tags.isNotEmpty) tags.join(' · '), + 'for ${file.path}', + if (file.steps.isNotEmpty) + 'changed by ${file.steps.join(' → ')}', + if (file.modeChanged && !file.binary) + 'mode ${file.beforeMode ?? ''}→' + '${file.afterMode ?? ''}', + ].join(', '), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Wrap( + spacing: 12, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Text( + changeKindTitle(file.kind), + style: Theme.of(context).textTheme.titleMedium, + ), + if (stat.isNotEmpty) Text(stat, style: mono), + if (tags.isNotEmpty) + Text( + tags.join(' · '), + style: Theme.of(context).textTheme.bodySmall, + ), + ], + ), + const SizedBox(height: 4), + Text(file.path, style: mono), + if (file.steps.isNotEmpty) + Text( + 'changed by ${file.steps.join(' → ')}', + style: Theme.of(context).textTheme.bodySmall, + ), + if (file.modeChanged && !file.binary) + Text( + 'mode ${file.beforeMode ?? ''}→' + '${file.afterMode ?? ''}', + style: Theme.of(context).textTheme.bodySmall, + ), + ], + ), + ), + ), + closeDiffControl(context, _close), + ], + ), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Wrap( + spacing: 8, + runSpacing: 8, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + if (file.hasPatch) + diffFormControl( + context, + form: _form, + onChanged: (value) => setState(() => _form = value), + ), + copyPatchControl( + context, + enabled: file.hasPatch, + copied: _copied, + onPressed: _copy, + ), + ], + ), + ), + Divider( + height: 16, + color: cupertino + ? CupertinoColors.separator.resolveFrom(context) + : Theme.of(context).dividerColor, + ), + Flexible(child: _body(context, cupertino, mono)), + ], + ), + ); + } + + Widget _body(BuildContext context, bool cupertino, TextStyle mono) { + final file = widget.file; + if (file.binary) return _message(context, binaryDiffMessage); + if (!file.hasPatch) { + return _message(context, patchUnavailableReason(file)); + } + if (_form == DiffForm.raw) { + return Semantics( + container: true, + label: 'Raw patch for ${file.path}', + value: file.patch, + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 16), + child: SingleChildScrollView( + // Raw patch bytes are one line each: scroll them sideways like the + // web view instead of wrapping a continuation under a new line. + scrollDirection: Axis.horizontal, + child: ExcludeSemantics( + child: SelectionArea( + child: Text( + file.patch!, + style: mono, + softWrap: false, + overflow: TextOverflow.visible, + ), + ), + ), + ), + ), + ); + } + return SingleChildScrollView( + padding: const EdgeInsets.only(bottom: 16), + child: PatchView(file: file), + ); + } + + Widget _message(BuildContext context, String text) { + return SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), + child: Text(text), + ); + } +} + +/// Open [file] in the platform's standard modal: a Material dialog on +/// Android/desktop/web, a Cupertino dialog with a popup surface on iOS/macOS. +Future showFileDiffViewer(BuildContext context, FileChange file) { + final cupertino = usesCupertino(context); + Widget buildDialog(BuildContext dialogContext) { + final viewer = FileDiffViewer( + file: file, + onClose: () => Navigator.of(dialogContext).pop(), + ); + if (cupertino) { + // A popup surface spans the window unless it is inset; on a phone the + // screen edge would clip its native rounded corners. + final width = MediaQuery.sizeOf(dialogContext).width; + return Padding( + padding: EdgeInsets.symmetric( + horizontal: width < 600 ? 16 : 40, + vertical: 24, + ), + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 900), + child: CupertinoPopupSurface(child: SafeArea(child: viewer)), + ), + ), + ); + } + return Dialog(child: SafeArea(child: viewer)); + } + + if (cupertino) { + return showCupertinoDialog(context: context, builder: buildDialog); + } + return showDialog(context: context, builder: buildDialog); +} diff --git a/app/lib/features/changes/widgets/patch_view.dart b/app/lib/features/changes/widgets/patch_view.dart new file mode 100644 index 00000000..dc4039bb --- /dev/null +++ b/app/lib/features/changes/widgets/patch_view.dart @@ -0,0 +1,193 @@ +import 'package:flutter/material.dart'; + +import '../domain/change_wording.dart'; +import '../domain/file_change.dart'; +import '../domain/unified_patch.dart'; +import 'change_style.dart'; + +/// The rendered reading of one recorded unified patch: each hunk's `@@` header, +/// the shared diff line language (`+`/`-`/space) and the old/new gutter numbers. +/// This is the only custom drawing in the feature; everything around it is a +/// standard platform control. +class PatchView extends StatelessWidget { + const PatchView({super.key, required this.file}); + + final FileChange file; + + @override + Widget build(BuildContext context) { + final parsed = file.parsedPatch; + final base = nativeDiffText(DefaultTextStyle.of(context).style); + final stat = changeStat(parsed.added, parsed.removed); + return Semantics( + container: true, + label: 'Rendered diff for ${file.path}', + value: stat.isEmpty ? noLineChangesMessage : stat, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + child: ExcludeSemantics( + child: _StatLine( + added: parsed.added, + removed: parsed.removed, + base: base, + ), + ), + ), + if (file.truncated) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), + child: Text( + truncatedPatchNote, + style: base.copyWith(color: mutedColor(context)), + ), + ), + // The web rendered view shows hunks, not the recorded `---`/`+++` + // file headers (they stay in the Raw view), so the dialog does not + // show a long header clipped at its edge. + for (final hunk in parsed.hunks) _HunkView(hunk: hunk), + ], + ), + ); + } +} + +/// `+N` in the add colour and `-M` in the remove colour, or the honest note when +/// the patch records no changed line. +class _StatLine extends StatelessWidget { + const _StatLine({ + required this.added, + required this.removed, + required this.base, + }); + + final int added; + final int removed; + final TextStyle base; + + @override + Widget build(BuildContext context) { + if (added == 0 && removed == 0) { + return Text( + noLineChangesMessage, + style: base.copyWith(color: mutedColor(context)), + ); + } + return Text.rich( + TextSpan( + children: [ + if (added > 0) + TextSpan( + text: '+$added', + style: base.copyWith( + color: diffLineColors(context, ChangeLineKind.add).text, + ), + ), + if (added > 0 && removed > 0) TextSpan(text: ' ', style: base), + if (removed > 0) + TextSpan( + text: '-$removed', + style: base.copyWith( + color: diffLineColors(context, ChangeLineKind.remove).text, + ), + ), + ], + ), + ); + } +} + +class _HunkView extends StatelessWidget { + const _HunkView({required this.hunk}); + + final PatchHunk hunk; + + @override + Widget build(BuildContext context) { + final base = nativeDiffText(DefaultTextStyle.of(context).style); + final width = gutterWidth(hunk); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Container( + color: hunkHeaderColor(context), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + child: Text(hunk.header, style: base), + ), + LayoutBuilder( + builder: (context, constraints) { + return SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: ConstrainedBox( + // At least the dialog's width, so a short hunk still paints + // full-width bands; wider content scrolls sideways. + constraints: BoxConstraints(minWidth: constraints.maxWidth), + // The widest recorded line sets the hunk's content width, so + // every line tint is a full-width band instead of a bar as long + // as its own text. + child: IntrinsicWidth( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (var index = 0; index < hunk.lines.length; index++) + _LineRow( + key: ValueKey('diff-line-$index'), + line: hunk.lines[index], + width: width, + base: base, + ), + ], + ), + ), + ), + ); + }, + ), + ], + ); + } +} + +class _LineRow extends StatelessWidget { + const _LineRow({ + super.key, + required this.line, + required this.width, + required this.base, + }); + + final PatchLine line; + final int width; + final TextStyle base; + + @override + Widget build(BuildContext context) { + final gutter = line.noNewlineMarker + ? ' ' * (width * 2 + 1) + : '${gutterText(line.oldLine, width)} ${gutterText(line.newLine, width)}'; + final colors = diffLineColors(context, line.kind); + final content = '${diffLineSymbol(line.kind)} ${line.text}'; + return Container( + color: colors.background, + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2), + child: Text.rich( + TextSpan( + children: [ + TextSpan( + text: gutter, + style: base.copyWith(color: mutedColor(context)), + ), + TextSpan( + text: content, + style: base.copyWith(color: colors.text), + ), + ], + ), + softWrap: false, + overflow: TextOverflow.visible, + ), + ); + } +} diff --git a/app/lib/features/chat/data/chat_repository.dart b/app/lib/features/chat/data/chat_repository.dart new file mode 100644 index 00000000..b97bd52a --- /dev/null +++ b/app/lib/features/chat/data/chat_repository.dart @@ -0,0 +1,215 @@ +import '../../../core/api_gateway.dart'; + +const webChatClient = 'Web'; + +String nativeChatMessageId(String operationId) { + final compact = operationId.replaceAll(RegExp('[^A-Za-z0-9]'), ''); + final capped = compact.length > 120 ? compact.substring(0, 120) : compact; + return capped.isEmpty ? '' : 'msg_$capped'; +} + +/// Chat wire adapter. ApiGateway supplies request ids and returns full envelopes. +class ChatRepository { + ChatRepository(this.gateway); + final ApiGateway gateway; + + Future> sessions() async => + _maps((await gateway.call('chat_sessions'))['chat_sessions']); + Future models(String sessionId) async { + final reply = await gateway.call('chat_models', { + 'chat_query': {'session_id': sessionId}, + }); + final catalog = reply['chat_models']; + return catalog is Map ? Map.from(catalog) : {}; + } + + Future selectModel( + String sessionId, + String provider, + String model, + ) => gateway.call('chat_model', { + 'chat_model': { + 'session_id': sessionId, + 'provider': provider, + 'model': model, + }, + }); + Future> shells(String sessionId) async => _maps( + (await gateway.call('chat_shells', { + 'chat_query': {'session_id': sessionId}, + }))['chat_shells'], + ); + Future> directories() async { + final value = (await gateway.call('chat_directories'))['chat_directories']; + if (value is! List) { + throw StateError('Server did not return chat directories.'); + } + return value + .whereType() + .where((entry) => entry.trim().isNotEmpty) + .toList(); + } + + Future> backends() async { + final value = (await gateway.call('chat_backends'))['chat_backends']; + if (value is! List) { + throw StateError('Server did not return chat backends.'); + } + final result = value + .whereType() + .where((entry) => entry.trim().isNotEmpty) + .toList(); + if (result.isEmpty) throw StateError('Server returned no chat backends.'); + return result; + } + + Future shellOutput( + String sessionId, + String shellId, { + int cursor = 0, + int limit = 65536, + }) => gateway.call('chat_shell_output', { + 'chat_shell_output_query': { + 'session_id': sessionId, + 'shell_id': shellId, + 'cursor': cursor, + 'limit': limit, + }, + }); + + Future history( + String sessionId, { + int limit = 200, + String cursor = '', + }) async { + final reply = await gateway.call('chat_messages', { + 'chat_query': {'session_id': sessionId, 'limit': limit, 'cursor': cursor}, + }); + final page = reply['chat_history']; + if (page is Map) { + return { + 'messages': _maps(page['messages']), + 'nextCursor': '${page['next_cursor'] ?? ''}', + 'hasMore': page['has_more'] == true, + }; + } + return { + 'messages': _maps(reply['chat_messages']), + 'nextCursor': '', + 'hasMore': false, + }; + } + + Future subscribe(String sessionId) => + gateway.call('chat_subscribe', { + 'chat_subscribe': {'session_id': sessionId}, + }); + Future create({ + required String title, + required String directory, + required String operationId, + String backend = 'opencode', + String instructions = '', + }) { + if (title.trim().isEmpty || directory.trim().isEmpty) { + throw ArgumentError('Enter a chat name and choose a directory.'); + } + return gateway.call('chat_create', { + 'chat_create': { + 'title': title.trim(), + 'directory': directory.trim(), + 'operation_id': operationId, + if (backend.isNotEmpty && backend != 'opencode') 'backend': backend, + if (instructions.trim().isNotEmpty) 'instructions': instructions.trim(), + }, + }); + } + + Future rename(String sessionId, String title) => + gateway.call('chat_rename', { + 'chat_rename': {'session_id': sessionId, 'title': title.trim()}, + }); + Future star(String sessionId, bool starred) => + gateway.call('chat_star', { + 'chat_query': {'session_id': sessionId, 'starred': starred}, + }); + Future close(String sessionId) => gateway.call('chat_close', { + 'chat_query': {'session_id': sessionId}, + }); + Future reopen(String sessionId) => gateway.call('chat_reopen', { + 'chat_query': {'session_id': sessionId}, + }); + + Future prompt( + String sessionId, + String text, { + required String operationId, + List files = const [], + List attachments = const [], + }) { + if (sessionId.trim().isEmpty) { + throw ArgumentError('Select a chat session first.'); + } + if (text.trim().isEmpty) { + throw ArgumentError('Enter a message before sending.'); + } + final body = { + 'session_id': sessionId, + 'text': text.trim(), + 'operation_id': operationId, + 'native_message_id': nativeChatMessageId(operationId), + }; + if (files.isNotEmpty) body['files'] = files; + if (attachments.isNotEmpty) body['attachments'] = attachments; + return gateway.call('chat_prompt', {'chat_prompt': body}); + } + + Future interrupt(String sessionId) => + gateway.call('chat_interrupt', { + 'chat_query': {'session_id': sessionId}, + }); + Future answerForm( + String sessionId, + String formId, + JsonMap answers, { + String action = '', + }) => gateway.call('chat_answer', { + 'chat_answer': { + 'session_id': sessionId, + 'form_id': formId, + 'answers': answers, + if (action.isNotEmpty) 'action': action, + }, + }); + Future replyPermission( + String sessionId, + String requestId, + String decision, { + String client = webChatClient, + String message = '', + }) { + if (sessionId.trim().isEmpty) { + throw ArgumentError('Select a chat session first.'); + } + if (requestId.trim().isEmpty) { + throw ArgumentError('This approval request is no longer available.'); + } + if (!const ['once', 'always', 'reject'].contains(decision.trim())) { + throw ArgumentError('Choose once, always or reject.'); + } + return gateway.call('chat_reply', { + 'chat_reply': { + 'session_id': sessionId, + 'request_id': requestId, + 'decision': decision, + 'client': client, + if (message.trim().isNotEmpty) 'message': message.trim(), + }, + }); + } + + static List _maps(Object? value) => (value as List? ?? const []) + .whereType() + .map((item) => Map.from(item)) + .toList(); +} diff --git a/app/lib/features/chat/domain/chat_sessions.dart b/app/lib/features/chat/domain/chat_sessions.dart new file mode 100644 index 00000000..76bacdf6 --- /dev/null +++ b/app/lib/features/chat/domain/chat_sessions.dart @@ -0,0 +1,64 @@ +import '../../../core/api_gateway.dart'; + +/// Pure session-list operations. Unknown server fields remain on each row. +String chatSessionTitle(JsonMap session) { + final title = '${session['title'] ?? ''}'; + if (title.trim().isNotEmpty) return title; + final id = '${session['id'] ?? ''}'; + return id.isEmpty ? 'Untitled chat' : id.substring(0, id.length.clamp(0, 18)); +} + +List filterChatSessions(List sessions, String query) { + final needle = query.trim().toLowerCase(); + if (needle.isEmpty) return sessions; + return sessions + .where( + (session) => + '${chatSessionTitle(session)}\u0000${session['directory'] ?? ''}' + .toLowerCase() + .contains(needle), + ) + .toList(); +} + +/// Directory groups retain server recency order, both within and between groups. +List<({String directory, List sessions})> groupChatSessions( + List sessions, +) { + final groups = >{}; + for (final session in sessions) { + groups.putIfAbsent('${session['directory'] ?? ''}', () => []).add(session); + } + return groups.entries + .map((entry) => (directory: entry.key, sessions: entry.value)) + .toList(); +} + +String chatSessionActivity({required bool running, required bool unseen}) => + running + ? 'streaming' + : unseen + ? 'new' + : 'idle'; + +/// Native reported values only; missing and invalid values remain unavailable. +JsonMap? chatUsageSnapshot(Object? value) { + if (value is! Map || value is List) return null; + final usage = Map.from(value); + final result = {}; + for (final key in ['total_tokens', 'context_tokens', 'context_window']) { + final n = usage[key]; + result[key] = n is int && n >= 0 ? n : null; + } + for (final key in ['cost_usd', 'output_tokens_per_second']) { + final n = usage[key]; + result[key] = n is num && n.isFinite && n >= 0 ? n : null; + } + result['scope'] = ['session', 'turn'].contains(usage['scope']) + ? usage['scope'] + : ''; + result['rate_basis'] = ['generation', 'turn'].contains(usage['rate_basis']) + ? usage['rate_basis'] + : ''; + return result.values.any((v) => v != null && v != '') ? result : null; +} diff --git a/app/lib/features/chat/domain/chat_transcript.dart b/app/lib/features/chat/domain/chat_transcript.dart new file mode 100644 index 00000000..b766f15e --- /dev/null +++ b/app/lib/features/chat/domain/chat_transcript.dart @@ -0,0 +1,235 @@ +import '../../../core/api_gateway.dart'; + +/// Merge chronological history pages by message id. Incoming authoritative +/// copies replace held copies without changing their order; cursor is opaque. +JsonMap mergeChatHistory(JsonMap previous, JsonMap page, {bool older = false}) { + final held = (previous['messages'] as List? ?? const []) + .whereType() + .map((m) => Map.from(m)) + .toList(); + final incoming = (page['messages'] as List? ?? const []) + .whereType() + .map((m) => Map.from(m)) + .toList(); + final latest = {}; + for (final message in incoming) { + if (message['id'] != null) latest[message['id']] = message; + } + final combined = older ? [...incoming, ...held] : [...held, ...incoming]; + final seen = {}; + final messages = []; + for (final message in combined) { + final id = message['id']; + if (id != null && !seen.add(id)) continue; + messages.add(id == null ? message : latest[id] ?? message); + } + return { + 'messages': messages, + 'nextCursor': '${page['nextCursor'] ?? ''}', + 'hasMore': page['hasMore'] == true, + 'loaded': true, + 'loading': false, + }; +} + +/// Consecutive assistant messages form one answer turn. All part fields (also +/// future/unknown protocol types) are preserved in original order. +List transcriptRows(List messages) { + final rows = []; + String? key; + final parts = []; + void flush() { + if (key != null && parts.isNotEmpty) { + rows.add({ + 'kind': 'assistant', + 'key': key, + 'parts': List.of(parts), + }); + } + key = null; + parts.clear(); + } + + for (final message in messages) { + if (message['role'] == 'assistant') { + key ??= '${message['id'] ?? ''}'; + for (final part in (message['parts'] as List? ?? const [])) { + if (part is Map) parts.add(Map.from(part)); + } + } else { + flush(); + rows.add({'kind': 'user', 'key': message['id'], 'message': message}); + } + } + flush(); + return rows; +} + +/// Replace a local optimistic user row when its server echo identifies the +/// same operation/native message; otherwise append once by authoritative id. +List reconcileChatUser(List messages, JsonMap remote) { + final operation = remote['operation_id']; + final nativeId = remote['native_message_id']; + final id = remote['id']; + final index = messages.indexWhere( + (message) => + (operation != null && message['operation_id'] == operation) || + (nativeId != null && message['native_message_id'] == nativeId) || + (id != null && message['id'] == id), + ); + if (index < 0) return [...messages, remote]; + final result = List.of(messages); + result[index] = remote; + return result; +} + +/// Fold a live chat frame into an immutable thread snapshot. Text and reasoning +/// deltas append by part id, tool snapshots merge without dropping prior fields, +/// and step frames update turn activity. Frames for another session are ignored. +JsonMap applyChatEvent(JsonMap thread, JsonMap frame) { + final session = thread['sessionId']; + if (session != null && + frame['session_id'] != null && + session != frame['session_id']) { + return thread; + } + final messages = (thread['messages'] as List? ?? const []) + .whereType() + .map((m) => Map.from(m)) + .toList(); + final kind = frame['kind']; + if (kind == 'user') { + final part = frame['part']; + final text = part is Map ? part['text'] : null; + final id = frame['message_id']; + if (text is! String || + text.isEmpty || + id == null || + messages.any( + (m) => + m['id'] == id || + (frame['operation_id'] != null && + m['operation_id'] == frame['operation_id']), + )) { + return thread; + } + messages.add({ + 'id': id, + 'session_id': frame['session_id'], + 'role': 'user', + 'client': frame['client'], + 'operation_id': frame['operation_id'], + 'parts': [ + {'type': 'text', 'text': text}, + ...(frame['attachments'] is List + ? frame['attachments'] as List + : const []), + ], + }); + return {...thread, 'messages': messages}; + } + if (kind == 'text' || kind == 'reasoning' || kind == 'tool') { + final incoming = frame['part']; + if (incoming is! Map || incoming['id'] == null) return thread; + final messageId = frame['message_id']; + var index = messages.indexWhere( + (m) => m['id'] == messageId && m['role'] == 'assistant', + ); + if (index < 0) { + messages.add({ + 'id': messageId, + 'session_id': frame['session_id'], + 'role': 'assistant', + 'parts': [], + }); + index = messages.length - 1; + } + final message = messages[index]; + final parts = (message['parts'] as List? ?? const []) + .whereType() + .map((p) => Map.from(p)) + .toList(); + final partIndex = parts.indexWhere( + (p) => p['id'] == incoming['id'] && p['type'] == kind, + ); + if (kind == 'text' || kind == 'reasoning') { + final delta = frame['delta']; + if (delta is! String || delta.isEmpty) return thread; + if (partIndex < 0) { + parts.add({'type': kind, 'id': incoming['id'], 'text': delta}); + } else { + parts[partIndex] = { + ...parts[partIndex], + 'text': '${parts[partIndex]['text'] ?? ''}$delta', + }; + } + } else if (partIndex < 0) { + parts.add(Map.from(incoming)); + } else { + final merged = { + ...parts[partIndex], + ...Map.from(incoming), + }; + if (parts[partIndex]['state'] is Map && incoming['state'] is Map) { + merged['state'] = { + ...Map.from(parts[partIndex]['state'] as Map), + ...Map.from(incoming['state'] as Map), + }; + } + parts[partIndex] = merged; + } + messages[index] = {...message, 'parts': parts}; + return {...thread, 'messages': messages, 'running': true}; + } + if (kind == 'step' && frame['step'] is Map) { + final step = frame['step'] as Map; + if (step['intermediate'] == true) return thread; + return { + ...thread, + 'running': step['status'] != 'ended', + 'nativeTurnId': step['status'] == 'ended' + ? '' + : (step['turn_id'] ?? thread['nativeTurnId'] ?? ''), + }; + } + return thread; +} + +/// Queue serialized sends per session; operation ids survive retries/replays. +class QueuedChatSend { + QueuedChatSend({ + required this.operationId, + required this.text, + this.files = const [], + }); + final String operationId; + final String text; + final List files; + + /// Retry the same immutable intent with the same idempotency key. + QueuedChatSend retry() => QueuedChatSend( + operationId: operationId, + text: text, + files: List.unmodifiable(files), + ); +} + +class ChatSendQueue { + final Map> _sessions = {}; + List forSession(String sessionId) => + List.unmodifiable(_sessions[sessionId] ?? const []); + bool enqueue(String sessionId, QueuedChatSend send) { + final queue = _sessions.putIfAbsent(sessionId, () => []); + if (queue.any((item) => item.operationId == send.operationId)) return false; + queue.add(send); + return true; + } + + QueuedChatSend? takeNext(String sessionId) { + final queue = _sessions[sessionId]; + if (queue == null || queue.isEmpty) return null; + final result = queue.removeAt(0); + if (queue.isEmpty) _sessions.remove(sessionId); + return result; + } +} diff --git a/app/lib/features/chat/session_screen.dart b/app/lib/features/chat/session_screen.dart new file mode 100644 index 00000000..782ccae3 --- /dev/null +++ b/app/lib/features/chat/session_screen.dart @@ -0,0 +1 @@ +export 'ui/sessions/chat_sessions_screen.dart'; diff --git a/app/lib/features/chat/ui/sessions/chat_adaptive.dart b/app/lib/features/chat/ui/sessions/chat_adaptive.dart new file mode 100644 index 00000000..4dcf7008 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/chat_adaptive.dart @@ -0,0 +1,200 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +/// Which standard control family this screen renders. +enum ChatControlsStyle { material, cupertino } + +/// Cupertino under a Cupertino app or an iOS/macOS Material theme, Material +/// everywhere else. The shell decides the app class, so a bare Cupertino app +/// never has to grow a Material ancestor just for this screen. +ChatControlsStyle chatControlsStyleOf(BuildContext context) { + if (context.findAncestorWidgetOfExactType() == null) { + return ChatControlsStyle.cupertino; + } + final platform = Theme.of(context).platform; + return platform == TargetPlatform.iOS || platform == TargetPlatform.macOS + ? ChatControlsStyle.cupertino + : ChatControlsStyle.material; +} + +class ChatBarAction extends StatelessWidget { + const ChatBarAction({ + super.key, + required this.label, + required this.onPressed, + required this.materialIcon, + required this.cupertinoIcon, + }); + + final String label; + final VoidCallback onPressed; + final IconData materialIcon; + final IconData cupertinoIcon; + + @override + Widget build(BuildContext context) { + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { + return Semantics( + label: label, + button: true, + child: CupertinoButton( + padding: EdgeInsets.zero, + onPressed: onPressed, + child: Icon(cupertinoIcon), + ), + ); + } + return IconButton( + tooltip: label, + onPressed: onPressed, + icon: Icon(materialIcon), + ); + } +} + +class ChatSearchField extends StatelessWidget { + const ChatSearchField({ + super.key, + required this.controller, + required this.onChanged, + }); + + final TextEditingController controller; + final ValueChanged onChanged; + + @override + Widget build(BuildContext context) { + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { + return Padding( + padding: const EdgeInsets.all(16), + child: CupertinoSearchTextField( + controller: controller, + placeholder: 'Search chats', + onChanged: onChanged, + ), + ); + } + return Padding( + padding: const EdgeInsets.all(16), + child: TextField( + controller: controller, + onChanged: onChanged, + decoration: const InputDecoration( + prefixIcon: Icon(Icons.search), + labelText: 'Search chats', + ), + ), + ); + } +} + +/// A grouped Cupertino card for a message that may wrap onto several lines. +/// +/// [CupertinoListTile] forces its title to one ellipsised line, which cut long +/// no-match queries and server reasons. This layout keeps the native card but +/// lets the message wrap, with its action on a separate button below. +class ChatCupertinoMessage extends StatelessWidget { + const ChatCupertinoMessage({ + super.key, + required this.message, + this.icon, + this.actionLabel, + this.onAction, + }); + + final String message; + final IconData? icon; + final String? actionLabel; + final VoidCallback? onAction; + + @override + Widget build(BuildContext context) { + return Semantics( + container: true, + explicitChildNodes: true, + child: CupertinoListSection.insetGrouped( + children: [ + Padding( + padding: const EdgeInsets.all(16), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (icon != null) ...[ + Icon( + icon, + color: CupertinoColors.secondaryLabel.resolveFrom(context), + ), + const SizedBox(width: 12), + ], + Expanded( + // Cupertino widgets normally supply their own text style. + // This card is also mounted under a bare MaterialApp (the + // iOS/macOS theme path), where Text would otherwise inherit + // MaterialApp's "missing Material" fallback style. + child: DefaultTextStyle.merge( + style: CupertinoTheme.of(context).textTheme.textStyle, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(message), + if (actionLabel != null && onAction != null) + Align( + alignment: AlignmentDirectional.centerStart, + child: CupertinoButton( + padding: const EdgeInsets.only(top: 8), + onPressed: onAction, + child: Text(actionLabel!), + ), + ), + ], + ), + ), + ), + ], + ), + ), + ], + ), + ); + } +} + +class ChatErrorNotice extends StatelessWidget { + const ChatErrorNotice({ + super.key, + required this.message, + required this.onRetry, + }); + + final String message; + final VoidCallback onRetry; + + @override + Widget build(BuildContext context) { + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { + return ChatCupertinoMessage( + message: message, + icon: CupertinoIcons.exclamationmark_circle, + actionLabel: 'Retry', + onAction: onRetry, + ); + } + return MaterialBanner( + content: Text(message), + actions: [TextButton(onPressed: onRetry, child: const Text('Retry'))], + ); + } +} + +class ChatLoadingIndicator extends StatelessWidget { + const ChatLoadingIndicator({super.key}); + + @override + Widget build(BuildContext context) { + return Center( + child: chatControlsStyleOf(context) == ChatControlsStyle.cupertino + ? const CupertinoActivityIndicator() + : const CircularProgressIndicator(), + ); + } +} diff --git a/app/lib/features/chat/ui/sessions/chat_create_fields.dart b/app/lib/features/chat/ui/sessions/chat_create_fields.dart new file mode 100644 index 00000000..f477811a --- /dev/null +++ b/app/lib/features/chat/ui/sessions/chat_create_fields.dart @@ -0,0 +1,185 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'chat_adaptive.dart'; + +/// The create dialog's server catalog area: loading, error with retry, the +/// empty-catalog message, or the two server-backed selectors. +class ChatCatalogFields extends StatelessWidget { + const ChatCatalogFields({ + super.key, + required this.loading, + required this.error, + required this.directories, + required this.backends, + required this.directory, + required this.backend, + required this.onDirectory, + required this.onBackend, + required this.onRetry, + }); + + final bool loading; + final String? error; + final List directories; + final List backends; + final String? directory; + final String? backend; + final ValueChanged onDirectory; + final ValueChanged onBackend; + final VoidCallback onRetry; + + @override + Widget build(BuildContext context) { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + if (loading) return const Text('Loading directories…'); + if (error != null) { + return _message(cupertino, 'Unable to load chat options: $error'); + } + if (directories.isEmpty || backends.isEmpty) { + return _message( + cupertino, + 'The server has no chat directories or backends available.', + ); + } + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (cupertino) + CupertinoPickerField( + label: 'Server directory', + value: directory, + values: directories, + onSelected: onDirectory, + ) + else + MaterialPickerField( + label: 'Server directory', + value: directory, + values: directories, + onSelected: onDirectory, + ), + if (cupertino) + CupertinoPickerField( + label: 'Backend', + value: backend, + values: backends, + onSelected: onBackend, + ) + else + MaterialPickerField( + label: 'Backend', + value: backend, + values: backends, + onSelected: onBackend, + ), + ], + ); + } + + Widget _message(bool cupertino, String text) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(text), + Align( + alignment: AlignmentDirectional.centerStart, + child: cupertino + ? CupertinoButton( + padding: EdgeInsets.zero, + onPressed: onRetry, + child: const Text('Retry'), + ) + : TextButton(onPressed: onRetry, child: const Text('Retry')), + ), + ], + ); + } +} + +class MaterialPickerField extends StatelessWidget { + const MaterialPickerField({ + super.key, + required this.label, + required this.value, + required this.values, + required this.onSelected, + }); + + final String label; + final String? value; + final List values; + final ValueChanged onSelected; + + @override + Widget build(BuildContext context) { + return DropdownButtonFormField( + key: Key('chat-create-${label.toLowerCase().replaceAll(' ', '-')}'), + initialValue: value, + decoration: InputDecoration(labelText: label), + items: [ + for (final item in values) + DropdownMenuItem(value: item, child: Text(item)), + ], + onChanged: (item) { + if (item != null) onSelected(item); + }, + ); + } +} + +class CupertinoPickerField extends StatelessWidget { + const CupertinoPickerField({ + super.key, + required this.label, + required this.value, + required this.values, + required this.onSelected, + }); + + final String label; + final String? value; + final List values; + final ValueChanged onSelected; + + Future _choose(BuildContext context) async { + final choice = await showCupertinoModalPopup( + context: context, + builder: (sheetContext) => CupertinoActionSheet( + title: Text(label), + actions: [ + for (final item in values) + CupertinoActionSheetAction( + onPressed: () => Navigator.pop(sheetContext, item), + child: Text(item), + ), + ], + cancelButton: CupertinoActionSheetAction( + onPressed: () => Navigator.pop(sheetContext), + child: const Text('Cancel'), + ), + ), + ); + if (choice != null) onSelected(choice); + } + + @override + Widget build(BuildContext context) { + return Semantics( + label: '$label: ${value ?? ''}', + button: true, + child: CupertinoButton( + key: Key('chat-create-${label.toLowerCase().replaceAll(' ', '-')}'), + padding: const EdgeInsets.symmetric(vertical: 4), + onPressed: () => _choose(context), + child: Row( + children: [ + Expanded(child: Text('$label: ${value ?? ''}')), + const Icon(CupertinoIcons.chevron_down), + ], + ), + ), + ); + } +} diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_body.dart b/app/lib/features/chat/ui/sessions/chat_sessions_body.dart new file mode 100644 index 00000000..0489a365 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/chat_sessions_body.dart @@ -0,0 +1,97 @@ +import 'package:flutter/material.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../domain/chat_sessions.dart'; +import 'chat_adaptive.dart'; +import 'session_list_cupertino.dart'; +import 'session_list_material.dart'; +import 'session_row_style.dart'; + +typedef ChatSessionSection = ({String title, List sessions}); + +/// Groups the visible sessions the way the server reports them. +class ChatSessionsBody extends StatelessWidget { + const ChatSessionsBody({ + super.key, + required this.sessions, + required this.query, + required this.loading, + required this.error, + required this.onOpen, + required this.onRename, + required this.onClose, + required this.onReopen, + required this.onStar, + required this.onClearSearch, + }); + + final List sessions; + final String query; + final bool loading; + final String? error; + final ValueChanged onOpen; + final ValueChanged onRename; + final ValueChanged onClose; + final ValueChanged onReopen; + final ValueChanged onStar; + final VoidCallback onClearSearch; + + @override + Widget build(BuildContext context) { + final visible = filterChatSessions(sessions, query); + final sections = [ + if (visible.any((s) => s['starred'] == true && s['closed_at'] == null)) + ( + title: 'Starred', + sessions: visible + .where((s) => s['starred'] == true && s['closed_at'] == null) + .toList(), + ), + if (visible.any((s) => s['starred'] != true && s['closed_at'] == null)) + ( + title: 'Chats', + sessions: visible + .where((s) => s['starred'] != true && s['closed_at'] == null) + .toList(), + ), + if (visible.any((s) => s['closed_at'] != null)) + ( + title: 'Closed', + sessions: visible.where((s) => s['closed_at'] != null).toList(), + ), + ]; + final emptyMessage = sessions.isEmpty + ? error == null + ? 'No chat sessions on this server yet.' + : null + : 'No chats match "${query.trim()}".'; + + if (loading && sessions.isEmpty) return const ChatLoadingIndicator(); + final clearSearch = query.trim().isEmpty ? null : onClearSearch; + final duplicateTitles = duplicateChatTitles(visible); + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { + return CupertinoSessionList( + sections: sections, + emptyMessage: visible.isEmpty ? emptyMessage : null, + duplicateTitles: duplicateTitles, + onOpen: onOpen, + onRename: onRename, + onClose: onClose, + onReopen: onReopen, + onStar: onStar, + onClearSearch: clearSearch, + ); + } + return MaterialSessionList( + sections: sections, + emptyMessage: visible.isEmpty ? emptyMessage : null, + duplicateTitles: duplicateTitles, + onOpen: onOpen, + onRename: onRename, + onClose: onClose, + onReopen: onReopen, + onStar: onStar, + onClearSearch: clearSearch, + ); + } +} diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart new file mode 100644 index 00000000..3c5799c6 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart @@ -0,0 +1,111 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../data/chat_repository.dart'; + +/// Owns the session list, its refresh generation and the row actions. +/// +/// A refresh that finishes after a newer one (or after the screen is gone) is +/// discarded, so a slow reply can never replace fresher state. +class ChatSessionsController extends ChangeNotifier { + ChatSessionsController(this.repository); + + ChatRepository repository; + List _sessions = const []; + String? _error; + bool _loading = true; + bool _disposed = false; + int _generation = 0; + + List get sessions => _sessions; + String? get error => _error; + bool get loading => _loading; + + void replaceRepository(ChatRepository next) { + if (identical(next.gateway, repository.gateway)) return; + repository = next; + refresh(); + } + + Future refresh() async { + if (_disposed) return; + final generation = ++_generation; + _loading = true; + _error = null; + _notify(); + try { + final sessions = await repository.sessions(); + if (generation != _generation) return; + _sessions = sessions; + _loading = false; + _notify(); + } catch (error) { + if (generation != _generation) return; + _error = '$error'; + _loading = false; + _notify(); + } + } + + Future star(String sessionId, bool starred) => + _mutate(() => repository.star(sessionId, starred)); + + Future close(String sessionId) => + _mutate(() => repository.close(sessionId)); + + Future reopen(String sessionId) => + _mutate(() => repository.reopen(sessionId)); + + Future rename(String sessionId, String title) => + _mutate(() => repository.rename(sessionId, title)); + + Future create({ + required String title, + required String directory, + required String backend, + required String instructions, + required String operationId, + }) async { + try { + final reply = await repository.create( + title: title, + directory: directory, + backend: backend, + operationId: operationId, + instructions: instructions, + ); + // Opening the created chat must not wait for the list refresh: the dialog + // has already closed, so a slow listing would look like a failed create. + unawaited(refresh()); + final session = reply['chat_session']; + return session is Map ? Map.from(session) : null; + } catch (error) { + _error = '$error'; + _notify(); + return null; + } + } + + Future _mutate(Future Function() action) async { + try { + await action(); + await refresh(); + } catch (error) { + _error = '$error'; + _notify(); + } + } + + void _notify() { + if (!_disposed) notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + _generation++; + super.dispose(); + } +} diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart new file mode 100644 index 00000000..ff345739 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart @@ -0,0 +1,176 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../data/chat_repository.dart'; +import 'chat_adaptive.dart'; +import 'chat_sessions_body.dart'; +import 'chat_sessions_controller.dart'; +import 'create_chat_dialog.dart'; +import 'rename_chat_dialog.dart'; +import 'session_actions.dart'; + +/// Browses server-owned sessions. Opening a row is read-only at this layer. +class ChatSessionsScreen extends StatefulWidget { + const ChatSessionsScreen({ + super.key, + required this.gateway, + required this.onOpen, + }); + final ApiGateway gateway; + final void Function(JsonMap session) onOpen; + + @override + State createState() => _ChatSessionsScreenState(); +} + +class _ChatSessionsScreenState extends State { + late final ChatSessionsController _controller = ChatSessionsController( + ChatRepository(widget.gateway), + )..refresh(); + final _search = TextEditingController(); + + @override + void didUpdateWidget(covariant ChatSessionsScreen oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.gateway != widget.gateway) { + _controller.replaceRepository(ChatRepository(widget.gateway)); + } + } + + @override + void dispose() { + _controller.dispose(); + _search.dispose(); + super.dispose(); + } + + String _sessionId(JsonMap session) => '${session['id'] ?? ''}'; + + Future _rename(JsonMap session) async { + final title = await showRenameChatDialog(context, session); + if (title == null || !mounted) return; + await _controller.rename(_sessionId(session), title); + } + + Future _close(JsonMap session) async { + if (!await confirmCloseChat(context, session)) return; + if (!mounted) return; + await _controller.close(_sessionId(session)); + } + + Future _newChat() async { + final operationId = 'native-chat-${DateTime.now().microsecondsSinceEpoch}'; + final draft = await showChatCreateDialog( + context, + repository: _controller.repository, + ); + if (draft == null || !mounted) return; + final session = await _controller.create( + title: draft.title, + directory: draft.directory, + backend: draft.backend, + instructions: draft.instructions, + operationId: operationId, + ); + if (session != null && mounted) widget.onOpen(session); + } + + @override + Widget build(BuildContext context) { + return ListenableBuilder( + listenable: _controller, + builder: (context, _) { + final body = Column( + children: [ + ChatSearchField( + controller: _search, + onChanged: (_) => setState(() {}), + ), + if (_controller.error != null) + ChatErrorNotice( + message: _controller.error!, + onRetry: _controller.refresh, + ), + Expanded( + child: ChatSessionsBody( + sessions: _controller.sessions, + query: _search.text, + loading: _controller.loading, + error: _controller.error, + onOpen: widget.onOpen, + onRename: _rename, + onClose: _close, + onReopen: (session) => _controller.reopen(_sessionId(session)), + onStar: (session) => _controller.star( + _sessionId(session), + session['starred'] != true, + ), + onClearSearch: () { + _search.clear(); + setState(() {}); + }, + ), + ), + ], + ); + + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { + return CupertinoPageScaffold( + navigationBar: CupertinoNavigationBar( + middle: const Text('Chats'), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + ChatBarAction( + key: const Key('chat-new-chat'), + label: 'New chat', + onPressed: _newChat, + materialIcon: Icons.add, + cupertinoIcon: CupertinoIcons.add, + ), + ChatBarAction( + key: const Key('chat-refresh'), + label: 'Refresh', + onPressed: _controller.refresh, + materialIcon: Icons.refresh, + cupertinoIcon: CupertinoIcons.refresh, + ), + ], + ), + ), + child: SafeArea(child: body), + ); + } + return Scaffold( + appBar: AppBar( + title: const Text('Chats'), + actions: [ + ChatBarAction( + key: const Key('chat-new-chat'), + label: 'New chat', + onPressed: _newChat, + materialIcon: Icons.add, + cupertinoIcon: CupertinoIcons.add, + ), + ChatBarAction( + key: const Key('chat-refresh'), + label: 'Refresh', + onPressed: _controller.refresh, + materialIcon: Icons.refresh, + cupertinoIcon: CupertinoIcons.refresh, + ), + ], + ), + body: body, + floatingActionButton: FloatingActionButton.extended( + key: const Key('chat-new-chat-fab'), + onPressed: _newChat, + icon: const Icon(Icons.add), + label: const Text('New chat'), + ), + ); + }, + ); + } +} diff --git a/app/lib/features/chat/ui/sessions/create_chat_dialog.dart b/app/lib/features/chat/ui/sessions/create_chat_dialog.dart new file mode 100644 index 00000000..6a0e2617 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/create_chat_dialog.dart @@ -0,0 +1,222 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../data/chat_repository.dart'; +import 'chat_adaptive.dart'; +import 'chat_create_fields.dart'; + +class ChatDraft { + const ChatDraft({ + required this.title, + required this.directory, + required this.backend, + required this.instructions, + }); + + final String title; + final String directory; + final String backend; + final String instructions; +} + +Future showChatCreateDialog( + BuildContext context, { + required ChatRepository repository, +}) { + final dialog = CreateChatDialog(repository: repository); + return chatControlsStyleOf(context) == ChatControlsStyle.cupertino + ? showCupertinoDialog(context: context, builder: (_) => dialog) + : showDialog(context: context, builder: (_) => dialog); +} + +class CreateChatDialog extends StatefulWidget { + const CreateChatDialog({super.key, required this.repository}); + + final ChatRepository repository; + + @override + State createState() => _CreateChatDialogState(); +} + +class _CreateChatDialogState extends State { + final _name = TextEditingController(text: 'New chat'); + final _instructions = TextEditingController(); + List _directories = const []; + List _backends = const []; + String? _directory; + String? _backend; + String? _catalogError; + String? _formError; + bool _loading = true; + int _attempt = 0; + + @override + void initState() { + super.initState(); + _loadCatalog(); + } + + @override + void dispose() { + _attempt++; + _name.dispose(); + _instructions.dispose(); + super.dispose(); + } + + Future _loadCatalog() async { + final attempt = ++_attempt; + setState(() { + _loading = true; + _catalogError = null; + }); + try { + final values = await Future.wait([ + widget.repository.directories(), + widget.repository.backends(), + ]); + if (!mounted || attempt != _attempt) return; + setState(() { + _directories = values[0]; + _backends = values[1]; + _directory = _directories.contains(_directory) + ? _directory + : _directories.isEmpty + ? null + : _directories.first; + _backend = _backends.contains(_backend) + ? _backend + : _backends.isEmpty + ? null + : _backends.first; + _loading = false; + }); + } catch (error) { + if (!mounted || attempt != _attempt) return; + setState(() { + _catalogError = '$error'; + _loading = false; + }); + } + } + + bool get _catalogReady => + !_loading && + _catalogError == null && + _directories.isNotEmpty && + _backends.isNotEmpty; + + void _submit() { + if (!_catalogReady) return; + final title = _name.text.trim(); + final directory = _directory ?? ''; + if (title.isEmpty || directory.isEmpty) { + setState(() => _formError = 'Enter a name and server directory.'); + return; + } + Navigator.pop( + context, + ChatDraft( + title: title, + directory: directory, + backend: _backend ?? '', + instructions: _instructions.text, + ), + ); + } + + @override + Widget build(BuildContext context) { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final content = SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (cupertino) + CupertinoTextField( + key: const Key('chat-create-name'), + controller: _name, + placeholder: 'Name', + ) + else + TextField( + key: const Key('chat-create-name'), + controller: _name, + decoration: const InputDecoration(labelText: 'Name'), + ), + const SizedBox(height: 12), + ChatCatalogFields( + loading: _loading, + error: _catalogError, + directories: _directories, + backends: _backends, + directory: _directory, + backend: _backend, + onDirectory: (value) => setState(() => _directory = value), + onBackend: (value) => setState(() => _backend = value), + onRetry: _loadCatalog, + ), + if (_catalogReady) ...[ + const SizedBox(height: 8), + const Text('New chats use the server default model.'), + ], + const SizedBox(height: 12), + if (cupertino) + CupertinoTextField( + key: const Key('chat-create-instructions'), + controller: _instructions, + placeholder: 'Instructions', + minLines: 1, + maxLines: 3, + ) + else + TextField( + key: const Key('chat-create-instructions'), + controller: _instructions, + decoration: const InputDecoration(labelText: 'Instructions'), + minLines: 1, + maxLines: 3, + ), + if (_formError != null) ...[ + const SizedBox(height: 8), + Text(_formError!), + ], + ], + ), + ); + + if (cupertino) { + return CupertinoAlertDialog( + title: const Text('New chat'), + content: content, + actions: [ + CupertinoDialogAction( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + CupertinoDialogAction( + isDefaultAction: true, + onPressed: _catalogReady ? _submit : null, + child: const Text('Create'), + ), + ], + ); + } + return AlertDialog( + title: const Text('New chat'), + content: content, + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: _catalogReady ? _submit : null, + child: const Text('Create'), + ), + ], + ); + } +} diff --git a/app/lib/features/chat/ui/sessions/rename_chat_dialog.dart b/app/lib/features/chat/ui/sessions/rename_chat_dialog.dart new file mode 100644 index 00000000..9dd0000d --- /dev/null +++ b/app/lib/features/chat/ui/sessions/rename_chat_dialog.dart @@ -0,0 +1,107 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../domain/chat_sessions.dart'; +import 'chat_adaptive.dart'; + +/// Renames one session. Save is disabled while the trimmed name is blank, +/// matching the web dialog. +Future showRenameChatDialog(BuildContext context, JsonMap session) { + final dialog = _RenameChatDialog(initialTitle: chatSessionTitle(session)); + return chatControlsStyleOf(context) == ChatControlsStyle.cupertino + ? showCupertinoDialog(context: context, builder: (_) => dialog) + : showDialog(context: context, builder: (_) => dialog); +} + +class _RenameChatDialog extends StatefulWidget { + const _RenameChatDialog({required this.initialTitle}); + + final String initialTitle; + + @override + State<_RenameChatDialog> createState() => _RenameChatDialogState(); +} + +class _RenameChatDialogState extends State<_RenameChatDialog> { + late final TextEditingController _title = + TextEditingController(text: widget.initialTitle) + ..selection = TextSelection( + baseOffset: 0, + extentOffset: widget.initialTitle.length, + ); + + @override + void dispose() { + _title.dispose(); + super.dispose(); + } + + void _save() { + final title = _title.text.trim(); + if (title.isEmpty) return; + Navigator.pop(context, title); + } + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder( + valueListenable: _title, + builder: (context, value, _) { + final canSave = value.text.trim().isNotEmpty; + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { + return CupertinoAlertDialog( + title: const Text('Rename chat'), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + CupertinoTextField( + key: const Key('chat-rename-field'), + controller: _title, + autofocus: true, + placeholder: 'Name', + ), + const SizedBox(height: 8), + const Text('This name is shared with every device.'), + ], + ), + actions: [ + CupertinoDialogAction( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + CupertinoDialogAction( + isDefaultAction: true, + onPressed: canSave ? _save : null, + child: const Text('Save'), + ), + ], + ); + } + return AlertDialog( + title: const Text('Rename chat'), + content: TextField( + key: const Key('chat-rename-field'), + controller: _title, + autofocus: true, + decoration: const InputDecoration( + labelText: 'Name', + helperText: 'This name is shared with every device.', + helperMaxLines: 2, + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: canSave ? _save : null, + child: const Text('Save'), + ), + ], + ); + }, + ); + } +} diff --git a/app/lib/features/chat/ui/sessions/session_actions.dart b/app/lib/features/chat/ui/sessions/session_actions.dart new file mode 100644 index 00000000..f70a20b2 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/session_actions.dart @@ -0,0 +1,161 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../domain/chat_sessions.dart'; +import 'chat_adaptive.dart'; +import 'session_row_style.dart'; + +enum SessionAction { rename, close, reopen } + +/// The close confirmation's body, matching the web client's explanation. +String closeChatConfirmation(String title) => + 'Closes "$title" and marks it closed on every device. ' + 'A turn that is running is stopped first. ' + 'Nothing is deleted — the chat and its history are kept, ' + 'and you can reopen it from the list.'; + +class SessionStarButton extends StatelessWidget { + const SessionStarButton({ + super.key, + required this.session, + required this.onPressed, + }); + + final JsonMap session; + final VoidCallback onPressed; + + @override + Widget build(BuildContext context) { + final starred = session['starred'] == true; + final label = starred ? 'Unstar chat' : 'Star chat'; + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { + return Semantics( + label: label, + button: true, + child: CupertinoButton( + padding: EdgeInsets.zero, + onPressed: onPressed, + child: Icon(starred ? CupertinoIcons.star_fill : CupertinoIcons.star), + ), + ); + } + return IconButton( + tooltip: label, + onPressed: onPressed, + icon: Icon(starred ? Icons.star : Icons.star_border), + ); + } +} + +class SessionActionsButton extends StatelessWidget { + const SessionActionsButton({ + super.key, + required this.session, + required this.onSelected, + this.duplicateTitles = const {}, + }); + + final JsonMap session; + final ValueChanged onSelected; + final Set duplicateTitles; + + @override + Widget build(BuildContext context) { + final label = sessionActionsLabel(session, duplicateTitles); + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { + return Semantics( + label: label, + button: true, + child: CupertinoButton( + padding: EdgeInsets.zero, + onPressed: () => _showSheet(context), + child: const Icon(CupertinoIcons.ellipsis), + ), + ); + } + return PopupMenuButton( + tooltip: label, + onSelected: onSelected, + itemBuilder: (context) => _menuItems(session), + ); + } + + Future _showSheet(BuildContext context) async { + final action = await showCupertinoModalPopup( + context: context, + builder: (sheetContext) => CupertinoActionSheet( + title: Text(chatSessionTitle(session)), + actions: [ + for (final item in _items(session)) + CupertinoActionSheetAction( + onPressed: () => Navigator.pop(sheetContext, item.action), + child: Text(item.label), + ), + ], + cancelButton: CupertinoActionSheetAction( + onPressed: () => Navigator.pop(sheetContext), + child: const Text('Cancel'), + ), + ), + ); + if (action != null && context.mounted) onSelected(action); + } +} + +List> _menuItems(JsonMap session) => [ + for (final item in _items(session)) + PopupMenuItem(value: item.action, child: Text(item.label)), +]; + +List<({SessionAction action, String label})> _items(JsonMap session) { + final isClosed = session['closed_at'] != null; + return [ + (action: SessionAction.rename, label: 'Rename…'), + isClosed + ? (action: SessionAction.reopen, label: 'Reopen') + : (action: SessionAction.close, label: 'Close chat…'), + ]; +} + +Future confirmCloseChat(BuildContext context, JsonMap session) async { + final title = chatSessionTitle(session); + final body = closeChatConfirmation(title); + final confirmed = chatControlsStyleOf(context) == ChatControlsStyle.cupertino + ? await showCupertinoDialog( + context: context, + builder: (context) => CupertinoAlertDialog( + title: const Text('Close chat?'), + content: Text(body), + actions: [ + CupertinoDialogAction( + onPressed: () => Navigator.pop(context, false), + child: const Text('Cancel'), + ), + CupertinoDialogAction( + isDestructiveAction: true, + onPressed: () => Navigator.pop(context, true), + child: const Text('Close chat'), + ), + ], + ), + ) + : await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Close chat?'), + content: Text(body), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () => Navigator.pop(context, true), + child: const Text('Close chat'), + ), + ], + ), + ); + return confirmed == true; +} diff --git a/app/lib/features/chat/ui/sessions/session_list_cupertino.dart b/app/lib/features/chat/ui/sessions/session_list_cupertino.dart new file mode 100644 index 00000000..a6f6456b --- /dev/null +++ b/app/lib/features/chat/ui/sessions/session_list_cupertino.dart @@ -0,0 +1,134 @@ +import 'package:flutter/cupertino.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../domain/chat_sessions.dart'; +import 'chat_adaptive.dart'; +import 'chat_sessions_body.dart'; +import 'session_actions.dart'; +import 'session_row_style.dart'; + +class CupertinoSessionList extends StatelessWidget { + const CupertinoSessionList({ + super.key, + required this.sections, + required this.emptyMessage, + required this.duplicateTitles, + required this.onOpen, + required this.onRename, + required this.onClose, + required this.onReopen, + required this.onStar, + required this.onClearSearch, + }); + + final List sections; + final String? emptyMessage; + final Set duplicateTitles; + final ValueChanged onOpen; + final ValueChanged onRename; + final ValueChanged onClose; + final ValueChanged onReopen; + final ValueChanged onStar; + final VoidCallback? onClearSearch; + + @override + Widget build(BuildContext context) { + return ListView( + padding: const EdgeInsets.only(bottom: 24), + children: [ + for (final section in sections) ..._section(section), + if (emptyMessage != null) + ChatCupertinoMessage( + message: emptyMessage!, + actionLabel: onClearSearch == null ? null : 'Clear search', + onAction: onClearSearch, + ), + ], + ); + } + + List _section(ChatSessionSection section) { + final groups = groupChatSessions(section.sessions); + return [ + for (final group in groups) + CupertinoListSection.insetGrouped( + header: Text( + groups.length > 1 + ? '${section.title} · ${group.directory.isEmpty ? 'No directory' : group.directory}' + : section.title, + ), + children: [ + for (final session in group.sessions) + _CupertinoSessionRow( + session: session, + duplicateTitles: duplicateTitles, + onOpen: onOpen, + onRename: onRename, + onClose: onClose, + onReopen: onReopen, + onStar: onStar, + ), + ], + ), + ]; + } +} + +class _CupertinoSessionRow extends StatelessWidget { + const _CupertinoSessionRow({ + required this.session, + required this.duplicateTitles, + required this.onOpen, + required this.onRename, + required this.onClose, + required this.onReopen, + required this.onStar, + }); + + final JsonMap session; + final Set duplicateTitles; + final ValueChanged onOpen; + final ValueChanged onRename; + final ValueChanged onClose; + final ValueChanged onReopen; + final ValueChanged onStar; + + @override + Widget build(BuildContext context) { + final id = '${session['id'] ?? ''}'; + return CupertinoListTile( + key: Key('chat-row-$id'), + leading: Icon(sessionCupertinoIcon(session)), + title: Text(chatSessionTitle(session)), + subtitle: Text(sessionSubtitle(session)), + onTap: () => onOpen(session), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + SessionStarButton( + key: Key('chat-star-$id'), + session: session, + onPressed: () => onStar(session), + ), + SessionActionsButton( + key: Key('chat-actions-$id'), + session: session, + duplicateTitles: duplicateTitles, + onSelected: _select, + ), + ], + ), + ); + } + + void _select(SessionAction action) { + switch (action) { + case SessionAction.rename: + onRename(session); + case SessionAction.close: + onClose(session); + case SessionAction.reopen: + onReopen(session); + } + } +} diff --git a/app/lib/features/chat/ui/sessions/session_list_material.dart b/app/lib/features/chat/ui/sessions/session_list_material.dart new file mode 100644 index 00000000..d05cc6e7 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/session_list_material.dart @@ -0,0 +1,140 @@ +import 'package:flutter/material.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../domain/chat_sessions.dart'; +import 'chat_sessions_body.dart'; +import 'session_actions.dart'; +import 'session_row_style.dart'; + +class MaterialSessionList extends StatelessWidget { + const MaterialSessionList({ + super.key, + required this.sections, + required this.emptyMessage, + required this.duplicateTitles, + required this.onOpen, + required this.onRename, + required this.onClose, + required this.onReopen, + required this.onStar, + required this.onClearSearch, + }); + + final List sections; + final String? emptyMessage; + final Set duplicateTitles; + final ValueChanged onOpen; + final ValueChanged onRename; + final ValueChanged onClose; + final ValueChanged onReopen; + final ValueChanged onStar; + final VoidCallback? onClearSearch; + + @override + Widget build(BuildContext context) { + return ListView( + children: [ + for (final section in sections) _section(section), + if (emptyMessage != null) + ListTile( + title: Text(emptyMessage!), + trailing: onClearSearch == null + ? null + : TextButton( + onPressed: onClearSearch, + child: const Text('Clear search'), + ), + ), + ], + ); + } + + Widget _section(ChatSessionSection section) { + final groups = groupChatSessions(section.sessions); + return ExpansionTile( + title: Text(section.title), + initiallyExpanded: true, + children: [ + for (final group in groups) ...[ + if (groups.length > 1) + ListTile( + dense: true, + leading: const Icon(Icons.folder_outlined), + title: Text( + group.directory.isEmpty ? 'No directory' : group.directory, + ), + ), + for (final session in group.sessions) + _MaterialSessionRow( + session: session, + duplicateTitles: duplicateTitles, + onOpen: onOpen, + onRename: onRename, + onClose: onClose, + onReopen: onReopen, + onStar: onStar, + ), + ], + ], + ); + } +} + +class _MaterialSessionRow extends StatelessWidget { + const _MaterialSessionRow({ + required this.session, + required this.duplicateTitles, + required this.onOpen, + required this.onRename, + required this.onClose, + required this.onReopen, + required this.onStar, + }); + + final JsonMap session; + final Set duplicateTitles; + final ValueChanged onOpen; + final ValueChanged onRename; + final ValueChanged onClose; + final ValueChanged onReopen; + final ValueChanged onStar; + + @override + Widget build(BuildContext context) { + final id = '${session['id'] ?? ''}'; + return ListTile( + key: Key('chat-row-$id'), + leading: Icon(sessionMaterialIcon(session)), + title: Text(chatSessionTitle(session)), + subtitle: Text(sessionSubtitle(session)), + onTap: () => onOpen(session), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + SessionStarButton( + key: Key('chat-star-$id'), + session: session, + onPressed: () => onStar(session), + ), + SessionActionsButton( + key: Key('chat-actions-$id'), + session: session, + duplicateTitles: duplicateTitles, + onSelected: (action) => _select(action), + ), + ], + ), + ); + } + + void _select(SessionAction action) { + switch (action) { + case SessionAction.rename: + onRename(session); + case SessionAction.close: + onClose(session); + case SessionAction.reopen: + onReopen(session); + } + } +} diff --git a/app/lib/features/chat/ui/sessions/session_row_style.dart b/app/lib/features/chat/ui/sessions/session_row_style.dart new file mode 100644 index 00000000..59b8f4b3 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/session_row_style.dart @@ -0,0 +1,51 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../domain/chat_sessions.dart'; + +/// Titles shared by more than one visible session, so row action labels can +/// add the session id the way the web client does. +Set duplicateChatTitles(Iterable sessions) { + final seen = {}; + final duplicates = {}; + for (final session in sessions) { + final title = chatSessionTitle(session); + if (!seen.add(title)) duplicates.add(title); + } + return duplicates; +} + +String sessionActionsLabel(JsonMap session, Set duplicateTitles) { + final title = chatSessionTitle(session); + return duplicateTitles.contains(title) + ? 'Chat actions for $title (${session['id'] ?? ''})' + : 'Chat actions for $title'; +} + +String sessionSubtitle(JsonMap session) { + final directory = '${session['directory'] ?? ''}'; + switch (chatSessionActivity( + running: session['running'] == true, + unseen: session['unseen'] == true, + )) { + case 'streaming': + return '$directory · Streaming'; + case 'new': + return '$directory · New'; + default: + return directory; + } +} + +IconData sessionMaterialIcon(JsonMap session) { + if (session['running'] == true) return Icons.sync; + if (session['starred'] == true) return Icons.star; + return Icons.chat_bubble_outline; +} + +IconData sessionCupertinoIcon(JsonMap session) { + if (session['running'] == true) return CupertinoIcons.arrow_2_circlepath; + if (session['starred'] == true) return CupertinoIcons.star_fill; + return CupertinoIcons.chat_bubble; +} diff --git a/app/lib/features/graph/domain/graph_definition.dart b/app/lib/features/graph/domain/graph_definition.dart new file mode 100644 index 00000000..60735fa9 --- /dev/null +++ b/app/lib/features/graph/domain/graph_definition.dart @@ -0,0 +1,152 @@ +import 'graph_protocol.dart'; + +/// The graph definition: nodes and edges declared by a pipeline, never the +/// evidence that a run executed them. Run evidence lives in +/// `run_graph_state.dart`; keeping the two shapes separate means a definition +/// can be drawn without claiming a visit happened. +/// +/// Mirrors `stageOutcomes`, `edgeLabel`, `graphEdges` and `nodeDisplayLabel` +/// from `web/src/graph.js` (and `web/src/runDetail.js`). Pure data only. + +/// Ordering priority: success first, error last, every other outcome +/// alphabetical in between (the web client's `outcomePriority`). +int _outcomePriority(String outcome) { + if (outcome == 'success') return 0; + if (outcome == 'error') return 2; + return 1; +} + +/// A stage's edge outcomes in the app's one stable order. +List stageOutcomes(dynamic stage) { + final edges = stage is Map ? stage['edges'] : null; + if (edges is! Map) return const []; + final outcomes = edges.keys.map((key) => '$key').toList(); + outcomes.sort((a, b) { + final priority = _outcomePriority(a) - _outcomePriority(b); + return priority != 0 ? priority : a.compareTo(b); + }); + return outcomes; +} + +/// The outcome label on an edge: `error*` for an implicit fallback error route. +String edgeLabel(dynamic stage, String outcome) { + final implicitFallback = stage is Map && stage['fallback_error'] == true; + return outcome == 'error' && implicitFallback ? 'error*' : outcome; +} + +/// One declared edge, in stable definition order. +class GraphEdge { + const GraphEdge({ + required this.id, + required this.source, + required this.outcome, + required this.target, + required this.label, + required this.fallback, + required this.knownTarget, + }); + + /// The 1-based id assigned in stable definition order (`Graph.edges()`). + final int id; + final String source; + final String outcome; + + /// The resolved target: `#` has already become `#success`/`#failure`. + final String target; + final String label; + + /// True only for the parser's implicit `error -> #failure` route. + final bool fallback; + + /// True when [target] is a terminal or a stage declared in this graph. + /// + /// An empty or unknown target is kept exactly as recorded, with this flag + /// false, so callers can show it honestly instead of inventing a node. + final bool knownTarget; + + bool get isTerminal => isTerminalTarget(target); +} + +/// One graph definition node: a declared stage, or a terminal the definition +/// routes to. +class GraphNode { + const GraphNode({required this.key, required this.terminal, this.stageIndex}); + + final String key; + final bool terminal; + + /// The node's stage declaration index, or null for a terminal. + final int? stageIndex; + + String get label => nodeDisplayLabel(key); + String get shortLabel => nodeLabel(key); +} + +List> _stages(dynamic graph) { + if (graph is! Map) return const >[]; + final stages = graph['stages']; + if (stages is! List) return const >[]; + return stages.whereType().map(Map.from).toList(); +} + +String _stageKey(Map stage) => '${stage['key'] ?? ''}'; + +/// Every definition edge in stable id order. +/// +/// Stages keep declaration order and each stage's outcomes use +/// [stageOutcomes]; ids are contiguous in that order. An absent (null) edge +/// value declares no edge and is skipped, while an empty or unknown target is +/// preserved with [GraphEdge.knownTarget] false. +List graphEdges(dynamic graph) { + final stages = _stages(graph); + final stageKeys = { + for (final stage in stages) + if (_stageKey(stage).isNotEmpty) _stageKey(stage), + }; + final result = []; + for (final stage in stages) { + final edges = stage['edges']; + if (edges is! Map) continue; + final source = _stageKey(stage); + for (final outcome in stageOutcomes(stage)) { + final raw = edges[outcome]; + if (raw == null) continue; + final target = resolveTarget(outcome, '$raw') ?? ''; + result.add( + GraphEdge( + id: result.length + 1, + source: source, + outcome: outcome, + target: target, + label: edgeLabel(stage, outcome), + fallback: outcome == 'error' && stage['fallback_error'] == true, + knownTarget: isTerminalTarget(target) || stageKeys.contains(target), + ), + ); + } + } + return result; +} + +/// The definition's nodes in declaration order. +/// +/// A stage key identifies one node even when it is declared twice; self edges +/// and loops therefore never duplicate identity. Terminal nodes are appended +/// failure first, then success, once any declared edge resolves to a terminal +/// (the same `hasTerminal` rule the web layout uses). They are still +/// definition nodes, not evidence that a run reached them. +List graphNodes(dynamic graph) { + final stages = _stages(graph); + final seen = {}; + final nodes = []; + for (var index = 0; index < stages.length; index += 1) { + final key = _stageKey(stages[index]); + if (key.isEmpty || !seen.add(key)) continue; + nodes.add(GraphNode(key: key, terminal: false, stageIndex: index)); + } + if (graphEdges(graph).any((edge) => edge.isTerminal)) { + nodes.add(const GraphNode(key: failureEnd, terminal: true)); + nodes.add(const GraphNode(key: successEnd, terminal: true)); + } + return nodes; +} diff --git a/app/lib/features/graph/domain/graph_protocol.dart b/app/lib/features/graph/domain/graph_protocol.dart new file mode 100644 index 00000000..a033884c --- /dev/null +++ b/app/lib/features/graph/domain/graph_protocol.dart @@ -0,0 +1,43 @@ +/// Protocol terminal targets and the labels the graph uses for them. +/// +/// Mirrors `web/src/protocol.js` (`SUCCESS_END`, `FAILURE_END`, +/// `isTerminal`, `resolveTarget`) and the label helpers in `web/src/graph.js`. +/// Pure Dart: no Flutter imports and no layout or rendering decisions. +library; + +/// The explicit success terminal (`Protocol.SUCCESS_END`). +const String successEnd = '#success'; + +/// The explicit failure terminal (`Protocol.FAILURE_END`). +const String failureEnd = '#failure'; + +/// True only for the two explicit terminal targets. +/// +/// A bare `#` is not itself terminal; [resolveTarget] turns it into one using +/// the outcome, exactly as the server and the web client do. +bool isTerminalTarget(String? target) => + target == successEnd || target == failureEnd; + +/// Mirrors `Protocol.resolveTarget`: a bare `#` is the outcome's terminal. +/// +/// Every other value is preserved verbatim, including an empty or unknown +/// stage key. A missing target stays null rather than becoming a terminal, so +/// a blank edge cannot fabricate a visit or a terminal node. +String? resolveTarget(String? outcome, String? target) { + if (target != '#') return target; + return outcome == 'error' ? failureEnd : successEnd; +} + +/// A graph node title: a stage keeps its key, a terminal reads Success/Failure. +String nodeDisplayLabel(String? key) { + if (key == successEnd) return 'Success'; + if (key == failureEnd) return 'Failure'; + return key ?? ''; +} + +/// The TUI-mirroring label: terminal targets are all caps. +String nodeLabel(String? key) { + if (key == successEnd) return 'SUCCESS'; + if (key == failureEnd) return 'FAILURE'; + return key ?? ''; +} diff --git a/app/lib/features/graph/domain/run_graph_state.dart b/app/lib/features/graph/domain/run_graph_state.dart new file mode 100644 index 00000000..ef3fb8be --- /dev/null +++ b/app/lib/features/graph/domain/run_graph_state.dart @@ -0,0 +1,124 @@ +import 'graph_protocol.dart'; + +/// Which stages and routes a run actually recorded. +/// +/// This is executed-route evidence, deliberately distinct from the graph +/// definition's nodes and edges. It mirrors `runGraphState` from +/// `web/src/runDetail.js` (Android `RunGraphState.from`): every recorded step's +/// stage is visited once in first-appearance order, a step with a non-blank +/// outcome and target contributes one deduplicated `source\0outcome\0target` +/// route, and only a resolved terminal is added by its target. A non-terminal +/// target is not visited until a step lands on it. +/// +/// The run map is the same detail produced by the runs feature; this helper +/// reads recorded steps and never folds live events a second time. +class RunGraphState { + RunGraphState({ + required List visitedStages, + required List takenRoutes, + required this.currentStage, + required this.executing, + required this.currentStageStartedAt, + }) : visitedStages = List.unmodifiable(visitedStages), + takenRoutes = List.unmodifiable(takenRoutes); + + /// Visited stage keys in first-appearance order, without duplicates. + final List visitedStages; + + /// Taken routes as `source\0outcome\0resolvedTarget`, in recorded order. + final List takenRoutes; + + /// The run's current stage, else the last recorded visit's stage, else null. + final String? currentStage; + final bool executing; + + /// The running visit's start for [currentStage], only while executing. + final String? currentStageStartedAt; + + bool isStageVisited(String key) => visitedStages.contains(key); + + /// True when a recorded visit took this definition route. The target is + /// resolved with the same `#` rule the definition edges use. + bool isRouteTaken(String source, String outcome, String target) { + final resolved = resolveTarget(outcome, target); + if (resolved == null || resolved.isEmpty) return false; + return takenRoutes.contains('$source\u0000$outcome\u0000$resolved'); + } + + /// The active stage for a live run, else null. A finished run has none. + String? get activeStage { + if (!executing || currentStage == null || currentStage!.isEmpty) { + return null; + } + return currentStage; + } +} + +List> _steps(dynamic run) { + if (run is! Map) return const >[]; + final steps = run['steps']; + if (steps is! List) return const >[]; + return steps.whereType().map(Map.from).toList(); +} + +String _text(dynamic value) => '${value ?? ''}'; + +/// Derives [RunGraphState] from one run detail map. +/// +/// Missing or malformed steps yield no visits and no routes; nothing is +/// fabricated from a missing capture. Repeated visits stay one identity per +/// stage, and self edges or loops never recurse. +RunGraphState runGraphState(dynamic run) { + final steps = _steps(run); + final visitedStages = []; + final seenStages = {}; + final takenRoutes = []; + final seenRoutes = {}; + + void visit(String? key) { + if (key == null || key.isEmpty || !seenStages.add(key)) return; + visitedStages.add(key); + } + + for (final step in steps) { + final stage = _text(step['stage']); + if (stage.isNotEmpty) visit(stage); + + final outcome = _text(step['outcome']); + final target = _text(step['target']); + if (outcome.trim().isEmpty || target.trim().isEmpty) continue; + + final resolved = resolveTarget(outcome, target); + if (resolved == null || resolved.isEmpty) continue; + final route = '$stage\u0000$outcome\u0000$resolved'; + if (seenRoutes.add(route)) takenRoutes.add(route); + if (isTerminalTarget(resolved)) visit(resolved); + } + + final lastStage = steps.isEmpty ? '' : _text(steps.last['stage']); + final rawCurrent = _text(run is Map ? run['current_stage'] : null); + final currentStage = rawCurrent.trim().isNotEmpty + ? rawCurrent + : (lastStage.trim().isNotEmpty ? lastStage : null); + final executing = run is Map && run['executing'] == true; + + String? currentStageStartedAt; + if (executing && currentStage != null) { + for (var index = steps.length - 1; index >= 0; index -= 1) { + final step = steps[index]; + if (_text(step['stage']) != currentStage) continue; + if (_text(step['status']) != 'running') continue; + final started = _text(step['started_at']); + if (started.trim().isNotEmpty) currentStageStartedAt = started; + break; + } + } + + return RunGraphState( + visitedStages: visitedStages, + takenRoutes: takenRoutes, + currentStage: currentStage, + executing: executing, + currentStageStartedAt: currentStageStartedAt, + ); +} diff --git a/app/lib/features/graph/domain/stage_visits.dart b/app/lib/features/graph/domain/stage_visits.dart new file mode 100644 index 00000000..4a546cfa --- /dev/null +++ b/app/lib/features/graph/domain/stage_visits.dart @@ -0,0 +1,107 @@ +import '../../../core/api_gateway.dart'; + +/// Recorded stage-visit selection, matching the web client's timeline and +/// stage pane. Visits are ordered by their recorded sequence, never by the +/// order a caller happens to pass them in; repeated visits to one stage stay +/// separate entries. Pure data: no widgets, layout or coordinates. + +int _sequenceOf(JsonMap step) { + final sequence = step['sequence']; + return sequence is num ? sequence.toInt() : 0; +} + +int _positiveVisit(dynamic control) { + if (control is! Map) return 0; + final visit = control['visit']; + if (visit is num) return visit > 0 ? visit.toInt() : 0; + return int.tryParse('${visit ?? ''}') ?? 0; +} + +/// The visit number a timeline row shows: the recorded `control.visit` when it +/// is positive, else the position within the stage's ordered visits. +int displayVisit(JsonMap step, int index) { + final recorded = _positiveVisit(step['control']); + return recorded > 0 ? recorded : index + 1; +} + +/// Clamps a visit index into `[0, count)`; an empty list yields 0. +int clampVisitIndex(int index, int count) { + if (count <= 0) return 0; + if (index < 0) return 0; + return index >= count ? count - 1 : index; +} + +List _ordered(List visits) { + final indexed = <({int position, JsonMap step})>[ + for (var index = 0; index < visits.length; index += 1) + (position: index, step: visits[index]), + ]; + indexed.sort((a, b) { + final bySequence = _sequenceOf(a.step).compareTo(_sequenceOf(b.step)); + return bySequence != 0 ? bySequence : a.position.compareTo(b.position); + }); + return [for (final entry in indexed) entry.step]; +} + +/// Every stage's recorded visits, ordered by sequence. +/// +/// The map keeps stage first-appearance order. Equal sequences keep their +/// recorded order (the web client's stable sort), and a stage with no recorded +/// visit is simply absent rather than present with a synthetic visit. +Map> visitsByStage(List steps) { + final grouped = >{}; + for (final step in steps) { + final stage = '${step['stage'] ?? ''}'; + grouped.putIfAbsent(stage, () => []).add(step); + } + return >{ + for (final entry in grouped.entries) entry.key: _ordered(entry.value), + }; +} + +/// One selected stage visit. [step] is null when the stage has no recorded +/// visit, so callers cannot mistake an absent capture for an execution. +class StageVisitSelection { + const StageVisitSelection({ + required this.stageKey, + required this.visits, + required this.index, + }); + + final String stageKey; + + /// The stage's visits ordered by sequence. + final List visits; + + /// The clamped index into [visits]; 0 when there are none. + final int index; + + bool get hasVisit => visits.isNotEmpty; + JsonMap? get step => hasVisit ? visits[index] : null; + int get visitNumber => step == null ? 0 : displayVisit(step!, index); + + /// True when an explicit requested index was clamped, so a caller can + /// correct its route exactly as the web stage route does. + bool correctedRequest(int? requested) => + requested != null && requested != index; +} + +/// Selects a stage's visit exactly as the web stage pane does. +/// +/// A null [visitIndex] means the stage's most recent recorded visit; an +/// out-of-range index is clamped to the last visit (negative values to the +/// first). A stage with no recorded visits returns [StageVisitSelection.step] +/// null instead of a fabricated visit. +StageVisitSelection selectStageVisit( + List steps, + String stageKey, { + int? visitIndex, +}) { + final visits = visitsByStage(steps)[stageKey] ?? const []; + final wanted = visitIndex ?? (visits.isEmpty ? 0 : visits.length - 1); + return StageVisitSelection( + stageKey: stageKey, + visits: visits, + index: clampVisitIndex(wanted, visits.length), + ); +} diff --git a/app/lib/features/graph/layout/graph_node_layout.dart b/app/lib/features/graph/layout/graph_node_layout.dart new file mode 100644 index 00000000..767426ea --- /dev/null +++ b/app/lib/features/graph/layout/graph_node_layout.dart @@ -0,0 +1,142 @@ +import 'dart:math' as math; + +import '../domain/graph_definition.dart'; +import 'graph_ranks.dart'; +import 'layout_models.dart'; + +/// Places definition nodes in topological columns. +/// +/// Nodes keep definition order inside a rank, each column is as wide as its +/// widest measured node, and columns are top-aligned. A node is centred in its +/// column, so heterogeneous widths and text-expanded heights stay separated by +/// [GraphLayoutConfig.rowGap] inside a rank and [GraphLayoutConfig.columnGap] +/// between ranks. Nothing is clipped to a fixed box: the supplied measured +/// width and height are used verbatim and the returned bounds include them. +/// +/// [nodes] and [edges] normally come from `graphNodes`/`graphEdges`. Edges whose +/// source or target is not one of [nodes] are ignored, so an unknown target can +/// never invent a node. A measurement is required for every node; a missing one +/// is an error rather than a made-up size. Extra measurement entries are +/// ignored because they cannot become nodes. +GraphLayout layoutGraphNodes({ + required List nodes, + required List edges, + required Map extents, + required GraphLayoutConfig config, +}) { + _validateNodeKeys(nodes); + final ranks = assignGraphRanks(nodes, edges); + final measured = {}; + final missing = []; + for (final node in nodes) { + final extent = extents[node.key]; + if (extent == null) { + missing.add(node.key); + } else { + measured[node.key] = extent; + } + } + if (missing.isNotEmpty) { + throw ArgumentError.value( + missing, + 'extents', + 'missing measured extents for graph nodes', + ); + } + + final columns = List>.generate( + ranks.rankCount, + (_) => [], + ); + for (final node in nodes) { + columns[ranks.rankOf[node.key]!].add(node); + } + + final columnWidths = [ + for (final column in columns) + column.fold( + 0, + (width, node) => math.max(width, measured[node.key]!.width), + ), + ]; + final columnHeights = [ + for (final column in columns) + _columnHeight(column, measured, config.rowGap), + ]; + final columnX = []; + var nextX = config.padding; + for (var rank = 0; rank < columns.length; rank += 1) { + columnX.add(nextX); + nextX += columnWidths[rank]; + if (rank + 1 < columns.length) nextX += config.columnGap; + } + + final boxes = []; + for (var rank = 0; rank < columns.length; rank += 1) { + var nextY = config.padding; + for (final node in columns[rank]) { + final extent = measured[node.key]!; + boxes.add( + GraphNodeBox( + key: node.key, + terminal: node.terminal, + stageIndex: node.stageIndex, + rank: rank, + x: columnX[rank] + (columnWidths[rank] - extent.width) / 2, + y: nextY, + width: extent.width, + height: extent.height, + ), + ); + nextY += extent.height + config.rowGap; + } + } + + final width = + config.padding * 2 + + columnWidths.fold(0, (sum, column) => sum + column) + + config.columnGap * math.max(0, columns.length - 1); + final height = + config.padding * 2 + + columnHeights.fold( + 0, + (tallest, column) => math.max(tallest, column), + ); + + return GraphLayout( + nodes: boxes, + width: width, + height: height, + rankCount: ranks.rankCount, + ranks: ranks.rankOf, + ); +} + +void _validateNodeKeys(List nodes) { + final seen = {}; + for (final node in nodes) { + if (node.key.isEmpty) { + throw ArgumentError.value( + node.key, + 'nodes', + 'node key must not be empty', + ); + } + if (!seen.add(node.key)) { + throw ArgumentError.value(node.key, 'nodes', 'duplicate graph node key'); + } + } +} + +double _columnHeight( + List column, + Map measured, + double rowGap, +) { + if (column.isEmpty) return 0; + var height = 0.0; + for (final node in column) { + height += measured[node.key]!.height; + } + return height + rowGap * (column.length - 1); +} diff --git a/app/lib/features/graph/layout/graph_ranks.dart b/app/lib/features/graph/layout/graph_ranks.dart new file mode 100644 index 00000000..f7558db2 --- /dev/null +++ b/app/lib/features/graph/layout/graph_ranks.dart @@ -0,0 +1,191 @@ +import 'dart:collection'; +import 'dart:math' as math; + +import '../domain/graph_definition.dart'; + +/// Deterministic 0-based ranks for a graph definition's nodes. +/// +/// Ranks come from the condensation DAG: every strongly connected component +/// shares one rank, and a component sits one past its deepest predecessor +/// (longest path). Self loops and cycles therefore stay finite, a cycle's +/// members do not drift apart, and disconnected nodes stay at rank 0. Edges +/// whose endpoints are not definition nodes are ignored: an unknown target +/// never invents a node. +class GraphRanks { + GraphRanks({ + required Map rankOf, + required this.rankCount, + required List> components, + }) : rankOf = Map.unmodifiable(rankOf), + components = List.unmodifiable(>[ + for (final component in components) List.unmodifiable(component), + ]); + + /// Every definition key's rank, in definition order. + final Map rankOf; + + /// Number of distinct ranks, 0 for an empty node set. + final int rankCount; + + /// Strongly connected components as keys, each sorted by definition order and + /// the list sorted by its first member. + final List> components; +} + +/// One DFS frame for the iterative Tarjan walk. +class _Frame { + _Frame(this.node); + + final int node; + int nextChild = 0; +} + +/// Assigns ranks to exactly the supplied [nodes]. +/// +/// [edges] is read for ordering only; it never adds nodes. Duplicate edges are +/// harmless. The walk is iterative, so a deep chain cannot overflow the call +/// stack, and the work is linear in nodes plus edges. +GraphRanks assignGraphRanks(List nodes, List edges) { + final indexOf = {}; + for (var index = 0; index < nodes.length; index += 1) { + indexOf[nodes[index].key] = index; + } + + final adjacency = List>.generate(nodes.length, (_) => []); + final seenPairs = {}; + for (final edge in edges) { + final source = indexOf[edge.source]; + final target = indexOf[edge.target]; + if (source == null || target == null) continue; + if (!seenPairs.add(source * nodes.length + target)) continue; + adjacency[source].add(target); + } + + final components = _components(adjacency); + final componentOf = List.filled(nodes.length, -1); + for (var component = 0; component < components.length; component += 1) { + for (final node in components[component]) { + componentOf[node] = component; + } + } + + // Condensation edges and their indegrees. + final successors = List>.generate(components.length, (_) => {}); + final indegree = List.filled(components.length, 0); + for (var source = 0; source < adjacency.length; source += 1) { + final from = componentOf[source]; + for (final target in adjacency[source]) { + final to = componentOf[target]; + if (from == to) continue; + if (successors[from].add(to)) indegree[to] += 1; + } + } + + // Longest-path ranks over the condensation. Queue order only has to be a + // topological order; the resulting rank per component is unique. + final ranks = List.filled(components.length, 0); + final ready = ListQueue(); + for (var component = 0; component < components.length; component += 1) { + if (indegree[component] == 0) ready.add(component); + } + var settled = 0; + while (ready.isNotEmpty) { + final component = ready.removeFirst(); + settled += 1; + for (final next in successors[component]) { + ranks[next] = math.max(ranks[next], ranks[component] + 1); + indegree[next] -= 1; + if (indegree[next] == 0) ready.add(next); + } + } + if (settled != components.length) { + // The condensation cannot contain a cycle by construction; stop rather than + // return a silently truncated layout. + throw StateError('graph condensation was not acyclic'); + } + + final componentKeys = >[ + for (final component in components) + [for (final node in component) nodes[node].key], + ]; + final componentOrder = [ + for (var component = 0; component < components.length; component += 1) + component, + ]..sort((a, b) => components[a].first.compareTo(components[b].first)); + + final rankOf = {}; + var rankCount = 0; + for (var index = 0; index < nodes.length; index += 1) { + final rank = ranks[componentOf[index]]; + rankOf[nodes[index].key] = rank; + if (rank + 1 > rankCount) rankCount = rank + 1; + } + + return GraphRanks( + rankOf: rankOf, + rankCount: rankCount, + components: >[ + for (final component in componentOrder) componentKeys[component], + ], + ); +} + +/// Tarjan's strongly connected components, emitted sinks first. +/// +/// Iterative rather than recursive so a long chain cannot exhaust the stack. +/// Members are sorted by definition index, which keeps every output stable. +List> _components(List> adjacency) { + final discovery = List.filled(adjacency.length, -1); + final low = List.filled(adjacency.length, 0); + final onStack = List.filled(adjacency.length, false); + final stack = []; + final components = >[]; + var nextDiscovery = 0; + + for (var root = 0; root < adjacency.length; root += 1) { + if (discovery[root] != -1) continue; + discovery[root] = low[root] = nextDiscovery; + nextDiscovery += 1; + stack.add(root); + onStack[root] = true; + final callStack = <_Frame>[_Frame(root)]; + + while (callStack.isNotEmpty) { + final frame = callStack.last; + final node = frame.node; + if (frame.nextChild < adjacency[node].length) { + final child = adjacency[node][frame.nextChild]; + frame.nextChild += 1; + if (discovery[child] == -1) { + discovery[child] = low[child] = nextDiscovery; + nextDiscovery += 1; + stack.add(child); + onStack[child] = true; + callStack.add(_Frame(child)); + } else if (onStack[child]) { + low[node] = math.min(low[node], discovery[child]); + } + continue; + } + + callStack.removeLast(); + if (callStack.isNotEmpty) { + final parent = callStack.last.node; + low[parent] = math.min(low[parent], low[node]); + } + if (low[node] == discovery[node]) { + final component = []; + while (stack.isNotEmpty) { + final member = stack.removeLast(); + onStack[member] = false; + component.add(member); + if (member == node) break; + } + component.sort(); + components.add(component); + } + } + } + + return components; +} diff --git a/app/lib/features/graph/layout/layout_models.dart b/app/lib/features/graph/layout/layout_models.dart new file mode 100644 index 00000000..4a8dac4e --- /dev/null +++ b/app/lib/features/graph/layout/layout_models.dart @@ -0,0 +1,129 @@ +/// Pure geometry for a workflow graph's node layout. +/// +/// Every size and gap is supplied by the caller. The native renderer measures +/// each node after text layout (including the platform's text scaling), so this +/// library never assumes a node width, font, palette or device class. +/// +/// No Flutter imports: rectangles are plain numbers so the same result can be +/// built into widgets, a canvas or a test fixture. +library; + +void _requireFiniteNonNegative(String name, double value) { + if (!value.isFinite || value < 0) { + throw ArgumentError.value(value, name, 'must be finite and non-negative'); + } +} + +/// One caller-measured node extent, in logical pixels. +/// +/// A width or height may be zero for an empty label; the layout still keeps the +/// node separate from its neighbours through the configured gaps. +class NodeExtent { + NodeExtent({required this.width, required this.height}) { + _requireFiniteNonNegative('width', width); + _requireFiniteNonNegative('height', height); + } + + final double width; + final double height; +} + +/// The gaps a caller reserves around measured nodes. +/// +/// [columnGap] separates adjacent ranks, [rowGap] separates nodes sharing a +/// rank, and [padding] is the outer margin included in [GraphLayout] bounds. +class GraphLayoutConfig { + GraphLayoutConfig({ + required this.columnGap, + required this.rowGap, + this.padding = 0, + }) { + _requireFiniteNonNegative('columnGap', columnGap); + _requireFiniteNonNegative('rowGap', rowGap); + _requireFiniteNonNegative('padding', padding); + } + + final double columnGap; + final double rowGap; + final double padding; +} + +/// One placed node. +/// +/// [key], [terminal] and [stageIndex] are the definition node's own identity, +/// copied unchanged. [x]/[y] are the measured rectangle's top-left corner in +/// graph space and [rank] is its 0-based topological column. +class GraphNodeBox { + const GraphNodeBox({ + required this.key, + required this.terminal, + required this.stageIndex, + required this.rank, + required this.x, + required this.y, + required this.width, + required this.height, + }); + + final String key; + final bool terminal; + final int? stageIndex; + final int rank; + final double x; + final double y; + final double width; + final double height; + + double get right => x + width; + double get bottom => y + height; + + @override + bool operator ==(Object other) => + other is GraphNodeBox && + other.key == key && + other.terminal == terminal && + other.stageIndex == stageIndex && + other.rank == rank && + other.x == x && + other.y == y && + other.width == width && + other.height == height; + + @override + int get hashCode => + Object.hash(key, terminal, stageIndex, rank, x, y, width, height); +} + +/// An immutable node layout: every placed box plus the total graph bounds. +/// +/// [nodes] is ordered by rank first and definition order inside a rank; use +/// [ranks] or [nodeFor] for keyed lookup. [width] and [height] include the +/// caller's padding; every box's [right] and [bottom] stay inside them. +/// [ranks] exposes each definition key's 0-based rank; [rankCount] is the +/// number of columns (0 for an empty node set). +class GraphLayout { + GraphLayout({ + required List nodes, + required this.width, + required this.height, + required this.rankCount, + required Map ranks, + }) : nodes = List.unmodifiable(nodes), + ranks = Map.unmodifiable(ranks); + + final List nodes; + final Map ranks; + final double width; + final double height; + final int rankCount; + + bool get isEmpty => nodes.isEmpty; + + /// The placed box for [key], or null when the definition has no such node. + GraphNodeBox? nodeFor(String key) { + for (final node in nodes) { + if (node.key == key) return node; + } + return null; + } +} diff --git a/app/lib/features/graph/painting/graph_edge_layer.dart b/app/lib/features/graph/painting/graph_edge_layer.dart new file mode 100644 index 00000000..3ce7d053 --- /dev/null +++ b/app/lib/features/graph/painting/graph_edge_layer.dart @@ -0,0 +1,160 @@ +import 'package:flutter/foundation.dart' show listEquals; +import 'package:flutter/material.dart'; + +import '../routing/route_models.dart'; + +/// A passive canvas for already-routed graph edges. +/// +/// Paints exactly the supplied [routes] at their graph coordinates on a +/// [canvasSize] canvas. The caller owns every measurement: routes come from the +/// routing library, and [color] plus [strokeWidth] come from its native theme. +/// No node is invented or resized and no layout runs here. +/// +/// The layer is transparent to pointer input: it covers the canvas but never +/// takes a hit, so node buttons, labels and other siblings keep their own +/// gestures. Labels are composed separately as native widgets; this layer never +/// paints text and never handles pointer, focus or semantics input. +class GraphEdgeLayer extends StatelessWidget { + const GraphEdgeLayer({ + super.key, + required this.routes, + required this.canvasSize, + required this.color, + required this.strokeWidth, + }) : assert(strokeWidth > 0); + + /// Orthogonal routes in graph space, with each arrow entering its target port. + final List routes; + + /// The graph-space canvas the caller reserved for the drawing. + final Size canvasSize; + + /// The caller's native edge/label color. + final Color color; + + /// The caller's native stroke width; the arrow scales with it. + final double strokeWidth; + + @override + Widget build(BuildContext context) { + return CustomPaint( + size: canvasSize, + painter: GraphEdgePainter( + routes: routes, + color: color, + strokeWidth: strokeWidth, + ), + ); + } +} + +/// Paints [GraphEdgeLayer] routes as a polyline plus a filled direction arrow. +/// +/// The painter is public so a renderer and its tests share the exact path and +/// arrow geometry. It clips to the size `CustomPaint` supplies and reports every +/// point as a miss, matching the layer's passive contract. +class GraphEdgePainter extends CustomPainter { + GraphEdgePainter({ + required this.routes, + required this.color, + required this.strokeWidth, + }) : assert(strokeWidth > 0), + _line = Paint() + ..color = color + ..strokeWidth = strokeWidth + ..style = PaintingStyle.stroke + ..strokeJoin = StrokeJoin.round, + _arrow = Paint() + ..color = color + ..style = PaintingStyle.fill; + + final List routes; + final Color color; + final double strokeWidth; + final Paint _line; + final Paint _arrow; + + /// Arrow length and half base width, as multiples of the caller's stroke. + static const double _arrowLength = 6; + static const double _arrowHalfWidth = 2; + + @override + void paint(Canvas canvas, Size size) { + if (routes.isEmpty) return; + canvas.save(); + canvas.clipRect(Offset.zero & size); + for (final route in routes) { + if (route.points.length < 2) continue; + assert( + route.points.last == route.targetPort.point, + 'EdgeRoute ${route.id} must end at its target port; the router ' + 'guarantees points.last == targetPort.point.', + ); + canvas.drawPath(linePath(route), _line); + } + for (final route in routes) { + if (route.points.length < 2) continue; + canvas.drawPath(arrowPath(route), _arrow); + } + canvas.restore(); + } + + /// The orthogonally joined polyline for [route], in painter coordinates. + Path linePath(EdgeRoute route) { + final path = Path(); + final points = route.points; + if (points.isEmpty) return path; + path.moveTo(points.first.x, points.first.y); + for (var index = 1; index < points.length; index += 1) { + path.lineTo(points[index].x, points[index].y); + } + return path; + } + + /// A filled triangle whose tip is exactly [EdgeRoute.targetPort]. The + /// direction follows the route's last segment, so forward, backward, + /// same-rank and self-loop edges keep their honest arrival direction. A + /// degenerate tail falls back to the target port's inward normal. + Path arrowPath(EdgeRoute route) { + final points = route.points; + if (points.length < 2) return Path(); + final tip = Offset(route.targetPort.point.x, route.targetPort.point.y); + final direction = _arrivalDirection(route); + final length = strokeWidth * _arrowLength; + final halfWidth = strokeWidth * _arrowHalfWidth; + final baseX = tip.dx - direction.dx * length; + final baseY = tip.dy - direction.dy * length; + final normalX = -direction.dy * halfWidth; + final normalY = direction.dx * halfWidth; + return Path() + ..moveTo(tip.dx, tip.dy) + ..lineTo(baseX + normalX, baseY + normalY) + ..lineTo(baseX - normalX, baseY - normalY) + ..close(); + } + + Offset _arrivalDirection(EdgeRoute route) { + final tip = route.targetPort.point; + for (var index = route.points.length - 1; index >= 0; index -= 1) { + final point = route.points[index]; + final delta = Offset(tip.x - point.x, tip.y - point.y); + if (delta != Offset.zero) return delta / delta.distance; + } + return switch (route.targetPort.side) { + RoutePortSide.top => const Offset(0, 1), + RoutePortSide.right => const Offset(-1, 0), + RoutePortSide.bottom => const Offset(0, -1), + RoutePortSide.left => const Offset(1, 0), + }; + } + + /// The layer is passive: every point misses so siblings keep their gestures. + @override + bool hitTest(Offset position) => false; + + @override + bool shouldRepaint(GraphEdgePainter oldDelegate) => + oldDelegate.color != color || + oldDelegate.strokeWidth != strokeWidth || + !listEquals(oldDelegate.routes, routes); +} diff --git a/app/lib/features/graph/routing/corridor_plan.dart b/app/lib/features/graph/routing/corridor_plan.dart new file mode 100644 index 00000000..33909013 --- /dev/null +++ b/app/lib/features/graph/routing/corridor_plan.dart @@ -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 sourceX, + required Map targetX, + }) : sourceX = Map.unmodifiable(sourceX), + targetX = Map.unmodifiable(targetX); + + final Map sourceX; + final Map 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 requests, + required RoutingConfig config, +}) { + final ordered = [...requests] + ..sort((a, b) => a.edgeId.compareTo(b.edgeId)); + final slots = >{}; + 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 = {}; + final targetX = {}; + 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 _trackPositions(GapBand band, int count, double spacing) { + if (count == 0) return const []; + if (band.open) { + return [ + for (var index = 0; index < count; index += 1) band.lo + spacing * index, + ]; + } + final width = band.hi - band.lo; + if (count == 1) return [(band.lo + band.hi) / 2]; + if (width <= 0) return List.filled(count, band.lo); + final step = math.min(spacing, width / (count - 1)); + return [ + 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; +} diff --git a/app/lib/features/graph/routing/edge_label_placement.dart b/app/lib/features/graph/routing/edge_label_placement.dart new file mode 100644 index 00000000..75264135 --- /dev/null +++ b/app/lib/features/graph/routing/edge_label_placement.dart @@ -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 nodes, + required List 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(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 nodes, + List 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 = [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; +} diff --git a/app/lib/features/graph/routing/edge_route_planner.dart b/app/lib/features/graph/routing/edge_route_planner.dart new file mode 100644 index 00000000..8b3d6ff4 --- /dev/null +++ b/app/lib/features/graph/routing/edge_route_planner.dart @@ -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 points, + }) : points = List.unmodifiable(points); + + final GraphEdge edge; + final RouteKind kind; + final bool straight; + final RoutePort sourcePort; + final RoutePort targetPort; + final List 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 planEdgeRoutes({ + required GraphLayout layout, + required List edges, + required double maxLabelHeight, + required RoutingConfig config, +}) { + if (edges.isEmpty) return const []; + final nodes = { + for (final node in layout.nodes) node.key: node, + }; + final kinds = {}; + 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 = {}; + 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( + 0, + (bottom, node) => math.max(bottom, node.bottom), + ); + final wrapPlans = <_WrapPlan>[]; + final corridorRequests = []; + 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 = {}; + final targetPorts = {}; + 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 = {}; + 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([ + 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([ + 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 [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 _collapse(List points) { + final result = []; + 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; +} diff --git a/app/lib/features/graph/routing/graph_edge_routing.dart b/app/lib/features/graph/routing/graph_edge_routing.dart new file mode 100644 index 00000000..33ad9a9a --- /dev/null +++ b/app/lib/features/graph/routing/graph_edge_routing.dart @@ -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 edges, + required Map labelExtents, + required RoutingConfig config, +}) { + final ordered = [...edges]..sort((a, b) => a.id.compareTo(b.id)); + final seenIds = {}; + for (final edge in ordered) { + if (!seenIds.add(edge.id)) { + throw ArgumentError.value(edge.id, 'edges', 'duplicate edge id'); + } + } + + final nodes = { + for (final node in layout.nodes) node.key: node, + }; + final routed = []; + final skipped = []; + 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 = [ + 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 = [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 = []; + 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, + ); +} diff --git a/app/lib/features/graph/routing/route_geometry.dart b/app/lib/features/graph/routing/route_geometry.dart new file mode 100644 index 00000000..aa89c4df --- /dev/null +++ b/app/lib/features/graph/routing/route_geometry.dart @@ -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 + ? [start] + : [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 nodes, + required this.rankCount, + required this.layoutWidth, + }) : _left = List.filled(rankCount + 1, 0), + _right = List.filled(rankCount + 1, layoutWidth) { + final rankRight = List.filled(rankCount, 0); + final rankLeft = List.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 _left; + final List _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; +} diff --git a/app/lib/features/graph/routing/route_models.dart b/app/lib/features/graph/routing/route_models.dart new file mode 100644 index 00000000..7ce2dc24 --- /dev/null +++ b/app/lib/features/graph/routing/route_models.dart @@ -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 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 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 routes, + required List labels, + required List skipped, + required this.width, + required this.height, + }) : routes = List.unmodifiable(routes), + labels = List.unmodifiable(labels), + skipped = List.unmodifiable(skipped); + + final List routes; + final List labels; + final List 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 a, List 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; +} diff --git a/app/lib/features/graph/routing/routing_inputs.dart b/app/lib/features/graph/routing/routing_inputs.dart new file mode 100644 index 00000000..4fafe115 --- /dev/null +++ b/app/lib/features/graph/routing/routing_inputs.dart @@ -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; +} diff --git a/app/lib/features/graph/widgets/graph_stage_node.dart b/app/lib/features/graph/widgets/graph_stage_node.dart new file mode 100644 index 00000000..d28d4a26 --- /dev/null +++ b/app/lib/features/graph/widgets/graph_stage_node.dart @@ -0,0 +1,126 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; +import '../domain/graph_definition.dart'; + +/// One content-sized stage node as an ordinary native control. +/// +/// [node] is the definition identity. [recordedStatus] is executed evidence the +/// caller read from the run; it is shown verbatim and never derived here, so an +/// unvisited or terminal definition node cannot be presented as executed. +class GraphStageNode extends StatelessWidget { + const GraphStageNode({ + super.key, + required this.node, + this.recordedStatus, + this.selected = false, + required this.onSelected, + }); + + final GraphNode node; + + /// The run's recorded status word for this node, or null when none exists. + final String? recordedStatus; + + /// Whether this definition node is the current graph selection. + final bool selected; + + /// Reports [node.key] exactly as the definition recorded it. + final ValueChanged onSelected; + + /// Content inset shared by both hosts. It is spacing, not a size: the control + /// still takes its size from its label, and the inset keeps wrapped glyphs + /// clear of a rounded surface's corners. + static const EdgeInsets _contentPadding = EdgeInsets.all(16); + + String? get _status { + final status = recordedStatus; + return status != null && status.trim().isNotEmpty ? status : null; + } + + String get _label { + final status = _status; + return status == null ? node.label : '${node.label}\n$status'; + } + + @override + Widget build(BuildContext context) { + final content = ExcludeSemantics(child: _content()); + void onPressed() => onSelected(node.key); + return MergeSemantics( + child: Semantics( + button: true, + selected: selected, + label: _label, + child: usesCupertinoHost(context) + ? _cupertinoButton(onPressed, content) + : _materialCard(onPressed, content), + ), + ); + } + + /// A stock card, not a stock button: Material's button shape is a stadium, + /// which assumes one line and cuts into a wrapped label's first and last + /// line. A card keeps the rounded-rectangle surface the web node uses, and + /// [selected] only chooses between two stock emphasis levels. + Widget _materialCard(VoidCallback onPressed, Widget content) { + final body = InkWell( + onTap: onPressed, + child: ConstrainedBox( + constraints: const BoxConstraints(minHeight: kMinInteractiveDimension), + child: Padding( + padding: _contentPadding, + child: Align( + alignment: AlignmentDirectional.centerStart, + widthFactor: 1, + heightFactor: 1, + child: content, + ), + ), + ), + ); + return selected + ? Card.filled( + margin: EdgeInsets.zero, + clipBehavior: Clip.antiAlias, + child: body, + ) + : Card.outlined( + margin: EdgeInsets.zero, + clipBehavior: Clip.antiAlias, + child: body, + ); + } + + /// Tinted is Cupertino's stock low-emphasis surface, so an unselected node is + /// still a visible node body; filled raises the selected one. + Widget _cupertinoButton(VoidCallback onPressed, Widget content) => selected + ? CupertinoButton.filled(onPressed: onPressed, child: content) + : CupertinoButton.tinted(onPressed: onPressed, child: content); + + Widget _content() { + final status = _status; + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(_breakable(node.label), softWrap: true), + if (status != null) Text(_breakable(status), softWrap: true), + ], + ); + } + + /// The web node uses `overflow-wrap: anywhere`; Flutter text does not break a + /// long unbroken key, so the same invisible break opportunities are added. + /// The visible text and the semantics label stay unchanged. + String _breakable(String value) { + final buffer = StringBuffer(); + for (final rune in value.runes) { + buffer + ..writeCharCode(rune) + ..write('\u200B'); + } + return buffer.toString(); + } +} diff --git a/app/lib/features/runs/actions/action_refusal.dart b/app/lib/features/runs/actions/action_refusal.dart new file mode 100644 index 00000000..87e03995 --- /dev/null +++ b/app/lib/features/runs/actions/action_refusal.dart @@ -0,0 +1,18 @@ +/// A refused operator action and, when one was started, the bounded re-read of +/// server truth that follows it. +/// +/// The prompt shows [message] and allows dismissal immediately; it must never +/// wait for [stillPossible]. That future is only observed so a retry can be +/// ruled out once server truth arrives: `true` means the re-read found the run +/// still allows the action, `false` means it plainly does not, and `null` means +/// the re-read failed or was overtaken, leaving a deliberate retry possible. +class ActionRefusal { + const ActionRefusal(this.message, {this.stillPossible}); + + final String message; + final Future? stillPossible; +} + +/// Local guards, distinct from a server refusal; they never claim success. +const actionOptionRequired = 'Choose an option before continuing.'; +const actionAlreadySending = 'That action is still being sent.'; diff --git a/app/lib/features/runs/actions/cancel_dialog.dart b/app/lib/features/runs/actions/cancel_dialog.dart new file mode 100644 index 00000000..1654f442 --- /dev/null +++ b/app/lib/features/runs/actions/cancel_dialog.dart @@ -0,0 +1,165 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'action_refusal.dart'; +import 'cancel_wording.dart'; + +/// Sends the confirmed cancellation. Returns null once the server has accepted +/// it, or an [ActionRefusal] carrying the server's words verbatim; the prompt +/// then stays open with dismissal available immediately. +typedef CancelSubmit = Future Function(); + +/// Opens the native cancel confirmation for [runId]. +/// +/// Nothing is sent until the operator presses the confirm action, and the +/// dismiss action (`Keep`) only closes the prompt. +Future showCancelRunPrompt({ + required BuildContext context, + required num runId, + required bool cupertino, + required CancelSubmit onSubmit, +}) { + final prompt = _CancelPrompt( + runId: runId, + cupertino: cupertino, + onSubmit: onSubmit, + ); + if (cupertino) { + return showCupertinoDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); + } + return showDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); +} + +class _CancelPrompt extends StatefulWidget { + const _CancelPrompt({ + required this.runId, + required this.cupertino, + required this.onSubmit, + }); + + final num runId; + final bool cupertino; + final CancelSubmit onSubmit; + + @override + State<_CancelPrompt> createState() => _CancelPromptState(); +} + +class _CancelPromptState extends State<_CancelPrompt> { + bool _sending = false; + bool _checking = false; + bool _blocked = false; + String? _error; + + void _keep() { + if (!_sending) Navigator.of(context).pop(); + } + + Future _confirm() async { + if (_sending || _checking || _blocked) return; + setState(() { + _sending = true; + _error = null; + }); + final refusal = await widget.onSubmit(); + if (!mounted) return; + if (refusal == null) { + Navigator.of(context).pop(); + return; + } + final check = refusal.stillPossible; + setState(() { + _sending = false; + _error = refusal.message; + _checking = check != null; + }); + if (check == null) return; + bool? stillPossible; + try { + stillPossible = await check; + } catch (_) { + // The action reports re-read failures as null; never fabricate one here. + } + if (!mounted) return; + setState(() { + _checking = false; + _blocked = stillPossible == false; + }); + } + + @override + Widget build(BuildContext context) { + final dialog = widget.cupertino ? _cupertino(context) : _material(context); + return PopScope(canPop: !_sending, child: dialog); + } + + bool get _confirmDisabled => _sending || _checking || _blocked; + + Widget _material(BuildContext context) { + final theme = Theme.of(context); + return AlertDialog( + scrollable: true, + title: Text(cancelDialogTitle(widget.runId)), + content: _body(errorStyle: TextStyle(color: theme.colorScheme.error)), + actions: [ + TextButton( + key: cancelKeepKey, + onPressed: _sending ? null : _keep, + child: const Text(cancelKeepLabel), + ), + FilledButton( + key: cancelConfirmKey, + onPressed: _confirmDisabled ? null : _confirm, + child: const Text(cancelConfirmLabel), + ), + ], + ); + } + + Widget _cupertino(BuildContext context) { + return CupertinoAlertDialog( + title: Text(cancelDialogTitle(widget.runId)), + content: _body( + errorStyle: TextStyle( + color: CupertinoColors.systemRed.resolveFrom(context), + ), + ), + actions: [ + CupertinoDialogAction( + key: cancelKeepKey, + onPressed: _sending ? null : _keep, + child: const Text(cancelKeepLabel), + ), + CupertinoDialogAction( + key: cancelConfirmKey, + isDestructiveAction: true, + onPressed: _confirmDisabled ? null : _confirm, + child: const Text(cancelConfirmLabel), + ), + ], + ); + } + + Widget _body({required TextStyle errorStyle}) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text(cancelDialogMessage), + if (_error case final error?) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(error, key: cancelErrorKey, style: errorStyle), + ), + ], + ); + } +} diff --git a/app/lib/features/runs/actions/cancel_eligibility.dart b/app/lib/features/runs/actions/cancel_eligibility.dart new file mode 100644 index 00000000..a8cbb620 --- /dev/null +++ b/app/lib/features/runs/actions/cancel_eligibility.dart @@ -0,0 +1,31 @@ +import '../../../core/api_gateway.dart'; + +/// Whether the operator may cancel [run], matching `canCancel` in +/// `web/src/actions.js` exactly: +/// +/// `(executing || (status == "waiting" && export_pending_sequence > 0)) && +/// !cancel_requested && !cleanup_unconfirmed` +/// +/// The status word alone is not enough: a stale `running` status without +/// `executing` is not cancellable, while a run waiting on a pending session +/// export is. +bool canCancelRun(JsonMap? run) { + if (run == null) return false; + final exportPending = _number(run['export_pending_sequence']); + return (run['executing'] == true || + (run['status'] == 'waiting' && exportPending > 0)) && + run['cancel_requested'] != true && + run['cleanup_unconfirmed'] != true; +} + +/// The run id used by the cancel request, or null for a malformed run. +num? cancelRunId(JsonMap run) { + final id = run['id']; + return id is num ? id : null; +} + +/// `Number(value) > 0`, tolerating numeric strings as the browser does. +double _number(dynamic value) { + if (value is num) return value.toDouble(); + return double.tryParse('${value ?? ''}'.trim()) ?? 0; +} diff --git a/app/lib/features/runs/actions/cancel_run_action.dart b/app/lib/features/runs/actions/cancel_run_action.dart new file mode 100644 index 00000000..19bdf181 --- /dev/null +++ b/app/lib/features/runs/actions/cancel_run_action.dart @@ -0,0 +1,119 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../data/runs_repository.dart'; +import 'action_refusal.dart'; +import 'cancel_dialog.dart'; +import 'cancel_eligibility.dart'; +import 'cancel_wording.dart'; + +/// The run detail's deliberate cancel entry point. +/// +/// Renders one native button only while [run] is cancellable under the browser +/// client's rule. Opening the prompt or choosing [cancelKeepLabel] sends +/// nothing; only the confirm action asks the server to stop the run. A refusal +/// is returned to the kept-open prompt immediately and the run is re-read +/// separately, so [onRunChanged] still receives server truth without locking +/// the prompt while that read is pending. +class CancelRunAction extends StatefulWidget { + const CancelRunAction({ + super.key, + required this.run, + required this.gateway, + required this.onRunChanged, + }); + + final JsonMap run; + final ApiGateway gateway; + final ValueChanged onRunChanged; + + @override + State createState() => _CancelRunActionState(); +} + +class _CancelRunActionState extends State { + bool _dialogOpen = false; + Future? _resync; + + bool _usesCupertino(BuildContext context) { + final material = Localizations.of( + context, + MaterialLocalizations, + ); + return material == null; + } + + Future _open() async { + final id = cancelRunId(widget.run); + if (id == null || !canCancelRun(widget.run) || _dialogOpen) return; + _dialogOpen = true; + try { + await showCancelRunPrompt( + context: context, + runId: id, + cupertino: _usesCupertino(context), + onSubmit: () => _submit(id), + ); + } finally { + _dialogOpen = false; + if (mounted) setState(() {}); + } + } + + Future _submit(num id) async { + final repository = RunsRepository(widget.gateway); + try { + final run = await repository.cancelRun(id); + if (!mounted) return null; + if (_owns(id)) widget.onRunChanged(run); + return null; + } catch (error) { + return ActionRefusal( + describeCancelError(error), + stillPossible: _resyncRun(id), + ); + } + } + + bool _owns(num id) => mounted && cancelRunId(widget.run) == id; + + /// One bounded re-read per refusal. A refusal that arrives while a read is + /// already in flight observes that same read instead of starting another. + Future _resyncRun(num id) { + return _resync ??= _readRun(id); + } + + Future _readRun(num id) async { + try { + final run = await RunsRepository(widget.gateway).getRun(id); + if (!_owns(id)) return null; + widget.onRunChanged(run); + return canCancelRun(run); + } catch (_) { + // Unknown server truth: keep the refusal and leave a deliberate retry. + return null; + } finally { + _resync = null; + } + } + + @override + Widget build(BuildContext context) { + if (cancelRunId(widget.run) == null || !canCancelRun(widget.run)) { + return const SizedBox.shrink(); + } + if (_usesCupertino(context)) { + return CupertinoButton.filled( + key: cancelActionKey, + onPressed: _open, + child: const Text(cancelActionLabel), + ); + } + return FilledButton( + key: cancelActionKey, + onPressed: _open, + child: const Text(cancelActionLabel), + ); + } +} diff --git a/app/lib/features/runs/actions/cancel_wording.dart b/app/lib/features/runs/actions/cancel_wording.dart new file mode 100644 index 00000000..b4812921 --- /dev/null +++ b/app/lib/features/runs/actions/cancel_wording.dart @@ -0,0 +1,23 @@ +import 'package:flutter/widgets.dart'; + +/// The browser client's cancel wording, kept verbatim. +const cancelActionLabel = 'Cancel run'; +const cancelDialogMessage = 'This asks the server to stop the active run.'; +const cancelConfirmLabel = 'Cancel run'; +const cancelKeepLabel = 'Keep'; + +/// Stable test/semantics keys shared by the action and its prompt. +const cancelActionKey = ValueKey('cancel-run-action'); +const cancelKeepKey = ValueKey('cancel-run-keep'); +const cancelConfirmKey = ValueKey('cancel-run-confirm'); +const cancelErrorKey = ValueKey('cancel-run-error'); + +/// The cancel dialog's title: `Cancel run {id}?`. +String cancelDialogTitle(num runId) => 'Cancel run $runId?'; + +/// The server's refusal, verbatim. Only a blank error gets a generic sentence +/// so the prompt never claims a cancellation that did not happen. +String describeCancelError(Object error) { + final message = '$error'.trim(); + return message.isEmpty ? 'The server did not cancel the run.' : message; +} diff --git a/app/lib/features/runs/actions/decision_action.dart b/app/lib/features/runs/actions/decision_action.dart new file mode 100644 index 00000000..246c66fb --- /dev/null +++ b/app/lib/features/runs/actions/decision_action.dart @@ -0,0 +1,176 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../data/runs_repository.dart'; +import '../domain/run_decisions.dart'; +import '../domain/run_models.dart'; +import 'action_refusal.dart'; +import 'decision_dialog.dart'; +import 'decision_wording.dart'; + +/// The run detail's deliberate human-decision entry point. +/// +/// Renders one native button only while [run] is genuinely waiting on a person. +/// Nothing is sent until the operator opens the prompt, chooses an option and +/// presses Confirm; cancel, selection and optional feedback stay local. A +/// server refusal is shown verbatim in the prompt immediately, the draft is +/// preserved and the run is re-read separately so [onRunChanged] still receives +/// server truth without locking the prompt while that read is pending. +class HumanDecisionAction extends StatefulWidget { + const HumanDecisionAction({ + super.key, + required this.run, + required this.gateway, + required this.onRunChanged, + this.cupertino, + }); + + final JsonMap run; + final ApiGateway gateway; + final ValueChanged onRunChanged; + + /// Overrides the platform style; by default it follows the enclosing app. + final bool? cupertino; + + @override + State createState() => _HumanDecisionActionState(); +} + +class _HumanDecisionActionState extends State { + PendingDecision? _pending; + bool _dialogOpen = false; + bool _sending = false; + Future? _resync; + + @override + void initState() { + super.initState(); + _pending = pendingDecision(widget.run); + } + + @override + void didUpdateWidget(covariant HumanDecisionAction oldWidget) { + super.didUpdateWidget(oldWidget); + _pending = pendingDecision(widget.run); + } + + bool _usesCupertino(BuildContext context) { + if (widget.cupertino != null) return widget.cupertino!; + final material = Localizations.of( + context, + MaterialLocalizations, + ); + return material == null; + } + + Future _open() async { + final decision = _pending; + if (decision == null || _dialogOpen) return; + _dialogOpen = true; + try { + await showHumanDecisionPrompt( + context: context, + decision: decision, + cupertino: _usesCupertino(context), + onSubmit: (draft) => _submit(decision, draft), + ); + } finally { + _dialogOpen = false; + if (mounted) setState(() {}); + } + } + + Future _submit( + PendingDecision decision, + DecisionDraft draft, + ) async { + final option = draft.selected?.trim() ?? ''; + if (option.isEmpty) return const ActionRefusal(actionOptionRequired); + if (_sending) return const ActionRefusal(actionAlreadySending); + _sending = true; + final repository = RunsRepository(widget.gateway); + try { + final JsonMap run; + try { + run = await repository.decideRun( + decision.runId, + stage: decision.stageKey, + option: option, + feedback: draft.feedback, + ); + } catch (error) { + return ActionRefusal( + _describe(error), + stillPossible: _resyncRun(decision), + ); + } + if (!mounted) return null; + if (_owns(decision.runId)) { + setState(() => _pending = pendingDecision(run)); + widget.onRunChanged(run); + } + return null; + } finally { + _sending = false; + } + } + + bool _owns(num id) => mounted && widget.run['id'] == id; + + /// One bounded re-read per refusal. A refusal that arrives while a read is + /// already in flight observes that same read instead of starting another. + Future _resyncRun(PendingDecision decision) { + return _resync ??= _readRun(decision); + } + + Future _readRun(PendingDecision expected) async { + try { + final run = await RunsRepository(widget.gateway).getRun(expected.runId); + if (!_owns(expected.runId)) return null; + final next = pendingDecision(run); + setState(() => _pending = next); + widget.onRunChanged(run); + return _stillDecidable(next, expected); + } catch (_) { + // Unknown server truth: keep the refusal and leave a deliberate retry. + return null; + } finally { + _resync = null; + } + } + + /// Whether the refreshed run offers the same decision the prompt is showing. + bool _stillDecidable(PendingDecision? next, PendingDecision expected) { + if (next == null || + next.runId != expected.runId || + next.stageKey != expected.stageKey) { + return false; + } + final keys = next.options.map((option) => option.key).toSet(); + return expected.options.every((option) => keys.contains(option.key)); + } + + @override + Widget build(BuildContext context) { + final decision = _pending; + if (decision == null) return const SizedBox.shrink(); + if (_usesCupertino(context)) { + return CupertinoButton.filled( + key: decisionActionKey, + onPressed: _open, + child: const Text(decisionActionLabel), + ); + } + return FilledButton( + key: decisionActionKey, + onPressed: _open, + child: const Text(decisionActionLabel), + ); + } +} + +String _describe(Object error) { + final message = '$error'; + return message.trim().isEmpty ? 'The server refused the decision.' : message; +} diff --git a/app/lib/features/runs/actions/decision_dialog.dart b/app/lib/features/runs/actions/decision_dialog.dart new file mode 100644 index 00000000..81aa717c --- /dev/null +++ b/app/lib/features/runs/actions/decision_dialog.dart @@ -0,0 +1,268 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../domain/run_decisions.dart'; +import '../domain/run_models.dart'; +import 'action_refusal.dart'; +import 'decision_wording.dart'; + +/// Sends the draft to the server. Returns null on success, or an +/// [ActionRefusal] with the server's words verbatim; the prompt stays open +/// with the draft intact and dismissal available immediately. +typedef DecisionSubmit = Future Function(DecisionDraft draft); + +/// Opens the native decision prompt for [decision]. +Future showHumanDecisionPrompt({ + required BuildContext context, + required PendingDecision decision, + required bool cupertino, + required DecisionSubmit onSubmit, +}) { + final prompt = _DecisionPrompt( + decision: decision, + cupertino: cupertino, + onSubmit: onSubmit, + ); + if (cupertino) { + return showCupertinoDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); + } + return showDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); +} + +class _DecisionPrompt extends StatefulWidget { + const _DecisionPrompt({ + required this.decision, + required this.cupertino, + required this.onSubmit, + }); + + final PendingDecision decision; + final bool cupertino; + final DecisionSubmit onSubmit; + + @override + State<_DecisionPrompt> createState() => _DecisionPromptState(); +} + +class _DecisionPromptState extends State<_DecisionPrompt> { + DecisionDraft _draft = const DecisionDraft(); + late final TextEditingController _feedback = TextEditingController(); + bool _sending = false; + bool _checking = false; + bool _blocked = false; + String? _error; + + @override + void dispose() { + _feedback.dispose(); + super.dispose(); + } + + void _select(String option) { + if (_sending) return; + setState(() => _draft = _draft.select(option)); + } + + void _feedbackChanged(String value) => _draft = _draft.withFeedback(value); + + void _cancel() { + if (!_sending) Navigator.of(context).pop(); + } + + Future _confirm() async { + if (_sending || _checking || _blocked || !_draft.canSubmit) return; + setState(() { + _sending = true; + _error = null; + }); + final refusal = await widget.onSubmit(_draft); + if (!mounted) return; + if (refusal == null) { + Navigator.of(context).pop(); + return; + } + final check = refusal.stillPossible; + setState(() { + _sending = false; + _error = refusal.message; + _checking = check != null; + }); + if (check == null) return; + bool? stillPossible; + try { + stillPossible = await check; + } catch (_) { + // The action reports re-read failures as null; never fabricate one here. + } + if (!mounted) return; + setState(() { + _checking = false; + _blocked = stillPossible == false; + }); + } + + @override + Widget build(BuildContext context) { + final dialog = widget.cupertino ? _cupertino(context) : _material(context); + return PopScope(canPop: !_sending, child: dialog); + } + + bool get _confirmDisabled => _sending || _checking || _blocked; + + Widget _material(BuildContext context) { + final theme = Theme.of(context); + return AlertDialog( + scrollable: true, + title: const Text(decisionWaitingTitle), + content: _body( + errorStyle: TextStyle(color: theme.colorScheme.error), + options: RadioGroup( + groupValue: _draft.selected, + onChanged: (value) { + if (value != null) _select(value); + }, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final option in widget.decision.options) + RadioListTile( + value: option.key, + enabled: !_sending, + title: Text(option.key), + subtitle: _target(option), + ), + ], + ), + ), + feedback: TextField( + key: decisionFeedbackKey, + controller: _feedback, + enabled: !_sending, + decoration: const InputDecoration(labelText: decisionFeedbackLabel), + textInputAction: TextInputAction.done, + onChanged: _feedbackChanged, + onSubmitted: (_) => _confirm(), + ), + ), + actions: [ + TextButton( + onPressed: _sending ? null : _cancel, + child: const Text(decisionCancelLabel), + ), + FilledButton( + onPressed: _confirmDisabled || !_draft.canSubmit ? null : _confirm, + child: Text(_sending ? decisionSendingLabel : decisionConfirmLabel), + ), + ], + ); + } + + Widget _cupertino(BuildContext context) { + return CupertinoAlertDialog( + title: const Text(decisionWaitingTitle), + content: _body( + errorStyle: TextStyle( + color: CupertinoColors.systemRed.resolveFrom(context), + ), + options: RadioGroup( + groupValue: _draft.selected, + onChanged: (value) { + if (value != null) _select(value); + }, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final option in widget.decision.options) + CupertinoButton( + onPressed: _sending ? null : () => _select(option.key), + child: Row( + children: [ + CupertinoRadio( + value: option.key, + useCheckmarkStyle: true, + enabled: !_sending, + ), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(option.key), + if (_targetText(option) case final target?) + Text(target), + ], + ), + ), + ], + ), + ), + ], + ), + ), + feedback: CupertinoTextField( + key: decisionFeedbackKey, + controller: _feedback, + enabled: !_sending, + placeholder: decisionFeedbackLabel, + textInputAction: TextInputAction.done, + onChanged: _feedbackChanged, + onSubmitted: (_) => _confirm(), + ), + ), + actions: [ + CupertinoDialogAction( + onPressed: _sending ? null : _cancel, + child: const Text(decisionCancelLabel), + ), + CupertinoDialogAction( + isDefaultAction: true, + onPressed: _confirmDisabled || !_draft.canSubmit ? null : _confirm, + child: Text(_sending ? decisionSendingLabel : decisionConfirmLabel), + ), + ], + ); + } + + Widget _body({ + required TextStyle errorStyle, + required Widget options, + required Widget feedback, + }) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(decisionMeta(widget.decision)), + if (widget.decision.instructions.trim().isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(widget.decision.instructions), + ), + Padding(padding: const EdgeInsets.only(top: 8), child: options), + Padding(padding: const EdgeInsets.only(top: 8), child: feedback), + if (_error case final error?) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(error, key: decisionErrorKey, style: errorStyle), + ), + ], + ); + } + + Widget? _target(DecisionOption option) { + final text = _targetText(option); + return text == null ? null : Text(text); + } + + String? _targetText(DecisionOption option) { + final text = decisionTargetText(option.target); + return text.isEmpty ? null : text; + } +} diff --git a/app/lib/features/runs/actions/decision_wording.dart b/app/lib/features/runs/actions/decision_wording.dart new file mode 100644 index 00000000..a9904946 --- /dev/null +++ b/app/lib/features/runs/actions/decision_wording.dart @@ -0,0 +1,24 @@ +import 'package:flutter/widgets.dart'; + +import '../domain/run_decisions.dart'; + +/// The browser client's decision wording, kept verbatim. +const decisionWaitingTitle = 'Waiting for your decision'; +const decisionActionLabel = 'Decide'; +const decisionFeedbackLabel = 'Feedback (optional)'; +const decisionCancelLabel = 'Cancel'; +const decisionConfirmLabel = 'Confirm decision'; +const decisionSendingLabel = 'Sending…'; + +/// Stable test/semantics keys shared by the action and its prompt. +const decisionActionKey = ValueKey('human-decision-action'); +const decisionFeedbackKey = ValueKey('human-decision-feedback'); +const decisionErrorKey = ValueKey('human-decision-error'); + +/// `{stage} · run {id} · {label}`, as the web decision card shows it. +String decisionMeta(PendingDecision decision) => + '${decision.stageKey} · run ${decision.runId} · ${decision.runLabel}'; + +/// The option's target line, `→ {target}`, or "" when no target was declared. +String decisionTargetText(String target) => + target.trim().isEmpty ? '' : '→ $target'; diff --git a/app/lib/features/runs/actions/retry_action.dart b/app/lib/features/runs/actions/retry_action.dart new file mode 100644 index 00000000..28cda388 --- /dev/null +++ b/app/lib/features/runs/actions/retry_action.dart @@ -0,0 +1,123 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../data/runs_repository.dart'; +import 'action_refusal.dart'; +import 'retry_dialog.dart'; +import 'retry_eligibility.dart'; +import 'retry_intent.dart'; +import 'retry_wording.dart'; + +/// The run detail's deliberate retry entry point. +/// +/// Renders one native button only while [run] is a stopped `failed` run. Opening +/// the resume or restart confirmation sends nothing; only the confirm action +/// asks the server to retry. A refusal is returned to the kept-open prompt +/// immediately and the run is re-read separately, so [onRunChanged] still +/// receives server truth without locking the prompt while that read is pending. +class RetryRunAction extends StatefulWidget { + const RetryRunAction({ + super.key, + required this.run, + required this.gateway, + required this.onRunChanged, + }); + + final JsonMap run; + final ApiGateway gateway; + final ValueChanged onRunChanged; + + @override + State createState() => _RetryRunActionState(); +} + +class _RetryRunActionState extends State { + bool _dialogOpen = false; + Future? _resync; + + bool _usesCupertino(BuildContext context) { + final material = Localizations.of( + context, + MaterialLocalizations, + ); + return material == null; + } + + Future _open() async { + final id = retryRunId(widget.run); + if (id == null || !canRetryRun(widget.run) || _dialogOpen) return; + _dialogOpen = true; + try { + await showRetryRunPrompt( + context: context, + runId: id, + cupertino: _usesCupertino(context), + onSubmit: (intent) => _submit(id, intent), + ); + } finally { + _dialogOpen = false; + if (mounted) setState(() {}); + } + } + + Future _submit(num id, RetryIntent intent) async { + final repository = RunsRepository(widget.gateway); + try { + final run = await repository.retryRun( + id, + requestKey: intent.requestKey, + mode: intent.mode.wireMode, + ); + if (!mounted) return null; + if (_owns(id)) widget.onRunChanged(run); + return null; + } catch (error) { + return ActionRefusal( + describeRetryError(error), + stillPossible: _resyncRun(id), + ); + } + } + + bool _owns(num id) => mounted && retryRunId(widget.run) == id; + + /// One bounded re-read per refusal. A refusal that arrives while a read is + /// already in flight observes that same read instead of starting another. + Future _resyncRun(num id) { + return _resync ??= _readRun(id); + } + + Future _readRun(num id) async { + try { + final run = await RunsRepository(widget.gateway).getRun(id); + if (!_owns(id)) return null; + widget.onRunChanged(run); + return canRetryRun(run); + } catch (_) { + // Unknown server truth: keep the refusal and leave a deliberate retry. + return null; + } finally { + _resync = null; + } + } + + @override + Widget build(BuildContext context) { + if (retryRunId(widget.run) == null || !canRetryRun(widget.run)) { + return const SizedBox.shrink(); + } + if (_usesCupertino(context)) { + return CupertinoButton.filled( + key: retryActionKey, + onPressed: _open, + child: const Text(retryActionLabel), + ); + } + return FilledButton( + key: retryActionKey, + onPressed: _open, + child: const Text(retryActionLabel), + ); + } +} diff --git a/app/lib/features/runs/actions/retry_dialog.dart b/app/lib/features/runs/actions/retry_dialog.dart new file mode 100644 index 00000000..846133a1 --- /dev/null +++ b/app/lib/features/runs/actions/retry_dialog.dart @@ -0,0 +1,207 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'action_refusal.dart'; +import 'retry_intent.dart'; +import 'retry_wording.dart'; + +/// Sends the confirmed retry intent. Returns null once the server has accepted +/// it, or an [ActionRefusal] carrying the server's words verbatim; the prompt +/// then stays open with dismissal available immediately. +typedef RetrySubmit = Future Function(RetryIntent intent); + +/// Opens the native retry confirmation for [runId]. +/// +/// The first confirmation offers resume (the default) and a secondary +/// `Restart from start` confirmation, exactly like the browser's retry dialog. +/// Nothing is sent until the operator presses a confirm action; `Keep` only +/// closes the prompt. +Future showRetryRunPrompt({ + required BuildContext context, + required num runId, + required bool cupertino, + required RetrySubmit onSubmit, +}) { + final prompt = _RetryPrompt( + runId: runId, + cupertino: cupertino, + onSubmit: onSubmit, + ); + if (cupertino) { + return showCupertinoDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); + } + return showDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); +} + +class _RetryPrompt extends StatefulWidget { + const _RetryPrompt({ + required this.runId, + required this.cupertino, + required this.onSubmit, + }); + + final num runId; + final bool cupertino; + final RetrySubmit onSubmit; + + @override + State<_RetryPrompt> createState() => _RetryPromptState(); +} + +class _RetryPromptState extends State<_RetryPrompt> { + RetryMode _mode = RetryMode.resume; + String? _requestKey; + bool _sending = false; + bool _checking = false; + bool _blocked = false; + bool _attempted = false; + String? _error; + + void _keep() { + if (!_sending) Navigator.of(context).pop(); + } + + void _restart() { + if (_sending || _checking || _attempted) return; + setState(() { + _mode = RetryMode.restart; + _error = null; + }); + } + + Future _confirm() async { + if (_sending || _checking || _blocked) return; + setState(() { + _sending = true; + _attempted = true; + _error = null; + }); + final intent = RetryIntent( + mode: _mode, + requestKey: _requestKey ??= newRetryRequestKey(widget.runId), + ); + final refusal = await widget.onSubmit(intent); + if (!mounted) return; + if (refusal == null) { + Navigator.of(context).pop(); + return; + } + final check = refusal.stillPossible; + setState(() { + _sending = false; + _error = refusal.message; + _checking = check != null; + }); + if (check == null) return; + bool? stillPossible; + try { + stillPossible = await check; + } catch (_) { + // The action reports re-read failures as null; never fabricate one here. + } + if (!mounted) return; + setState(() { + _checking = false; + _blocked = stillPossible == false; + }); + } + + @override + Widget build(BuildContext context) { + final dialog = widget.cupertino ? _cupertino(context) : _material(context); + return PopScope(canPop: !_sending, child: dialog); + } + + bool get _confirmDisabled => _sending || _checking || _blocked; + bool get _showRestart => _mode == RetryMode.resume && !_attempted; + + Widget _material(BuildContext context) { + final theme = Theme.of(context); + return AlertDialog( + scrollable: true, + title: Text(_dialogTitle), + content: _body(errorStyle: TextStyle(color: theme.colorScheme.error)), + actions: [ + if (_showRestart) + TextButton( + key: retryRestartKey, + onPressed: _sending || _checking ? null : _restart, + child: const Text(restartConfirmLabel), + ), + TextButton( + key: retryKeepKey, + onPressed: _sending ? null : _keep, + child: const Text(retryKeepLabel), + ), + FilledButton( + key: retryConfirmKey, + onPressed: _confirmDisabled ? null : _confirm, + child: Text(_confirmLabel), + ), + ], + ); + } + + Widget _cupertino(BuildContext context) { + return CupertinoAlertDialog( + title: Text(_dialogTitle), + content: _body( + errorStyle: TextStyle( + color: CupertinoColors.systemRed.resolveFrom(context), + ), + ), + actions: [ + if (_showRestart) + CupertinoDialogAction( + key: retryRestartKey, + onPressed: _sending || _checking ? null : _restart, + child: const Text(restartConfirmLabel), + ), + CupertinoDialogAction( + key: retryKeepKey, + onPressed: _sending ? null : _keep, + child: const Text(retryKeepLabel), + ), + CupertinoDialogAction( + key: retryConfirmKey, + isDestructiveAction: _mode == RetryMode.restart, + onPressed: _confirmDisabled ? null : _confirm, + child: Text(_confirmLabel), + ), + ], + ); + } + + Widget _body({required TextStyle errorStyle}) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(_dialogMessage), + if (_error case final error?) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(error, key: retryErrorKey, style: errorStyle), + ), + ], + ); + } + + String get _dialogTitle => _mode == RetryMode.restart + ? restartDialogTitle(widget.runId) + : retryDialogTitle(widget.runId); + + String get _dialogMessage => + _mode == RetryMode.restart ? restartDialogMessage : retryDialogMessage; + + String get _confirmLabel => + _mode == RetryMode.restart ? restartConfirmLabel : retryConfirmLabel; +} diff --git a/app/lib/features/runs/actions/retry_eligibility.dart b/app/lib/features/runs/actions/retry_eligibility.dart new file mode 100644 index 00000000..13026230 --- /dev/null +++ b/app/lib/features/runs/actions/retry_eligibility.dart @@ -0,0 +1,16 @@ +import '../../../core/api_gateway.dart'; + +/// Whether the operator may retry [run], matching `canRetry` in +/// `web/src/actions.js` exactly: a loaded run that is not executing and whose +/// status is `failed`. A stale `failed` status while the run still executes is +/// not retryable. +bool canRetryRun(JsonMap? run) { + if (run == null) return false; + return run['executing'] != true && run['status'] == 'failed'; +} + +/// The run id used by the retry request, or null for a malformed run. +num? retryRunId(JsonMap run) { + final id = run['id']; + return id is num ? id : null; +} diff --git a/app/lib/features/runs/actions/retry_intent.dart b/app/lib/features/runs/actions/retry_intent.dart new file mode 100644 index 00000000..17140a70 --- /dev/null +++ b/app/lib/features/runs/actions/retry_intent.dart @@ -0,0 +1,29 @@ +import 'dart:math'; + +/// The two deliberate retry choices. `resume` is the server's default, so its +/// wire field is omitted; `restart` replays the whole pipeline. +enum RetryMode { + resume, + restart; + + /// The `retry_mode` value to send, or null to let the server resume. + String? get wireMode => this == RetryMode.restart ? 'restart' : null; +} + +/// One confirmed retry intent: the chosen mode plus the idempotency key that +/// belongs to it. Retrying the same uncertain intent reuses [requestKey] so the +/// server can dedupe it; a fresh deliberate intent uses a new key. +class RetryIntent { + const RetryIntent({required this.mode, required this.requestKey}); + + final RetryMode mode; + final String requestKey; +} + +/// A fresh `request_key` for one retry intent. The server requires one and caps +/// it at 128 characters; this stays well inside that bound and unique per call. +String newRetryRequestKey(num runId, {DateTime? now, int? random}) { + final stamp = (now ?? DateTime.now()).microsecondsSinceEpoch; + final entropy = random ?? Random().nextInt(1 << 32); + return 'app-retry-$runId-$stamp-${entropy.toRadixString(36)}'; +} diff --git a/app/lib/features/runs/actions/retry_wording.dart b/app/lib/features/runs/actions/retry_wording.dart new file mode 100644 index 00000000..efec7d86 --- /dev/null +++ b/app/lib/features/runs/actions/retry_wording.dart @@ -0,0 +1,33 @@ +import 'package:flutter/widgets.dart'; + +/// The browser client's retry wording, kept verbatim. +const retryActionLabel = 'Retry'; +const retryDialogMessage = + 'Only failed runs can be retried. The server starts a new run from the ' + 'same input.'; +const retryConfirmLabel = 'Retry'; +const restartDialogMessage = + 'This replays the whole pipeline from the start instead of resuming the ' + 'failed stage.'; +const restartConfirmLabel = 'Restart from start'; +const retryKeepLabel = 'Keep'; + +/// Stable test/semantics keys shared by the action and its prompt. +const retryActionKey = ValueKey('retry-run-action'); +const retryKeepKey = ValueKey('retry-run-keep'); +const retryConfirmKey = ValueKey('retry-run-confirm'); +const retryRestartKey = ValueKey('retry-run-restart'); +const retryErrorKey = ValueKey('retry-run-error'); + +/// The retry dialog's title: `Retry run {id}?`. +String retryDialogTitle(num runId) => 'Retry run $runId?'; + +/// The restart dialog's title: `Restart run {id}?`. +String restartDialogTitle(num runId) => 'Restart run $runId?'; + +/// The server's refusal, verbatim. Only a blank error gets a generic sentence +/// so the prompt never claims a retry that did not happen. +String describeRetryError(Object error) { + final message = '$error'.trim(); + return message.isEmpty ? 'The server did not retry the run.' : message; +} diff --git a/app/lib/features/runs/actions/title_action.dart b/app/lib/features/runs/actions/title_action.dart new file mode 100644 index 00000000..7a5b9b97 --- /dev/null +++ b/app/lib/features/runs/actions/title_action.dart @@ -0,0 +1,109 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../data/runs_repository.dart'; +import 'action_refusal.dart'; +import 'title_dialog.dart'; +import 'title_wording.dart'; + +/// The run detail's rename entry point, mirroring the browser's rename row. +/// +/// The prompt starts with [run]'s stored title exactly as the server sent it +/// (never a prompt or output fallback). Typing and Cancel send nothing; only +/// Save sends `set_run_title` with the exact run id and title text. A refusal is +/// returned verbatim to the kept-open prompt, and only the server's returned +/// `run_detail` is delivered through [onRunChanged], once. +class RunTitleAction extends StatefulWidget { + const RunTitleAction({ + super.key, + required this.run, + required this.gateway, + required this.onRunChanged, + }); + + final JsonMap run; + final ApiGateway gateway; + final ValueChanged onRunChanged; + + @override + State createState() => _RunTitleActionState(); +} + +class _RunTitleActionState extends State { + bool _dialogOpen = false; + bool _saving = false; + + bool _usesCupertino(BuildContext context) { + final material = Localizations.of( + context, + MaterialLocalizations, + ); + return material == null; + } + + Future _open() async { + final id = runTitleId(widget.run); + if (id == null || _dialogOpen) return; + _dialogOpen = true; + try { + await showRunTitlePrompt( + context: context, + runId: id, + initialTitle: storedRunTitle(widget.run), + cupertino: _usesCupertino(context), + onSubmit: (title) => _submit(id, title), + ); + } finally { + _dialogOpen = false; + if (mounted) setState(() {}); + } + } + + Future _submit(num id, String title) async { + if (_saving) return const ActionRefusal(actionAlreadySending); + _saving = true; + try { + final run = await RunsRepository(widget.gateway).setRunTitle(id, title); + if (!mounted) return null; + if (_owns(id)) widget.onRunChanged(run); + return null; + } catch (error) { + return ActionRefusal(describeTitleError(error)); + } finally { + _saving = false; + } + } + + bool _owns(num id) => mounted && runTitleId(widget.run) == id; + + @override + Widget build(BuildContext context) { + if (runTitleId(widget.run) == null) return const SizedBox.shrink(); + if (_usesCupertino(context)) { + return CupertinoButton( + key: runTitleActionKey, + onPressed: _open, + child: const Text(runTitleActionLabel), + ); + } + return OutlinedButton( + key: runTitleActionKey, + onPressed: _open, + child: const Text(runTitleActionLabel), + ); + } +} + +/// The run id used by the rename request, or null for a malformed run. +num? runTitleId(JsonMap run) { + final id = run['id']; + return id is num ? id : null; +} + +/// The run's stored title exactly as the browser reads it +/// (`String(d.title ?? "")`); never inferred from the prompt or output. +String storedRunTitle(JsonMap run) { + final title = run['title']; + return title == null ? '' : '$title'; +} diff --git a/app/lib/features/runs/actions/title_dialog.dart b/app/lib/features/runs/actions/title_dialog.dart new file mode 100644 index 00000000..9ae03a11 --- /dev/null +++ b/app/lib/features/runs/actions/title_dialog.dart @@ -0,0 +1,183 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'action_refusal.dart'; +import 'title_wording.dart'; + +/// Sends the typed title. Returns null once the server has accepted it, or an +/// [ActionRefusal] carrying the server's words verbatim; the prompt then stays +/// open with the typed title intact. +typedef TitleSubmit = Future Function(String title); + +/// Opens the native rename prompt for [runId], seeded with the run's stored +/// [initialTitle]. +/// +/// Typing and the dismiss action send nothing; only Save sends the title. The +/// title is passed through exactly as typed, including surrounding whitespace, +/// matching `setRunTitle` in `web/src/repository.js`; the server decides whether +/// a blank title is acceptable. +Future showRunTitlePrompt({ + required BuildContext context, + required num runId, + required String initialTitle, + required bool cupertino, + required TitleSubmit onSubmit, +}) { + final prompt = _TitlePrompt( + runId: runId, + initialTitle: initialTitle, + cupertino: cupertino, + onSubmit: onSubmit, + ); + if (cupertino) { + return showCupertinoDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); + } + return showDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); +} + +class _TitlePrompt extends StatefulWidget { + const _TitlePrompt({ + required this.runId, + required this.initialTitle, + required this.cupertino, + required this.onSubmit, + }); + + final num runId; + final String initialTitle; + final bool cupertino; + final TitleSubmit onSubmit; + + @override + State<_TitlePrompt> createState() => _TitlePromptState(); +} + +class _TitlePromptState extends State<_TitlePrompt> { + late final TextEditingController _title = TextEditingController( + text: widget.initialTitle, + ); + bool _sending = false; + String? _error; + + @override + void dispose() { + _title.dispose(); + super.dispose(); + } + + void _cancel() { + if (!_sending) Navigator.of(context).pop(); + } + + Future _save() async { + if (_sending) return; + setState(() { + _sending = true; + _error = null; + }); + final refusal = await widget.onSubmit(_title.text); + if (!mounted) return; + if (refusal == null) { + Navigator.of(context).pop(); + return; + } + setState(() { + _sending = false; + _error = refusal.message; + }); + } + + @override + Widget build(BuildContext context) { + final dialog = widget.cupertino ? _cupertino(context) : _material(context); + return PopScope(canPop: !_sending, child: dialog); + } + + Widget _material(BuildContext context) { + final theme = Theme.of(context); + return AlertDialog( + scrollable: true, + title: const Text(runTitleDialogTitle), + content: _body( + field: TextField( + key: runTitleFieldKey, + controller: _title, + enabled: !_sending, + autofocus: true, + decoration: const InputDecoration(labelText: runTitleFieldLabel), + textInputAction: TextInputAction.done, + onSubmitted: (_) => _save(), + ), + errorStyle: TextStyle(color: theme.colorScheme.error), + ), + actions: [ + TextButton( + key: runTitleCancelKey, + onPressed: _sending ? null : _cancel, + child: const Text(runTitleCancelLabel), + ), + FilledButton( + key: runTitleSaveKey, + onPressed: _sending ? null : _save, + child: const Text(runTitleSaveLabel), + ), + ], + ); + } + + Widget _cupertino(BuildContext context) { + return CupertinoAlertDialog( + title: const Text(runTitleDialogTitle), + content: _body( + field: CupertinoTextField( + key: runTitleFieldKey, + controller: _title, + enabled: !_sending, + autofocus: true, + placeholder: runTitleFieldLabel, + textInputAction: TextInputAction.done, + onSubmitted: (_) => _save(), + ), + errorStyle: TextStyle( + color: CupertinoColors.systemRed.resolveFrom(context), + ), + ), + actions: [ + CupertinoDialogAction( + key: runTitleCancelKey, + onPressed: _sending ? null : _cancel, + child: const Text(runTitleCancelLabel), + ), + CupertinoDialogAction( + key: runTitleSaveKey, + isDefaultAction: true, + onPressed: _sending ? null : _save, + child: const Text(runTitleSaveLabel), + ), + ], + ); + } + + Widget _body({required Widget field, required TextStyle errorStyle}) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + field, + if (_error case final error?) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(error, key: runTitleErrorKey, style: errorStyle), + ), + ], + ); + } +} diff --git a/app/lib/features/runs/actions/title_wording.dart b/app/lib/features/runs/actions/title_wording.dart new file mode 100644 index 00000000..8fa85891 --- /dev/null +++ b/app/lib/features/runs/actions/title_wording.dart @@ -0,0 +1,24 @@ +import 'package:flutter/widgets.dart'; + +/// The browser client's rename wording, kept verbatim. +const runTitleActionLabel = 'Rename'; +const runTitleDialogTitle = 'Rename'; +const runTitleFieldLabel = 'Run title'; +const runTitleSaveLabel = 'Save'; +const runTitleCancelLabel = 'Cancel'; + +/// Stable test/semantics keys shared by the action and its prompt. +const runTitleActionKey = ValueKey('rename-run-action'); +const runTitleFieldKey = ValueKey('rename-run-field'); +const runTitleSaveKey = ValueKey('rename-run-save'); +const runTitleCancelKey = ValueKey('rename-run-cancel'); +const runTitleErrorKey = ValueKey('rename-run-error'); + +/// The server's refusal, verbatim. Only a blank error gets a generic sentence +/// so the prompt never claims a rename that did not happen. +String describeTitleError(Object error) { + final message = '$error'; + return message.trim().isEmpty + ? 'The server did not rename the run.' + : message; +} diff --git a/app/lib/features/runs/data/runs_repository.dart b/app/lib/features/runs/data/runs_repository.dart new file mode 100644 index 00000000..5a1ea8c4 --- /dev/null +++ b/app/lib/features/runs/data/runs_repository.dart @@ -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 listRuns() async { + final reply = await _gateway.call('list_runs'); + final runs = reply['runs']; + return RunListResult( + runs is List + ? runs + .whereType() + .map((r) => Map.from(r)) + .toList() + : const [], + reply['usage'] is Map + ? Map.from(reply['usage'] as Map) + : null, + ); + } + + Future getRun(num id) async => + _required(await _gateway.call('get_run', {'run_id': id}), 'run_detail'); + Future cancelRun(num id) async => _required( + await _gateway.call('cancel_run', {'run_id': id}), + 'run_detail', + ); + + Future retryRun( + num id, { + required String requestKey, + String? mode, + }) async { + final fields = {'run_id': id, 'request_key': requestKey}; + if (mode == 'restart') fields['retry_mode'] = mode; + return _required(await _gateway.call('retry_run', fields), 'run_detail'); + } + + Future 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 = {'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 setRunTitle(num id, String title) async => _required( + await _gateway.call('set_run_title', {'run_id': id, 'title': title}), + 'run_detail', + ); + + Future 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 = { + '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.from(value); + } +} diff --git a/app/lib/features/runs/domain/run_decisions.dart b/app/lib/features/runs/domain/run_decisions.dart new file mode 100644 index 00000000..339508e6 --- /dev/null +++ b/app/lib/features/runs/domain/run_decisions.dart @@ -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 options; +} + +JsonMap? lastWaitingStep(List steps) { + for (final value in steps.reversed) { + if (value is Map && value['status'] == 'waiting') { + return Map.from(value); + } + } + return null; +} + +String waitingPrompt(dynamic output) => + output is Map && output['prompt'] is String + ? output['prompt'] as String + : ''; + +List waitingOptions(dynamic output) { + final options = output is Map ? output['options'] : null; + if (options is! List) return const []; + return options + .whereType() + .where((entry) => entry.trim().isNotEmpty) + .toList(); +} + +List 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()) { + if (value['key'] == stage) { + declaration = Map.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'; diff --git a/app/lib/features/runs/domain/run_events.dart b/app/lib/features/runs/domain/run_events.dart new file mode 100644 index 00000000..3ce3bc87 --- /dev/null +++ b/app/lib/features/runs/domain/run_events.dart @@ -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 = { + ...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 = { + '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 runs, bool needsResync}) foldRunEvent( + List 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((s) => Map.from(s)) + .toList() + : [], + Map.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(); diff --git a/app/lib/features/runs/domain/run_models.dart b/app/lib/features/runs/domain/run_models.dart new file mode 100644 index 00000000..0f0d4941 --- /dev/null +++ b/app/lib/features/runs/domain/run_models.dart @@ -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 filterRuns( + List runs, { + Set 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 sortRuns(List 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 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 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 orderAttention( + List runs, { + Set 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; +} diff --git a/app/lib/features/runs/domain/run_step_evidence.dart b/app/lib/features/runs/domain/run_step_evidence.dart new file mode 100644 index 00000000..f4fdb710 --- /dev/null +++ b/app/lib/features/runs/domain/run_step_evidence.dart @@ -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 upsertRunStep(List 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 = []; + final oldVisits = current?['visits']; + if (oldVisits is List) { + visits = oldVisits + .whereType() + .map((v) => Map.from(v)) + .toList(); + } + final additions = []; + 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()) { + final delta = Map.from(item); + visits = upsertRunStep(visits, { + 'sequence': delta['sequence'], + 'stage': delta['stage'], + 'status': delta['status'], + 'outcome': delta['outcome'], + 'target': delta['target'], + }); + } + final latestByStage = {}; + final routeSequence = {}; + 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) => { + 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; diff --git a/app/lib/features/runs/screen.dart b/app/lib/features/runs/screen.dart new file mode 100644 index 00000000..607dde93 --- /dev/null +++ b/app/lib/features/runs/screen.dart @@ -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? onRunSelected; + final VoidCallback? onBack; + + @override + State createState() => _RunsScreenState(); +} + +class _RunsScreenState extends State { + 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), + ], + ); + } +} diff --git a/app/lib/features/runs/ui/run_detail_content.dart b/app/lib/features/runs/ui/run_detail_content.dart new file mode 100644 index 00000000..5c48756f --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_content.dart @@ -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 detailUsageMetrics(dynamic raw) { + if (raw is! Map || raw.isEmpty) return const []; + final usage = Map.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 = [ + 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 detailTimeline(dynamic steps) { + if (steps is! List) return const []; + return [ + for (final step in steps.whereType()) + ( + 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; diff --git a/app/lib/features/runs/ui/run_detail_cupertino.dart b/app/lib/features/runs/ui/run_detail_cupertino.dart new file mode 100644 index 00000000..28fdddfe --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_cupertino.dart @@ -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('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, + ); +} diff --git a/app/lib/features/runs/ui/run_detail_material.dart b/app/lib/features/runs/ui/run_detail_material.dart new file mode 100644 index 00000000..27d98316 --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_material.dart @@ -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('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)), + ); +} diff --git a/app/lib/features/runs/ui/run_detail_view.dart b/app/lib/features/runs/ui/run_detail_view.dart new file mode 100644 index 00000000..0fda7ad7 --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_view.dart @@ -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 createState() => _RunDetailViewState(); +} + +class _RunDetailViewState extends State { + 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 _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))); + } + } +} diff --git a/app/lib/features/runs/ui/runs_controller.dart b/app/lib/features/runs/ui/runs_controller.dart new file mode 100644 index 00000000..0dbd12f7 --- /dev/null +++ b/app/lib/features/runs/ui/runs_controller.dart @@ -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? _subscription; + List runs = []; + JsonMap? detail, usage; + String? error; + bool loading = false, detailLoading = false; + String query = '', + sort = 'newest_first', + scheduled = 'any', + timeRange = 'any_time'; + final Set 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 frames) { + _subscription?.cancel(); + _subscription = frames + .where((f) => f['type'] == 'run_event') + .listen(_event); + } + + Future 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 resync() async { + final selected = _selectedId; + await load(); + if (selected != null && _selectedId == selected) await select(selected); + } + + Future 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 _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 _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 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(); + } +} diff --git a/app/lib/features/runs/ui/runs_list.dart b/app/lib/features/runs/ui/runs_list.dart new file mode 100644 index 00000000..0f974eac --- /dev/null +++ b/app/lib/features/runs/ui/runs_list.dart @@ -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 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( + 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( + 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 _choose( + BuildContext context, + String title, + List<(String, String)> values, + String selected, + ValueChanged onSelected, + ) async { + final value = await showCupertinoModalPopup( + 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)}'; diff --git a/app/lib/features/schedules/data/schedules_repository.dart b/app/lib/features/schedules/data/schedules_repository.dart new file mode 100644 index 00000000..432bf841 --- /dev/null +++ b/app/lib/features/schedules/data/schedules_repository.dart @@ -0,0 +1,116 @@ +import '../../../core/api_gateway.dart'; +import '../domain/saved_schedule.dart'; +import '../domain/schedule_json.dart'; + +/// Client-side protocol failure. Server refusals and transport errors are not +/// wrapped: [ApiGateway] already surfaces their exact text. +class SchedulesRepositoryException implements Exception { + const SchedulesRepositoryException(this.message); + final String message; + @override + String toString() => message; +} + +/// The saved-schedule commands of the current web client. +/// +/// These are run configurations, not pipeline definitions: this repository +/// never submits, validates or publishes a workflow, and it never starts or +/// polls a run. Timer execution belongs to the server. +class SchedulesRepository { + SchedulesRepository(this._gateway); + + final ApiGateway _gateway; + + /// Lists saved schedules, optionally for one pipeline. + /// + /// An explicit empty reply is a valid empty list. A reply without the + /// `schedules` type is not: that is an older/unsupported server and must be + /// reported rather than shown as "no schedules". + Future> listSchedules({int? pipelineId}) async { + final fields = {}; + if (pipelineId != null) { + if (!_isPositiveId(pipelineId)) { + throw const SchedulesRepositoryException( + 'A positive pipeline ID is required.', + ); + } + fields['pipeline_id'] = pipelineId; + } + final reply = await _gateway.call('list_schedules', fields); + final schedules = reply['schedules']; + if (reply['type'] != 'schedules' || + (schedules != null && schedules is! List)) { + throw const SchedulesRepositoryException( + 'The server returned no schedules response.', + ); + } + if (schedules == null) return const []; + return [ + for (final item in schedules as List) + if (item is Map) + SavedSchedule(Map.from(item)) + else + throw const SchedulesRepositoryException( + 'The server returned an invalid schedule record.', + ), + ]; + } + + /// Creates or updates one saved schedule. + /// + /// Creation sends the web client's sentinel record (`id` 0, no revision) and + /// may carry a stable request key so a lost reply is retried instead of + /// creating a duplicate. Updating sends the record read from the server, + /// whose `revision` is the compare-and-swap token; the key is omitted, as in + /// the web client. A stale revision is refused by the server and propagated + /// unchanged, never overwritten locally. + Future saveSchedule( + JsonMap schedule, { + String? requestKey, + }) async { + if (requestKey != null && requestKey.length > 128) { + throw const SchedulesRepositoryException( + 'Schedule request keys must be strings of at most 128 characters.', + ); + } + final fields = {'schedule': cloneJsonMap(schedule)}; + if (requestKey != null && requestKey.isNotEmpty) { + fields['request_key'] = requestKey; + } + final reply = await _gateway.call('save_schedule', fields); + final saved = reply['schedule']; + if (saved is! Map) { + throw const SchedulesRepositoryException( + 'The server returned no saved schedule.', + ); + } + return SavedSchedule(Map.from(saved)); + } + + /// Deletes exactly the revision the caller read. + /// + /// Both identity and revision are required before any request is sent; a + /// confirmation for a different schedule is treated as a failed delete. + Future deleteSchedule(int id, int revision) async { + if (!_isPositiveId(id) || !_isPositiveId(revision)) { + throw const SchedulesRepositoryException( + 'An exact schedule ID and revision are required.', + ); + } + final reply = await _gateway.call('delete_schedule', { + 'schedule_id': id, + 'expected_revision': revision, + }); + if (reply['type'] != 'schedule_deleted' || reply['schedule_id'] != id) { + throw const SchedulesRepositoryException( + 'The server did not confirm deletion of this schedule.', + ); + } + } +} + +/// JSON/JavaScript integers are safe up to 2^53-1; the web client checks +/// `Number.isSafeInteger` before sending an identity. +const _maxSafeInteger = 9007199254740991; + +bool _isPositiveId(int value) => value > 0 && value <= _maxSafeInteger; diff --git a/app/lib/features/schedules/domain/saved_schedule.dart b/app/lib/features/schedules/domain/saved_schedule.dart new file mode 100644 index 00000000..32570b72 --- /dev/null +++ b/app/lib/features/schedules/domain/saved_schedule.dart @@ -0,0 +1,87 @@ +import '../../../core/api_gateway.dart'; +import 'schedule_json.dart'; +import 'schedule_rule.dart'; + +/// One saved run configuration from `list_schedules` or `save_schedule`. +/// +/// A saved schedule is a complete run request pinned to one pipeline version. +/// It is deliberately not a pipeline definition: nothing here is published, +/// validated as a graph or treated as the pipeline's current version. +/// +/// [raw] keeps the exact server record, including fields this client does not +/// know yet. Typed getters are views; they never rewrite [raw]. +class SavedSchedule { + SavedSchedule(JsonMap raw) : raw = cloneJsonMap(raw); + + final JsonMap raw; + + /// Server identity; null when an older reply omits it. Never defaulted to 0, + /// because 0 is the create sentinel rather than a saved identity. + int? get id => _integer(raw['id']); + + /// Compare-and-swap token. Updates reuse it and deletes send it as + /// `expected_revision`; this client never invents or increments it. + int? get revision => _integer(raw['revision']); + + int? get pipelineId => _integer(raw['pipeline_id']); + int? get version => _integer(raw['version']); + String get name => _text(raw['name']); + bool get enabled => raw['enabled'] == true; + + JsonMap get input => _map(raw['input']); + String get prompt => _text(input['prompt']); + String get workspace => _text(raw['workspace']); + ScheduleRule get rule => ScheduleRule(_map(raw['rule'])); + + List get writePaths => _texts(raw['write_paths']); + bool get allowTools => raw['allow_tools'] == true; + String get model => _text(raw['model']); + Map get stageModels => { + for (final entry in _map(raw['stage_models']).entries) + if (entry.value is String) entry.key: entry.value as String, + }; + String get notifyMode => _text(raw['notify_mode']); + String get title => _text(raw['title']); + String get outputFormat => _text(raw['output_format']); + + String get nextDue => _text(raw['next_due']); + String get createdAt => _text(raw['created_at']); + String get updatedAt => _text(raw['updated_at']); + + /// The record to pass to `save_schedule`, deep-copied so callers cannot + /// mutate this snapshot by aliasing. + JsonMap toJson() => cloneJsonMap(raw); + + /// Pause/enable copy. Identity, revision and every unknown field are kept so + /// the update still targets the revision this record was read at. + SavedSchedule withEnabled(bool value) { + final copy = toJson(); + copy['enabled'] = value; + return SavedSchedule(copy); + } +} + +int? _integer(dynamic value) { + if (value is int) return value; + if (value is num && value.isFinite && value == value.truncateToDouble()) { + return value.toInt(); + } + return null; +} + +String _text(dynamic value) => value is String ? value : ''; + +JsonMap _map(dynamic value) { + if (value is! Map) return {}; + return { + for (final entry in value.entries) + '${entry.key}': cloneJsonValue(entry.value), + }; +} + +List _texts(dynamic value) => value is List + ? [ + for (final item in value) + if (item is String) item, + ] + : const []; diff --git a/app/lib/features/schedules/domain/schedule_json.dart b/app/lib/features/schedules/domain/schedule_json.dart new file mode 100644 index 00000000..a0e541bf --- /dev/null +++ b/app/lib/features/schedules/domain/schedule_json.dart @@ -0,0 +1,22 @@ +import '../../../core/api_gateway.dart'; + +/// Deep copy of a decoded JSON value. +/// +/// Saved schedules travel back to the server unchanged, so unknown fields (and +/// unknown nested values) must survive every round trip without sharing state +/// with the reply map that produced them. +dynamic cloneJsonValue(dynamic value) { + if (value is Map) { + return { + for (final entry in value.entries) + '${entry.key}': cloneJsonValue(entry.value), + }; + } + if (value is List) { + return [for (final item in value) cloneJsonValue(item)]; + } + return value; +} + +JsonMap cloneJsonMap(JsonMap value) => + Map.from(cloneJsonValue(value) as Map); diff --git a/app/lib/features/schedules/domain/schedule_rule.dart b/app/lib/features/schedules/domain/schedule_rule.dart new file mode 100644 index 00000000..7eb4bed5 --- /dev/null +++ b/app/lib/features/schedules/domain/schedule_rule.dart @@ -0,0 +1,41 @@ +import '../../../core/api_gateway.dart'; +import 'schedule_json.dart'; + +/// Weekday keys the server accepts for an interval rule. +const scheduleDays = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']; + +/// The timer part of a saved schedule (`rule` on the wire). +/// +/// This is a view over the decoded server record, not a timer implementation: +/// it never calculates due times, converts timezones or starts runs. Unknown +/// rule fields stay in [raw] and are returned by [toJson]. +class ScheduleRule { + ScheduleRule([JsonMap? raw]) : raw = cloneJsonMap(raw ?? const {}); + + final JsonMap raw; + + /// Go-style duration such as `24h` or `1h30m`; empty for a clock rule. + String get every => _text(raw['every']); + + /// Distinct 24-hour times such as `09:00`; empty for an interval rule. + List get times => _texts(raw['times']); + + /// Empty means every day (written as absent on the wire). + List get days => _texts(raw['days']); + + /// Empty or `Local` means the server's timezone. + String get timezone => _text(raw['timezone']); + + bool get isClock => times.isNotEmpty; + + JsonMap toJson() => cloneJsonMap(raw); +} + +String _text(dynamic value) => value is String ? value : ''; + +List _texts(dynamic value) => value is List + ? [ + for (final item in value) + if (item is String) item, + ] + : const []; diff --git a/app/lib/features/schedules/screen.dart b/app/lib/features/schedules/screen.dart new file mode 100644 index 00000000..5b78e853 --- /dev/null +++ b/app/lib/features/schedules/screen.dart @@ -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 onOpen; + final int? pipelineId; + + @override + State createState() => _SchedulesScreenState(); +} + +class _SchedulesScreenState extends State { + 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( + 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()), + ), + ); + } +} diff --git a/app/lib/features/schedules/ui/list/schedule_list_controller.dart b/app/lib/features/schedules/ui/list/schedule_list_controller.dart new file mode 100644 index 00000000..6028a36d --- /dev/null +++ b/app/lib/features/schedules/ui/list/schedule_list_controller.dart @@ -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 _schedules = const []; + List? _visibleSchedules; + bool _loading = false; + bool _loaded = false; + ScheduleListFailure? _failure; + String _query = ''; + ScheduleListFilter _filter = ScheduleListFilter.all; + int _generation = 0; + bool _disposed = false; + + List 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 get visibleSchedules => + _visibleSchedules ??= _filterSchedules(); + + List _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 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(); + } +} diff --git a/app/lib/features/schedules/ui/list/schedule_list_format.dart b/app/lib/features/schedules/ui/list/schedule_list_format.dart new file mode 100644 index 00000000..308e0eb5 --- /dev/null +++ b/app/lib/features/schedules/ui/list/schedule_list_format.dart @@ -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'; +} diff --git a/app/lib/features/schedules/ui/list/schedule_list_row.dart b/app/lib/features/schedules/ui/list/schedule_list_row.dart new file mode 100644 index 00000000..010bf53b --- /dev/null +++ b/app/lib/features/schedules/ui/list/schedule_list_row.dart @@ -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); +} diff --git a/app/lib/features/schedules/ui/list/schedule_list_toolbar.dart b/app/lib/features/schedules/ui/list/schedule_list_toolbar.dart new file mode 100644 index 00000000..374c7424 --- /dev/null +++ b/app/lib/features/schedules/ui/list/schedule_list_toolbar.dart @@ -0,0 +1,179 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'schedule_list_controller.dart'; + +const scheduleSearchFieldKey = ValueKey('schedule-search-field'); +const scheduleFilterKey = ValueKey('schedule-filter'); +const scheduleRefreshKey = ValueKey('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( + 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( + key: scheduleFilterKey, + segments: [ + for (final filter in ScheduleListFilter.values) + ButtonSegment( + 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, + ); +} diff --git a/app/lib/features/schedules/ui/list/schedule_list_view.dart b/app/lib/features/schedules/ui/list/schedule_list_view.dart new file mode 100644 index 00000000..0ca34236 --- /dev/null +++ b/app/lib/features/schedules/ui/list/schedule_list_view.dart @@ -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('schedule-list'); +const scheduleRetryKey = ValueKey('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 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( + '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'), + ); + } +} diff --git a/app/lib/features/search/data/search_repository.dart b/app/lib/features/search/data/search_repository.dart new file mode 100644 index 00000000..391aac13 --- /dev/null +++ b/app/lib/features/search/data/search_repository.dart @@ -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 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.from(results)); + } +} diff --git a/app/lib/features/search/domain/search_controller.dart b/app/lib/features/search/domain/search_controller.dart new file mode 100644 index 00000000..b9a3f8f8 --- /dev/null +++ b/app/lib/features/search/domain/search_controller.dart @@ -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 _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 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 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 = []; + 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 submit() => sendNow(); + + /// Retry the current query after a failure. + Future retry() => sendNow(); + + Future 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 _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(); + } +} diff --git a/app/lib/features/search/domain/search_format.dart b/app/lib/features/search/domain/search_format.dart new file mode 100644 index 00000000..8e2f480a --- /dev/null +++ b/app/lib/features/search/domain/search_format.dart @@ -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'; +} diff --git a/app/lib/features/search/domain/search_models.dart b/app/lib/features/search/domain/search_models.dart new file mode 100644 index 00000000..671e38d9 --- /dev/null +++ b/app/lib/features/search/domain/search_models.dart @@ -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((row) => Map.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 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; +} diff --git a/app/lib/features/search/domain/search_query.dart b/app/lib/features/search/domain/search_query.dart new file mode 100644 index 00000000..a7971540 --- /dev/null +++ b/app/lib/features/search/domain/search_query.dart @@ -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; +} diff --git a/app/lib/features/search/domain/search_row.dart b/app/lib/features/search/domain/search_row.dart new file mode 100644 index 00000000..283feca7 --- /dev/null +++ b/app/lib/features/search/domain/search_row.dart @@ -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 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 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? _map(Object? value) { + if (value is! Map) return null; + return Map.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 parts) => + parts.whereType().where((part) => part.isNotEmpty).join(' · '); diff --git a/app/lib/features/search/search_screen.dart b/app/lib/features/search/search_screen.dart new file mode 100644 index 00000000..3c2e80ce --- /dev/null +++ b/app/lib/features/search/search_screen.dart @@ -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 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 createState() => _SearchScreenState(); +} + +class _SearchScreenState extends State { + 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 _pickKind(BuildContext context) async { + final selected = await showCupertinoModalPopup( + 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( + 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.'; diff --git a/app/lib/features/search/ui/cupertino_search_body.dart b/app/lib/features/search/ui/cupertino_search_body.dart new file mode 100644 index 00000000..2f29d3b0 --- /dev/null +++ b/app/lib/features/search/ui/cupertino_search_body.dart @@ -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 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 _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 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 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'), + ), + ], + ), + ), + ); +} diff --git a/app/lib/features/search/ui/material_search_body.dart b/app/lib/features/search/ui/material_search_body.dart new file mode 100644 index 00000000..462f75ee --- /dev/null +++ b/app/lib/features/search/ui/material_search_body.dart @@ -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 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 _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 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 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'), + ), + ], + ), + ), + ); +} diff --git a/app/lib/features/search/ui/search_result_view.dart b/app/lib/features/search/ui/search_result_view.dart new file mode 100644 index 00000000..fef687f3 --- /dev/null +++ b/app/lib/features/search/ui/search_result_view.dart @@ -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, +}; diff --git a/app/lib/features/settings/default_endpoint.dart b/app/lib/features/settings/default_endpoint.dart new file mode 100644 index 00000000..993bc713 --- /dev/null +++ b/app/lib/features/settings/default_endpoint.dart @@ -0,0 +1,24 @@ +import 'package:flutter/foundation.dart'; + +/// The websocket endpoint the web build offers by default: the page's own +/// origin, upgraded to ws/wss, at the server's `/connect` path. +/// +/// The web client is served by a same-origin proxy, so this is a configurable +/// starting value, not a baked host: it is derived from the page the operator +/// actually loaded. Native builds have no such origin and start blank, so no +/// server host or production endpoint is compiled into the app. +/// +/// `web` and `base` are injectable only so the rule can be tested without a +/// browser; production callers use the platform defaults. +String defaultServerUrl({bool? web, Uri? base}) { + if (!(web ?? kIsWeb)) return ''; + final origin = base ?? Uri.base; + if (origin.host.isEmpty) return ''; + final secure = origin.scheme.toLowerCase() == 'https'; + return Uri( + scheme: secure ? 'wss' : 'ws', + host: origin.host, + port: origin.hasPort ? origin.port : null, + path: '/connect', + ).toString(); +} diff --git a/app/lib/features/settings/settings.dart b/app/lib/features/settings/settings.dart new file mode 100644 index 00000000..06abe08e --- /dev/null +++ b/app/lib/features/settings/settings.dart @@ -0,0 +1,12 @@ +/// Public API the manager needs to register the Settings destination. +/// +/// The screen receives the shared `PipelinesClient`; it never creates, replaces +/// or disposes one. `SettingsController` is exposed for previews and focused +/// tests, not for the shell to construct separately. +library; + +export 'default_endpoint.dart'; +export 'settings_controller.dart' show PingCallback, SettingsController; +export 'settings_copy.dart'; +export 'settings_screen.dart'; +export 'settings_store.dart'; diff --git a/app/lib/features/settings/settings_controller.dart b/app/lib/features/settings/settings_controller.dart new file mode 100644 index 00000000..8d8bc715 --- /dev/null +++ b/app/lib/features/settings/settings_controller.dart @@ -0,0 +1,281 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../../core/transport/pipelines_client.dart' as transport; +import '../../core/transport/server_url.dart'; +import 'settings_copy.dart'; +import 'settings_store.dart'; + +/// The ping request the status card makes once per connection. The default is +/// the shared client's own `ping` request; tests inject a recorded callback. +typedef PingCallback = Future> Function(); + +/// Owns the Settings screen's draft text, validation and the actions that drive +/// the shared [transport.PipelinesClient]. +/// +/// The feature never owns the client: it subscribes to the client's state and +/// calls connect/disconnect, but never calls `dispose()` on it, and it never +/// opens a connection by itself. One controller is created per screen, not per +/// rebuild, so rebuilding Settings cannot start a second connection. +class SettingsController extends ChangeNotifier { + SettingsController({ + required this.client, + required this.store, + this.initialEndpoint, + String defaultEndpoint = '', + PingCallback? ping, + }) : _defaultServerUrl = defaultEndpoint, + _ping = ping ?? (() => client.call('ping')), + _connection = client.state { + _lastKind = _connection.kind; + _subscription = client.states.listen(_onConnectionState); + // Details belong to the current socket, not to the preferences read. + // Mark them pending before the first frame when opening Settings live. + if (_connection.kind == transport.ConnectionKind.connected) _requestPing(); + } + + final transport.PipelinesClient client; + final SettingsStore store; + final Uri? initialEndpoint; + final String _defaultServerUrl; + final PingCallback _ping; + + late final StreamSubscription _subscription; + + transport.ConnectionState _connection; + transport.ConnectionKind _lastKind = transport.ConnectionKind.idle; + String _serverUrl = ''; + String _urlError = ''; + String _workspaceDraft = ''; + String _savedWorkspace = ''; + String _workspaceSaveError = ''; + String _endpointSaveError = ''; + String _actionError = ''; + String _buildVersion = ''; + String _buildCommit = ''; + String _serverTime = ''; + String _pingError = ''; + bool _pingInFlight = false; + bool _pingRequestedForConnected = false; + int _pingToken = 0; + bool _initialized = false; + bool _serverUrlEdited = false; + bool _workspaceEdited = false; + bool _disposed = false; + + transport.ConnectionState get connection => _connection; + String get serverUrl => _serverUrl; + String get urlError => _urlError; + String get workspaceDraft => _workspaceDraft; + String get savedWorkspace => _savedWorkspace; + String get workspaceError => validateWorkspacePath(_workspaceDraft) ?? ''; + String get workspaceSaveError => _workspaceSaveError; + String get endpointSaveError => _endpointSaveError; + String get actionError => _actionError; + String get buildVersion => _buildVersion; + String get buildCommit => _buildCommit; + String get serverTime => _serverTime; + String get pingError => _pingError; + bool get pingInFlight => _pingInFlight; + + bool get connectionActive => + _connection.kind == transport.ConnectionKind.connected || + _connection.kind == transport.ConnectionKind.connecting; + + String get primaryActionLabel => connectionActive ? 'Disconnect' : 'Connect'; + String get secondaryActionLabel => connectionActive ? 'Connect' : 'Reconnect'; + + List get connectionLines => connectionCardLines( + _connection, + buildVersion: _buildVersion, + buildCommit: _buildCommit, + serverTime: _serverTime, + pingError: _pingError, + pingInFlight: _pingInFlight, + ); + + /// Reads the feature's own persisted values once. A draft the operator has + /// already typed into is never overwritten by the asynchronous read. + Future initialize() async { + if (_initialized) return; + _initialized = true; + final values = await store.load(); + if (_disposed) return; + if (!_serverUrlEdited) { + final saved = values.serverUrl.trim(); + _serverUrl = + initialEndpoint?.toString() ?? + (saved.isNotEmpty ? saved : _defaultServerUrl); + } + if (!_workspaceEdited) { + _workspaceDraft = values.workspace; + _savedWorkspace = values.workspace.trim(); + } + // The screen may be opened while the shared client is already connected; + // find out what that server is. This never opens a connection. + if (_connection.kind == transport.ConnectionKind.connected) _requestPing(); + _notify(); + } + + void updateServerUrl(String value) { + _serverUrlEdited = true; + _serverUrl = value; + _urlError = ''; + _actionError = ''; + _notify(); + } + + void updateWorkspace(String value) { + _workspaceEdited = true; + _workspaceDraft = value; + _workspaceSaveError = ''; + _notify(); + } + + /// Validates the draft, persists the endpoint and connects the shared client. + /// An invalid draft names the problem on the field and touches no socket. + Future connect() async { + final raw = _serverUrl; + String wsUrl; + try { + wsUrl = ServerUrl.validate(raw).wsUrl; + } on FormatException catch (error) { + _urlError = error.message.toString(); + _notify(); + return; + } + _urlError = ''; + _actionError = ''; + if (_serverUrl != wsUrl) _serverUrl = wsUrl; + final stored = await store.saveServerUrl(wsUrl); + if (_disposed) return; + _endpointSaveError = stored + ? '' + : 'The server URL could not be saved; it applies to this session only.'; + _notify(); + try { + await client.connect(Uri.parse(wsUrl)); + } catch (error) { + if (_disposed) return; + _actionError = 'Could not connect: ${_describe(error)}'; + _notify(); + } + } + + /// Re-opening the validated endpoint is the same client operation as + /// connecting; only the label differs, matching the web/Android settings. + Future reconnect() => connect(); + + /// Closes this screen's connection through the shared client. It never + /// disposes the client: other features keep using the same instance. + Future disconnect() async { + _actionError = ''; + try { + await client.disconnect(); + } catch (error) { + if (_disposed) return; + _actionError = 'Could not disconnect: ${_describe(error)}'; + } + if (!_disposed) _notify(); + } + + /// Persists the trimmed absolute workspace. Only a stored value updates the + /// `Saved workspace:` line; a failed write says so instead of claiming one. + Future saveWorkspace() async { + if (!canSaveWorkspace(_workspaceDraft)) { + _notify(); + return; + } + final value = _workspaceDraft.trim(); + final stored = await store.saveWorkspace(value); + if (_disposed) return; + _workspaceDraft = value; + if (stored) { + _savedWorkspace = value; + _workspaceSaveError = ''; + } else { + _workspaceSaveError = + 'The workspace could not be saved; it is not stored on this device.'; + } + _notify(); + } + + void _onConnectionState(transport.ConnectionState state) { + if (_disposed) return; + final previous = _lastKind; + _connection = state; + _lastKind = state.kind; + if (state.kind == transport.ConnectionKind.connected) { + _requestPing(); + } else { + // Never keep one server's build/time while another connection, or no + // connection, is being shown. + _clearPingDetails(); + if (previous == transport.ConnectionKind.connected) _pingToken++; + } + _notify(); + } + + void _requestPing() { + if (_disposed || _pingRequestedForConnected) return; + _pingRequestedForConnected = true; + _pingError = ''; + _pingInFlight = true; + final token = ++_pingToken; + unawaited(_runPing(token)); + } + + Future _runPing(int token) async { + try { + final reply = await _ping(); + if (!_isCurrentPing(token)) return; + final build = reply['build']; + _buildVersion = build is Map + ? '${build['version'] ?? ''}'.trim() + : '${build ?? ''}'.trim(); + _buildCommit = build is Map ? '${build['commit'] ?? ''}'.trim() : ''; + _serverTime = '${reply['time'] ?? ''}'.trim(); + _pingError = ''; + } catch (error) { + if (!_isCurrentPing(token)) return; + _pingError = 'Server details unavailable: ${_describe(error)}'; + } finally { + if (_isCurrentPing(token)) { + _pingInFlight = false; + _notify(); + } + } + } + + bool _isCurrentPing(int token) => + !_disposed && token == _pingToken && _pingRequestedForConnected; + + void _clearPingDetails() { + _pingRequestedForConnected = false; + _pingInFlight = false; + _pingError = ''; + _buildVersion = ''; + _buildCommit = ''; + _serverTime = ''; + } + + String _describe(Object error) { + final text = error.toString().trim(); + return text.isEmpty ? 'unknown error' : text; + } + + void _notify() { + if (!_disposed) notifyListeners(); + } + + @override + void dispose() { + if (_disposed) return; + _disposed = true; + _pingToken++; + _subscription.cancel(); + // The shared client outlives this screen; it is deliberately not disposed. + super.dispose(); + } +} diff --git a/app/lib/features/settings/settings_controls.dart b/app/lib/features/settings/settings_controls.dart new file mode 100644 index 00000000..2c652823 --- /dev/null +++ b/app/lib/features/settings/settings_controls.dart @@ -0,0 +1,212 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'settings_layout.dart'; +import 'settings_theme.dart'; + +export 'settings_theme.dart'; + +/// A native text field with a label and one supporting line. Both platforms lay +/// the label out as wrapping text above the field; Material uses an outlined +/// [TextField] and iOS a [CupertinoTextField]. Labels and helper/error copy are +/// never line-capped, so large text cannot truncate them. No font sizes, heights +/// or colours are fixed here. +class SettingsTextField extends StatelessWidget { + const SettingsTextField({ + super.key, + required this.controller, + required this.label, + required this.placeholder, + required this.helper, + required this.onChanged, + this.error = '', + }); + + final TextEditingController controller; + final String label; + final String placeholder; + final String helper; + final ValueChanged onChanged; + final String error; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final hasError = error.trim().isNotEmpty; + // The label is laid out as normal wrapping text on both platforms. A + // Material floating label is single-line and ellipsizes the workspace label + // at narrow widths or large text, dropping required words. + final labelWidget = ExcludeSemantics( + child: Text( + label, + style: usesCupertinoControls(context) + ? settingsTextStyle(context) + : theme.textTheme.titleSmall, + ), + ); + if (!usesCupertinoControls(context)) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + labelWidget, + const SizedBox(height: settingsFieldGap), + Semantics( + label: label, + child: TextField( + controller: controller, + onChanged: onChanged, + keyboardType: TextInputType.url, + autocorrect: false, + enableSuggestions: false, + textInputAction: TextInputAction.done, + decoration: InputDecoration( + hintText: placeholder, + // `helperText`/`errorText` single-line-ellipsize unless capped + // by `helperMaxLines`/`errorMaxLines`. Widgets wrap with no line + // cap, so the full instructions stay readable at 2x. + helper: hasError + ? null + : Text( + helper, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + error: hasError + ? Text( + error, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.error, + ), + ) + : null, + border: const OutlineInputBorder(), + ), + ), + ), + ], + ); + } + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + labelWidget, + const SizedBox(height: settingsFieldGap), + Semantics( + label: label, + child: CupertinoTextField( + controller: controller, + onChanged: onChanged, + placeholder: placeholder, + keyboardType: TextInputType.url, + autocorrect: false, + enableSuggestions: false, + clearButtonMode: OverlayVisibilityMode.editing, + textInputAction: TextInputAction.done, + ), + ), + const SizedBox(height: settingsFieldGap), + Text( + hasError ? error : helper, + style: settingsTextStyle( + context, + error: hasError, + secondary: !hasError, + ), + ), + ], + ); + } +} + +/// The filled primary and outlined secondary settings actions. Buttons wrap on +/// a narrow window (or with large text) instead of overflowing. +class SettingsActions extends StatelessWidget { + const SettingsActions({ + super.key, + required this.primaryLabel, + required this.secondaryLabel, + required this.onPrimary, + required this.onSecondary, + this.primaryKey, + this.secondaryKey, + }); + + final String primaryLabel; + final String secondaryLabel; + final VoidCallback onPrimary; + final VoidCallback onSecondary; + final Key? primaryKey; + final Key? secondaryKey; + + @override + Widget build(BuildContext context) { + if (usesCupertinoControls(context)) { + return Wrap( + spacing: settingsControlGap, + runSpacing: settingsControlGap, + children: [ + CupertinoButton.filled( + key: primaryKey, + onPressed: onPrimary, + child: Text(primaryLabel), + ), + CupertinoButton( + key: secondaryKey, + onPressed: onSecondary, + child: Text(secondaryLabel), + ), + ], + ); + } + return Wrap( + spacing: settingsControlGap, + runSpacing: settingsControlGap, + children: [ + FilledButton( + key: primaryKey, + onPressed: onPrimary, + child: Text(primaryLabel), + ), + OutlinedButton( + key: secondaryKey, + onPressed: onSecondary, + child: Text(secondaryLabel), + ), + ], + ); + } +} + +/// One standard settings card: a Material [Card] or an inset-grouped Cupertino +/// section, both using theme surfaces and native corner/padding defaults. +class SettingsCard extends StatelessWidget { + const SettingsCard({super.key, required this.child}); + + final Widget child; + + @override + Widget build(BuildContext context) { + if (usesCupertinoControls(context)) { + return CupertinoListSection.insetGrouped( + margin: EdgeInsets.zero, + children: [ + SizedBox( + width: double.infinity, + child: Padding( + padding: const EdgeInsets.all(settingsCardPadding), + child: child, + ), + ), + ], + ); + } + return Card( + margin: EdgeInsets.zero, + child: Padding( + padding: const EdgeInsets.all(settingsCardPadding), + child: child, + ), + ); + } +} diff --git a/app/lib/features/settings/settings_copy.dart b/app/lib/features/settings/settings_copy.dart new file mode 100644 index 00000000..37c6c29f --- /dev/null +++ b/app/lib/features/settings/settings_copy.dart @@ -0,0 +1,113 @@ +import '../../core/transport/pipelines_client.dart' as transport; + +/// Field and explanatory copy, matching the current web Settings destination +/// (web/src/settings.js) and the Android SettingsScreen it quotes. +const String serverUrlPlaceholder = 'ws://192.168.1.20:8081/connect'; + +const String serverUrlHelper = + 'ws:// on a trusted LAN/VPN, or wss:// through a proxy/VPN. ' + 'No authentication is used.'; + +const String workspacePlaceholder = '/Users/you/repos/pipelines'; + +const String workspaceHelper = + 'An absolute directory that already exists on the execution server. For ' + 'Docker, mount the host directory at the same absolute path with its ' + "owner's UID/GID. This is not the phone's storage."; + +const String workspacePathError = + 'The workspace must be an absolute path that exists on the execution ' + 'server.'; + +const String trustTitle = 'Trusted LAN/VPN only'; + +const String trustBody = + 'The Pipelines API has no authentication and is not internet-safe. Do not ' + 'expose it to untrusted networks, and never enter provider credentials ' + 'here \u2014 the app stores none.'; + +/// The workspace draft is valid when it is untouched (empty) or absolute. A +/// relative path is the one rejected value; the execution server resolves the +/// path, so the phone's filesystem is irrelevant. +String? validateWorkspacePath(String value) { + final trimmed = value.trim(); + if (trimmed.isEmpty) return null; + if (!trimmed.startsWith('/')) return workspacePathError; + return null; +} + +/// Saving requires a real absolute path, not just "no error": the web Settings +/// page deliberately refuses a blank field and records that strictness. +bool canSaveWorkspace(String value) { + final trimmed = value.trim(); + return trimmed.isNotEmpty && validateWorkspacePath(trimmed) == null; +} + +/// The persisted workspace line. An absent value is named, never rendered as a +/// zero or an empty gap. +String savedWorkspaceLine(String value) { + final trimmed = value.trim(); + return 'Saved workspace: ${trimmed.isEmpty ? '(none)' : trimmed}'; +} + +/// The exact shared connecting sentence used by the banner and status card. +String connectingLabel(int attempt) => 'Connecting (attempt $attempt)\u2026'; + +/// `Server build {version} ({commit})`, with whichever parts the ping reported. +String serverBuildLabel({String? version, String? commit}) { + final v = (version ?? '').trim(); + final c = (commit ?? '').trim(); + final parts = [if (v.isNotEmpty) v, if (c.isNotEmpty) '($c)']; + if (parts.isEmpty) return ''; + return 'Server build ${parts.join(' ')}'; +} + +/// The pending sentence shown between `Connected` and the ping reply. It is a +/// request in flight, not a missing value. +const String serverDetailsPending = 'Loading server details\u2026'; + +/// The status card's lines in the web/Android order. While the ping is in +/// flight the card says it is loading. A completed reply names the build and +/// time, saying "unavailable" only when that reply omitted them; a failed ping +/// is one explicit line instead of two "unavailable" lines plus the error. +List connectionCardLines( + transport.ConnectionState state, { + String? buildVersion, + String? buildCommit, + String? serverTime, + String pingError = '', + bool pingInFlight = false, +}) { + switch (state.kind) { + case transport.ConnectionKind.connected: + final build = serverBuildLabel( + version: buildVersion, + commit: buildCommit, + ); + final time = (serverTime ?? '').trim(); + final failure = pingError.trim(); + if (pingInFlight && build.isEmpty && time.isEmpty && failure.isEmpty) { + return const ['Connected', serverDetailsPending]; + } + if (failure.isNotEmpty && build.isEmpty && time.isEmpty) { + return ['Connected', failure]; + } + return [ + 'Connected', + build.isEmpty ? 'Server build unavailable' : build, + time.isEmpty ? 'Server time unavailable' : 'Server time $time', + if (failure.isNotEmpty) failure, + ]; + case transport.ConnectionKind.connecting: + return [connectingLabel(state.attempt)]; + case transport.ConnectionKind.disconnected: + final reason = state.reason.trim(); + return [ + 'Disconnected', + if (reason.isNotEmpty) reason, + if (state.retrying) 'Retrying with backoff\u2026', + ]; + case transport.ConnectionKind.idle: + return const ['Not connected']; + } +} diff --git a/app/lib/features/settings/settings_keys.dart b/app/lib/features/settings/settings_keys.dart new file mode 100644 index 00000000..47575721 --- /dev/null +++ b/app/lib/features/settings/settings_keys.dart @@ -0,0 +1,12 @@ +import 'package:flutter/material.dart'; + +/// The keys the screen and its widget tests share. They name controls, not +/// dimensions or copy. +abstract final class SettingsKeys { + static const serverUrl = ValueKey('settings.serverUrl'); + static const connect = ValueKey('settings.connect'); + static const disconnect = ValueKey('settings.disconnect'); + static const reconnect = ValueKey('settings.reconnect'); + static const workspace = ValueKey('settings.workspace'); + static const saveWorkspace = ValueKey('settings.saveWorkspace'); +} diff --git a/app/lib/features/settings/settings_layout.dart b/app/lib/features/settings/settings_layout.dart new file mode 100644 index 00000000..dd9a59cf --- /dev/null +++ b/app/lib/features/settings/settings_layout.dart @@ -0,0 +1,27 @@ +/// The one place the Settings screen keeps its necessary layout constraints. +/// +/// Everything else (control heights, font sizes, colours, button padding) comes +/// from the active Material or Cupertino theme, so text scaling and platform +/// defaults are never overridden here. +library; + +/// A comfortable reading width on wide windows; the body is centred inside it. +const double settingsContentMaxWidth = 720; + +/// Space between the Settings sections. +const double settingsSectionGap = 24; + +/// Space between a section title and its controls. +const double settingsTitleGap = 12; + +/// Space between a field and its supporting text. +const double settingsFieldGap = 6; + +/// Space between wrapped action buttons. +const double settingsControlGap = 8; + +/// Padding around the page body on narrow windows. +const double settingsPagePadding = 16; + +/// Padding inside a standard Material card / Cupertino inset row. +const double settingsCardPadding = 16; diff --git a/app/lib/features/settings/settings_screen.dart b/app/lib/features/settings/settings_screen.dart new file mode 100644 index 00000000..13891ca4 --- /dev/null +++ b/app/lib/features/settings/settings_screen.dart @@ -0,0 +1,153 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../core/transport/pipelines_client.dart' as transport; +import 'default_endpoint.dart'; +import 'settings_controller.dart'; +import 'settings_controls.dart'; +import 'settings_layout.dart'; +import 'settings_sections.dart'; +import 'settings_store.dart'; + +/// The Settings destination: the server connection and the server-side +/// workspace, in native Material (native platforms) or Cupertino (iOS) controls. +/// +/// The shared [transport.PipelinesClient] is supplied by the shell. This screen +/// subscribes to it, connects/disconnects it and pings it on connected, but it +/// never opens a connection on its own and never disposes the client. One +/// controller is created in [initState], so rebuilding the screen cannot start +/// a second connection. +class SettingsScreen extends StatefulWidget { + const SettingsScreen({ + super.key, + required this.client, + this.initialEndpoint, + this.store, + this.ping, + this.embedded = false, + }); + + final transport.PipelinesClient client; + + /// A fixture/preview seed for the URL field. Persisted settings still load; + /// this value takes precedence for the draft and is never written by itself. + final Uri? initialEndpoint; + + /// The feature's own persistence. Defaults to the `pipelines.next` keys. + final SettingsStore? store; + + /// Test seam for the exact ping request. Production uses `client.call('ping')`. + final PingCallback? ping; + + /// The application shell already owns the native navigation bar and safe area. + final bool embedded; + + @override + State createState() => _SettingsScreenState(); +} + +class _SettingsScreenState extends State { + final TextEditingController _serverUrlField = TextEditingController(); + final TextEditingController _workspaceField = TextEditingController(); + late final SettingsController _controller; + + @override + void initState() { + super.initState(); + _controller = SettingsController( + client: widget.client, + store: widget.store ?? const SharedPreferencesSettingsStore(), + initialEndpoint: widget.initialEndpoint, + defaultEndpoint: defaultServerUrl(), + ping: widget.ping, + ); + _controller.addListener(_onSettingsChanged); + unawaited(_controller.initialize()); + } + + void _onSettingsChanged() { + if (!mounted) return; + _syncField(_serverUrlField, _controller.serverUrl); + _syncField(_workspaceField, _controller.workspaceDraft); + setState(() {}); + } + + /// Follow the controller's value (a restored value or the normalised URL) + /// without disturbing a field the operator is already typing in. + void _syncField(TextEditingController field, String value) { + if (field.text == value) return; + field.value = TextEditingValue( + text: value, + selection: TextSelection.collapsed(offset: value.length), + ); + } + + @override + void dispose() { + _controller.removeListener(_onSettingsChanged); + _controller.dispose(); + _serverUrlField.dispose(); + _workspaceField.dispose(); + // The shared client is owned by the shell and deliberately outlives this + // screen, so it is not disposed here. + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final content = SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.all(settingsPagePadding), + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints( + maxWidth: settingsContentMaxWidth, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const _SectionTitle('Connection'), + const SizedBox(height: settingsTitleGap), + SettingsConnectionSection( + controller: _controller, + serverUrlField: _serverUrlField, + ), + const SizedBox(height: settingsSectionGap), + const _SectionTitle('Workspace'), + const SizedBox(height: settingsTitleGap), + SettingsWorkspaceSection( + controller: _controller, + workspaceField: _workspaceField, + ), + ], + ), + ), + ), + ), + ); + if (widget.embedded) return content; + if (usesCupertinoControls(context)) { + return CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar(middle: Text('Settings')), + child: content, + ); + } + return Scaffold( + appBar: AppBar(title: const Text('Settings')), + body: content, + ); + } +} + +class _SectionTitle extends StatelessWidget { + const _SectionTitle(this.title); + + final String title; + + @override + Widget build(BuildContext context) { + return Text(title, style: settingsTextStyle(context, title: true)); + } +} diff --git a/app/lib/features/settings/settings_sections.dart b/app/lib/features/settings/settings_sections.dart new file mode 100644 index 00000000..4bf9581f --- /dev/null +++ b/app/lib/features/settings/settings_sections.dart @@ -0,0 +1,200 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../core/transport/pipelines_client.dart' as transport; +import 'settings_controller.dart'; +import 'settings_controls.dart'; +import 'settings_copy.dart'; +import 'settings_keys.dart'; +import 'settings_trust_warning.dart'; +import 'settings_layout.dart'; + +/// Connection controls: the editable endpoint, the truthful connection card and +/// the trusted-network warning. Every action goes through the shared client the +/// controller was given; nothing here opens a second connection. +class SettingsConnectionSection extends StatelessWidget { + const SettingsConnectionSection({ + super.key, + required this.controller, + required this.serverUrlField, + }); + + final SettingsController controller; + final TextEditingController serverUrlField; + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SettingsTextField( + controller: serverUrlField, + key: SettingsKeys.serverUrl, + label: 'Server URL', + placeholder: serverUrlPlaceholder, + helper: serverUrlHelper, + error: controller.urlError, + onChanged: controller.updateServerUrl, + ), + const SizedBox(height: settingsTitleGap), + SettingsActions( + primaryLabel: controller.primaryActionLabel, + secondaryLabel: controller.secondaryActionLabel, + primaryKey: controller.connectionActive + ? SettingsKeys.disconnect + : SettingsKeys.connect, + secondaryKey: controller.connectionActive + ? SettingsKeys.connect + : SettingsKeys.reconnect, + onPrimary: () => unawaited( + controller.connectionActive + ? controller.disconnect() + : controller.connect(), + ), + onSecondary: () => unawaited( + controller.connectionActive + ? controller.connect() + : controller.reconnect(), + ), + ), + if (controller.endpointSaveError.isNotEmpty) ...[ + const SizedBox(height: settingsFieldGap), + Text( + controller.endpointSaveError, + style: settingsTextStyle(context, error: true), + ), + ], + if (controller.actionError.isNotEmpty) ...[ + const SizedBox(height: settingsFieldGap), + Text( + controller.actionError, + style: settingsTextStyle(context, error: true), + ), + ], + const SizedBox(height: settingsTitleGap), + SettingsStatusCard(controller: controller), + const SizedBox(height: settingsTitleGap), + const SettingsTrustWarning(), + ], + ); + } +} + +/// The status card's first line is the state; the remaining lines are the +/// build/time/reason/backoff facts. Missing ping values stay explicit. +class SettingsStatusCard extends StatelessWidget { + const SettingsStatusCard({super.key, required this.controller}); + + final SettingsController controller; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final state = controller.connection; + final lines = controller.connectionLines; + final title = lines.isEmpty ? '' : lines.first; + final details = lines.length > 1 ? lines.sublist(1) : const []; + final titleColor = switch (state.kind) { + transport.ConnectionKind.connected => + usesCupertinoControls(context) + ? CupertinoTheme.of(context).primaryColor + : theme.colorScheme.primary, + transport.ConnectionKind.disconnected => settingsErrorColor(context), + _ => settingsTextStyle(context).color, + }; + final titleWidget = Text( + title, + style: settingsTextStyle( + context, + title: true, + ).copyWith(color: titleColor), + ); + return SettingsCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (state.kind == transport.ConnectionKind.connecting) + Row( + children: [ + if (usesCupertinoControls(context)) + const CupertinoActivityIndicator() + else + const CircularProgressIndicator(strokeWidth: 2), + const SizedBox(width: settingsControlGap), + Expanded(child: titleWidget), + ], + ) + else + titleWidget, + for (final line in details) ...[ + const SizedBox(height: settingsFieldGap), + Text(line, style: settingsTextStyle(context, secondary: true)), + ], + ], + ), + ); + } +} + +/// Workspace controls. The path is resolved by the execution server, and the +/// helper says so explicitly; an empty saved value is named "(none)". +class SettingsWorkspaceSection extends StatelessWidget { + const SettingsWorkspaceSection({ + super.key, + required this.controller, + required this.workspaceField, + }); + + final SettingsController controller; + final TextEditingController workspaceField; + + @override + Widget build(BuildContext context) { + final saveError = controller.workspaceSaveError; + final canSave = canSaveWorkspace(controller.workspaceDraft); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SettingsTextField( + controller: workspaceField, + key: SettingsKeys.workspace, + label: 'Workspace path (on the server)', + placeholder: workspacePlaceholder, + helper: workspaceHelper, + error: controller.workspaceError, + onChanged: controller.updateWorkspace, + ), + const SizedBox(height: settingsTitleGap), + Align( + alignment: AlignmentDirectional.centerStart, + child: usesCupertinoControls(context) + ? CupertinoButton.filled( + key: SettingsKeys.saveWorkspace, + onPressed: canSave + ? () => unawaited(controller.saveWorkspace()) + : null, + child: const Text('Save workspace'), + ) + : FilledButton( + key: SettingsKeys.saveWorkspace, + onPressed: canSave + ? () => unawaited(controller.saveWorkspace()) + : null, + child: const Text('Save workspace'), + ), + ), + const SizedBox(height: settingsFieldGap), + Text( + savedWorkspaceLine(controller.savedWorkspace), + style: settingsTextStyle(context), + ), + if (saveError.isNotEmpty) ...[ + const SizedBox(height: settingsFieldGap), + Text(saveError, style: settingsTextStyle(context, error: true)), + ], + ], + ); + } +} diff --git a/app/lib/features/settings/settings_store.dart b/app/lib/features/settings/settings_store.dart new file mode 100644 index 00000000..84f2562e --- /dev/null +++ b/app/lib/features/settings/settings_store.dart @@ -0,0 +1,107 @@ +import 'package:shared_preferences/shared_preferences.dart'; + +/// The app's own settings keys. They are deliberately independent of the legacy +/// web/Android storage: no value is imported, migrated or written under an old +/// key, and nothing but the endpoint and the server workspace is persisted. +const String settingsServerUrlKey = 'pipelines.next.serverUrl.v1'; +const String settingsWorkspaceKey = 'pipelines.next.workspace.v1'; + +/// The persisted settings, read as a pair. Both values are trimmed strings; an +/// absent or unreadable value is empty rather than an error. +class SettingsValues { + const SettingsValues({this.serverUrl = '', this.workspace = ''}); + + final String serverUrl; + final String workspace; +} + +/// The persistence seam used by the screen and its tests. Saves report whether +/// the value is actually stored, so the UI never claims a save that failed. +abstract interface class SettingsStore { + Future load(); + + Future saveServerUrl(String value); + + Future saveWorkspace(String value); +} + +/// `shared_preferences`-backed storage under the `pipelines.next` keys. +/// +/// Reads are tolerant (an unavailable store means "nothing saved yet"). Saves +/// return false instead of throwing, letting the screen keep the in-memory +/// value while saying plainly that it was not stored. +class SharedPreferencesSettingsStore implements SettingsStore { + const SharedPreferencesSettingsStore(); + + Future _preferences() async { + try { + return await SharedPreferences.getInstance(); + } catch (_) { + return null; + } + } + + @override + Future load() async { + final preferences = await _preferences(); + if (preferences == null) return const SettingsValues(); + try { + return SettingsValues( + serverUrl: preferences.getString(settingsServerUrlKey) ?? '', + workspace: preferences.getString(settingsWorkspaceKey) ?? '', + ); + } catch (_) { + return const SettingsValues(); + } + } + + @override + Future saveServerUrl(String value) async { + final preferences = await _preferences(); + if (preferences == null) return false; + try { + return await preferences.setString(settingsServerUrlKey, value.trim()); + } catch (_) { + return false; + } + } + + @override + Future saveWorkspace(String value) async { + final preferences = await _preferences(); + if (preferences == null) return false; + try { + return await preferences.setString(settingsWorkspaceKey, value.trim()); + } catch (_) { + return false; + } + } +} + +/// An in-memory store for previews and tests. It never touches the platform +/// store, so no production preference can be mutated by a fixture. +class MemorySettingsStore implements SettingsStore { + MemorySettingsStore({this.serverUrl = '', this.workspace = ''}); + + String serverUrl; + String workspace; + bool failSaves = false; + + @override + Future load() async => + SettingsValues(serverUrl: serverUrl, workspace: workspace); + + @override + Future saveServerUrl(String value) async { + if (failSaves) return false; + serverUrl = value.trim(); + return true; + } + + @override + Future saveWorkspace(String value) async { + if (failSaves) return false; + workspace = value.trim(); + return true; + } +} diff --git a/app/lib/features/settings/settings_theme.dart b/app/lib/features/settings/settings_theme.dart new file mode 100644 index 00000000..75868479 --- /dev/null +++ b/app/lib/features/settings/settings_theme.dart @@ -0,0 +1,42 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../ui/adaptive/host.dart'; + +bool usesCupertinoControls(BuildContext context) => + usesCupertinoHost(context) || + Theme.of(context).platform == TargetPlatform.iOS; + +Color settingsErrorColor(BuildContext context) => usesCupertinoControls(context) + ? CupertinoColors.destructiveRed.resolveFrom(context) + : Theme.of(context).colorScheme.error; + +/// Resolve native text roles from the actual host, not Material's fallback +/// light theme when mounted under a dark CupertinoApp. +TextStyle settingsTextStyle( + BuildContext context, { + bool title = false, + bool secondary = false, + bool error = false, +}) { + if (usesCupertinoControls(context)) { + final text = CupertinoTheme.of(context).textTheme; + return (title ? text.navTitleTextStyle : text.textStyle).copyWith( + color: error + ? settingsErrorColor(context) + : (secondary ? CupertinoColors.secondaryLabel : CupertinoColors.label) + .resolveFrom(context), + ); + } + final theme = Theme.of(context); + final base = (title + ? theme.textTheme.titleMedium + : theme.textTheme.bodyMedium)!; + return base.copyWith( + color: error + ? theme.colorScheme.error + : secondary + ? theme.colorScheme.onSurfaceVariant + : base.color, + ); +} diff --git a/app/lib/features/settings/settings_trust_warning.dart b/app/lib/features/settings/settings_trust_warning.dart new file mode 100644 index 00000000..9f6fe116 --- /dev/null +++ b/app/lib/features/settings/settings_trust_warning.dart @@ -0,0 +1,44 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'settings_controls.dart'; +import 'settings_copy.dart'; +import 'settings_layout.dart'; + +/// The trusted-network warning, using the app's exact web/Android copy. It is a +/// card, not a dialog: no confirmation is required to read it. +class SettingsTrustWarning extends StatelessWidget { + const SettingsTrustWarning({super.key}); + + @override + Widget build(BuildContext context) { + final icon = usesCupertinoControls(context) + ? CupertinoIcons.exclamationmark_triangle + : Icons.warning_amber_rounded; + return SettingsCard( + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(icon, color: settingsErrorColor(context)), + const SizedBox(width: settingsControlGap), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + trustTitle, + style: settingsTextStyle(context, title: true, error: true), + ), + const SizedBox(height: settingsFieldGap), + Text( + trustBody, + style: settingsTextStyle(context, secondary: true), + ), + ], + ), + ), + ], + ), + ); + } +} diff --git a/app/lib/features/templates/data/template_repository.dart b/app/lib/features/templates/data/template_repository.dart new file mode 100644 index 00000000..da56f5ea --- /dev/null +++ b/app/lib/features/templates/data/template_repository.dart @@ -0,0 +1,84 @@ +import '../../../core/api_gateway.dart'; +import '../domain/template_entry.dart'; + +/// A templates protocol refusal kept separate from transport errors; server +/// error envelopes are propagated unchanged by [ApiGateway]. +class TemplateRepositoryException implements Exception { + const TemplateRepositoryException(this.message); + final String message; + @override + String toString() => message; +} + +/// Template catalogue, definition validation and create-only submission over +/// the application's shared gateway. +/// +/// These are reads plus one explicit submit. No method publishes, runs, +/// overwrites or schedules a pipeline, so merely loading or validating a +/// template can never start work. +class TemplateRepository { + TemplateRepository(this._gateway); + final ApiGateway _gateway; + + /// The server's template catalogue, exactly as `list_templates` returns it. + /// A reply without a `templates` field is the older server answering with no + /// catalogue, which is an empty list rather than an error. + Future> listTemplates() async { + final reply = await _gateway.call('list_templates'); + final templates = reply['templates']; + if (templates == null) return const []; + if (templates is! List) { + throw const TemplateRepositoryException( + 'The server returned no template catalogue.', + ); + } + return List.unmodifiable( + templates.map((entry) { + if (entry is! Map) { + throw const TemplateRepositoryException( + 'The server returned a template that is not an object.', + ); + } + return TemplateEntry.fromJson(Map.from(entry)); + }), + ); + } + + /// Parses one definition source on the server (`validate`) and returns the + /// graph it produced. The source is sent byte-for-byte: no trimming, casing or + /// whitespace changes. A malformed definition rejects with the server's own + /// error; a reply without a graph is refused rather than reported as valid. + Future validate(String source) async { + final reply = await _gateway.call('validate', {'source': source}); + final graph = reply['graph']; + if (graph is! Map) { + throw const TemplateRepositoryException('The server returned no graph.'); + } + return Map.from(graph); + } + + /// Creates a new draft pipeline from [source] (`submit`), create-only. + /// + /// A blank name is refused locally before anything is sent, matching the + /// browser and Android clients; the name that is sent is trimmed. The source + /// is not changed. `create_only` is always true, so an existing pipeline can + /// never be overwritten, and no run is started. + Future submit(String name, String source) async { + final trimmed = name.trim(); + if (trimmed.isEmpty) { + throw const TemplateRepositoryException('Enter a pipeline name.'); + } + final reply = await _gateway.call('submit', { + 'name': trimmed, + 'source': source, + 'create_only': true, + }); + final detail = reply['detail']; + if (detail is! Map) { + throw const TemplateRepositoryException( + 'The server returned no pipeline detail.', + ); + } + return Map.from(detail); + } +} diff --git a/app/lib/features/templates/domain/template_entry.dart b/app/lib/features/templates/domain/template_entry.dart new file mode 100644 index 00000000..6c86bcbf --- /dev/null +++ b/app/lib/features/templates/domain/template_entry.dart @@ -0,0 +1,63 @@ +import '../../../core/api_gateway.dart'; + +/// One template from the server catalogue. +/// +/// The server owns this record: [key], [name], [description], [source] and +/// [scheduled] are read from it verbatim and every other field is kept in +/// [raw], so a later view or round-trip never loses fields this client does not +/// understand yet. Loading a template is a read; it never publishes or runs it. +class TemplateEntry { + const TemplateEntry({ + required this.key, + required this.name, + required this.description, + required this.source, + required this.scheduled, + required this.raw, + }); + + factory TemplateEntry.fromJson(JsonMap json) { + final raw = _frozenMap(json); + return TemplateEntry( + key: _text(raw['key']), + name: _text(raw['name']), + description: _text(raw['description']), + source: _text(raw['source']), + scheduled: raw['scheduled'] == true, + raw: raw, + ); + } + + /// The stable catalogue key the gallery selects on. + final String key; + final String name; + final String description; + + /// The template's complete, untrimmed definition source. + final String source; + + /// Whether the source declares a schedule (the summary's "Includes a schedule"). + final bool scheduled; + + /// Every field the server sent, including fields this client does not model. + /// Deeply unmodifiable: nested maps and lists are copied into read-only + /// collections too, so a view cannot mutate the server reply through it. + final JsonMap raw; + + static String _text(dynamic value) => value == null ? '' : '$value'; + + static JsonMap _frozenMap(Map json) => + Map.unmodifiable( + json.map((key, value) => MapEntry(key, _frozen(value))), + ); + + static dynamic _frozen(dynamic value) { + if (value is Map) { + return _frozenMap(Map.from(value)); + } + if (value is List) { + return List.unmodifiable(value.map(_frozen)); + } + return value; + } +} diff --git a/app/lib/main.dart b/app/lib/main.dart index 244a702c..ef65859c 100644 --- a/app/lib/main.dart +++ b/app/lib/main.dart @@ -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 createState() => _MyHomePageState(); -} - -class _MyHomePageState extends State { - 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(); diff --git a/app/lib/shell/adaptive_shell.dart b/app/lib/shell/adaptive_shell.dart new file mode 100644 index 00000000..1300769c --- /dev/null +++ b/app/lib/shell/adaptive_shell.dart @@ -0,0 +1,145 @@ +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 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? onDestinationSelected; + + @override + State createState() => _AdaptiveShellState(); +} + +class _AdaptiveShellState extends State { + late AppDestination _selected; + final Set _visited = {}; + + @override + void initState() { + super.initState(); + _selected = widget.destination ?? AppDestination.pipelines; + _visited.add(_selected); + } + + @override + void didUpdateWidget(covariant AdaptiveShell oldWidget) { + super.didUpdateWidget(oldWidget); + final destination = widget.destination; + if (destination != null) { + _selected = destination; + _visited.add(destination); + } + } + + void _select(AppDestination destination) { + final callback = widget.onDestinationSelected; + if (callback != null) { + callback(destination); + return; + } + setState(() { + _selected = destination; + _visited.add(destination); + }); + } + + List _items(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: _visited.contains(destination) + ? widget.destinationBodies[destination]?.call(context) ?? + Center(child: Text('${item.label} — Not implemented')) + : const SizedBox.shrink(), + ); + }).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 contents, int index) => + IndexedStack(index: index, children: contents); +} diff --git a/app/lib/shell/destination.dart b/app/lib/shell/destination.dart new file mode 100644 index 00000000..932bc92c --- /dev/null +++ b/app/lib/shell/destination.dart @@ -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, + ), +}; diff --git a/app/lib/ui/adaptive/host.dart b/app/lib/ui/adaptive/host.dart new file mode 100644 index 00000000..80f68825 --- /dev/null +++ b/app/lib/ui/adaptive/host.dart @@ -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(context, MaterialLocalizations) == + null; diff --git a/app/notes/A1-list.md b/app/notes/A1-list.md new file mode 100644 index 00000000..0c51c8f3 --- /dev/null +++ b/app/notes/A1-list.md @@ -0,0 +1,150 @@ +# A1-list — read-only artifact visit list with selection + +## What changed + +All files are 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, url, preview, share, +download, filter or gallery code was written. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/artifacts/ui/artifact_visit_list.dart` | 231 | One public read-only widget, its selection callback, and the visit-scoped identity helper | +| `test/features/artifacts/ui/artifact_visit_list_fixture.dart` | 85 | Shared recorded fixtures and the native host composition used by the tests | +| `test/features/artifacts/ui/artifact_visit_list_test.dart` | 230 | Identity, Material/Cupertino rows, duplicate filename selection, 2x wrapping, honest fallbacks, empty wording | +| `test/features/artifacts/ui/artifact_visit_list_semantics_test.dart` | 165 | Header semantics, heading/row separation, read-only rows, selected state | +| `tool/artifact_list_probe.dart` | 194 | Isolated fixture entry for browser captures; never changes `main.dart` or the shell | + +## API + +```dart +typedef ArtifactSelected = + void Function(ArtifactGroup group, ArtifactRecord artifact); + +String artifactVisitIdentity(ArtifactGroup group, ArtifactRecord artifact); + +ArtifactVisitList({ + required List groups, + String? selectedIdentity, + ArtifactSelected? onSelected, +}) +``` + +`artifactVisitIdentity` combines the recorded stage key, the group's recorded +display visit and the record's recorded url (or its name when no url was +recorded). A filename alone is never an identity, so `result.csv` from visit 1 +and visit 2 remain distinct even when both records carry the same url. The +callback returns the exact `ArtifactGroup` and `ArtifactRecord` that was tapped. + +## Behaviour + +- Each group heading is the web client's vocabulary: `stage · visit N`, taken + from the existing `ArtifactGroup` (`displayVisit` already owns the number). +- Each row shows the recorded filename, the recorded MIME (parameters trimmed) + and the recorded size via the existing `humanBytes`. An empty name renders + `(unnamed artifact)` and an empty content type renders `type not recorded`; + nothing is inferred from the extension, and no url is displayed or resolved. +- The size value and unit are joined by a non-breaking space, so `120.6 KiB` + never splits across lines at narrow widths. +- Material hosts get `ListTile` rows (title = name, subtitle = facts); Cupertino + hosts get `CupertinoListSection.insetGrouped` with a native `CupertinoButton` + row so the name can wrap (the stock `CupertinoListTile` title is forced to one + line). Name uses the theme text style and facts use the platform + `secondaryLabel` colour, so the recorded name leads the hierarchy. No custom + font, palette or fixed row/button dimensions are declared; rows grow with + content and text scale. +- Cupertino rows set `hasLeading: false`, so the inter-row divider aligns with + the text instead of an absent leading column. +- Both hosts expose every group heading as its own header semantics node, and + every Cupertino row as its own node. A heading can neither be read as part of + a row nor activate one (see the regression tests). +- A row without `onSelected` is read-only: Material has no tap action, and the + Cupertino row is a plain padded row rather than a disabled `CupertinoButton` + (which still exposes a button role). It never renders as a button; the + semantics regression asserts both no tap action and no button role. +- Empty input says `No stage artifacts recorded.`, the web client's wording. +- The only action is `onSelected`. No capture/visit facts are invented or masked. + +## Fixes from UI review visit 1 + +1. **Cupertino heading semantics.** `CupertinoListSection` does not create + semantics for its header. The header is now wrapped in + `Semantics(container: true, header: true, …)` and each Cupertino row is its + own `Semantics(container: true, …)` node. Browser check: three + `

` nodes now exist, the `review · visit 2` heading rect is + `[20, 482.5, 118.2, 23]` and its row `[20, 511.5, 350, 72]`; the row label is + `result.csv / text/csv · 4.0 KiB` without the heading. Clicking the heading + centre leaves the selection at `Selected: none`. +2. **Cupertino grouped background seam.** The probe composition now sets + `CupertinoPageScaffold(backgroundColor: CupertinoColors.systemGroupedBackground)`. + At logical x=10 the whole 390×844 viewport is uniformly `rgb(242,242,247)` + in light mode, before and after selection; no white band below the last + section. **Requirement for the future gallery:** the composing page must set + the same background, or paint the grouped background behind the list. + +Advisories from both earlier reviews were addressed where they touch this +slice: dangling `selectedIdentity` doc link, divider inset, name/metadata +hierarchy, value/unit wrapping and read-only rows. Unit coverage now uses a +record the server actually sent without a url, so the identity fallback to the +recorded name is exercised directly, alongside the unnamed and +missing-content-type fallbacks. The 2x wrap regression asserts a multi-line +height rather than a single-line threshold. + +## Real browser evidence + +Built with `flutter build web -t tool/artifact_list_probe.dart` and driven in an +isolated headless Chrome (Chrome 155, DevTools protocol, `prefers-color-scheme: +light`, 390×844 at DPR 2) against a loopback static server on an OS-assigned +port. No production server, no real run data. The probe fixture contains two +same-named `result.csv` records in different visits. + +- Initial: `Selected: none`; three heading nodes `build · visit 1`, + `review · visit 1`, `review · visit 2`. +- Heading `review · visit 2` clicked: status stays `Selected: none`; no + `aria-current` row. +- Row `review · visit 2` clicked: `Selected: review · visit 2 · result.csv`; + only that row has `aria-current="true"`. +- Material host still exposes three `

` headings and the same four rows. + +Shared evidence: + +- `/Users/alan/.local/share/pipelines/data/artifacts/65/public/a1-code-cupertino-390-initial.png` +- `/Users/alan/.local/share/pipelines/data/artifacts/65/public/a1-code-cupertino-390-visit2.png` +- `/Users/alan/.local/share/pipelines/data/artifacts/65/public/a1-code-material-390.png` +- `/Users/alan/.local/share/pipelines/data/artifacts/65/public/a1-code-manifest.json` + +The capture driver is stage-private (`04-Code/private/capture_a1_fix.mjs`); +Chrome and its temporary profile were removed after the run. + +## Checks actually run + +On the branch after merging `main` (fast-forward, no conflicts): + +``` +flutter test test/features/artifacts/ui # 11 passed +flutter test test/features/artifacts # 71 passed +flutter test # 524 passed (whole app) +flutter analyze # No issues found! (1.4s) +dart format --set-exit-if-changed # 5 files, 0 changed +flutter build web -t tool/artifact_list_probe.dart # ✓ Built build/web (15.9s) +``` + +`git status --short --untracked-files=all` lists only the six new files above; +`pubspec.yaml`/`pubspec.lock` are unchanged. The branch merges current `main` +with no conflicts and nothing is pushed or deployed. + +## Honest limits + +- No gallery screen, shell registration, preview, viewer, share or download is + part of this slice; the widget is ready for the manager to compose. +- The list is scrollable and requires bounded height (a `ListView`); composition + into the run detail is a later slice. The gallery must supply the grouped page + background noted above. +- The browser pass covered Cupertino light 390 (initial and visit 2) and a + Material heading/row check; large-text Cupertino and dark-mode recaptures were + not repeated this visit. The 2x wrapping regression runs in the widget tests. + Full rendered acceptance belongs to the UI review stage. +- Mobile is unverified: only web was built and captured; no Android/iOS build, + emulator, ADB or device was used. +- Handed to landing: committed on `flutter/a1-visit-list` after merging `main`; + the manager owns integration into `main` and delivery. diff --git a/app/notes/A1a.md b/app/notes/A1a.md new file mode 100644 index 00000000..2d5802e1 --- /dev/null +++ b/app/notes/A1a.md @@ -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. diff --git a/app/notes/C1.md b/app/notes/C1.md new file mode 100644 index 00000000..8a4736f1 --- /dev/null +++ b/app/notes/C1.md @@ -0,0 +1,5 @@ +# C1 — Chat sessions and repository adapter + +The sessions browser now requests server directory and backend catalogs before showing the create dialog, exposes both selectors and model-default guidance, and reports unavailable catalog capabilities instead of silently substituting values. Catalog envelope regressions are covered. Closed starred rows no longer appear twice; directory headings appear only when grouping multiple directories; empty and search-no-match states are distinct. + +Verification: focused chat tests, `flutter analyze`, fixture `flutter build web -t tool/chat_sessions_probe_entry.dart`, `git diff --check`, and an isolated Chrome DevTools probe passed. Captures: `/private/var/folders/jp/q0qvjyg54fl_c5vhhk1ylz2m0000gn/T/opencode/chat-sessions-capture/chat-sessions-phone.png` and `chat-sessions-create-dialog.png` (plus desktop). The probe enabled semantics, matched the exact “New chat” label, and verified the rendered body changed to show server catalog controls. Cupertino-specific controls, controller/row/dialog decomposition under 250 lines, and wider out-of-order reply UI regression coverage remain incomplete; this is not a parity-complete delivery. Mobile builds were not performed. The fixture entry point is `tool/chat_sessions_probe_entry.dart`. diff --git a/app/notes/C1b.md b/app/notes/C1b.md new file mode 100644 index 00000000..cd1d56c3 --- /dev/null +++ b/app/notes/C1b.md @@ -0,0 +1,163 @@ +# C1b — Chat session browser completion + +The 406-line sessions screen is split into a controller, adaptive primitives, +session groups/rows, action dialogs, a rename dialog and a create dialog. The +server directory and backend catalogs, the instructions field, the closed/star +grouping and the distinct empty/no-match states are retained. No repository, +domain, shell or pubspec file changed. + +The UI review's must-fix is addressed: Cupertino no-match, empty and error +messages are no longer forced through `CupertinoListTile`'s one-line title. They +use a wrapping grouped card with `Clear search`/`Retry` as separate buttons. The +same turn also fixed the related behavioural findings: a failed initial load no +longer also shows the empty-server message, creating a chat opens it without +waiting for the list refresh, blank rename disables Save, and row action labels +name their session (adding the id when titles repeat). + +The second UI review's must-fixes are also addressed: + +- `ChatCupertinoMessage` now sets `DefaultTextStyle.merge` from + `CupertinoTheme.of(context).textTheme.textStyle`. Mounted under a bare + `MaterialApp` (the screen's iOS/macOS path, no `Material` ancestor), its text + previously inherited MaterialApp's intentional "missing Material" fallback + style (48px red monospace with a double yellow underline). The card now + renders as ordinary Cupertino body text in that configuration. +- The Material rename dialog sets `helperMaxLines: 2`, so "This name is shared + with every device." wraps instead of being ellipsised at 2.0x text scale. + +## Source layout + +All paths under `lib/features/chat/ui/sessions/` (1,584 lines total): + +| File | Lines | Responsibility | +| --- | ---: | --- | +| `chat_sessions_screen.dart` | 176 | Screen composition, toolbar/FAB, controller wiring | +| `chat_sessions_controller.dart` | 111 | List state, generation-guarded refresh, row actions, create | +| `chat_sessions_body.dart` | 97 | Filtering, starred/open/closed sections, duplicate titles | +| `session_list_material.dart` | 140 | Material list sections and rows | +| `session_list_cupertino.dart` | 134 | Cupertino list sections and rows | +| `session_row_style.dart` | 51 | Shared subtitle, icons and action labels | +| `session_actions.dart` | 161 | Star control, actions menu/sheet, close confirmation | +| `rename_chat_dialog.dart` | 107 | Rename dialog and its blank-name guard | +| `create_chat_dialog.dart` | 222 | Create state, draft fields, submit | +| `chat_create_fields.dart` | 185 | Catalog loading/error/retry and directory/backend pickers | +| `chat_adaptive.dart` | 200 | Style detection, bar actions, search, wrapping message card, loading | + +`chatControlsStyleOf` chooses Cupertino for a Cupertino app (no `MaterialApp` +ancestor) and for iOS/macOS Material themes; Material otherwise. The Cupertino +branch uses only Cupertino controls (`CupertinoPageScaffold`, +`CupertinoNavigationBar`, `CupertinoSearchTextField`, `CupertinoListSection`/ +`CupertinoListTile`, `CupertinoAlertDialog`, `CupertinoActionSheet`, +`CupertinoTextField`, `CupertinoActivityIndicator`). It therefore has no +Material ancestor dependency. The `SafeArea` in that branch keeps the search +field below the translucent navigation bar (the first browser capture caught +this overlap). + +Behavior: + +- `chat_sessions`, `chat_directories`, `chat_backends` and `chat_create` use the + existing repository envelopes; no fallback directory or backend is invented. +- A catalog failure keeps the dialog open, shows the server reason with Retry, + and retains the typed name and instructions. +- Closed starred rows appear once, only under Closed. +- Directory headings appear only when a section has more than one directory. +- Empty and search-no-match states stay distinct; "Clear search" restores the + list. In the Cupertino branch the message and its action are a wrapping + `ChatCupertinoMessage` card, and a failed load uses the same card for the + server reason with Retry. The failed initial load no longer also renders the + empty-server message. The card supplies a Cupertino text style, so it renders + normally when the Cupertino branch is mounted under the app's bare + `MaterialApp` root instead of a `Material`/`CupertinoApp`. +- Creating a chat opens it as soon as `chat_create` replies; the list refresh + continues in the background, so a slow listing cannot look like a failed + create. +- Star, rename, close (with the web's confirmation wording), reopen and row + opening keep their existing request shapes. Save is disabled while the + rename name is blank, matching the web dialog. +- Row action labels are `Chat actions for {title}`, adding `({id})` when two + visible sessions share a title, matching the web's accessible label. + +## Checks (actual) + +- `flutter test test/features/chat/ui/sessions`: 24 widget tests, all passed. + They cover Material and Cupertino list branches, both create branches, the + delayed catalog failure with draft retention and Retry, rename/close/reopen/ + star, blank-name Save disabling in both branches, the close confirmation, + catalog-empty state, stale refresh ordering, dispose while a reply is + pending, opening a created chat before the refresh completes, Cupertino + no-match/error wrapping (including 2x text scale), separate Clear search + semantics, duplicate-title action labels, the Cupertino message card under a + bare `MaterialApp` iOS theme (empty, no-match, long error style), and the + Material rename helper at 2x text scale. The three MaterialApp-hosted tests + fail when the `DefaultTextStyle` merge is removed (verified). +- `flutter test`: 46 tests passed. +- `flutter analyze`: no issues. +- `flutter build web`: built `lib/main.dart` successfully. +- Fixture probe built for both variants and run in real headless Chrome through + the local loopback server in `tool/chat_sessions_probe.mjs`. Each run loaded + the list, opened the create dialog, confirmed the rendered catalog controls, + opened a row action menu/sheet, and captured PNGs. The probe now clicks the + per-session action label and requires `Rename…` in the action labels instead + of accepting the dismiss barrier. Material and Cupertino PNGs were inspected. + +Captures from this turn's fix (shared with later stages under +`public/c1b-fix/`): + +- `/Users/alan/.local/share/pipelines/data/artifacts/42/public/c1b-fix/cupertino-fix-search-no-match.png` — light, 390x844, long query wraps in full with Clear search on its own line. +- `.../cupertino-fix-search-no-match-dark.png` — same state in dark appearance. +- `.../cupertino-fix-load-error.png` — long server reason wraps; Retry is separate and the empty-server message is absent. +- `.../cupertino-fix-list-phone.png` and `.../material-fix-actions.png` — probe list and actions after the label change. + +Probe commands (run from `app/`): + +```sh +flutter build web -t tool/chat_sessions_probe_entry.dart \ + --dart-define=CHAT_PROBE_STYLE=material --output build/probe-material-fix +PROBE_WEB_ROOT="$PWD/build/probe-material-fix" PROBE_VARIANT=material \ + OPENCODE_ARTIFACT_DIR=/private/var/folders/jp/q0qvjyg54fl_c5vhhk1ylz2m0000gn/T/opencode/chat-sessions-capture \ + node tool/chat_sessions_probe.mjs +# repeat with CHAT_PROBE_STYLE=cupertino and build/probe-cupertino-fix +``` + +Captures for the second review's fixes (same `public/c1b-fix/` folder, real +headless Chrome at 390x844 through a temporary fixture entry that was deleted +afterwards; the shipped probe entry was not changed): + +- `platform-default-empty-phone.png` — `MaterialApp` default theme (macOS → + Cupertino branch), empty server. The message is ordinary body text. +- `platform-default-search-no-match-phone.png` — long query; message wraps and + `Clear search` is a separate control. +- `platform-default-error-phone.png` — long server reason wraps; `Retry` is + separate and no empty-server message appears. +- `material-scale2-rename-phone.png` — Material rename dialog at 2.0x text + scale; the helper sentence wraps onto two lines in full. + +## Not changed in this turn + +These review notes remain advisory and were left alone because they predate +C1b or are native behaviour: + +- The Material FAB can still cover the last row's star/actions when the list + exactly fills a phone viewport. Same as the base screen. +- Raw exception text (`Bad state: …`, `Exception: …`) is still shown to the + operator; wording belongs to a separate error-presentation change. +- Cupertino row titles/subtitles still truncate to one line (standard + `CupertinoListTile` behaviour). The no-match/error messages no longer do. +- The Cupertino-under-MaterialApp probe still takes its accent from the ambient + `ThemeData`. No theme override was added. + +## Remaining gaps + +- Mobile is unverified: no Android/iOS builds, devices or installs were run. + Source is portable but only web was exercised. +- Browser evidence uses the fixture gateway, not an authenticated live server. + No real chat was created, renamed, closed or starred in the browser; those + request paths are covered by widget tests. +- The Cupertino list/actions probes use the local Chrome dark appearance; the + no-match fix was captured in both light and dark. The long-error capture came + from a temporary private fixture entry that was deleted afterwards. +- The create dialog still omits the web's default instruction text and its + backend segmented control; it preserves the existing name/directory/backend/ + instructions request fields. +- This stage did not commit. The changes remain an uncommitted working-tree + candidate for the next stage. diff --git a/app/notes/D1.md b/app/notes/D1.md new file mode 100644 index 00000000..4dc83394 --- /dev/null +++ b/app/notes/D1.md @@ -0,0 +1,323 @@ +# D1 — run changes and the file diff viewer + +New feature under `lib/features/changes/`; no server, legacy web/Android or +pubspec changes remain after manager acceptance corrections. + +## Current manager acceptance (supersedes earlier presentation evidence below) + +The pipeline's bundled font and fixed green/red palette were rejected against +the user's native-defaults requirement. Manager removed both and the font assets +without changing raw patch, capture or visit semantics. Typography inherits the +host; colours use native semantic roles and no row tint. The original candidate +and its review evidence remain referenced at15cca17; later font/palette evidence +in this note is historical, NOT evidence for the final native-defaults patch. + +Updated regressions failed against the original overrides, then all47 focused +tests passed after correction; analyzer clean. Fresh fixture web build and +changes_probe passed (including absence of custom font), producing18 new captures +under approved temp/native-diff-manager-captures. Manager inspected both native +phone2x rendered views. Preview/shell integration and mobile remain unverified. + +## Public API + +Import the barrel: + +```dart +import 'package:pipelines_app/features/changes/changes.dart'; +``` + +Integration widgets: + +- `ChangesViewer({Key? key, required List steps})` + - The run detail's `steps` exactly as returned by `get_run`. Pass the same + list instance until the server reply changes: captures and the summary are + derived once per list identity, not on every rebuild or filter keystroke. + - It fills the available height, so place it in a bounded parent (Scaffold + body, tab body or `Expanded`). It does not open a socket or request data. +- `FileDiffViewer({Key? key, required FileChange file, VoidCallback? onClose})` + - The reusable viewer for one recorded file. Without `onClose` it pops the + enclosing route. +- `Future showFileDiffViewer(BuildContext context, FileChange file)` + - Opens the platform modal: `showDialog` with a Material `Dialog` on + Android/desktop/web, `showCupertinoDialog` with `CupertinoPopupSurface` on + iOS/macOS. + +Data and pure helpers exported for integration/tests: + +- `FileChange` — `path`, `kind`, `patch` (server bytes or null), `binary`, + `truncated`, `beforeMode`, `afterMode`, `steps`; `FileChange.fromJson(JsonMap)`, + `FileChange.tryParse(dynamic)`. +- `ChangeCapture` — `status`, `scope`, `files`, `skipped`, `omitted`, + `diagnostic`; `ChangeCapture.fromJson(JsonMap)`. +- `StageCapture` / `StageCapture.fromStep(JsonMap)` / `stageCaptures(steps)` — + one stage visit per step, ordered by numeric sequence, including steps with no + capture. `sequence` is the run-wide step ordinal (ordering and keys); `visit` + is the display visit number within the stage. +- `RunChanges` / `runChanges(steps)` / `runChangesFor(captures)` — final-state + aggregate (last recorded visit wins per path; each path counted once) with the + same fields. `runChangesFor` avoids re-deriving captures a caller already has. +- `parseUnifiedPatch`, `PatchHunk`, `PatchLine`, `ChangeLineKind`, `gutterWidth`, + `gutterText`, `changeStat`, `changeKind`, `changeKindLabel`, `changeKindTitle`. +- Wording: `runChangesHeader`, `runChangesNote`, `changesListSummary`, + `noChangeDetail`, `patchUnavailableReason`, `changeEntryTags`, `changeRowMeta`, + `changeFileMeta`, `fileChangesSummary`, `filterFileChanges`, + `changePositionLabel`, `binaryDiffMessage`, `truncatedPatchNote`, + `noLineChangesMessage`, `missingCaptureDetail`, `unavailableCaptureDetail`, + `malformedCaptureDetail`, `emptyCaptureDetail`, `partialCaptureDetail`. + +Example integration: + +```dart +final steps = (detail['steps'] as List).cast(); +// ... +ChangesViewer(steps: steps) +``` + +The manager owns shell/run-detail registration; this item does not edit them. + +## Recorded-evidence semantics (matches `web/src/changes.js`) + +- `file_changes == null` is **missing evidence**, not “no changes”. A + running/waiting step is “pending”; any other missing capture is counted and + named. The UI says the capture is unavailable and explicitly says that does not + mean the workspace was unchanged. +- `status: "unavailable"` means the snapshots could not be compared. No change + list is fabricated; the server diagnostic is shown. A non-null `file_changes` + value that is not an object is also unreadable evidence, so it is treated as + unavailable with `malformedCaptureDetail`; it never becomes an empty capture. +- A present complete capture with `files: []` is the only “no changes observed” + state (“the captured snapshots were identical”). +- `status: "partial"`, any per-file `truncated`, or any `omitted` count makes the + run partial; `skipped`, `omitted`, truncated-file count and the diagnostic are + shown. `scope` is shown per stage capture. +- Files are grouped by stage/visit. The visit label is the recorded + `control.visit` when it is positive (a resumed run), otherwise the visit's + 1-based position among the steps of its own stage, ordered by sequence and + stable for ties. This mirrors the web client's `displayVisit`; the run-wide + step `sequence` is only the ordering/key, never shown as a visit number. +- Kinds are `added`, `modified`, `deleted` and the safe `changed` fallback. + Binary, truncated and mode-only entries carry labels; a mode-only entry has no + text diff and says so. +- The run summary is final-state: a path recorded by several visits is one row, + keeping first-seen order and the last visit's kind/patch/stat/flags/modes, with + the stage names that touched it. Per-stage sections still show each visit's own + capture. +- Filtering matches changed filenames case-insensitively (substring) and keeps + missing/unavailable evidence sections visible. The counter names **paths**, + matching the summary's unit; the sections below still list one row per visit. +- A changed-file row's semantics label names the action, path, kind and visible + meta (`+N -M`, binary/truncated/mode), so the excluded icon and subtitle are + still announced. + +## Diff rendering + +- Only patch content is custom-drawn: `@@` hunk headers, old/new gutter numbers, + the shared `+`/`-`/space language, context and `\ No newline` markers. +- The recorded `---`/`+++` file headers stay in the Raw view, matching the web + rendered view; rendered content is the stat line and the hunks. Long lines + scroll horizontally; vertical content scrolls inside the dialog. The Raw view + keeps each recorded line on one line and scrolls sideways, like the web's + `white-space: pre` pane, so a wrapped continuation can never be mistaken for a + new patch line. +- Patch/path text inherits the native host typography without a font-family, + size or weight override. Manager removed the candidate's bundled code font: + a previous visual review requested it, but that contradicts the user's + explicit native-defaults requirement, which also applies to diffs. The web + default may be proportional; no monospace guarantee is claimed. Raw patch + bytes are unchanged. No bundled font or pubspec change remains. +- Rendered/Raw is a native Material `SegmentedButton` or Cupertino + `CupertinoSlidingSegmentedControl`. Copy patch and Close are native Material + buttons/icon button or Cupertino buttons with exact labels. +- Copy patch writes the recorded `patch` string byte-for-byte (trailing newline + and truncated final line included). Copy is disabled when no readable patch + exists. +- Binary uses the honest binary message; truncated-with-patch shows the note plus + the retained text; truncated-without-patch and mode-only show the recorded + reason, never an invented empty diff. +- Add/remove markers and stats use native semantic colours (Material primary/ + error; Cupertino systemGreen/destructiveRed), with no bespoke palette or added + tint. +/- and recorded gutter numbers distinguish changes without colour. + Rows share the hunk width, at least the dialog width. +- A Cupertino list row lets its recorded path wrap instead of inheriting the + tile's single ellipsized line, and the Cupertino dialog surface is inset from + the window edge (16 on phones, 40 on wide windows) so its native rounded + corners are visible. + +## Files + +``` +lib/features/changes/changes.dart +lib/features/changes/domain/change_capture.dart +lib/features/changes/domain/change_kind.dart +lib/features/changes/domain/change_wording.dart +lib/features/changes/domain/file_change.dart +lib/features/changes/domain/patch_models.dart +lib/features/changes/domain/run_changes.dart +lib/features/changes/domain/unified_patch.dart +lib/features/changes/widgets/change_style.dart +lib/features/changes/widgets/changes_viewer.dart +lib/features/changes/widgets/capture_section.dart +lib/features/changes/widgets/file_diff_viewer.dart +lib/features/changes/widgets/patch_view.dart +assets/fonts/RobotoMono.ttf +assets/fonts/OFL.txt +pubspec.yaml (fonts + assets declaration) +test/features/changes/fixtures.dart +test/features/changes/widget_hosts.dart +test/features/changes/unified_patch_test.dart +test/features/changes/run_changes_test.dart +test/features/changes/changes_viewer_test.dart +test/features/changes/diff_presentation_test.dart +tool/changes_probe_entry.dart +tool/changes_probe.mjs +``` + +Every path above is new except `pubspec.yaml`, which gains only the +`RobotoMono` family and the font licence asset declaration. + +## Checks + +Presentation revision (bundled code face, diff colours/tints, Cupertino rows and +dialog inset) re-ran the full set: + +- `/Users/alan/development/flutter/bin/flutter test` — **76 tests passed**. +- `/Users/alan/development/flutter/bin/flutter test test/features/changes` — + **47 tests passed**. +- `/Users/alan/development/flutter/bin/flutter analyze` — **No issues found**. +- `/Users/alan/development/flutter/bin/dart format --output=none + --set-exit-if-changed lib/features/changes test/features/changes + tool/changes_probe_entry.dart` — 20 files, 0 changed. +- `/Users/alan/development/flutter/bin/flutter build web` — **built + `build/web`** successfully. +- `node --check tool/changes_probe.mjs` — passed. +- `/Users/alan/development/flutter/bin/flutter build web --target + tool/changes_probe_entry.dart --output build/probe-web-fix` — built. +- `node tool/changes_probe.mjs --root build/probe-web-fix --out /d1` — + passed every check (11 checks, below). + +`flutter pub get` resolved the existing lock; `pubspec.lock` is unchanged. + +## Real browser evidence + +Fixture entry `tool/changes_probe_entry.dart`, driven by `tool/changes_probe.mjs` +(loopback, OS-assigned port, headless Chrome, Flutter semantics enabled). The +fixture uses server-shaped captures for partial, complete, missing, unavailable +and empty states, plus binary, truncated, mode-only, deleted, added and +multi-hunk patches. `/?visits=1` is a compact second fixture that repeats stages +and records one explicit `control.visit`. It is rendering data only; no server or +operator run touched. + +Captures (in the run's public artifacts `d1/`): + +- `d1-changes-phone-list.png` (390×844, dark) +- `d1-changes-phone-diff.png` +- `d1-changes-phone-raw.png` +- `d1-changes-phone-copied.png` +- `d1-changes-phone-filtered.png` +- `d1-changes-phone-visits.png` (390×844, repeated-stage visit labels) +- `d1-changes-phone-light-list.png`, `d1-changes-phone-light-diff.png`, + `d1-changes-phone-light-diff-2x.png`, `d1-changes-phone-light-raw.png` + (light theme, 2x where glyphs and tints are inspected) +- `d1-changes-desktop-diff.png` (1280×800) +- `d1-changes-desktop-list.png` +- `d1-changes-desktop-light-list.png`, `d1-changes-desktop-light-diff.png` +- `d1-changes-cupertino-diff.png` (1280×800, Cupertino fixture) +- `d1-changes-cupertino-light-list.png` (390×844, wrapped paths), + `d1-changes-cupertino-light-diff.png`, `d1-changes-cupertino-light-diff-2x.png` + (390×844, inset popup) + +Observed checks from `d1-probe.json`: + +- Root `/` served `text/html; charset=utf-8`. +- `assets/FontManifest.json` lists a `RobotoMono` family and + `assets/fonts/RobotoMono.ttf` is served as `font/ttf` (183,700 bytes), so the + web build carries a real code face. +- The body showed `Changes probe` and `Capture unavailable`, and a file row whose + semantics label starts with + `Open diff for lib/features/changes/domain/unified_patch.dart` (the label now + also announces kind and meta). +- Opening the diff changed `document.body.innerText`; `Rendered`, `Raw patch`, + `Copy patch` and `Close diff` labels appeared. +- `Raw patch` changed the body and produced a different PNG from the rendered + capture; the raw semantics value contains the recorded `---`/`+++` header. +- Clipboard readback after `Copy patch` started with + `--- "a/lib/features/changes/domain/unified_patch.dart"` (540 bytes). +- Filtering `unified` left both matching visit rows (`unifiedRows: 2`) and hid + `assets/pipelines-mark.png` (`binaryRows: 0`); the counter read + `1 of 6 changed paths match`. +- The visits fixture rendered `implementer` with `Visit 1` and `Visit 2`, and + `reviewer` with `Visit 1` and the recorded `control.visit` `Visit 6`; the probe + fails if either list differs. +- `Close diff` returned to the list; the desktop and Cupertino viewers opened. + +Measured from `d1-changes-phone-light-diff-2x.png` (Pillow): the light add tint is +`#E3F3E7` and the remove tint `#FBE7E5` (ΔR 24); every changed line paints a +618 px (309 logical px) band — the full dialog content width — and the two added +lines and one removed line are each 92/46 device px tall. Previously the tints +were `#FFD8E4`/`#F9DEDC` (Δ 6,6,8) and only as wide as each line's text. Dark +captures measure `#394643` (green) and `#4D3C42` (red) tints. + +The screenshots show real Material and Cupertino controls, light and dark themes, +phone and desktop widths, wrapped Cupertino paths and an inset Cupertino popup. +Mobile targets were not built, installed or run. + +## Review revision + +- **B1 (blocking, visit labels):** `StageCapture.visit` is derived from positive + `control.visit` else the stage position; sections render it instead of the + run-wide `sequence`. Unit/widget tests cover repeated stages, a resumed visit + and sequence ties; the browser visits fixture and capture above show the result. +- **A1 (malformed capture):** a non-object `file_changes` is now unavailable with + `malformedCaptureDetail`, never an empty “no changes” capture. +- **A2 (rendered headers):** rendered view shows hunks only, matching the web + rendered view; the exact headers remain in Raw and Copy. +- **A3 (re-derivation):** `ChangesViewer` derives captures/aggregate on init and + when the steps list changes, not on filter keystrokes; `runChangesFor` reuses + those captures, and `FileChange.withSteps` reuses the parsed patch. +- **A4 (test fixtures):** the run-changes test helpers now delegate to + `test/features/changes/fixtures.dart`. +- **A5 (row semantics):** the row label includes kind and visible meta. +- **A6 (filter counter):** counts and names changed **paths**, matching the + summary; the list remains per visit. +- **A7 (paging):** unchanged; the one-file viewer API is the documented limit. + +## Presentation revision (UI review) + +- **M1 (monospace):** `pubspec.yaml` declares the bundled `RobotoMono` family + (`assets/fonts/RobotoMono.ttf`, SIL OFL 1.1, licence in `assets/fonts/OFL.txt`) + and `monospaceText` uses it on every platform. The browser build's + `FontManifest.json` and font response are checked by the probe, and the 2x + captures show even advances and aligned gutters. +- **M2 (add/remove colours and tints):** the diff no longer uses Material + `tertiaryContainer`/`errorContainer`. `diffLineColors` supplies theme-aware + green/red pairs (light `#116B33` on `#E3F3E7`, `#B3261E` on `#FBE7E5`; dark + `#7FE0A8`/`#FF9E9E` on a 16% wash), the `+N`/`-M` stat is split into those two + hues, and every line tint spans the full hunk width (at least the dialog width) + via `IntrinsicWidth` inside a width-bounded scroll view. +- **M3 (Cupertino):** list rows clear `CupertinoListTile`'s inherited single-line + cap so the recorded path wraps, and the Cupertino dialog is inset (16 on + phones, 40 on wide windows) so its rounded corners are visible. +- **Nonblocking raw wrap:** the Raw view now keeps one recorded line per line and + scrolls horizontally (`SelectionArea` over a `Text` with `softWrap: false`), + matching the web's `pre` pane. +- **Left as-is (nonblocking):** list-row stat strings stay neutral (Android/web + colour them), the unavailable diagnostic still appears in both the section meta + and the note (web parity), and the one-file viewer has no paging. + +## Deliberate limits + +- One file per `FileDiffViewer`; the browser viewer's previous/next gallery + paging is not implemented here. The task asked for a reusable one-file viewer. +- The shell/run-detail screen is not wired; that remains the manager's + integration step (feature lanes do not edit shell/main). +- Run status gating (`showRunChangesSummary`, succeeded-only in the browser) is + the caller's choice; `ChangesViewer` renders whatever steps it is given. +- The bundled font is Latin/Greek/Cyrillic: a patch containing CJK or symbol + glyphs outside that coverage falls back for those glyphs, so their advance may + not be monospaced. Copy and Raw bytes are unaffected. +- Android and iOS were not built, installed or run in this revision; the + Cupertino path is verified only through the fixture's browser rendering and + widget tests, so **mobile remains unverified**. +- No backend capability is missing for this item: `file_changes` already carries + status, scope, files, skipped, omitted, diagnostic, binary/truncated flags, + modes and patches. diff --git a/app/notes/F1.md b/app/notes/F1.md new file mode 100644 index 00000000..3b8504b0 --- /dev/null +++ b/app/notes/F1.md @@ -0,0 +1,21 @@ +# F1 transport + +`PipelinesClient` implements the shared `ApiGateway` contract using one +`web_socket_channel` connection, correlated JSON replies, timeout handling, +unsolicited envelope broadcast, and reconnect with capped exponential backoff. +The URL helper validates ws/wss endpoints and resolves artifact URLs. + +Manager integration import: `package:pipelines_app/core/transport/pipelines_client.dart`; +endpoint helper: `package:pipelines_app/core/transport/server_url.dart`. + +The client accepts an injected `ChannelFactory` for deterministic tests. No live +server was used. Browser and mobile target verification should be reported +separately from these unit tests. + +## Manager verification +Expanded to 12 focused tests, including serialized requests, queue recovery +after protocol errors/timeouts, late replies, replacement of queued requests, +send-only subscriptions, concurrent connects, reconnect and disposal. Corrected +generation races and socket cleanup; URI construction now retains bracketed +IPv6 hosts and encoded artifact query strings. Analyze passes after formatting. +These are unit checks, not browser/live-server acceptance or mobile verification. diff --git a/app/notes/F2.md b/app/notes/F2.md new file mode 100644 index 00000000..12d851f4 --- /dev/null +++ b/app/notes/F2.md @@ -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= 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. diff --git a/app/notes/F3.md b/app/notes/F3.md new file mode 100644 index 00000000..687abed2 --- /dev/null +++ b/app/notes/F3.md @@ -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. diff --git a/app/notes/F4.md b/app/notes/F4.md new file mode 100644 index 00000000..a2578786 --- /dev/null +++ b/app/notes/F4.md @@ -0,0 +1,17 @@ +# F4 chat foundation + +Non-visual chat foundations for the UI lane, using the shared `ApiGateway` and no socket ownership. + +## Imports and API + +- `package:pipelines_app/features/chat/domain/chat_sessions.dart`: `chatSessionTitle`, `filterChatSessions`, `groupChatSessions`, `chatSessionActivity`, and `chatUsageSnapshot`. +- `package:pipelines_app/features/chat/domain/chat_transcript.dart`: `mergeChatHistory`, `transcriptRows`, `reconcileChatUser`, `applyChatEvent`, `QueuedChatSend`, and `ChatSendQueue`. +- `package:pipelines_app/features/chat/data/chat_repository.dart`: `ChatRepository(gateway)`; exposes sessions, directories, history, subscribe, create/rename/star/close/reopen, prompt/interrupt, form answer, permission reply, models/shells and model selection. `gateway.frames` remains the UI/controller's unsolicited event source. + +History uses `chat_history.next_cursor` verbatim, falls back to legacy `chat_messages`, and replaces duplicate authoritative messages while preserving order. `transcriptRows` preserves unknown part maps. Live fold supports user echoes, text/reasoning deltas, tool state snapshots, and step activity; UI should retain its richer thread/timing state as needed. Queue operation IDs are stable across retry objects and deduplicated within each session. Usage values remain unavailable unless reported and valid. + +Wire envelopes are asserted in `test/features/chat/chat_foundation_test.dart`. Current backend has no `chat_forms` or `chat_permissions` list command; forms and permissions arrive as live events and are answered through `chat_answer` / `chat_reply`. + +## Verification + +`/Users/alan/development/flutter/bin/flutter test test/features/chat` passed. Nonvisual foundation: UI/browser review and captures are not applicable at this stage. Web is the only permitted target; Android/iOS remain unverified. diff --git a/app/notes/F5.md b/app/notes/F5.md new file mode 100644 index 00000000..f4383c02 --- /dev/null +++ b/app/notes/F5.md @@ -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. diff --git a/app/notes/I1.md b/app/notes/I1.md new file mode 100644 index 00000000..7b59bbb8 --- /dev/null +++ b/app/notes/I1.md @@ -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. diff --git a/app/notes/N1-wire.md b/app/notes/N1-wire.md new file mode 100644 index 00000000..03f040cc --- /dev/null +++ b/app/notes/N1-wire.md @@ -0,0 +1,27 @@ +# Settings registered in the normal app + +- `/settings` mounts the landed SettingsScreen with the app-owned client, not a + second socket. Embedded mode leaves the single native bar to the shell. +- Destinations are initialized on first visit and kept mounted thereafter; an + unvisited Settings screen issues no hidden ping or preference read. +- Session Retry uses the transport's current validated endpoint, including one + selected in Settings, rather than reverting to the bootstrap server. A native + missing-endpoint gate can be cleared by a successful Settings configuration. +- Real CupertinoApp dark-host capture exposed Material fallback text colours. + Settings now resolves typography/semantic colours from its actual native host. + The new dark-label regression failed before this correction and passes after. + No fixed font, palette or component dimensions were added. + +## Verification + +- 516 integrated Flutter tests pass; analyzer clean; normal-entry web build pass. +- Widget coverage mounts real Material and dark Cupertino app composition, + asserts one bar, no background Settings ping before visiting, shared socket, + and resolved server build after ping. Endpoint-change Retry has a regression. +- Extended normal-entry Runs CDP fixture answers real ping and drives Settings + in both hosts. Probe passes all existing history/drop/reconnect checks plus + Settings navigation and single-socket checks:20 captures. Both registered + phone screenshots inspected; dark Cupertino labels are readable after fix. +- Evidence in approved temp/settings-wired-browser and corresponding logs. +- Authenticated production-data interaction and Android/iOS remain unverified. + No real server endpoint/workspace preferences were changed by the fixtures. diff --git a/app/notes/N1.md b/app/notes/N1.md new file mode 100644 index 00000000..194247de --- /dev/null +++ b/app/notes/N1.md @@ -0,0 +1,130 @@ +# N1 Settings + +The Settings destination for the Flutter client: server connection and the +server-side workspace, in native Material controls and Cupertino controls on iOS. + +## Files + +- `lib/features/settings/settings_screen.dart` — `SettingsScreen`. +- `lib/features/settings/settings_controller.dart` — draft/validation, shared + client actions, ping-on-connected, workspace persistence, dispose ownership. +- `lib/features/settings/settings_store.dart` — `SettingsStore`, + `SharedPreferencesSettingsStore`, `MemorySettingsStore`. +- `lib/features/settings/settings_copy.dart` — the web/Android words, workspace + validation, connection-card lines. +- `lib/features/settings/default_endpoint.dart` — same-origin web default. +- `lib/features/settings/settings_controls.dart`, `settings_sections.dart`, + `settings_trust_warning.dart`, `settings_layout.dart`, `settings_keys.dart`. +- `lib/features/settings/settings.dart` — public barrel for manager registration. +- `test/features/settings/*` — copy, persistence, controller and widget tests. +- `tool/settings_probe.dart`, `tool/settings_probe_server.dart`, + `tool/settings_probe_capture.dart` — isolated browser fixture/capture entry. + +## Manager registration + +```dart +import 'package:pipelines_app/features/settings/settings.dart'; + +SettingsScreen(client: sharedPipelinesClient) +// optional: initialEndpoint: Uri?, store: SettingsStore?, ping: PingCallback? +``` + +`SettingsScreen` takes the shell's single `PipelinesClient`. It subscribes to +`client.states`, sends `ping` once per connected transition (plus once when the +screen opens against an already-connected client), and offers Connect / +Disconnect / Reconnect. It never calls `client.dispose()` and never opens a +connection on construction, so registering/rebuilding the screen cannot start a +second socket or tear down another feature's connection. + +While connected it shows `Server build {version} ({commit})` and +`Server time {time}` from the ping reply. Until that reply arrives the card says +`Loading server details…`, so a request in flight is never reported as an +unavailable value. Only a completed reply that omits a field renders `Server +build unavailable` / `Server time unavailable`; a failed ping renders one +explicit `Server details unavailable: …` line instead of repeating both +"unavailable" lines. No zero or stale value is substituted. Disconnect and +reconnect clear the previous server's details. + +Connection card copy and state lines follow `web/src/settings.js` and +`SettingsScreen.kt`: `Not connected`, `Connecting (attempt N)…`, `Connected`, +`Disconnected` + reason + `Retrying with backoff…`, plus the trusted-LAN/VPN +warning. A dropped socket's attempt/backoff state comes from the transport. + +Workspace validation is the web rule: blank is untouched (no error), a relative +path is rejected, Save is enabled only for a trimmed absolute path. The saved +line is `Saved workspace: /path` or `Saved workspace: (none)`, and the helper +states that the path is an absolute directory on the execution server, not the +phone's storage. Save failures keep the previous saved value and say so. + +## Persistence + +`shared_preferences` keys are owned by this feature: + +- `pipelines.next.serverUrl.v1` +- `pipelines.next.workspace.v1` + +No legacy Android/web key (`server_url`, `workspace`, +`pipelines.web.serverUrl.v2`, `pipelines.web.workspace.v1`, notification keys) +is read, migrated or written. The endpoint is validated and persisted before +`client.connect` is attempted, matching the web's write-before-connect +behaviour; a value that fails to connect stays stored. When the store write +itself fails, the screen still connects and says the value applies to this +session only. Credentials in a URL are rejected before any write or socket. +Only those two strings are stored; nothing else. + +The web `shared_preferences` implementation may namespace its keys internally; +the logical keys above are the independent feature keys and tests assert the +legacy keys stay untouched. + +## Web default endpoint + +`defaultServerUrl()` returns `''` on native builds. On web it derives +`ws(s):///connect` from `Uri.base` (`kIsWeb`, no `dart:html`), +so the screen starts from the configurable same-origin proxy and no server host +or production endpoint is baked into the app. The field remains editable and +only the validated value is persisted. + +## Verification + +- `flutter test test/features/settings` — 39 tests pass (copy/default endpoint, + persistence keys/legacy isolation, controller connect/validation/ping/ + disconnect/reconnect/backoff/dispose ownership/workspace errors, Material and + Cupertino widgets, invalid URL, pending vs completed-empty ping, failed-ping + single line, field labels in semantics, narrow + 2× text with full labels and + helper copy, unmount ownership). +- `flutter test` (full app) — 52 tests pass. +- `flutter analyze` — no issues; `dart format --set-exit-if-changed` clean on the + 19 Dart settings/test/tool files. +- `flutter build web` (main) and `flutter build web -t tool/settings_probe.dart` + — both built. +- Real browser evidence from an isolated loopback probe server (`/connect` + answers `ping` with `probe-1.2.3`/`abc1234`/time), headless Chrome over CDP: + `settings-idle`, `settings-connected`, `settings-validation` (clicked Connect + after an `http://` draft), `settings-workspace` (typed `/srv/pipelines`, + clicked Save), `settings-dark`, `settings-ios`, `settings-narrow` (390×844, + 1.6× text). See `public/settings-captures/manifest.md`. +- Fix verification with a 6 s delayed pong: at 1.5 s the card shows + `Connected` + `Loading server details…` (no "unavailable"), and after the pong + it shows the real build/time. At 320×700/2× and 390×844/2× the full + `Server URL`/`Workspace path (on the server)` labels and the complete helper + and error sentences render (no ellipsis or line cap). See + `public/settings-fix-captures/manifest.md`. +- The 20 candidate paths are new and currently **untracked** (`??`, none + ignored); landing must `git add` them. The candidate is left uncommitted per + the stage instruction. + +## Gaps / not done + +- Notifications are not part of this screen yet. The queue item names them, but + the task scope here was connection/workspace and the project has no + notification plugin; adding one needs a dependency decision. +- No Templates card: navigation into the templates feature is shell/feature + registration work owned elsewhere. +- No protocol-mismatch warning (the web page shows one); it needs a shared + protocol-version constant not present in the app yet. +- Mobile builds/devices and the real production server were not used. The + Cupertino rendering is shown through the web probe with an iOS platform theme, + not on an actual iOS device. +- The probe's `connected` capture is an automatic fixture connect; validation + and workspace-save captures use actual browser clicks/typing. The main web + entry (`lib/main.dart`) is still the scaffold and was not modified. diff --git a/app/notes/P2-edge.md b/app/notes/P2-edge.md new file mode 100644 index 00000000..6775deb9 --- /dev/null +++ b/app/notes/P2-edge.md @@ -0,0 +1,119 @@ +# P2-edge — passive edge layer over landed routing + +## What changed + +App-only, new files. No existing routing, layout, domain, shell, `main.dart`, +pubspec, server, web client or platform source was edited. The Land stage +committed the candidate on `flutter/p2-edge-layer` and merged `main`. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/graph/painting/graph_edge_layer.dart` | 160 | `GraphEdgeLayer` widget + `GraphEdgePainter` path/arrow painting | +| `test/features/graph/painting/edge_layer_fixtures.dart` | 41 | hand-built routes and arrival helper for the tests | +| `test/features/graph/painting/graph_edge_geometry_test.dart` | 240 | path and arrow geometry, routed forward/self-loop/cycle edges, a hand-built backward route and an off-port tip case | +| `test/features/graph/painting/graph_edge_layer_test.dart` | 190 | draw calls, clip, hit-test transparency, style colors, repaint rules, widget size | +| `tool/graph_edge_probe.dart` | 182 | isolated browser-capture entry (not wired into the app) | + +## Public API + +```dart +GraphEdgeLayer( + routes: List, // from routing/route_models.dart + canvasSize: Size, // graph-space canvas supplied by the caller + color: Color, // caller's native outline color + strokeWidth: double, // caller's native stroke width +) +``` + +`GraphEdgePainter` is public so a compositor and its tests share the exact +geometry through `linePath(route)` and `arrowPath(route)`. + +## Behavior + +- **Passive and hit-test transparent:** a single `CustomPaint`; no child, + gesture, focus, semantics or label text. `GraphEdgePainter.hitTest` returns + `false` for every point, so the layer never becomes a full-canvas hit sink and + siblings below it keep their taps, including with `routes: const []` and on a + painted stroke. Default `CustomPainter.hitTest` returns `null`, which + `RenderCustomPaint.hitTestSelf` treats as a hit; the explicit `false` is the + fix and the regression covers it. Node boxes and measured extents are + caller-owned and are never read or changed here. +- **Same coordinates:** every `RoutePoint` is used verbatim. A route with fewer + than two points draws nothing. Painting clips to the `CustomPaint` size. +- **Orthogonal paths:** consecutive points are joined with straight segments, + so the landed orthogonal routes keep every bend; no smoothing or re-routing. +- **Direction arrows:** one filled triangle per route, tip exactly at + `targetPort.point`. The router guarantees `points.last == targetPort.point`; + `paint` asserts that invariant, while `arrowPath` reads the tip from the port + so a caller-supplied mismatch cannot move the arrow off the port. Direction is + the route's last non-degenerate segment, so forward, backward, same-rank and + self-loop edges keep their real arrival direction; a degenerate tail falls + back to the target port's inward normal. +- **Theme-owned style:** the caller supplies color and stroke width; the arrow + length is 6x and its half base 2x that stroke width, so it scales with the + caller's native thickness. No absolute palette, font or dimension is + hard-coded. +- **Repaint:** `shouldRepaint` compares color, stroke width and routes by value + (`listEquals` over `EdgeRoute ==`), so equal rebuilt lists do not repaint while + a moved route, color or stroke change does. + +## Checks actually run + +``` +dart format lib/features/graph/painting test/features/graph/painting tool/graph_edge_probe.dart +flutter test test/features/graph/painting # 18 passed +flutter test test/features/graph/painting test/features/graph/routing # 38 passed +flutter test # 466 passed +flutter analyze # No issues found! +flutter build web -t tool/graph_edge_probe.dart -o build/graph_edge_probe +flutter build web # ✓ Built build/web +``` + +The hit-test regression was confirmed to fail (`taps` stayed `0`) when +`hitTest` returned `true`, and pass with the shipped `false`. + +`public/P2-edge.patch` is the reviewed new-file diff. `public/P2-edge-land.patch` +is the landed `git diff main..HEAD`, which also carries the landing caption +correction and the 160-line trim; it reverse-applies cleanly to the merged tree. + +## Rendered evidence + +Three real Chrome captures of the isolated probe build, served from a temporary +loopback server on an OS-assigned port with a throwaway profile. No Pipelines +server, authentication, production data, device or preview service was touched. + +| File | Bytes | Shows | +| --- | --- | --- | +| `public/graph-edge-layer-web.png` | 90,739 | light theme: three measured cards, Success/Failure terminals, same-rank cycle edges, forward terminal edges and a self-loop | +| `public/graph-edge-layer-web-dark.png` | 85,431 | the same graph in the native dark theme | +| `public/graph-edge-layer-web-same-rank.png` | 69,601 | `?case=same-rank`: a two-node cycle, both edges same-rank between distinct nodes | + +All are 2700x2700 (900x900 CSS at 3x). Arrow tips land on target ports; the +layer uses `colorScheme.outline` and `dividerTheme.thickness`. + +The caption wording was corrected at landing to name the actual routes +(same-rank cycle edges, forward terminal edges and a self-loop). Fresh captures +of the rebuilt probe are `public/land-edge-light.png`, +`public/land-edge-dark.png` and `public/land-edge-same-rank.png`. The earlier +`public/graph-edge-layer-*.png` and `public/ui-review-edge-*.png` captures +predate that text-only correction; their geometry is unchanged and remains valid +evidence for the rendered layout. + +## Honest limits + +- **No labels or nodes.** Edge labels are deliberately excluded for later + native widget composition (the router already returns measured + `EdgeLabelBox`es); this slice paints no text. The probe's cards are fixture-only, + not a node widget and not shell registration. +- **One style per layer.** `color`/`strokeWidth` are single values; the web run + graph's per-outcome colors and dashed/dotted not-executed/fallback styles are + not expressible yet. A run-graph compositor will need a per-route style input + or several layers. +- **No interaction.** Selection, focus, hover and semantics belong to callers. + If per-wire hover is added later it needs stroke-only hit testing, not a + canvas-wide sink. +- **Browser capture only on web.** The probe ran in Chrome; mobile was not + built, installed or verified. +- **Committed, not delivered.** The candidate is committed locally on + `flutter/p2-edge-layer` with `main` merged. Nothing was pushed, deployed or + installed. diff --git a/app/notes/P2-node.md b/app/notes/P2-node.md new file mode 100644 index 00000000..98d4ae72 --- /dev/null +++ b/app/notes/P2-node.md @@ -0,0 +1,188 @@ +# P2-node — native content-sized stage-node control + +## This visit: both UI-review must-fixes + +| Finding | Change | +| --- | --- | +| Material stadium outline cut into a wrapped 2x label | Material no longer uses a stock **button**. It is a stock **card** body: `Card.outlined` when unselected, `Card.filled` when selected, wrapped in an `InkWell` with a 16 px content inset and the framework's `kMinInteractiveDimension` tap target. A card's painted shape is a rounded rectangle, so a long wrapped label stays inside the visible boundary at 1x and 2x. | +| Cupertino unselected stages and terminals were bare tinted text | Unselected Cupertino nodes are `CupertinoButton.tinted`, so every node has a visible native surface; selected stays `CupertinoButton.filled`. | + +Both fixes use stock widgets and stock variants only: no shape override, no +font, size, padding on a button, palette value or CSS token was added. + +| File | Lines | Responsibility | +| --- | ---: | --- | +| `lib/features/graph/widgets/graph_stage_node.dart` | 126 | one content-sized node as a native Material card or Cupertino button | +| `test/features/graph/widgets/graph_stage_node_test.dart` | 235 | key identity, semantics, keyboard, focus retention, wrap and terminal honesty | +| `test/features/graph/widgets/graph_stage_node_render_test.dart` | 210 | painted-boundary and painted-surface checks on real render objects/pixels | +| `tool/graph_node_probe.dart` | 90 | isolated browser fixture with stock light/dark themes, 1x and 2x narrow cases | +| `tool/graph_node_probe.mjs` | 151 | headless-Chrome runner: labels, click identity, `aria-current`, captures | +| `notes/P2-node.md` | this page | facts for review/landing | + +No existing app source, domain, layout, routing, shell, `main.dart`, pubspec, +server, web client or platform file was modified. + +## Public API + +```dart +GraphStageNode({ + required GraphNode node, + String? recordedStatus, + bool selected = false, + required ValueChanged onSelected, +}) +``` + +Unchanged from the reviewed candidate. `onSelected` reports `node.key` verbatim, +including `#success` / `#failure`; the display label is never used as identity. + +## Native mapping + +| State | Material | Cupertino | +| --- | --- | --- | +| unselected | `Card.outlined` + `InkWell` | `CupertinoButton.tinted` | +| selected | `Card.filled` + `InkWell` | `CupertinoButton.filled` | + +- The host is chosen with the existing `usesCupertinoHost` helper. +- Material content sits in a `Padding` of 16 logical px inside the card, so + wrapped glyphs stay clear of the rounded corners; the control is still + content-sized (no fixed width or height) and grows with its label. +- `MergeSemantics` + `Semantics(button: true, selected: …, label: …)` keep one + accessibility node per stage: button role, tap action, exact label/status and + selected state. The painted content stays `ExcludeSemantics`. +- Selection keeps the same widget type on both hosts (`Card` / `CupertinoButton`), + so keyboard focus survives activation; the previous Material + `OutlinedButton` → `FilledButton` swap replaced the focus node (review note 1). +- **Break-anywhere parity.** The web node uses `overflow-wrap: anywhere`; the + painted lines get invisible U+200B break opportunities. The accessible label + stays exact, with no invisible characters. +- **Recorded status only.** `recordedStatus` is shown verbatim on a second line + when non-blank; blank or whitespace-only status adds no line. Nothing is + derived from `terminal`, `stageIndex` or the label, so a terminal reads only + `Success` / `Failure` unless the caller supplies real run evidence. + +## Rendered checks (new) + +`graph_stage_node_render_test.dart` closes the gap the previous 2x test had +(line metrics versus paragraph width, not glyphs versus the painted boundary): + +- **Painted-boundary containment.** Reads the actual `Material.shape` and render + rect of the Material control, builds its outer `Path`, converts every laid-out + line box of the label to card-local coordinates with + `RenderParagraph.localToGlobal`, and requires all four corners of every line + box to be inside the painted path — at 1x and 2x in a 150 logical px box. + A rounded rectangle is convex, so corner containment means the whole line box + is inside; no padding/shape override can hide a crossing. +- **The check has teeth.** Running the same test against the identical widget + while a `StadiumBorder` is temporarily set on the card fails with + `at 1.0x a glyph box corner at Offset(16.1, 19.0) escapes the painted control + boundary`. The shape assertion (`material node paints a rounded surface, not a + stadium`) fails too. The override was reverted before this page was written. +- **Cupertino container.** Renders the unselected node over an opaque page, + reads pixels back from a real `RepaintBoundary.toImage`, and requires the point + just inside the control's left edge to differ from the page background by more + than 24/255. Reverting to plain `CupertinoButton` fails this test. +- **Visible selection.** The same pixel path requires the painted surface to + change between unselected and selected in both hosts. +- **Focus retention.** Tab + Enter on the Material node, then the primary focus + must still be a descendant of the node's `Card`. + +## Checks actually run (landing, after merging main) + +``` +dart format --output=none --set-exit-if-changed lib/features/graph/widgets \ + test/features/graph/widgets tool/graph_node_probe.dart # 0 changed, exit 0 +flutter pub get # dependencies resolved +flutter test test/features/graph/widgets # 13 passed +flutter test test/features/graph # 113 passed +flutter test # 526 passed +flutter analyze # No issues found! +flutter build web -t tool/graph_node_probe.dart --release # ✓ Built build/web +PROBE_VARIANT=material PROBE_SCHEME=dark node tool/graph_node_probe.mjs # passed, 6 captures +PROBE_VARIANT=material PROBE_SCHEME=light node tool/graph_node_probe.mjs # passed, 6 captures +PROBE_VARIANT=cupertino PROBE_SCHEME=dark node tool/graph_node_probe.mjs # passed, 6 captures +PROBE_VARIANT=cupertino PROBE_SCHEME=light node tool/graph_node_probe.mjs # passed, 6 captures +flutter build web --release # ✓ app bundle restored +``` + +The whole-suite count is 526 after `main` brought in the changes viewer and +routed-edge tests; the earlier figure of 460 was measured before that merge. + +The runner asserts the initial labels (`Selected: build`, `plan`, `build`, +`running`, `Success`, `Failure`), that exactly the `build` node carries +`aria-current="true"` (Flutter web maps `Semantics(selected:)` to `aria-current`, +not `aria-selected` — review note 5), that clicking `plan` and `Success` yields +exactly `Selected: plan` and `Selected: #success`, and that the selected +`aria-current` moves to `plan`. + +## Browser evidence (landing, current) + +Real headless Chrome, loopback fixture only, 390×844 phone and 1280×800 desktop. +The Material fixture now supplies a stock dark theme (`darkTheme` + +`themeMode.system`), so `PROBE_SCHEME=dark` and `=light` are genuinely different +renders (phone PNG SHA-256 `ac6272fd…` versus `c603c119…`); Cupertino follows the +platform scheme (`3e39555f…` versus `1f40f8b5…`). The runner writes +`material-nodes-*.png`, `light-material-nodes-*.png`, `cupertino-nodes-*.png` and +`light-cupertino-nodes-*.png`, plus `-long-1x-crop.png` / `-long-2x-crop.png`; +the shared copies below use a `land-p2-node-` prefix. + +- `/Users/alan/.local/share/pipelines/data/artifacts/64/public/land-p2-node-material-dark-phone.png` +- `.../land-p2-node-material-light-phone.png` +- `.../land-p2-node-material-dark-long-2x-crop.png` +- `.../land-p2-node-cupertino-dark-phone.png` +- `.../land-p2-node-cupertino-light-phone.png` +- `.../land-p2-node-cupertino-dark-long-2x-crop.png` +- Runner: `.../public/graph_node_probe.mjs` (same file as `tool/graph_node_probe.mjs`) + +The visit-2 `p2-node-fix-material-dark-*` captures were the default light theme +with a "dark" name because the fixture had no dark theme; they are history only, +as are the visit-1 `material-nodes-*.png` / `cupertino-nodes-*.png` set and the +UI-review crops. + +Pixel measurements of the current 2x crops (crops are 2x, 8 logical px margin): + +| Node | Container (px) | Glyph ink (px) | Corner band | +| --- | --- | --- | --- | +| Material | x 16–316, y 16–560 | x 50–269, y 66–507 | 24 px (radius 12) | +| Cupertino | x 16–316, y 16–640 | x 60–268, y 63–590 | 16 px (radius 8) | + +At 1x the same nodes measure Material ink x 50–268, y 61–147 inside a +x 16–316, y 16–200 container, and Cupertino ink x 59–264, y 59–164. +No glyph ink enters a corner band or crosses the visible boundary in either +scaling; the previous outline crossing is gone. + +Inspected captures: Material shows outlined node bodies and a visibly filled +selected node in real light and dark, `running` only on `build`, and no status on +either terminal; Cupertino shows a tinted body for every unselected node and a +filled selected node in both schemes. + +## Honest limits + +- **Material selection is tonal.** `Card.filled` (surfaceContainerHighest) versus + `Card.outlined` (surface + border) is the strongest stock card pairing, but it + is lighter than the previous primary-filled button. It is visible in the + captures and asserted by pixels; if UI review wants a stronger accent, that + needs an explicit theme-colour decision rather than a bespoke palette. +- **Stage vs terminal is label-driven.** Both hosts give every node the same + stock container; the web's terminal pill and outcome tints are styling the + rules exclude. Terminals read `Success` / `Failure` (and no invented status). + Composition can add a stock type affordance if it is still wanted. +- **Material content inset is a spacing choice.** 16 logical px inside the card + keeps wrapped glyphs clear of the 12 px corner radius; the framework's + `kMinInteractiveDimension` keeps the tap target at the native minimum. +- **No measurement API yet.** The control shrink-wraps; the caller imposes width + (the fixture uses 150). The renderer still needs to measure this same control. +- **`onSelected` identity and wrapping are unchanged**, but U+200B break + opportunities would split exotic grapheme clusters (acceptable for stage keys). +- **Space activation** is a framework default and is not exercised; only + Tab + Enter is tested. +- **No composition.** No canvas, layout invocation, edge painter, visit menu, + shell registration or `main.dart` wiring: the widget is still not visible in + the app. +- **State of the branch.** The six paths are committed on + `flutter/p2-node-widget` and `main` is merged in with no conflicts; the server + performs the landing and the post-landing ancestry check. +- **Fixture-only browser evidence**: no Pipelines server, real run, + authentication change, deployment or production data. +- **Mobile unverified**: web test/analyze/build only; no Android/iOS build, + emulator, ADB or install. diff --git a/app/notes/P2a.md b/app/notes/P2a.md new file mode 100644 index 00000000..a77dc77d --- /dev/null +++ b/app/notes/P2a.md @@ -0,0 +1,114 @@ +# P2a — graph domain: nodes, edges, terminals, run evidence and stage visits + +## What changed + +New, app-only, pure-Dart files. No server, web client, legacy client, shell, +`main.dart`, pubspec, other feature or platform source was edited. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/graph/domain/graph_protocol.dart` | 43 | terminal constants, `resolveTarget`, terminal labels | +| `lib/features/graph/domain/graph_definition.dart` | 152 | outcome/edge order, definition edges, definition nodes | +| `lib/features/graph/domain/run_graph_state.dart` | 124 | recorded visited stages/routes, current-stage fallback, live start | +| `lib/features/graph/domain/stage_visits.dart` | 107 | sequence-ordered visits, display visit, clamped visit selection | +| `test/features/graph/domain/graph_fixtures.dart` | 96 | linear/diamond/self-loop/incomplete definitions and step fixtures | +| `test/features/graph/domain/graph_protocol_test.dart` | 56 | shorthand and terminal-label regressions | +| `test/features/graph/domain/graph_definition_test.dart` | 229 | edge order/ids, loops, duplicate keys, missing/unknown targets | +| `test/features/graph/domain/run_graph_state_test.dart` | 170 | linear/diamond/self-loop/repeated visits/outcomes/terminals/no evidence | +| `test/features/graph/domain/run_graph_state_live_test.dart` | 91 | current/last-stage fallback, live start, finished run | +| `test/features/graph/domain/stage_visits_test.dart` | 150 | repeated visits by sequence, latest default, clamping, absent visit | + +No layout, coordinates, widgets, styles or rendering were added. + +## Behavior copied from the current web client + +- **Terminals and `#`** (`web/src/protocol.js`): `#success`, `#failure`, + `isTerminal` only for the explicit keys, and `resolveTarget`: a bare `#` + becomes `#failure` for the `error` outcome and `#success` for every other + outcome. All other values are preserved verbatim, including `""` and unknown + stage keys. A missing target stays `null`, never a fabricated terminal. +- **Labels** (`web/src/graph.js`): `nodeDisplayLabel` gives `Success` / + `Failure` for graph nodes; `nodeLabel` gives the TUI-mirroring `SUCCESS` / + `FAILURE`. Stage keys are unchanged. +- **Definition edges** (`web/src/graph.js`): outcomes are success first, other + outcomes alphabetical, `error` last; stages keep declaration order; ids are + contiguous in that order; the label carries `error*` only when + `fallback_error` is true. A `null` edge value declares no edge and is + skipped. Empty/unknown targets are kept, with `knownTarget == false`. +- **Definition nodes** (`web/src/graph.js` `layoutGraph`): stage nodes keep + declaration order and one identity per key; terminal nodes are appended + failure then success once any declared edge resolves to a terminal. These + are definition nodes only, never run evidence. +- **Run evidence** (`web/src/runDetail.js` `runGraphState`): visited stages in + first-appearance order without duplicates; routes keyed + `source\0outcome\0resolvedTarget` without duplicates; only a resolved + terminal is visited by its target; a non-terminal target is not visited until + a step lands there. Current stage is `current_stage` when non-blank, else the + last recorded step's stage, else `null`. A start timestamp is read only while + executing, for a `running` visit of the current stage. +- **Visits** (`web/src/runDetail.js` `runTimeline`, `clampVisitIndex`, + `displayVisit`, and `web/src/app.js` stage routing): visits are grouped by + stage and ordered by recorded sequence with stable ties; the display visit + is a positive `control.visit`, else position + 1; no requested visit selects + the stage's most recent visit; an explicit index clamps to `[0, count)`; a + stage with no recorded visit yields `step == null`. + +The run map is the same detail the runs feature already holds; this slice only +reads `steps`, so it adds no second event fold. Live-event merging remains in +`lib/features/runs/domain/run_step_evidence.dart` and `run_events.dart`. + +## Honest edge handling + +- A missing/`null` definition edge produces no edge and no node. +- An empty or unknown target is returned as recorded, flagged `knownTarget: + false`; it never becomes a stage node or terminal and never produces a + visited stage. +- A blank recorded stage key is not turned into an empty visited identity. A + step with a blank outcome or target records no route and no terminal visit. +- Self edges and loops record one route and one node identity; nothing recurses. +- A stage with no recorded visits cannot be presented as visited: selection + exposes a null step rather than synthesizing one. + +## Checks actually run + +``` +flutter pub get +dart format lib/features/graph test/features/graph # 10 files, 0 changed after formatting +flutter test test/features/graph/domain # 41 passed +flutter analyze # No issues found! (0.8s) +flutter test # 139 passed +``` + +Focused coverage is the requested matrix: + +- **Linear**: plan -> build -> ship, contiguous ids, implicit `error*` + fallback, terminals. +- **Diamond**: fan-out/fan-in edges stay distinct and ordered; converging + routes do not merge. +- **Self loop**: `a/retry -> a` is one edge and one node identity; one run + self-loop is one route and one visited stage. +- **Repeated stage**: repeated visits remain separate ordered entries; visited + stage identity is not duplicated; repeated identical routes collapse. +- **Different outcomes**: success/approved/rejected routes to the same target + remain distinct. +- **Terminals**: bare `#` resolves by outcome, explicit terminals normalize, + labels are `SUCCESS`/`FAILURE`, mid-run targets do not fabricate visits. +- **Missing evidence**: null/absent/malformed steps and graphs yield empty + evidence, no terminals and no fabricated visits. + +## Honest limits + +- **No UI, layout or wiring.** This is deliberately the nonvisual foundation + slice; the native graph screen, layout, highlighting and interaction are + later work and are not claimed here. +- **No browser evidence.** A nonvisual pure-Dart change has no rendered + behavior to capture; no browser or screenshot check applies. +- **No live server or device used.** All tests use local fixtures. No run, + pipeline, schedule, workflow or service was created, changed or restarted. +- **Mobile unverified.** Only web-targeted Flutter tests and analysis ran; no + Android/iOS build, emulator, ADB or device. +- **Committed, not deployed.** The reviewed slice is commit `2c10507` on + `flutter/p2-model`; current `main` was merged in after review (final merge + `f07ada0`, which includes `main` `e8bde4f`). No push, install, preview server + or canonical-URL change was made by this landing stage; server-side checks and + the actual land follow. diff --git a/app/notes/P2b.md b/app/notes/P2b.md new file mode 100644 index 00000000..91d5e07a --- /dev/null +++ b/app/notes/P2b.md @@ -0,0 +1,100 @@ +# P2b — deterministic pure node layout + +## What changed + +New app-only, pure-Dart files. No existing file, server, web client, legacy +client, shell, `main.dart`, pubspec, other feature or platform source was edited. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/graph/layout/layout_models.dart` | 127 | measured extents, gap config, immutable node box, layout + ranks | +| `lib/features/graph/layout/graph_ranks.dart` | 191 | deterministic SCC ranks over the landed definition nodes/edges | +| `lib/features/graph/layout/graph_node_layout.dart` | 142 | column/row placement, bounds, validation | +| `test/features/graph/layout/layout_fixtures.dart` | 102 | shared definitions and measured extents | +| `test/features/graph/layout/graph_ranks_test.dart` | 116 | linear/diamond/cycle/self-loop/disconnected/unknown/long-chain ranks | +| `test/features/graph/layout/graph_node_layout_test.dart` | 224 | ordering, terminals, heterogeneous and expanded extents, bounds, determinism | +| `test/features/graph/layout/graph_layout_validation_test.dart` | 96 | empty input, missing/extra measurements, duplicate keys, invalid sizes | + +No layout widgets, painters, edge routing, styling or shell wiring were added. + +## Public API + +```dart +GraphRanks assignGraphRanks(List nodes, List edges); + +GraphLayout layoutGraphNodes({ + required List nodes, + required List edges, + required Map extents, + required GraphLayoutConfig config, +}); +``` + +`NodeExtent` is the caller's measured width/height after text layout. +`GraphLayoutConfig` takes `columnGap`, `rowGap` and an optional outer `padding`. +No node size, font, colour or device value is assumed in the library. + +`GraphLayout` returns an unmodifiable `nodes` list of `GraphNodeBox` +(`key`, `terminal`, `stageIndex`, `rank`, `x`, `y`, `width`, `height`), an +unmodifiable `ranks` map, `rankCount`, and total `width`/`height` including +padding. Node keys, terminal flags and stage indices are copied from the +landed `graphNodes` identities unchanged. + +## Ranking behavior + +Ranks are read from the definition supplied by the caller; the existing +`graphNodes`/`graphEdges` helpers remain the source of identities. + +- Iterative Tarjan strongly connected components (no recursion; a 2000-stage + chain is covered), then longest-path ranks over the condensation DAG. +- Every member of a cycle shares one rank, so cyclic routes cannot recurse or + push members apart. Self loops are internal supervision and add no rank. +- Disconnected stages and disconnected terminals stay at rank 0. +- Edges whose source or target is not a node are ignored. An unknown or empty + target never creates a node or a rank. +- Ranking is linear in nodes plus edges and stable for repeated input. + +## Placement behavior + +- One column per rank; nodes keep definition order inside a rank. +- A column is as wide as its widest measured node; columns are separated by + `columnGap` and top-aligned. +- Nodes are centred in their column and stacked with exactly `rowGap` between + measured boxes (centres are compared in the heterogeneous test). +- Supplied widths/heights are placed verbatim, so expanded text is never + clipped to a fixed box; growing the extents grows the total bounds. +- Bounds include every box: tests assert `right <= width` and + `bottom <= height` for every fixture. +- The result is immutable and identical for identical input. + +Measurements are required for every node; a missing key throws +`ArgumentError` rather than inventing a default size. Extra measurements are +ignored because they cannot become nodes. Duplicate/empty node keys, negative +or non-finite gaps and extents are rejected. + +## Checks actually run + +``` +flutter pub get +dart format lib/features/graph/layout test/features/graph/layout +flutter test test/features/graph/layout # 21 passed +flutter analyze # No issues found! +flutter test # 173 passed +git diff --check # clean +``` + +Tests cover linear, diamond, cycle, self-loop, disconnected, terminals, +unknown/empty targets, heterogeneous extents, 2.6x expanded text, determinism, +bounds and invalid input. + +## Honest limits + +- **Nodes only.** Edge routing, ports, labels, lanes, hit testing, selection + highlighting, painting and native controls are separate later items. +- **Not rendered.** A pure nonvisual slice has no browser behavior to capture; + no screenshot or browser check applies. +- **No server or device.** Tests use local fixtures only; no run, pipeline, + schedule, service, emulator, ADB, Android/iOS build or live chat was touched. +- **Mobile unverified.** Only web-targeted Flutter test/analyze ran. +- **Uncommitted candidate.** Per this stage's instruction the slice is left in + the worktree; no commit, push or deployment was made. diff --git a/app/notes/P2c.md b/app/notes/P2c.md new file mode 100644 index 00000000..f8837940 --- /dev/null +++ b/app/notes/P2c.md @@ -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 edges, + required Map 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. diff --git a/app/notes/R1a.md b/app/notes/R1a.md new file mode 100644 index 00000000..b43992bd --- /dev/null +++ b/app/notes/R1a.md @@ -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. diff --git a/app/notes/R1b.md b/app/notes/R1b.md new file mode 100644 index 00000000..406dec62 --- /dev/null +++ b/app/notes/R1b.md @@ -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. diff --git a/app/notes/R1c2.md b/app/notes/R1c2.md new file mode 100644 index 00000000..e7eced2e --- /dev/null +++ b/app/notes/R1c2.md @@ -0,0 +1,50 @@ +# R1c2 — run detail native widget slice + +## Change + +`RunDetailView` keeps its existing `controller` and `onBack` API but now selects +its presentation from the host: MaterialApp uses the standard Material controls, +CupertinoApp uses Cupertino controls without a Material ancestor. Selection is +based on `MaterialLocalizations`, so it works on the web's desktop host and in +widget tests without relying on the browser's target platform. + +- Material: `Chip`, `ExpansionTile`, `ListTile`, `TextButton`, `IconButton`, + selectable text and `SnackBar` feedback. +- Cupertino: `CupertinoButton`, `CupertinoExpansionTile`, `CupertinoListTile` + and grouped list sections. Copy feedback is inline in a live-region status; + no `ScaffoldMessenger`/`SnackBar` is used. +- Loading and failure states are platform-specific and honest: only the error + text is shown when no detail exists, and the Back action remains available. + A refresh with retained detail reports `Refreshing run details…` instead of + clearing the view. +- The scrollable list has a stable per-run key and a test proves a live detail + update keeps its scroll offset. + +Detail-only helpers split formatting from presentation: + +- `run_detail_content.dart`: title/pipeline, prompt extraction, nested JSON, + usage metrics and recorded timeline entries. +- `run_detail_material.dart` and `run_detail_cupertino.dart`: the two native + presentations. +- Input/output are pretty-printed, selectable JSON. Copy prompt passes the + stored string byte-for-byte (no trim, no fallback field). +- Usage distinguishes reported zero from unknown: token/cost totals are + `Unavailable` unless the corresponding stage count proves reporting; a known + stage count with an omitted zero cost renders `$0.000000`. Timeline rows show + the server's recorded sequence. + +## Verification + +- `flutter test test/features/runs/ui/run_detail_widget_test.dart`: 7 tests + passed. They run both platforms at 390px width with 2x text, exercise + loading/error and Back, exact prompt copy and denied clipboard feedback, + nested JSON, recorded sequences, zero vs missing usage, and scroll retention. +- `flutter test test/features/runs`: 24 tests passed. +- `flutter analyze`: no issues. +- `flutter build web`: succeeded. + +## Limits + +No real browser interaction or rendered capture was performed in this slice; the +manager separately tracks R1 browser acceptance. Android/iOS builds and devices +were not run, so mobile is unverified. No commit, push or deployment was made. diff --git a/app/notes/R2a.md b/app/notes/R2a.md new file mode 100644 index 00000000..30ec1ace --- /dev/null +++ b/app/notes/R2a.md @@ -0,0 +1,84 @@ +# R2a — native human-decision action + +## What changed + +New `lib/features/runs/actions/` slice (no existing source file edited): + +| File | Lines | Responsibility | +| --- | --- | --- | +| `decision_action.dart` | 141 | `HumanDecisionAction`, gating, submit/refusal/resync orchestration | +| `decision_dialog.dart` | 248 | Material `AlertDialog` / Cupertino `CupertinoAlertDialog` prompt | +| `decision_wording.dart` | 24 | Web-verbatim words, meta/target formatting and test keys | +| `test/.../decision_action_test.dart` | 237 | Material/Cupertino deliberate send and gating | +| `test/.../decision_resilience_test.dart` | 240 | refusal resync, double submit, disposal, 2x/narrow | + +`HumanDecisionAction` takes the run, the shared `ApiGateway` and an +`onRunChanged` callback. It renders one `FilledButton` (`Decide`) on Material +and one `CupertinoButton.filled` on Cupertino, and nothing at all when +`pendingDecision(run)` is null. Recorded waiting-step options therefore win over +the pinned graph, and a pending session export suppresses the action through the +existing domain rule without duplicating it here. + +Opening the prompt sends nothing. The prompt uses the web wording +(`Waiting for your decision`, `Feedback (optional)`, `Cancel`, +`Confirm decision`, `Sending…`), shows the stage/run meta line and each option's +`→ target` when declared. Confirm is disabled until an option is selected; +selecting itself only updates the draft. Confirm calls `RunsRepository.decideRun` +with the exact stage, trimmed option and trimmed optional feedback (blank +feedback is omitted by the repository). + +A refusal is shown verbatim inside the kept-open prompt; the option selection +and feedback controller are untouched. The action then calls +`RunsRepository.getRun` and passes the refreshed run to `onRunChanged`. A +successful decision passes the server's `run_detail` to `onRunChanged` and +closes the prompt. Both sends are guarded in the prompt and in the owner state; +buttons are disabled while `Sending…`. Every asynchronous resume checks +`mounted` before `setState` or `onRunChanged`, so a late reply after disposal is +ignored. + +Platform style follows the enclosing app: `MaterialApp` gets the Material +dialog and controls, `CupertinoApp` gets the Cupertino dialog with native +buttons/radios/field. No custom palette, font family, fixed button/row size, +dependency or CSS token was added; the theme's error color and default control +spacing are used. The one optional `cupertino` override exists for +callers/tests that do not wrap in either app. + +## Checks actually run + +``` +flutter pub get # dependencies resolved +dart format lib/features/runs/actions test/features/runs/actions +flutter analyze # No issues found! +flutter test test/features/runs # 18 passed +flutter test # 36 passed +flutter test test/features/runs/actions # 7 passed +flutter build web # Built build/web (14.2s) +``` + +Focused coverage maps to the requested acceptance: + +- material: action visible, dialog open, selection does not send, Confirm is + disabled before selection, exact `decide_run` stage/option/`looks good` + feedback, callback gets the decided run and the action disappears; +- cupertino: native `CupertinoAlertDialog`, disabled Confirm first, blank + feedback omitted, exact request fields; +- gating: running, export-pending and non-human runs render no action; +- refusal: `decide_run` then `get_run`, verbatim error still visible, selected + option and typed feedback retained, refreshed failed run delivered to owner; +- double submit: two Confirm taps produce one `decide_run`, Cancel is disabled + while sending; +- stale disposal: completing the decision after the tree is replaced produces + no exception and no owner callback; +- 320×480 at 2x text on both apps: prompt opens with no rendering exception. + +## Honest limits + +- **Not wired into a run-detail screen.** `lib/features/runs/` has no screen or + controller on this branch; the manager owns that integration. There is + therefore no real browser interaction or capture for this widget. The + `flutter build web` result proves compilation only, not rendered behavior. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. + Source uses only portable Flutter/Cupertino/Material widgets. +- No real server or run was mutated. Tests use a local fake gateway. +- No repository/domain/controller/screen/main, `web/`, Go server, installer or + deployment file was changed. Nothing was committed, pushed or deployed. diff --git a/app/notes/R2b-refusal.md b/app/notes/R2b-refusal.md new file mode 100644 index 00000000..65851110 --- /dev/null +++ b/app/notes/R2b-refusal.md @@ -0,0 +1,92 @@ +# R2b-refusal — immediate refusals, separate resync + +Focused correction on the retained `faa5866` cancellation candidate. The action +source is now shared by both deliberate run actions (cancel and human decision); +no wiring, screen, controller, repository, socket, pubspec, web, server or +device file was touched. + +## What changed + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/runs/actions/action_refusal.dart` | 18 | Refusal message plus optional bounded re-read outcome; local guard words | +| `lib/features/runs/actions/cancel_run_action.dart` | 119 | Immediate refusal return, single-flight resync, ownership checks | +| `lib/features/runs/actions/cancel_dialog.dart` | 165 | Shows the refusal and re-enables Keep before the resync settles | +| `lib/features/runs/actions/decision_action.dart` | 176 | Same async flow for `decide_run`, draft preserved | +| `lib/features/runs/actions/decision_dialog.dart` | 268 | Shows refusal, keeps draft, disables retry only on server truth | +| `test/features/runs/actions/cancel_resilience_test.dart` | 271 | Three new fake-gateway regressions | +| `test/features/runs/actions/decision_resilience_test.dart` | 351 | Three new fake-gateway regressions | +| `test/features/runs/actions/decision_action_test.dart` | 265 | Cancel/no-request coverage | + +## Async flow + +A refused mutation no longer awaits `get_run` before returning: + +1. `_submit` catches the mutation error and computes the refusal text. +2. It returns `ActionRefusal(message, stillPossible: _resyncRun(id))` at once. + `_resyncRun` starts one `get_run` for that refusal; a concurrent refusal + observes the same future instead of issuing another request. +3. The prompt clears its sending state, shows the server's words and makes + Keep/Cancel available in the same frame. Back is enabled too (`PopScope` + only gates the in-flight mutation). Confirm stays disabled while the check + is pending and after it proves the action impossible, so a doomed mutation + cannot be resubmitted from the open prompt. +4. The resync runs detached but bounded: exactly one `get_run`, no retries or + polling. Every exception becomes `null` (unknown truth), which leaves the + refusal visible and a deliberate retry available. +5. Before delivering a refreshed run, the action checks `mounted` and that the + run id it owns is still the request's id. A late read after disposal or + navigation touches nothing and raises nothing. + +On success the mutation reply is still used directly, the prompt closes, and no +duplicate `get_run` is issued. The dialog and action keep the existing +in-flight double-submit guard. The human-decision prompt keeps the selected +option and feedback controller untouched while a refusal or resync is pending; +its retry is disabled only when the refreshed run no longer offers the same +decision (same stage and option keys). + +No repository, protocol or socket code changed. The web's `cancel_run` plus +silent refresh remains the reference; this version keeps the diagnostic in the +open prompt rather than moving it to the web's separate Action-failed dialog. + +## Regression coverage added + +Fake gateway, no socket or real server: + +- immediate `cancel_run` refusal plus a deliberately unresolved `get_run`: the + exact message is visible, Keep is enabled, confirm is disabled and no run + callback has fired **before** the resync completes; Keep closes the prompt; + a late resync still delivers server truth safely; +- late cancel resync after the whole action is disposed: no exception, no + callback; +- resync proving the run is no longer cancellable: refusal stays visible, + confirm cannot submit again (an attempted tap adds no request), Keep + dismisses and the ineligible run is delivered; +- immediate `decide_run` refusal plus an unresolved `get_run`: exact message, + selection and feedback retained, Cancel enabled, no callback yet; after the + resync proves the decision gone, the message remains and confirm is disabled; +- decision resync that fails: message and draft remain, Confirm is re-enabled + because server truth is unknown; +- late decision resync after disposal: no exception, no callback; +- Cancel on an untouched decision draft sends nothing and keeps the action + available. + +## Checks actually run + +``` +dart format lib/features/runs/actions test/features/runs/actions # clean +flutter analyze # No issues found! +flutter test test/features/runs/actions # 23 passed +flutter test # 52 passed +flutter build web # Built build/web +``` + +## Honest limits + +- Still **not wired into a run-detail screen** on this branch; there is no + browser interaction or rendered capture for this widget. `flutter build web` + proves compilation only. +- Mobile remains unverified: no Android/iOS build, emulator, ADB or device. +- No real server or run was mutated; all evidence uses local fakes. +- No commit, push, deployment or canonical-URL change is claimed here beyond + the candidate commit checked by the manager. diff --git a/app/notes/R2b.md b/app/notes/R2b.md new file mode 100644 index 00000000..0fda73b5 --- /dev/null +++ b/app/notes/R2b.md @@ -0,0 +1,96 @@ +# R2b — native run cancellation + +## What changed + +New `lib/features/runs/actions/cancel*` slice plus its tests. No existing source +file was edited. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/runs/actions/cancel_eligibility.dart` | 31 | Web-exact `canCancelRun`, run-id extraction, numeric export counter | +| `lib/features/runs/actions/cancel_wording.dart` | 23 | Web-verbatim words, dialog title, error text, test keys | +| `lib/features/runs/actions/cancel_dialog.dart` | 145 | Native Material/Cupertino confirmation and inline refusal | +| `lib/features/runs/actions/cancel_run_action.dart` | 101 | `CancelRunAction`, gating, send/refusal/resync orchestration | +| `test/features/runs/actions/cancel_test_support.dart` | 101 | Fake gateway, run fixtures, stateful host, app wrappers | +| `test/features/runs/actions/cancel_action_test.dart` | 192 | Eligibility and both-platform deliberate-confirm flows | +| `test/features/runs/actions/cancel_resilience_test.dart` | 176 | Refusal/resync, resync failure, double submit, disposal, 2x/narrow | + +`CancelRunAction` takes the run, the shared `ApiGateway` and an +`onRunChanged` callback. It renders one native `FilledButton` (`Cancel run`) on +Material and one `CupertinoButton.filled` on Cupertino, and nothing at all when +the browser rule says the run is not cancellable. Platform style follows the +enclosing app (`MaterialLocalizations` presence); no extra style parameter or +dependency was added. + +## Behaviour + +Eligibility is a direct port of `canCancel` in `../web/src/actions.js`: + +``` +(executing || (status == "waiting" && export_pending_sequence > 0)) + && !cancel_requested && !cleanup_unconfirmed +``` + +A run with a stale `running` status but `executing == false` is therefore not +cancellable, while a `waiting` run with a pending session export is. A run +without a numeric `id` is not offered because the request cannot be addressed +(the pure eligibility function still matches the web rule exactly). + +Opening the prompt sends nothing and `Keep` only closes it. The prompt uses the +web wording (`Cancel run {id}?`, `This asks the server to stop the active run.`, +`Cancel run`, `Keep`). Only the confirm action calls +`RunsRepository.cancelRun(id)`, which sends the exact envelope +`cancel_run {"run_id": id}`. + +Both the dialog and the action guard the in-flight state: a second confirm tap +or a `Keep` tap while sending is ignored, and the dialog's actions are disabled +until the reply arrives. A successful reply closes the prompt and passes the +server's returned `run_detail` to `onRunChanged`; no local status is invented. + +A refusal keeps the prompt open and shows the server's message verbatim. The +action then calls `RunsRepository.getRun(id)` and passes the refreshed run to +`onRunChanged`, so the owner sees server truth (for example the run finished +before cancellation). If the re-read also fails, the original refusal stays +visible and no synthetic run is delivered. Every asynchronous resume checks +`mounted` before `setState` or `onRunChanged`, so a late reply after disposal is +ignored. + +## Checks actually run + +``` +flutter pub get # dependencies resolved +dart format lib/features/runs/actions/cancel*.dart \ + test/features/runs/actions/cancel*.dart # clean +flutter analyze # No issues found! +flutter test test/features/runs/actions # 16 passed +flutter test # 45 passed +flutter build web # Built build/web (15.5s) +``` + +Focused coverage maps to the requested acceptance: + +- eligibility: executing, export-wait, waiting without export, stale `running` + without `executing`, already stopping, cleanup unconfirmed, finished/failed; + plus widget visibility for the same states; +- both platforms: native prompt opens, nothing is sent on open or `Keep`, exact + `cancel_run` envelope, callback receives the returned run, action disappears; +- refusal: cancellation error shown verbatim, `get_run` resync delivered to the + owner, and a failed resync leaves the refusal visible with no callback; +- double submit: two confirm taps produce one `cancel_run`, both actions disable; +- stale disposal: a reply after the tree is replaced causes no exception and no + callback; +- 320x480 at 2x text: both prompts open with no rendering exception. + +## Honest limits + +- **Not wired into a run-detail screen.** This branch has no run-detail screen + or controller; the manager owns integration. There is therefore no real + browser interaction or capture for this widget. `flutter build web` proves + compilation only, not rendered behavior, and no visible feature is claimed. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. + Source uses only portable Flutter/Cupertino/Material widgets. +- No real server or run was mutated. Tests use a local fake gateway with no + socket. +- No controller/screen/main/domain/repository/pubspec, `web/`, Go server, + installer or deployment file was changed. Nothing was committed, pushed or + deployed. diff --git a/app/notes/R2c.md b/app/notes/R2c.md new file mode 100644 index 00000000..f2240602 --- /dev/null +++ b/app/notes/R2c.md @@ -0,0 +1,114 @@ +# R2c — native retry / restart action + +Small app-only addition, new files only. `RetryRunAction(run, gateway, +onRunChanged)` is the deliberate retry entry point for a stopped failed run; it +does not add a screen or controller and is not wired into the shell. + +## What changed + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/runs/actions/retry_action.dart` | 123 | `RetryRunAction`, gating, send/refusal/resync orchestration | +| `lib/features/runs/actions/retry_dialog.dart` | 207 | Native resume/restart confirmation, refusal display, key lifetime | +| `lib/features/runs/actions/retry_eligibility.dart` | 16 | `canRetryRun` mirroring the web `canRetry` | +| `lib/features/runs/actions/retry_intent.dart` | 29 | Mode, confirmed intent and idempotency-key generation | +| `lib/features/runs/actions/retry_wording.dart` | 33 | Web-verbatim words, titles, error wording and test keys | +| `test/.../retry_test_support.dart` | 112 | Fake gateway and Material/Cupertino hosts | +| `test/.../retry_action_test.dart` | 245 | Eligibility, both platforms, modes and key fields | +| `test/.../retry_resilience_test.dart` | 223 | Immediate refusals, recheck outcomes, key retention | +| `test/.../retry_safety_test.dart` | 133 | Double submit, late replies, narrow 2x layout | + +No repository, gateway, socket, controller, shell, main, pubspec, web, server or +device file was edited. + +## Behavior + +Eligibility is exactly the browser's rule: a loaded run that is not executing and +whose status is `failed` (`run != null && !run.executing && status == "failed"`). +A stale `failed` status while execution is still in flight, a running/waiting/ +succeeded/canceled run, and a malformed run render nothing. + +The button is a Material `FilledButton` or a Cupertino `CupertinoButton.filled`, +labelled `Retry`. Opening the prompt sends nothing, and `Keep` only closes it. + +The first confirmation is the browser's retry copy: title `Retry run {id}?`, +message `Only failed runs can be retried. The server starts a new run from the +same input.`, confirm `Retry`, dismiss `Keep`, plus the browser-only secondary +`Restart from start` that leads to a distinct confirmation. That second prompt +uses title `Restart run {id}?`, message `This replays the whole pipeline from the +start instead of resuming the failed stage.` and confirm `Restart from start`; +the resume actions are gone, so the more destructive choice cannot be mistaken +for resume. + +Resume calls `RunsRepository.retryRun` with only `run_id` and `request_key`, so +`retry_mode` is omitted and the server's `resume` default applies. Restart sends +`retry_mode: "restart"` with the same two required fields. + +A `request_key` is created on the first confirm of an open prompt, not on opening +or `Keep`. It survives a refusal, so pressing confirm again for the same +uncertain request reuses the key and the server can dedupe it. Closing the prompt +and opening it again is a fresh deliberate intent and gets a new key, so a resume +attempt followed by a restart attempt never shares a key. Switching to the +restart confirmation before any send simply confirms restart with that prompt's +first key. Keys are bounded and run-scoped (`app-retry-{runId}-…`, well under the +server's 128-character cap). + +A server refusal returns to the prompt immediately: the exact server words are +visible and `Keep`/back are available while the detached `get_run` recheck is +still pending. One bounded re-read is issued per refusal, single-flight through a +retained future, with no retry loop or polling. If server truth says the run is no +longer retryable, confirm is disabled and an attempted tap sends nothing; the +refusal stays visible until dismissal. If the recheck itself fails, truth is +unknown, so confirm is re-enabled and a deliberate retry uses the retained key. +Late retry replies and late rechecks after disposal or navigation are ignored. + +Construction, controls and error colour are standard Material/Cupertino defaults; +there is no custom palette, fixed control size or dependency. The narrow layout +relies on the native dialog's own scrolling/wrapping. + +## Acceptance checks + +Fake-gateway widget tests, both platforms, no socket or real server: + +- eligibility table for stopped failed vs executing failed, running, waiting, + succeeded and canceled runs, plus the same visibility table under both apps; +- `Retry` opens the native `AlertDialog`/`CupertinoAlertDialog`, `Keep` closes it + and the recorded gateway calls are still empty; +- resume sends exactly `{run_id, request_key}` and no `retry_mode`; restart sends + exactly `{run_id, request_key, retry_mode: "restart"}`; +- key format is deterministic under an injected clock/entropy, bounded, fresh per + call, retained across an uncertain retry (resume and restart), and different + after a deliberate reopen or mode change; +- refusal message appears while `get_run` is deliberately unresolved, with Keep + enabled, confirm disabled and no callback yet; Keep then closes and the late + recheck still delivers server truth safely; +- ineligible recheck (`succeeded`) blocks a repeat action; failed recheck leaves + the same key and a working deliberate retry; +- two confirm taps while in flight produce one `retry_run`; both the retry reply + and the recheck are safe after disposal; +- 320×480 at 2× text: both resume and restart confirmations render on both apps + with no exception, and Keep sends nothing. + +## Checks actually run + +``` +dart format lib/features/runs/actions test/features/runs/actions # clean +flutter analyze # No issues found! +flutter test test/features/runs/actions # 40 passed +flutter test # 69 passed +flutter build web # Built build/web (14.5s) +``` + +## Honest limits + +- **Not wired into a run-detail screen.** This branch has no runs screen or + controller; the manager owns that integration. There is no browser interaction + or rendered capture for this widget, and `flutter build web` proves compilation + only, not rendered behavior. +- Browser parity is by source/word/request-shape comparison with + `web/src/actions.js` and `web/src/repository.js`; the web client itself was not + changed and no live web retry was performed. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. +- No real server or run was retried, canceled or otherwise mutated; all evidence + uses local fakes. +- The candidate is committed, not pushed or deployed. diff --git a/app/notes/R2d.md b/app/notes/R2d.md new file mode 100644 index 00000000..c262351f --- /dev/null +++ b/app/notes/R2d.md @@ -0,0 +1,93 @@ +# R2d — native run title rename + +## What changed + +New `lib/features/runs/actions/title*` slice plus its tests and this note. No +existing source file was edited. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/runs/actions/title_wording.dart` | 24 | Web-verbatim words, test keys, refusal wording | +| `lib/features/runs/actions/title_dialog.dart` | 183 | Native Material/Cupertino text-field prompt and inline refusal | +| `lib/features/runs/actions/title_action.dart` | 109 | `RunTitleAction`, stored-title seeding, send/deliver orchestration | +| `test/features/runs/actions/title_test_support.dart` | 110 | Fake gateway, run fixtures, stateful host, app wrappers | +| `test/features/runs/actions/title_action_test.dart` | 244 | Both-platform open/cancel/exact-save and stored-title seeding | +| `test/features/runs/actions/title_resilience_test.dart` | 243 | Refusal retention, double save, disposal, stale owner, 2x/narrow | + +`RunTitleAction(run: …, gateway: …, onRunChanged: …)` renders one native +`OutlinedButton` (`Rename`) on Material and one plain `CupertinoButton` on +Cupertino, and nothing for a run without a numeric id. Platform style follows the +enclosing app (`MaterialLocalizations` presence). No style overrides, fixed +component sizes or new dependencies. + +## Behaviour and web parity + +The prompt is seeded with the run's actual stored title exactly as the browser +reads it, `String(d.title ?? "")` in `web/src/views/runDetail.js`. It is never +derived from `input.prompt`, stage output or a placeholder. A missing title seeds +an empty field. + +Typing, opening and the dismiss action send nothing. Only `Save` calls the +existing `RunsRepository.setRunTitle(id, title)`, which sends the exact envelope: + +``` +set_run_title {"run_id": , "title": } +``` + +The field text is passed through untrimmed, matching `repo.setRunTitle(id, +String(state.renameValue ?? ""))` in `web/src/repository.js`. Leading/trailing +spaces and Unicode are preserved, and a blank title is sent as `""` so the server, +not the client, decides whether it is acceptable. There is no local +`canSubmit` gate on blank text. + +A refusal (including a blank-title refusal) is shown verbatim below the field and +the prompt stays open with the typed draft intact. Nothing is updated locally. +Only an accepted reply closes the prompt and passes the server's returned +`run_detail` once through `onRunChanged`; the action never fabricates a run or a +title. A second Save tap while sending is ignored, both dialog actions disable +until the reply, and every asynchronous resume checks `mounted`. A reply for a run +the widget no longer owns is dropped. + +## Checks actually run + +``` +dart format lib/features/runs/actions/title*.dart \ + test/features/runs/actions/title*.dart # clean +flutter analyze # No issues found! +flutter test test/features/runs/actions/title_action_test.dart \ + test/features/runs/actions/title_resilience_test.dart # 11 passed +flutter test test/features/runs # 45 passed +flutter test # 63 passed +flutter build web # Built build/web (16.2s) +``` + +Focused acceptance coverage: + +- both platforms: native button and dialog, stored title in the field, typing and + Cancel produce zero gateway calls, Save sends exact `set_run_title` fields; +- exact field values: Unicode plus leading/trailing whitespace preserved; blank + title sent as `""` and the server refusal shown with the blank draft retained; +- failed save: server words verbatim, draft retained, dialog open, no callback and + no local title change; transport failure likewise; +- double Save: one request, action buttons disabled while in flight; +- disposal: a late reply after the tree is replaced throws nothing and delivers + nothing; a reply after the widget's run id changes is not delivered; +- 320x480 at 2x text: both prompts open, show a long title and a refusal, and close + with no rendering exception; +- malformed run: no rename button, and the stored-title helper ignores prompts. + +## Honest limits + +- **Not wired into a run-detail screen.** This branch has no run-detail screen or + controller; the manager owns integration. No real browser interaction or + capture was performed, so rendered feature parity is not claimed. `flutter build + web` proves compilation of the existing entrypoint, not that this widget is + reachable or visible. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. + Source uses portable Flutter/Cupertino/Material widgets only. +- No real server, operator run or chat was touched. Tests use a local fake gateway + with no socket. +- No repository/domain/controller/shell/main/pubspec, `web/`, Go server, + installer or deployment file was changed. +- Nothing was committed, pushed or deployed; the files above are the candidate in + the working tree, per the stage instruction not to commit. diff --git a/app/notes/S1a.md b/app/notes/S1a.md new file mode 100644 index 00000000..58426e32 --- /dev/null +++ b/app/notes/S1a.md @@ -0,0 +1,94 @@ +# S1a — saved-schedule repository and record + +## What changed + +New, app-only files (no existing feature, shell, transport, `main` or pubspec +source edited): + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/schedules/data/schedules_repository.dart` | 116 | `list_schedules`, `save_schedule`, `delete_schedule` envelopes and reply checks | +| `lib/features/schedules/domain/saved_schedule.dart` | 87 | typed view over one saved run configuration; exact raw record retained | +| `lib/features/schedules/domain/schedule_rule.dart` | 41 | interval/clock/timezone/weekday fields of `rule` | +| `lib/features/schedules/domain/schedule_json.dart` | 22 | deep JSON copy used by every round trip | +| `test/features/schedules/data/schedules_repository_test.dart` | 132 | list/create/update envelopes, unchanged input, CAS revision | +| `test/features/schedules/data/schedules_delete_test.dart` | 131 | delete envelope, confirmations, refusals, missing/empty replies | +| `test/features/schedules/data/schedules_protocol_bounds_test.dart` | 81 | web-mirrored ID/revision/request-key bounds | +| `test/features/schedules/data/saved_schedule_record_test.dart` | 101 | provenance, unknown fields, deep-copy and absent-field behavior | +| `test/features/schedules/data/schedule_test_support.dart` | 83 | recording fake gateway and server-shaped fixtures | + +`app/.gitignore` also gained the missing `!/test/**/data/` exception. The root +`.gitignore` ignores every `data/` directory, so without it these assigned tests +would silently disappear from a fresh checkout. The existing `!/lib/**/data/` +exception is for the same reason. + +## Behavior copied from the current web client + +Requests are exactly the ones in `web/src/repository.js`: + +- `list_schedules` with no field, or `pipeline_id` for one pipeline. A positive + safe integer is required before sending; `{type:"schedules"}` or + `schedules:null` is an empty list, while a reply without `type:"schedules"` is + an error, not "no schedules". +- `save_schedule` with `schedule` unchanged. A non-empty `request_key` (at most + 128 characters) is added only for a create retry; updates omit it, as the web + editor does. Creation keeps the web sentinel `id: 0` and no revision. Updates + send the record read from the server, whose `revision` is the server's + compare-and-swap token. The reply is only accepted when it contains + `schedule`. +- `delete_schedule` with exactly `schedule_id` and `expected_revision`; only + `{type:"schedule_deleted", schedule_id:}` counts as success. + +Server refusals are not wrapped or translated. `ApiGateway` already turns an +`error` envelope into `ProtocolError` with the server's text, and the repository +lets that object through unchanged (conflict and unknown-command coverage in +`server refusals and conflicts propagate verbatim`). The repository has no +capability flags, no "not supported" substitution and no local fallback. + +Saved schedules are run configurations, never pipeline definitions. `SavedSchedule` +keeps the complete server map, including unknown future nested fields, and +exposes pipeline, version, prompt/input, workspace, rule (every/times/days/ +timezone), enabled, model/stage models, notify mode, write paths/tools, title, +output format, due time and timestamps. `toJson()` is a deep copy; `withEnabled` +preserves identity, revision and unknowns. Missing identity/revision stays +`null` rather than becoming a fabricated `0`. There is no timer execution, +polling, rule parsing into due dates or timezone conversion in this slice. + +## Checks actually run + +``` +flutter pub get +dart format lib/features/schedules test/features/schedules # 9 files, 5 changed, then clean +flutter test test/features/schedules/data # 18 passed +flutter analyze # No issues found! (1.4s) +flutter test # 70 passed +``` + +Focused coverage maps to the requested acceptance: + +- exact `list_schedules`/`save_schedule`/`delete_schedule` bodies recorded by a + fake gateway, including `expected_revision` only on delete and no invented + create revision/key; +- untouched caller record on save; deep equality of returned records with the + server reply including unknown top-level/rule/input fields; +- update reuses revision 3, accepts server revision 4 and leaves the stale draft + at 3; a mismatch is the server's refusal, propagated verbatim; +- empty list vs missing/unsupported schedules reply, missing/invalid saved + schedule, and delete confirmation for the wrong id/type; +- preflight bounds match the web client: pipeline id, schedule id, revision and + 129-character request keys send nothing; 128 characters is accepted; +- no fabricated identity when a reply contains an empty schedule object. + +## Honest limits + +- **No UI or wiring.** There is no schedules screen, editor, pause/delete control + or shell registration in this slice; the manager owns later UI integration. + No browser interaction or screenshot applies to this nonvisual item. +- **No live server used.** All checks use local recording fakes; no production + schedule, run or workflow was created, changed or deleted. No polling or + scheduler was touched. +- **Mobile unverified.** Only web-targeted Flutter tests and analysis ran. No + Android/iOS build, emulator, ADB or device was used; the code is pure Dart. +- **Not committed.** The stage instruction for this visit forbids commit, push + and deploy, so the candidate remains in the `flutter/s1-data` worktree for the + manager to inspect and commit. No deployment or preview was performed. diff --git a/app/notes/S1b.md b/app/notes/S1b.md new file mode 100644 index 00000000..95149094 --- /dev/null +++ b/app/notes/S1b.md @@ -0,0 +1,167 @@ +# S1b — saved-schedules list (read-only) + +## What changed + +App-only files; no existing feature, shell, `main`, pubspec, data/domain or +server source edited. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/schedules/screen.dart` | 94 | `SchedulesScreen(gateway, onOpen, pipelineId)` body; owns controller, search text and scroll | +| `lib/features/schedules/ui/list/schedule_list_controller.dart` | 168 | list load, newest-only publish, search/enabled filter, failure classification, cached visible view | +| `lib/features/schedules/ui/list/schedule_list_view.dart` | 188 | adaptive list, loading/empty/error states, stable error-banner slot | +| `lib/features/schedules/ui/list/schedule_list_toolbar.dart` | 179 | native search, all/enabled filter, refresh, count | +| `lib/features/schedules/ui/list/schedule_list_row.dart` | 115 | tappable row with server fields | +| `lib/features/schedules/ui/list/schedule_list_format.dart` | 70 | honest value/date/count wording | +| `test/features/schedules/ui/list/schedules_screen_test.dart` | 171 | search, filter, empty-filter wording, onOpen, states, unsubscribe | +| `test/features/schedules/ui/list/schedules_refresh_test.dart` | 119 | query/scroll preservation across successful and failed refresh | +| `test/features/schedules/ui/list/schedules_layout_test.dart` | 79 | Material + Cupertino at 390px, 1x and 2x text | +| `test/features/schedules/ui/list/schedule_list_controller_test.dart` | 182 | envelopes, empty/unsupported/error wording, ordering, dispose | +| `test/features/schedules/ui/list/schedule_list_filter_test.dart` | 87 | search/filter behavior and cache invalidation | +| `test/features/schedules/ui/list/schedule_list_format_test.dart` | 72 | complete/missing/invalid values and fixed due-time wording | +| `test/features/schedules/ui/list/schedule_list_test_support.dart` | 143 | recorded/immediate and controlled fake gateways | +| `test/features/schedules/ui/list/schedule_screen_harness.dart` | 33 | 390px test app builder | +| `tool/schedules_list_probe_app.dart` | 110 | local-only browser fixture (fake schedules, light/dark) | +| `tool/schedules_list_probe.mjs` | 252 | real Chrome probe, content assertions, five captures | + +## Behavior + +`SchedulesRepository.listSchedules` and `SavedSchedule` are reused unchanged. +The screen calls only `list_schedules`, with `pipeline_id` when supplied. There +is no add/edit/delete/pause/enable control and no other request type. + +- A valid empty reply shows `No schedules yet.` An older/unsupported envelope is + a distinct error (`This server does not support saved schedules…`), and a + transport/repository error keeps its actual text. A failed refresh with rows + already loaded keeps those rows and shows the error above them. +- Older-server detection now matches the web client's wording + (`unknown (message|request|command)` and `unsupported…schedule`, case + insensitive) in addition to the repository's `no schedules response` report, + so a real server refusal receives the same upgrade guidance as the web. +- Search matches schedule name, prompt and the actual pipeline ID (`Pipeline 4`, + including a bare `4`). No pipeline name exists in the saved-schedule record, so + matching names is not possible without another request; none is faked. +- Filter is `All` / `Enabled`. Paused rows remain visible under `All`. When the + search box is empty and only the filter hides every row, the empty state says + `No enabled schedules.`; an entered query still says + `No schedules match this search.` +- Rows show the server's pipeline ID, pinned version, workspace, timer rule, + timezone and `next_due`. Missing values stay `Pipeline unavailable`, + `Version unavailable`, `Workspace unavailable`, `Timer unavailable`; an + omitted/`Local` timezone is `Server timezone`; an absent/invalid due time is + `Not scheduled` / `Next time unavailable`; a paused row shows `Paused`. + Due values are converted to local time and labelled `(your local time)`, + matching the web client's wording. +- Selecting a row passes the exact `SavedSchedule` object from the loaded list to + `onOpen`; it does not re-fetch, copy into a draft or mutate it. +- Query, filter and list are not recreated by refresh, so the search text and + `ScrollController` offset survive. The failed-refresh banner occupies a + permanently present slot above the list, so showing or clearing it does not + change the list's ancestor chain or rebuild its `Scrollable`. Only the newest + refresh generation may publish; stale replies and replies after dispose are + ignored. +- The filtered view is cached in the controller and invalidated on query, + filter and new replies, so one rebuild does not repeat the same O(n) pass for + the body, count and toolbar. + +Controls are native defaults: Material `TextField`, `SegmentedButton`, +`IconButton`, `TextButton`, `Divider`, `CircularProgressIndicator`; Cupertino +`CupertinoSearchTextField`, `CupertinoSlidingSegmentedControl`, +`CupertinoButton`, `CupertinoActivityIndicator`. No CSS palette, custom font, +fixed row height or bespoke control was added. Layout is a content-driven column +with wrapping text; a single max-width constraint keeps the filter compact on +wide screens. + +## Review findings addressed + +- **M1 (must-fix), failed refresh reset the scroll offset.** Reproduced with the + new `schedules_refresh_test.dart` against the previous structure: the test + failed because the `Expanded` child changed from `ListView` to + `Column(banner, Expanded(ListView))`, recreating the `Scrollable`. With the + permanent banner slot the test passes for both the failure transition and the + later recovery/retry, at the unchanged offset. The test was also run against a + temporary local revert of the fix and failed as expected, then restored. +- **Advisory 1**, filter-only empty state: now `No enabled schedules.` unless a + query is active. +- **Advisory 2**, older-server wording: web-parity regex added and tested with + raw `unknown request`, `UNKNOWN COMMAND` and `Unsupported schedules command` + errors; unrelated errors keep their exact text. +- **Advisory 5**, repeated filtering: visible list cached and invalidated. +- **Advisory 6**, test oracle: the layout test now asserts the literal + `Next due: 2026-10-22 09:00 (your local time)` from a zone-less fixture instant; + the duplicated formatter helper was removed from the harness. +- **Advisory 7**, Material dark evidence: the fixture accepts + `?brightness=dark` and the probe captures Material dark at 390px. + +Advisory 3 (typed repository reason instead of matching a private message +string) needs a change in the landed `data/schedules_repository.dart`, outside +this list slice; the exact-string mapping is retained and documented. Advisory +4 (formatting in the rule's IANA timezone) still needs a timezone package. + +## Checks actually run + +``` +dart format --set-exit-if-changed lib/features/schedules \ + test/features/schedules/ui/list tool/schedules_list_probe_app.dart + # 19 files, 0 changed + +flutter test test/features/schedules/ui/list # 29 passed +flutter test # 110 passed +flutter analyze # No issues found! +flutter build web # ✓ Built build/web +flutter build web -t tool/schedules_list_probe_app.dart # ✓ Built build/web +node --check tool/schedules_list_probe.mjs # clean +node tool/schedules_list_probe.mjs --out …/public/s1b-schedules-captures + # 5 captures, content assertions passed +``` + +The focused suite covers the list envelope (with and without `pipeline_id`), +empty vs unsupported vs transport errors, older-server wording, a failed refresh +retaining rows, out-of-order refresh, disposal safety, search/filter behavior and +cache invalidation, `onOpen` receiving the exact raw record, no mutation calls, +query preservation, a successful and a failed refresh preserving scroll (plus +recovery), filter-only empty wording, both MaterialApp and CupertinoApp at 390px +with 1x and 2x text, and no render overflow. + +## Browser evidence + +Real headless Chrome served the fixture build on an OS-assigned loopback port, +with explicit MIME types, Flutter semantics enabled, and content assertions +before each capture: + +- `/Users/alan/.local/share/pipelines/data/artifacts/58/public/s1b-schedules-captures/s1b-schedules-material-390.png` +- `…/s1b-schedules-material-390-2x.png` +- `…/s1b-schedules-material-390-dark.png` +- `…/s1b-schedules-cupertino-390.png` (platform dark appearance) +- `…/s1b-schedules-material-1100.png` +- `…/manifest.json` + +The fixture uses a local fake gateway with four records (enabled, paused, clock +rule, sparse record). It never contacted a Pipelines server, bypassed +authentication or created/changed a real schedule or run. + +## Full diff + +Every changed path is new and untracked; no pre-existing work was modified, +reset or deleted. The complete patch is saved at: + +`/Users/alan/.local/share/pipelines/data/artifacts/58/public/s1b-schedules-list.diff` + +## Honest limits + +- **Not committed.** This stage forbids commit/push/deploy, so the candidate + remains uncommitted in the `flutter/s1-list` worktree for the manager. +- **Not wired into the shell.** `lib/main.dart`, `lib/shell/` and destination + registration are untouched; the Schedules destination still shows its + placeholder until the separate integration item. +- **No schedule editor.** Create/edit/delete/pause remain separate follow-up + items; no mutation was implemented or exercised. +- **Pipeline-name search unavailable.** The saved-schedule record exposes only + `pipeline_id`; search uses that exact ID rather than inventing a name. +- **Due times use the device timezone.** The absolute `next_due` instant is shown + as `(your local time)` and the rule timezone separately. The web client can + format in the rule's IANA timezone; that needs a timezone package not available + in this slice. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. +- **Live server unverified.** Browser evidence is fixture-only by design; no + production authentication or schedule data was used. diff --git a/app/notes/T1a.md b/app/notes/T1a.md new file mode 100644 index 00000000..e8a39fc4 --- /dev/null +++ b/app/notes/T1a.md @@ -0,0 +1,140 @@ +# T1a — template catalogue, validate and create-only submit + +## What changed + +New nonvisual `templates` data/domain slice. One shared file was edited: +`app/.gitignore` re-includes `test/**/data/`, because the repository's runtime +`data/` rule was silently excluding this slice's tests from the candidate. No +other lane's work, `lib/main.dart`, shell, pubspec, `web/`, server or Android +file was touched. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/templates/domain/template_entry.dart` | 63 | Immutable server template; models key/name/description/source/scheduled and keeps every unknown field in deeply read-only `raw` | +| `lib/features/templates/data/template_repository.dart` | 84 | `TemplateRepository(ApiGateway)`: list, validate, create-only submit | +| `test/features/templates/data/template_test_support.dart` | 47 | Recording/refusing fake gateways, server-refusal error, Unicode source fixture | +| `test/features/templates/data/template_list_test.dart` | 165 | Catalogue request shape, field preservation, deep immutability, missing/malformed catalogue | +| `test/features/templates/data/template_create_test.dart` | 147 | Validate/submit envelopes, blank-name gate, missing payloads, verbatim refusals | +| `app/.gitignore` | +4 | Re-includes `test/**/data/` so test files enter the candidate | + +Nothing under `lib/main.dart`, `lib/shell/`, another feature, `pubspec.*`, +`web/`, the Go server or `android/` was changed. No dependency was added. + +## Review findings addressed + +- **Tests could never land (blocking).** `test/features/templates/data/` was + excluded by the repository root rule `data/`; `app/.gitignore` only re-included + `lib/**/data/`. The same negation now covers `test/**/data/`, so these three + test files are untracked-but-visible to git and `git add -n` succeeds. Fixing + the rule (rather than `git add -f`) also protects later `test/**/data/` lanes + such as S1a. No test was moved, so `test/` still mirrors `lib/`. +- **`raw` was only shallowly immutable (advisory).** `TemplateEntry.fromJson` + now deep-copies nested maps/lists into read-only collections, and the listed + test proves nested mutation throws and that the copy does not alias the reply. +- **Malformed-catalogue branches were untested (advisory).** Added tests for a + non-list `templates` value and a non-object catalogue entry, both rejecting + with explicit messages. +- `_text` still stringifies a non-string protocol value with `'$value'`; the + protocol only sends strings, and this matches how the browser would render + such a value, so the behaviour was left unchanged and is documented here + rather than claimed as strict parity. + +## Wire behaviour (mirrors `web/src/repository.js`) + +- `listTemplates()` sends exactly `{"type":"list_templates"}` with no fields and + returns the `templates` catalogue. A reply with no `templates` field is the + older server's empty catalogue (`?? []` in the browser), not a fake template. + Each entry keeps `key`, `name`, `description`, `source`, `scheduled` and all + unknown fields in `TemplateEntry.raw`; the reply list/maps are never mutated. + `raw` is a deep unmodifiable copy: nested unknown maps and lists are copied + into read-only collections, so neither the view nor a later caller can mutate + the server reply through it. +- `listTemplates()` rejects a malformed envelope instead of fabricating + entries: a non-list `templates` throws + `"The server returned no template catalogue."` and a non-object entry throws + `"The server returned a template that is not an object."`. The real server + cannot produce either, but a protocol mistake must not look like an empty or + half-populated catalogue. +- `validate(source)` sends exactly `{"type":"validate","source":}` and + returns the reply's `graph`. A reply without a graph throws + `TemplateRepositoryException("The server returned no graph.")` — the browser's + exact words — rather than reporting a valid definition. +- `submit(name, source)` sends exactly + `{"type":"submit","name":,"source":,"create_only":true}`. + A blank/whitespace-only name is refused locally with + `TemplateRepositoryException("Enter a pipeline name.")` and no gateway call is + made; the accepted name is trimmed. A reply without `detail` throws + `TemplateRepositoryException("The server returned no pipeline detail.")`. +- The source string is never trimmed, normalised or re-encoded: Unicode, tabs, + newlines and significant leading/trailing whitespace arrive unchanged. +- A server refusal is never caught or reworded by the repository. It reaches the + caller as the same gateway error object, so the server's own text is shown. +- The repository exposes only these three operations. It has no publish, run, + schedule or overwrite path, so loading or validating a template cannot start + work or mutate a retained pipeline. + +## Checks actually run + +``` +flutter pub get # Got dependencies +dart format lib/features/templates test/features/templates # clean +flutter analyze # No issues found! (0.9s) +flutter test test/features/templates # 13 passed +flutter test # 76 passed +flutter build web # ✓ Built build/web (15.5s) +git diff --check # clean +git check-ignore / git add -n # tests are no longer ignored +``` + +Tests are part of the candidate, not merely present on disk: + +``` +$ git add -n app/test/features/templates/data/template_list_test.dart \ + app/test/features/templates/data/template_create_test.dart \ + app/test/features/templates/data/template_test_support.dart +add 'app/test/features/templates/data/template_create_test.dart' +add 'app/test/features/templates/data/template_list_test.dart' +add 'app/test/features/templates/data/template_test_support.dart' +exit=0 + +$ git status --porcelain=v1 -uall + M app/.gitignore +?? app/lib/features/templates/data/template_repository.dart +?? app/lib/features/templates/domain/template_entry.dart +?? app/notes/T1a.md +?? app/test/features/templates/data/template_create_test.dart +?? app/test/features/templates/data/template_list_test.dart +?? app/test/features/templates/data/template_test_support.dart +``` + +Focused acceptance coverage: + +- exact `list_templates` request (no fields, one call) and preservation of + modelled plus unknown fields, including nested unknown data; +- listing does not mutate the reply's template list or entry maps; `raw` and + every nested map/list are read-only, and the copy does not alias the reply; +- missing catalogue -> empty list; malformed catalogue -> explicit refusal; +- blank/whitespace name -> refusal with zero gateway calls; +- Unicode/emoji, tab/newline and leading/trailing source whitespace preserved in + both `validate` and `submit`; submit sends only name, source and + `create_only: true`, with the name trimmed; +- missing `graph` and missing `detail` rejected with the browser's exact + messages, with no fabricated graph/detail; +- validate and submit server refusals surface as the identical error object, + not a wrapper. + +## Honest limits + +- **Not wired into a screen.** This branch has no templates screen and the task + owns data/domain only; the manager owns integration. No browser capture was + made because there is no rendered change in this slice. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. + The code is plain Dart with no platform-specific code. +- No live server, template catalogue, validate call or submit/creation was + performed. All tests use local fake gateways with no socket, so no real + pipeline was created or run. +- No export-gate workaround, server change or service operation was made; the + pending export-cap fix remains another lane's scope. +- **Not committed.** The stage instruction says not to commit, push or deploy, + so the candidate above is uncommitted in the working tree even though the run + prompt asks to commit a reviewed candidate. Nothing was pushed or deployed. diff --git a/app/notes/X1.md b/app/notes/X1.md new file mode 100644 index 00000000..72e19645 --- /dev/null +++ b/app/notes/X1.md @@ -0,0 +1,121 @@ +# X1 — Omni-search + +## Scope and API + +Implemented the `search` feature under `lib/features/search/` with no +`main.dart`, shell, pubspec, server, web or Android edits. + +Entry point: + +```dart +SearchScreen( + gateway: apiGateway, // required ApiGateway + onOpen: (hit) { ... }, // required ValueChanged + cupertino: null, // optional; omitted = iOS/macOS Cupertino, else Material +) +``` + +`onOpen` always receives the server's original result map unchanged, including +its `target`. Unknown/absent payloads and results without a target are +read-only and never call `onOpen`; the client never invents a route or mutates +server state. + +Request shape is exact and shared-gateway only: + +```json +{"type":"search","search":{"query":"plan","kind":"","limit":0}} +``` + +`limit` is always `0` (server default cap), never a client-chosen larger value. + +## Behaviour + +- `t:`/`type:` tokens: unquoted, whitespace-delimited, case-insensitive, last + supported token wins; quoted, escaped, unknown and trailing-punctuation + tokens stay literal. The parser mirrors `web/src/search.js`. +- Kind selector: All kinds / Pipelines / Runs / Steps / Fields / Artifacts / + Versions. Changing it removes recognised type tokens from the field and sends + at once, like the browser's selector. +- Empty text with All kinds clears locally and sends nothing. Blank text with a + valid kind is a kind-only browse, matching the server/browser contract. +- 250 ms debounce; Enter sends at once. Every request carries a monotonically + increasing token, and replies for superseded edits are dropped. +- Loading, searching, retained-results refresh progress, empty (query-specific + and kind-only wording) and error are distinct. A truncated reply with no rows + says the server's scan limit was reached and keeps its truncation/scan bounds + on screen instead of claiming a complete empty; a complete empty has no bounds + line. A reply without `search_results` and an unknown-command rejection use + the server-upgrade sentence; any other failure shows the server's own text. + Error state offers Retry. +- Rows show the kind derived from the server payload (`Unrecognised result` for + an unknown payload), title, snippet (first case-insensitive query occurrence in + bold), and recency. Bounds show result count, cap, scanned steps/bytes, scan + limit and a truncation sentence when the server reports it, including for a + truncated reply with zero rows. +- In-hand results are re-narrowed by the effective kind while a narrowed request + loads, so the list always agrees with the control. +- Standard platform controls only: Material `SearchBar`, dropdown, + `LinearProgressIndicator`, `CircularProgressIndicator`, `ListTile`, + `FilledButton.tonalIcon`; Cupertino `CupertinoSearchTextField`, action-sheet + kind picker, `CupertinoListSection`/`CupertinoListTile`, + `CupertinoActivityIndicator`, `CupertinoButton.filled`. No CSS port, custom + palette, fixed row/bubble dimensions or bespoke buttons. Typography and + colours come from the ambient Material/Cupertino theme; rows and the header + scroll in one `CustomScrollView` so 2× text never clips. + +## Automated checks + +Run from `app/` with `/Users/alan/development/flutter/bin/flutter`: + +- `flutter test test/features/search` — **36 passed** (controller, repository, + query/token parser, row/snippet/routing, Material + Cupertino widget tests). +- `flutter test` — **65 passed** (whole app suite, including existing transport, + runs and shell tests). +- `flutter analyze` — **No issues found**. +- `flutter build web` (default `lib/main.dart`) — **succeeded**. +- `flutter build web -t tool/search_fixture/main.dart` — **succeeded** for the + rendered probe. +- `node --check tool/search_probe.mjs` — passed. +- `git diff --no-index --check /dev/null ` on every touched file — no + whitespace errors (all task files are untracked, so plain `git diff --check` + would not see them). + +Tests were written before the implementation (initial run failed on missing +symbols). Coverage includes the exact envelope, token parsing, selector token +clearing, no-request empty state, stale success and failure replies, +error/retry, truncation/bounds (including a truncated reply with zero rows), +per-kind row text, snippet spans, read-only hits, `onOpen` targets, and +MaterialApp/CupertinoApp at 390/1000 wide with 2× text. + +## Rendered browser evidence + +Built the Web-only fixture (`tool/search_fixture/main.dart`) and drove real +headless Chrome through CDP with `tool/search_probe.mjs` on an OS-assigned +loopback port. The probe typed `plan` into the real field, asserted five rows, +the server snippet, recency and truncation/scanned bounds, then clicked the +pipeline row and asserted that the fixture receiver got `pipeline:24`. It also +typed `needle` with no matching fixtures and asserted the Material and Cupertino +truncated-empty copy plus the retained `Results truncated … 0 results … scanned +2000 steps … scan limit 1.0 MiB` line, capturing both. + +Captures are in the run's shared artifacts: + +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-material-phone.png` — 390×844, Material controls, five mixed-kind results with recency/snippet/bounds. +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-material-desktop.png` — 1280×800, same results. +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-cupertino-phone.png` — 390×844, Cupertino search field/kind picker/grouped rows, dark system theme. +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-open-target.png` — the row click landing on `Opened pipeline target: pipeline:24`. +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-truncated-empty.png` — 390×844 Material, zero rows with the server's scan-limit sentence and truncation/scan bounds. +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-truncated-empty-cupertino.png` — 390×844 Cupertino dark, the same bounded empty state. + +The fixture and probe are development-only entry points; they are not imported +by `lib/main.dart` and are not part of the production routing. The browser run +used a static fake gateway, not a live Pipelines server or operator data. + +## Not verified / open items + +- No shell registration or navigation wiring was added (manager owns + `main.dart`/`shell/`); the screen is exported for that integration. +- No real server, operator chat/run, or production URL was used. +- Mobile targets (Android/iOS) were **not** built, installed or exercised; + only Web was rendered and tested. Source is kept portable. +- No commit, push, deployment or canonical URL change was made. diff --git a/app/pubspec.lock b/app/pubspec.lock index 8cdb6395..b36726e5 100644 --- a/app/pubspec.lock +++ b/app/pubspec.lock @@ -108,7 +108,7 @@ packages: source: sdk version: "0.0.0" flutter_web_plugins: - dependency: transitive + dependency: "direct main" description: flutter source: sdk version: "0.0.0" diff --git a/app/pubspec.yaml b/app/pubspec.yaml index b29fa9d1..fa4a079a 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -36,6 +36,8 @@ dependencies: cupertino_icons: ^1.0.8 web_socket_channel: ^3.0.3 shared_preferences: ^2.5.6 + flutter_web_plugins: + sdk: flutter dev_dependencies: flutter_test: diff --git a/app/test/application/app_route_test.dart b/app/test/application/app_route_test.dart new file mode 100644 index 00000000..598dce52 --- /dev/null +++ b/app/test/application/app_route_test.dart @@ -0,0 +1,52 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/app_route.dart'; + +void main() { + test('parses each destination and a run detail', () { + expect(AppRoute.parse('/pipelines'), AppRoute.pipelines); + expect(AppRoute.parse('/runs'), AppRoute.runs); + expect(AppRoute.parse('/runs/12'), AppRoute.run(12)); + expect(AppRoute.parse('/chat'), AppRoute.chat); + expect(AppRoute.parse('/settings'), AppRoute.settings); + }); + + test('normalises slashes and accepts a full URL, query and fragment', () { + expect(AppRoute.parse('/runs/'), AppRoute.runs); + expect(AppRoute.parse('/pipelines///'), AppRoute.pipelines); + expect( + AppRoute.parse('http://127.0.0.1:8096/runs/7?action=decide#top'), + AppRoute.run(7), + ); + expect(AppRoute.parse('/runs/7/'), AppRoute.run(7)); + }); + + test('a malformed or unknown location is the default Pipelines route', () { + for (final path in [ + '', + '/', + '/runs/abc', + '/runs/0', + '/runs/-1', + '/runs/1/extra', + '/pipelines/2', + '/chat/session', + '/unknown', + '/runs/%E0%A4%A', + ]) { + expect(AppRoute.parse(path), AppRoute.pipelines, reason: path); + } + }); + + test('serialises every route back to a parsable path', () { + for (final route in [ + AppRoute.pipelines, + AppRoute.runs, + AppRoute.run(3), + AppRoute.chat, + AppRoute.settings, + ]) { + expect(AppRoute.parse(route.path), route); + } + expect(AppRoute.run(3).path, '/runs/3'); + }); +} diff --git a/app/test/application/app_session_test.dart b/app/test/application/app_session_test.dart new file mode 100644 index 00000000..28233da0 --- /dev/null +++ b/app/test/application/app_session_test.dart @@ -0,0 +1,174 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/app_session.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; + +import '../core/transport/pipelines_client_test.dart' show FakeChannel; + +Future flush() => Future.delayed(Duration.zero); + +Future waitFor(bool Function() condition, String reason) async { + for (var attempt = 0; attempt < 200; attempt++) { + if (condition()) return; + await Future.delayed(const Duration(milliseconds: 5)); + } + fail('Timed out: $reason'); +} + +List types(FakeChannel channel) => [ + for (final frame in channel.outgoing) + (jsonDecode(frame as String) as Map)['type'] as String, +]; + +void main() { + test('Retry preserves an endpoint changed through shared Settings', () async { + final endpoints = []; + final client = PipelinesClient( + channelFactory: (uri) { + endpoints.add(uri); + return FakeChannel()..readyCompleter.complete(); + }, + ); + final session = AppSession( + endpoint: Uri.parse('ws://original.test/connect'), + client: client, + ); + addTearDown(session.dispose); + await session.start(); + final changed = Uri.parse('ws://selected.test/connect'); + await session.client.connect(changed); + await session.stop(); + await session.retry(); + expect(endpoints, [ + Uri.parse('ws://original.test/connect'), + changed, + changed, + ]); + expect(session.endpoint, changed); + }); + + test( + 'start subscribes once, stop unsubscribes, and the app owns the socket', + () async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final session = AppSession( + endpoint: Uri.parse('ws://example.test/connect'), + client: client, + ); + + await session.start(); + await flush(); + expect(session.connected, isTrue); + expect(types(channel), ['subscribe']); + final frame = jsonDecode(channel.outgoing.single as String) as Map; + expect(frame['workspace'], ''); + + await session.stop(); + await flush(); + expect(types(channel), ['subscribe', 'unsubscribe']); + expect(session.connected, isFalse); + session.dispose(); + }, + ); + + test('reconnect subscribes the new socket again', () async { + final first = FakeChannel()..readyCompleter.complete(); + final second = FakeChannel()..readyCompleter.complete(); + var sockets = 0; + final client = PipelinesClient( + channelFactory: (_) => sockets++ == 0 ? first : second, + backoffBase: const Duration(milliseconds: 5), + ); + final session = AppSession( + endpoint: Uri.parse('ws://example.test/connect'), + client: client, + ); + addTearDown(session.dispose); + + await session.start(); + await flush(); + expect(types(first), ['subscribe']); + expect(session.connectionEpoch, 1); + + first.incoming.addError(StateError('network drop')); + await waitFor( + () => sockets == 2 && session.connected && second.outgoing.isNotEmpty, + 'reconnected socket did not subscribe', + ); + expect(types(second), ['subscribe']); + expect(session.connectionEpoch, 2); + }); + + test('a subscribe ack marks the watch live, a refusal reports it', () async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final session = AppSession( + endpoint: Uri.parse('ws://example.test/connect'), + client: client, + ); + addTearDown(session.dispose); + + await session.start(); + await flush(); + final subscribe = + jsonDecode(channel.outgoing.single as String) as Map; + expect(session.subscription, RunSubscriptionState.pending); + + channel.incoming.add( + jsonEncode({'id': subscribe['id'], 'type': 'subscribe'}), + ); + await flush(); + expect(session.subscription, RunSubscriptionState.live); + expect(session.subscriptionError, isEmpty); + + session.resubscribe(); + await flush(); + final repeated = + jsonDecode(channel.outgoing.last as String) as Map; + expect(repeated['type'], 'subscribe'); + channel.incoming.add( + jsonEncode({ + 'id': repeated['id'], + 'type': 'error', + 'error': 'too many run subscriptions on this connection', + }), + ); + await flush(); + expect(session.subscription, RunSubscriptionState.refused); + expect(session.subscriptionError, contains('too many run subscriptions')); + }); + + test('dispose drops the watch and releases the client', () async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final session = AppSession( + endpoint: Uri.parse('ws://example.test/connect'), + client: client, + ); + + await session.start(); + await flush(); + session.dispose(); + await flush(); + + expect(types(channel), ['subscribe', 'unsubscribe']); + await expectLater( + client.connect(Uri.parse('ws://example.test/connect')), + throwsStateError, + ); + }); + + test('a missing endpoint is not replaced by a guessed connection', () async { + final channel = FakeChannel(); + final client = PipelinesClient(channelFactory: (_) => channel); + final session = AppSession(endpoint: null, client: client); + addTearDown(session.dispose); + + await session.start(); + await flush(); + expect(channel.outgoing, isEmpty); + expect(session.connected, isFalse); + }); +} diff --git a/app/test/application/pipelines_app_test.dart b/app/test/application/pipelines_app_test.dart new file mode 100644 index 00000000..b92c3b41 --- /dev/null +++ b/app/test/application/pipelines_app_test.dart @@ -0,0 +1,177 @@ +import 'dart:convert'; + +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/pipelines_app.dart'; +import 'package:pipelines_app/application/server_endpoint.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; + +import '../core/transport/pipelines_client_test.dart' show FakeChannel; + +ServerEndpoint webServer() => ServerEndpoint.resolve( + base: Uri.parse('http://127.0.0.1:8096/'), + web: true, +); + +Map? requestOf(FakeChannel channel, String type) => channel + .outgoing + .map((frame) => jsonDecode(frame as String) as Map) + .where((frame) => frame['type'] == type) + .firstOrNull; + +Future pumpApp( + WidgetTester tester, { + required FakeChannel channel, + required PipelinesClient client, + required PlatformRouteInformationProvider provider, +}) async { + await tester.pumpWidget( + PipelinesApp( + server: webServer(), + client: client, + cupertino: false, + routeInformationProvider: provider, + ), + ); + await tester.pump(); +} + +Future replyList( + WidgetTester tester, + FakeChannel channel, { + required List> runs, +}) async { + for ( + var attempt = 0; + attempt < 40 && requestOf(channel, 'list_runs') == null; + attempt++ + ) { + await tester.pump(const Duration(milliseconds: 5)); + } + final request = requestOf(channel, 'list_runs')!; + channel.incoming.add( + jsonEncode({'id': request['id'], 'type': 'runs', 'runs': runs}), + ); + await tester.pump(); + await tester.pump(); +} + +Future replyDetail( + WidgetTester tester, + FakeChannel channel, + num id, +) async { + for ( + var attempt = 0; + attempt < 40 && requestOf(channel, 'get_run') == null; + attempt++ + ) { + await tester.pump(const Duration(milliseconds: 5)); + } + final request = requestOf(channel, 'get_run')!; + expect(request['run_id'], id); + channel.incoming.add( + jsonEncode({ + 'id': request['id'], + 'type': 'run', + 'run_detail': {'id': id, 'title': 'Run $id', 'status': 'running'}, + }), + ); + await tester.pump(); + await tester.pump(); +} + +void main() { + testWidgets('a /runs/1 boot link opens that run and Back returns to /runs', ( + tester, + ) async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('/runs/1')), + ); + addTearDown(provider.dispose); + + await pumpApp(tester, channel: channel, client: client, provider: provider); + await replyList( + tester, + channel, + runs: [ + {'id': 1, 'name': 'Deep-linked run', 'status': 'running'}, + ], + ); + await replyDetail(tester, channel, 1); + + expect(find.text('Run 1'), findsWidgets); + expect(find.text('Back to list'), findsOneWidget); + expect(provider.value.uri.path, '/runs/1'); + expect(find.text('Pipelines — Not implemented'), findsNothing); + + await tester.tap(find.text('Back to list')); + await tester.pump(); + expect(provider.value.uri.path, '/runs'); + expect(find.text('Deep-linked run'), findsWidgets); + }); + + testWidgets('tabs and run selection update the route; browser Back pops it', ( + tester, + ) async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('/pipelines')), + ); + addTearDown(provider.dispose); + + await pumpApp(tester, channel: channel, client: client, provider: provider); + expect(provider.value.uri.path, '/pipelines'); + + await tester.tap(find.text('Runs').last); + await tester.pump(); + expect(provider.value.uri.path, '/runs'); + + await replyList( + tester, + channel, + runs: [ + {'id': 2, 'name': 'Beta run', 'status': 'failed'}, + ], + ); + await tester.tap(find.text('Beta run')); + await tester.pump(); + expect(provider.value.uri.path, '/runs/2'); + await replyDetail(tester, channel, 2); + expect(find.text('Back to list'), findsOneWidget); + + // The engine's browser Back arrives as new route information. + await provider.didPushRouteInformation( + RouteInformation(uri: Uri.parse('/runs')), + ); + await tester.pump(); + expect(find.text('Beta run'), findsWidgets); + expect(find.text('Back to list'), findsNothing); + + // Forward re-opens the same run. + await provider.didPushRouteInformation( + RouteInformation(uri: Uri.parse('/runs/2')), + ); + await tester.pump(); + await replyDetail(tester, channel, 2); + expect(find.text('Back to list'), findsOneWidget); + }); + + testWidgets('a malformed boot path is corrected to /pipelines', ( + tester, + ) async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('/runs/abc')), + ); + addTearDown(provider.dispose); + + await pumpApp(tester, channel: channel, client: client, provider: provider); + expect(provider.value.uri.path, '/pipelines'); + expect(find.text('Pipelines — Not implemented'), findsOneWidget); + }); +} diff --git a/app/test/application/runs_destination_test.dart b/app/test/application/runs_destination_test.dart new file mode 100644 index 00000000..abdd07fd --- /dev/null +++ b/app/test/application/runs_destination_test.dart @@ -0,0 +1,302 @@ +import 'dart:convert'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/app_session.dart'; +import 'package:pipelines_app/application/runs_destination.dart'; +import 'package:pipelines_app/application/server_endpoint.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:pipelines_app/features/runs/screen.dart'; + +import '../core/transport/pipelines_client_test.dart' show FakeChannel; + +ServerEndpoint webServer() => ServerEndpoint.resolve( + base: Uri.parse('http://127.0.0.1:8096/'), + web: true, +); + +Widget materialApp( + AppSession session, + ServerEndpoint server, { + int? initialRunId, + ValueChanged? onRunSelected, + VoidCallback? onBack, +}) => MaterialApp( + home: Scaffold( + body: RunsDestination( + session: session, + server: server, + initialRunId: initialRunId, + onRunSelected: onRunSelected, + onBack: onBack, + ), + ), +); + +Map? listRequest(FakeChannel channel) => channel.outgoing + .map((frame) => jsonDecode(frame as String) as Map) + .where((frame) => frame['type'] == 'list_runs') + .firstOrNull; + +Iterable> detailRequests(FakeChannel channel, int id) => + channel.outgoing + .map((frame) => jsonDecode(frame as String) as Map) + .where((frame) => frame['type'] == 'get_run' && frame['run_id'] == id); + +void main() { + testWidgets('gate explains missing native configuration without connecting', ( + tester, + ) async { + final channel = FakeChannel(); + final client = PipelinesClient(channelFactory: (_) => channel); + final server = ServerEndpoint.resolve( + base: Uri.parse('http://127.0.0.1:8096/'), + web: false, + ); + final session = AppSession(endpoint: server.uri, client: client); + addTearDown(session.dispose); + + await tester.pumpWidget(materialApp(session, server)); + expect(find.text('Server endpoint not configured'), findsOneWidget); + expect(find.textContaining('PIPELINES_SERVER_URL'), findsOneWidget); + expect(find.byType(RunsScreen), findsNothing); + expect(channel.outgoing, isEmpty); + }); + + testWidgets('gate shows connecting, then mounts the normal runs screen', ( + tester, + ) async { + final channel = FakeChannel(); + final client = PipelinesClient(channelFactory: (_) => channel); + final server = webServer(); + final session = AppSession(endpoint: server.uri, client: client); + addTearDown(session.dispose); + + final starting = session.start(); + await tester.pumpWidget(materialApp(session, server)); + await tester.pump(); + expect(find.text('Connecting to Pipelines…'), findsOneWidget); + expect(find.byType(CircularProgressIndicator), findsOneWidget); + expect(find.byType(RunsScreen), findsNothing); + + channel.readyCompleter.complete(); + await starting; + await tester.pump(); + await tester.pump(); + expect(find.byType(RunsScreen), findsOneWidget); + + final list = listRequest(channel)!; + channel.incoming.add( + jsonEncode({ + 'id': list['id'], + 'type': 'runs', + 'runs': [ + {'id': 5, 'name': 'Live fixture run', 'status': 'succeeded'}, + ], + }), + ); + await tester.pump(); + expect(find.text('Live fixture run'), findsOneWidget); + }); + + testWidgets('a refused socket shows a friendly reason, never the exception', ( + tester, + ) async { + final channel = FakeChannel(); + final client = PipelinesClient( + channelFactory: (_) => channel, + backoffBase: const Duration(hours: 1), + backoffMax: const Duration(hours: 1), + ); + final server = webServer(); + final session = AppSession(endpoint: server.uri, client: client); + addTearDown(session.dispose); + + final starting = session.start(); + channel.readyCompleter.completeError( + StateError('WebSocketChannelException: Failed to connect'), + ); + await starting; + await tester.pumpWidget(materialApp(session, server)); + await tester.pump(); + expect(find.text('Pipelines server unavailable'), findsOneWidget); + expect(find.textContaining('Retrying automatically'), findsOneWidget); + expect(find.textContaining('WebSocketChannelException'), findsNothing); + expect(find.widgetWithText(FilledButton, 'Retry'), findsOneWidget); + expect(find.byType(RunsScreen), findsNothing); + // The client keeps retrying by design; end the retry loop explicitly so + // the test does not leave a wall-clock timer behind. + session.dispose(); + }); + + testWidgets( + 'a drop keeps the list and reports reconnecting, not unavailable', + (tester) async { + final first = FakeChannel()..readyCompleter.complete(); + final second = FakeChannel()..readyCompleter.complete(); + var sockets = 0; + final client = PipelinesClient( + channelFactory: (_) => sockets++ == 0 ? first : second, + backoffBase: const Duration(milliseconds: 200), + ); + final server = webServer(); + final session = AppSession(endpoint: server.uri, client: client); + addTearDown(session.dispose); + + await session.start(); + await tester.pumpWidget(materialApp(session, server)); + await tester.pump(); + await tester.pump(); + first.incoming.add( + jsonEncode({ + 'id': listRequest(first)!['id'], + 'type': 'runs', + 'runs': [ + {'id': 1, 'name': 'Before reconnect', 'status': 'running'}, + ], + }), + ); + await tester.pump(); + expect(find.text('Before reconnect'), findsOneWidget); + + first.incoming.addError(StateError('network drop')); + await tester.pump(); + expect(find.byType(RunsScreen), findsOneWidget); + expect(find.text('Reconnecting to Pipelines…'), findsOneWidget); + expect(find.text('Pipelines server unavailable'), findsNothing); + expect(find.text('Before reconnect'), findsOneWidget); + + for ( + var attempt = 0; + attempt < 40 && listRequest(second) == null; + attempt++ + ) { + await tester.pump(const Duration(milliseconds: 50)); + } + expect(listRequest(second), isNotNull); + expect(find.text('Reconnecting to Pipelines…'), findsNothing); + second.incoming.add( + jsonEncode({ + 'id': listRequest(second)!['id'], + 'type': 'runs', + 'runs': [ + {'id': 2, 'name': 'After reconnect', 'status': 'succeeded'}, + ], + }), + ); + await tester.pump(); + expect(find.text('After reconnect'), findsOneWidget); + expect(find.text('Before reconnect'), findsNothing); + }, + ); + + testWidgets( + 'reconnect keeps the open detail instead of resetting to the list', + (tester) async { + final first = FakeChannel()..readyCompleter.complete(); + final second = FakeChannel()..readyCompleter.complete(); + var sockets = 0; + final client = PipelinesClient( + channelFactory: (_) => sockets++ == 0 ? first : second, + backoffBase: const Duration(milliseconds: 10), + ); + final server = webServer(); + final session = AppSession(endpoint: server.uri, client: client); + addTearDown(session.dispose); + + await session.start(); + await tester.pumpWidget(materialApp(session, server, initialRunId: 1)); + await tester.pump(); + await tester.pump(); + first.incoming.add( + jsonEncode({ + 'id': listRequest(first)!['id'], + 'type': 'runs', + 'runs': [ + {'id': 1, 'name': 'Open run', 'status': 'running'}, + ], + }), + ); + await tester.pump(); + final firstDetail = detailRequests(first, 1).single; + first.incoming.add( + jsonEncode({ + 'id': firstDetail['id'], + 'type': 'run', + 'run_detail': {'id': 1, 'title': 'Open run', 'status': 'running'}, + }), + ); + await tester.pump(); + expect(find.text('Open run'), findsOneWidget); + expect(find.text('Back to list'), findsOneWidget); + + first.incoming.addError(StateError('network drop')); + await tester.pump(); + expect(find.byType(RunsScreen), findsOneWidget); + expect(find.text('Open run'), findsOneWidget); + expect(find.text('Reconnecting to Pipelines…'), findsOneWidget); + + for ( + var attempt = 0; + attempt < 60 && listRequest(second) == null; + attempt++ + ) { + await tester.pump(const Duration(milliseconds: 10)); + } + expect(listRequest(second), isNotNull); + second.incoming.add( + jsonEncode({ + 'id': listRequest(second)!['id'], + 'type': 'runs', + 'runs': [ + {'id': 1, 'name': 'Open run', 'status': 'running'}, + ], + }), + ); + for ( + var attempt = 0; + attempt < 20 && detailRequests(second, 1).isEmpty; + attempt++ + ) { + await tester.pump(const Duration(milliseconds: 10)); + } + final refreshed = detailRequests(second, 1).single; + expect(find.text('Open run'), findsOneWidget); + second.incoming.add( + jsonEncode({ + 'id': refreshed['id'], + 'type': 'run', + 'run_detail': {'id': 1, 'title': 'Open run', 'status': 'succeeded'}, + }), + ); + await tester.pump(); + expect(find.text('Open run'), findsOneWidget); + expect(find.text('Back to list'), findsOneWidget); + }, + ); + + testWidgets('gate uses Cupertino progress without a Material ancestor', ( + tester, + ) async { + final channel = FakeChannel(); + final client = PipelinesClient(channelFactory: (_) => channel); + final server = webServer(); + final session = AppSession(endpoint: server.uri, client: client); + addTearDown(session.dispose); + + session.start(); + await tester.pumpWidget( + CupertinoApp( + home: CupertinoPageScaffold( + child: RunsDestination(session: session, server: server), + ), + ), + ); + await tester.pump(); + expect(find.text('Connecting to Pipelines…'), findsOneWidget); + expect(find.byType(CupertinoActivityIndicator), findsOneWidget); + expect(find.byType(CircularProgressIndicator), findsNothing); + expect(find.byType(Material), findsNothing); + }); +} diff --git a/app/test/application/server_endpoint_test.dart b/app/test/application/server_endpoint_test.dart new file mode 100644 index 00000000..d5d398d3 --- /dev/null +++ b/app/test/application/server_endpoint_test.dart @@ -0,0 +1,61 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/server_endpoint.dart'; + +void main() { + test('web infers its own origin over ws at /connect', () { + final server = ServerEndpoint.resolve( + base: Uri.parse('http://127.0.0.1:8096/runs?filter=active'), + web: true, + ); + expect(server.uri, Uri.parse('ws://127.0.0.1:8096/connect')); + expect(server.error, isNull); + expect(server.requiresConfiguration, isFalse); + }); + + test('secure web origin uses wss and the default port', () { + final server = ServerEndpoint.resolve( + base: Uri.parse('https://pipelines.example.test/runs'), + web: true, + ); + expect(server.uri, Uri.parse('wss://pipelines.example.test/connect')); + }); + + test('web never guesses an endpoint when the page is not HTTP(S)', () { + final server = ServerEndpoint.resolve( + base: Uri.parse('file:///tmp/index.html'), + web: true, + ); + expect(server.uri, isNull); + expect(server.error, contains('page URL')); + }); + + test('native requires an explicit endpoint instead of a baked host', () { + final server = ServerEndpoint.resolve( + base: Uri.parse('http://127.0.0.1:8096/'), + web: false, + ); + expect(server.uri, isNull); + expect(server.requiresConfiguration, isTrue); + expect(server.error, isNull); + }); + + test('native validates and normalizes the configured endpoint', () { + final server = ServerEndpoint.resolve( + base: Uri.parse('http://127.0.0.1:8096/'), + web: false, + configured: ' ws://192.168.1.20:8081 ', + ); + expect(server.uri, Uri.parse('ws://192.168.1.20:8081/connect')); + expect(server.requiresConfiguration, isFalse); + }); + + test('invalid native configuration reports the reason, never a fallback', () { + final server = ServerEndpoint.resolve( + base: Uri.parse('http://127.0.0.1:8096/'), + web: false, + configured: 'https://pipelines.example.test', + ); + expect(server.uri, isNull); + expect(server.error, contains('Unsupported scheme')); + }); +} diff --git a/app/test/application/settings_registration_test.dart b/app/test/application/settings_registration_test.dart new file mode 100644 index 00000000..238287ab --- /dev/null +++ b/app/test/application/settings_registration_test.dart @@ -0,0 +1,86 @@ +import 'dart:convert'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/pipelines_app.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../core/transport/pipelines_client_test.dart' show FakeChannel; +import 'pipelines_app_test.dart' show webServer, requestOf; + +void main() { + for (final cupertino in [false, true]) { + testWidgets('Settings shares socket and one native bar ($cupertino)', ( + tester, + ) async { + SharedPreferences.setMockInitialValues({}); + if (cupertino) { + tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark; + addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue); + } + final channel = FakeChannel()..readyCompleter.complete(); + var sockets = 0; + final client = PipelinesClient( + channelFactory: (_) { + sockets++; + return channel; + }, + ); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('/pipelines')), + ); + addTearDown(provider.dispose); + await tester.pumpWidget( + PipelinesApp( + server: webServer(), + client: client, + cupertino: cupertino, + routeInformationProvider: provider, + ), + ); + await tester.pump(); + expect( + requestOf(channel, 'ping'), + isNull, + reason: 'Unvisited settings must not issue hidden requests', + ); + + await tester.tap(find.text('Settings').last); + await tester.pump(); + await tester.pump(); + expect(provider.value.uri.path, '/settings'); + expect(find.text('Server URL'), findsOneWidget); + if (cupertino) { + final title = tester.widget(find.text('Connection')); + expect( + title.style!.color!.computeLuminance(), + greaterThan(0.5), + reason: 'Cupertino dark host must not inherit light Material text', + ); + } + expect(find.text('Settings — Not implemented'), findsNothing); + expect(sockets, 1); + expect( + cupertino ? find.byType(CupertinoNavigationBar) : find.byType(AppBar), + findsOneWidget, + ); + final ping = requestOf(channel, 'ping')!; + channel.incoming.add( + jsonEncode({ + 'id': ping['id'], + 'type': 'pong', + 'build': {'version': 'settings-fixture'}, + 'time': 'fixture time', + }), + ); + await tester.pump(); + await tester.pump(); + expect(find.textContaining('settings-fixture'), findsOneWidget); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + }); + } +} diff --git a/app/test/core/transport/client_regression_test.dart b/app/test/core/transport/client_regression_test.dart new file mode 100644 index 00000000..2409ac5b --- /dev/null +++ b/app/test/core/transport/client_regression_test.dart @@ -0,0 +1,144 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; + +import 'pipelines_client_test.dart' show FakeChannel; + +Future flush() => Future.delayed(Duration.zero); +Map sent(FakeChannel channel, [int index = 0]) => + jsonDecode(channel.outgoing[index] as String) as Map; +void reply(FakeChannel channel, {int index = 0, String type = 'pong'}) => + channel.incoming.add( + jsonEncode({'id': sent(channel, index)['id'], 'type': type}), + ); + +void main() { + test( + 'requests serialize through replies, errors do not poison queue', + () async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + await client.connect(Uri.parse('ws://example.test')); + final first = client.call('ping'); + final firstError = expectLater(first, throwsA(isA())); + final second = client.call('list_runs'); + await flush(); + expect(channel.outgoing, hasLength(1)); + channel.incoming.add( + jsonEncode({ + 'id': sent(channel)['id'], + 'type': 'error', + 'error': 'refused', + }), + ); + await firstError; + await flush(); + expect(channel.outgoing, hasLength(2)); + reply(channel, index: 1, type: 'runs'); + expect((await second)['type'], 'runs'); + await client.dispose(); + }, + ); + + test( + 'timeout releases queue and late response is an unsolicited frame', + () async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient( + channelFactory: (_) => channel, + requestTimeout: const Duration(milliseconds: 10), + ); + await client.connect(Uri.parse('ws://example.test')); + await expectLater(client.call('ping'), throwsA(isA())); + final late = client.frames.first; + reply(channel); + expect((await late)['type'], 'pong'); + await client.dispose(); + }, + ); + + test( + 'replacement fails queued calls rather than sending on new socket', + () async { + final channels = [ + FakeChannel()..readyCompleter.complete(), + FakeChannel()..readyCompleter.complete(), + ]; + var index = 0; + final client = PipelinesClient(channelFactory: (_) => channels[index++]); + await client.connect(Uri.parse('ws://old.test')); + final firstError = expectLater(client.call('ping'), throwsStateError); + final queuedError = expectLater( + client.call('list_runs'), + throwsStateError, + ); + await flush(); + await client.connect(Uri.parse('ws://new.test')); + await Future.wait([firstError, queuedError]); + expect(channels.last.outgoing, isEmpty); + expect(client.state.kind, ConnectionKind.connected); + await client.dispose(); + }, + ); + + test('sendOnly never blocks correlated requests', () async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + await client.connect(Uri.parse('ws://example.test')); + client.sendOnly('subscribe', {'workspace': ''}); + final ping = client.call('ping'); + await flush(); + expect(sent(channel)['type'], 'subscribe'); + reply(channel, index: 1); + expect((await ping)['type'], 'pong'); + await client.dispose(); + }); + + test('overlapping connect cannot create a superseded socket', () async { + var factories = 0; + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient( + channelFactory: (_) { + factories++; + return channel; + }, + ); + await Future.wait([ + client.connect(Uri.parse('ws://old.test')), + client.connect(Uri.parse('ws://new.test')), + ]); + expect(factories, 1); + expect(client.state.kind, ConnectionKind.connected); + await client.dispose(); + await expectLater( + client.connect(Uri.parse('ws://new.test')), + throwsStateError, + ); + }); + + test('socket failure reconnects, disconnect cancels retry', () async { + final first = FakeChannel()..readyCompleter.complete(); + final next = FakeChannel()..readyCompleter.complete(); + var factories = 0; + final client = PipelinesClient( + channelFactory: (_) => factories++ == 0 ? first : next, + backoffBase: const Duration(milliseconds: 5), + ); + await client.connect(Uri.parse('ws://example.test')); + final connectedAgain = client.states.firstWhere( + (s) => s.kind == ConnectionKind.connected, + ); + first.incoming.addError(StateError('network drop')); + await connectedAgain.timeout(const Duration(seconds: 2)); + expect(factories, 2); + await client.disconnect(); + expect(client.state.retrying, isFalse); + expect( + () => client.sendOnly('subscribe'), + throwsA(isA()), + ); + await client.dispose(); + }); +} diff --git a/app/test/core/transport/pipelines_client_test.dart b/app/test/core/transport/pipelines_client_test.dart new file mode 100644 index 00000000..e71b78f6 --- /dev/null +++ b/app/test/core/transport/pipelines_client_test.dart @@ -0,0 +1,87 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:web_socket_channel/web_socket_channel.dart'; + +class FakeChannel implements WebSocketChannel { + final incoming = StreamController(); + final outgoing = []; + final readyCompleter = Completer(); + @override + Stream get stream => incoming.stream; + @override + WebSocketSink get sink => FakeSink(outgoing, incoming); + @override + Future get ready => readyCompleter.future; + @override + String? get protocol => null; + @override + int? get closeCode => null; + @override + String? get closeReason => null; + @override + noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +class FakeSink implements WebSocketSink { + FakeSink(this.outgoing, this.incoming); + final List outgoing; + final StreamController incoming; + @override + void add(dynamic event) => outgoing.add(event); + @override + void addError(Object error, [StackTrace? stackTrace]) => throw error; + @override + Future addStream(Stream stream) async { + await for (final item in stream) { + add(item); + } + } + + @override + Future close([int? closeCode, String? closeReason]) async { + await incoming.close(); + } + + @override + Future get done async {} + @override + noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +void main() { + test('correlates replies and broadcasts unclaimed frames', () async { + final channel = FakeChannel(); + final client = PipelinesClient(channelFactory: (_) => channel); + final frames = >[]; + client.frames.listen(frames.add); + final connecting = client.connect(Uri.parse('ws://example.test')); + channel.readyCompleter.complete(); + await connecting; + final request = client.call('ping', {'value': 1}); + await Future.delayed(Duration.zero); + final sent = + jsonDecode(channel.outgoing.single as String) as Map; + channel.incoming.add(jsonEncode({'id': sent['id'], 'type': 'pong'})); + expect((await request)['type'], 'pong'); + channel.incoming.add(jsonEncode({'type': 'run_event'})); + await Future.delayed(Duration.zero); + expect(frames.single['type'], 'run_event'); + await client.dispose(); + }); + + test('disconnect fails pending requests', () async { + final channel = FakeChannel(); + final client = PipelinesClient(channelFactory: (_) => channel); + final connecting = client.connect(Uri.parse('ws://example.test')); + channel.readyCompleter.complete(); + await connecting; + final pending = client.call('ping'); + await Future.delayed(Duration.zero); + await client.disconnect(); + await expectLater(pending, throwsA(isA())); + await client.dispose(); + }); +} diff --git a/app/test/core/transport/server_url_test.dart b/app/test/core/transport/server_url_test.dart new file mode 100644 index 00000000..e2634f99 --- /dev/null +++ b/app/test/core/transport/server_url_test.dart @@ -0,0 +1,51 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/transport/server_url.dart'; + +void main() { + test('IPv6 authorities and encoded artifact queries stay intact', () { + expect( + ServerUrl.validate('ws://[::1]:8081').wsUrl, + 'ws://[::1]:8081/connect', + ); + expect( + ServerUrl.resolveArtifactUrl( + 'ws://[::1]:8081/connect', + '/artifacts/a%20b?download=1', + ).toString(), + 'http://[::1]:8081/artifacts/a%20b?download=1', + ); + expect(() => ServerUrl.validate('ws://host:70000'), throwsFormatException); + }); + test('validates and normalizes endpoint with path and query', () { + final value = ServerUrl.validate(' wss://example.test:8443/?token=x '); + expect(value.wsUrl, 'wss://example.test:8443/connect?token=x'); + expect(value.httpUrl, 'https://example.test:8443/connect?token=x'); + expect(value.secure, isTrue); + }); + + test('rejects unsupported schemes and credentials', () { + expect( + () => ServerUrl.validate('https://example.test'), + throwsFormatException, + ); + expect( + () => ServerUrl.validate('ws://user:pass@example.test'), + throwsFormatException, + ); + }); + + test('resolves relative artifacts at the server origin', () { + expect( + ServerUrl.resolveArtifactUrl( + 'ws://example.test:8081/connect', + '/artifacts/a', + )!.toString(), + 'http://example.test:8081/artifacts/a', + ); + expect(ServerUrl.resolveArtifactUrl('', '/artifacts/a'), isNull); + expect( + ServerUrl.resolveArtifactUrl('', 'https://cdn.test/a')!.toString(), + 'https://cdn.test/a', + ); + }); +} diff --git a/app/test/features/artifacts/domain/artifact_capture_test.dart b/app/test/features/artifacts/domain/artifact_capture_test.dart new file mode 100644 index 00000000..adf2f01a --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_capture_test.dart @@ -0,0 +1,241 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_capture.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_summary.dart'; + +import 'artifact_fixtures.dart'; + +void main() { + group('capture facts', () { + test('an absent or null artifact field is an unavailable capture', () { + final absent = ArtifactCapture.fromStep(step(includeArtifacts: false)); + final explicitNull = ArtifactCapture.fromStep(step(artifacts: null)); + + expect(absent.availability, ArtifactCaptureAvailability.unavailable); + expect(absent.isAvailable, isFalse); + expect(absent.artifacts, isEmpty); + expect(explicitNull.isAvailable, isFalse); + }); + + test('a malformed artifact field is unavailable, not empty', () { + final capture = ArtifactCapture.fromStep({ + 'artifacts': 'not a list', + }); + expect(capture.isAvailable, isFalse); + expect(capture.artifacts, isEmpty); + }); + + test('an explicitly recorded empty list is an available empty capture', () { + final capture = ArtifactCapture.fromStep(step(artifacts: const [])); + expect(capture.availability, ArtifactCaptureAvailability.recorded); + expect(capture.isAvailable, isTrue); + expect(capture.artifacts, isEmpty); + expect(capture.isPartial, isFalse); + }); + + test('records the skipped and truncated counts as capture facts', () { + final capture = ArtifactCapture.fromStep( + step( + artifacts: >[artifact('shot.png')], + skipped: 4, + truncated: 7, + ), + ); + expect(capture.artifacts.length, 1); + expect(capture.skipped, 4); + expect(capture.truncated, 7); + expect(capture.isPartial, isTrue); + expect( + ArtifactCapture.fromStep(step(artifacts: const [])).isPartial, + isFalse, + ); + }); + }); + + group('run and visit wording', () { + test('a running or unavailable capture never claims no artifacts', () { + expect( + artifactsSummary(step(status: 'running', artifacts: null)), + 'Artifacts · capture pending', + ); + expect( + artifactsSummary(step(status: 'running', artifacts: const [])), + 'Artifacts · capture pending', + ); + expect( + artifactsSummary(step(status: 'completed', artifacts: null)), + 'Artifacts · capture unavailable', + ); + expect( + artifactsSummary(step(status: 'completed', includeArtifacts: false)), + 'Artifacts · capture unavailable', + ); + }); + + test( + 'a finished available empty capture says not recorded for this visit', + () { + expect( + artifactsSummary(step(status: 'completed', artifacts: const [])), + 'Artifacts · not recorded for this visit', + ); + }, + ); + + test('counts presented stage artifacts and flags partial capture', () { + final full = step( + artifacts: >[ + artifact('a.png'), + artifact('b.png'), + artifact('input.md'), + artifact('session.md'), + ], + truncated: 1, + ); + expect( + artifactsSummary(full), + 'Artifacts · 2 recorded · partial capture', + ); + expect( + artifactsSummary( + step(artifacts: >[artifact('a.png')]), + ), + 'Artifacts · 1 recorded', + ); + }); + + test( + 'capture notes use the exact web wording and stay silent otherwise', + () { + final partial = step( + artifacts: >[artifact('a.png')], + skipped: 4, + truncated: 7, + ); + expect(artifactCaptureNotes(partial), [ + '4 files excluded from artifact capture.', + '7 files omitted by artifact capture limits.', + ]); + expect( + artifactCaptureNotes( + step( + artifacts: >[artifact('a.png')], + skipped: 2, + ), + ), + ['2 files excluded from artifact capture.'], + ); + expect( + artifactCaptureNotes( + step(artifacts: >[artifact('a.png')]), + ), + isEmpty, + ); + expect( + artifactCaptureNotes(step(artifacts: const [], skipped: 4)), + isEmpty, + ); + expect( + artifactCaptureNotes(step(includeArtifacts: false, skipped: 4)), + isEmpty, + ); + }, + ); + + test('the run empty message keeps the web running wording', () { + expect(artifactsEmptyMessage(true), 'Artifacts · capture pending'); + expect( + artifactsEmptyMessage(false), + 'No artifacts recorded for this run.', + ); + expect( + artifactsHeader(const [], executing: true), + 'Artifacts · capture pending', + ); + }); + + test( + 'an unavailable run capture is not reported as no recorded artifacts', + () { + final steps = >[ + step(stage: 'planner', sequence: 1, artifacts: null), + step(stage: 'build', sequence: 2, artifacts: const []), + ]; + expect( + artifactsHeader(steps, executing: false), + 'Artifacts · capture unavailable', + ); + }, + ); + + test('a fully available empty run says no artifacts were recorded', () { + final steps = >[ + step(stage: 'planner', sequence: 1, artifacts: const []), + step(stage: 'build', sequence: 2, artifacts: const []), + ]; + expect( + artifactsHeader(steps, executing: false), + 'No artifacts recorded for this run.', + ); + }); + + test( + 'the run header counts exactly the gallery tiles, singular for one', + () { + final one = >[ + step(artifacts: >[artifact('one.png')]), + ]; + expect(artifactsHeader(one, executing: false), 'Artifact · 1 recorded'); + + final four = >[ + step( + stage: 'planner', + sequence: 1, + artifacts: >[ + artifact('a.png'), + artifact('session.md'), + ], + ), + step( + stage: 'build', + sequence: 2, + artifacts: >[ + artifact('b.png'), + artifact('c.png'), + artifact('d.png'), + ], + ), + ]; + expect( + artifactsHeader(four, executing: false), + 'Artifacts · 4 recorded', + ); + expect(four, isNotEmpty); + }, + ); + + test('partial capture is flagged on the run header', () { + final steps = >[ + step(artifacts: >[artifact('a.png')], skipped: 2), + ]; + expect( + artifactsHeader(steps, executing: false), + 'Artifact · 1 recorded · partial capture', + ); + }); + + test('a visit that recorded only the retired session.md has no tile', () { + final steps = >[ + step(artifacts: >[artifact('session.md')]), + ]; + expect( + artifactsHeader(steps, executing: false), + 'No artifacts recorded for this run.', + ); + expect( + artifactsSummary(steps.first), + 'Artifacts · not recorded for this visit', + ); + expect(artifactCaptureNotes(steps.first), isEmpty); + }); + }); +} diff --git a/app/test/features/artifacts/domain/artifact_fixtures.dart b/app/test/features/artifacts/domain/artifact_fixtures.dart new file mode 100644 index 00000000..04c26bd5 --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_fixtures.dart @@ -0,0 +1,44 @@ +import 'package:pipelines_app/core/api_gateway.dart'; + +/// A minimal recorded [stage artifact], named so tests read like the web +/// client's fixtures. Every field the server records is present. +JsonMap artifact( + String name, { + String? url, + String contentType = '', + int sizeBytes = 0, + Map extra = const {}, +}) { + return { + 'name': name, + 'url': url ?? '/artifacts/1/1/$name', + 'content_type': contentType, + 'size_bytes': sizeBytes, + ...extra, + }; +} + +/// A minimal recorded step. [includeArtifacts] false omits the field entirely +/// (an unavailable capture); a null [artifacts] records an explicit null. +JsonMap step({ + String stage = 'review', + int sequence = 1, + String status = 'completed', + int visit = 1, + List? artifacts, + bool includeArtifacts = true, + int? skipped, + int? truncated, + List? repairs, +}) { + return { + 'stage': stage, + 'sequence': sequence, + 'status': status, + 'control': {'visit': visit}, + if (includeArtifacts) 'artifacts': artifacts, + 'artifacts_skipped': ?skipped, + 'artifacts_truncated': ?truncated, + 'session_export_repairs': ?repairs, + }; +} diff --git a/app/test/features/artifacts/domain/artifact_groups_test.dart b/app/test/features/artifacts/domain/artifact_groups_test.dart new file mode 100644 index 00000000..cf7173f6 --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_groups_test.dart @@ -0,0 +1,308 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_selection.dart'; + +import 'artifact_fixtures.dart'; + +void main() { + group('grouping', () { + test('groups interleaved steps by stage then recorded visit', () { + final steps = >[ + step( + stage: 'planner', + sequence: 1, + visit: 1, + artifacts: >[artifact('a.png')], + ), + step( + stage: 'build', + sequence: 2, + visit: 1, + artifacts: >[artifact('b.png')], + ), + step( + stage: 'planner', + sequence: 3, + visit: 2, + artifacts: >[artifact('c.png')], + ), + ]; + + final groups = artifactGroups(steps); + expect( + groups.map((group) => '${group.stageKey}/${group.visit}'), + ['planner/1', 'planner/2', 'build/1'], + ); + expect(groups.first.artifacts.map((record) => record.name), [ + 'a.png', + ]); + }); + + test('repeated stage visits stay separate and ordered by sequence', () { + final steps = >[ + step( + stage: 'review', + sequence: 7, + visit: 2, + artifacts: >[artifact('second.md')], + ), + step( + stage: 'review', + sequence: 3, + visit: 1, + artifacts: >[artifact('first.md')], + ), + ]; + + final groups = artifactGroups(steps); + expect(groups.map((group) => group.visit), [1, 2]); + expect(groups.map((group) => group.artifacts.single.name), [ + 'first.md', + 'second.md', + ]); + }); + + test( + 'a display visit is control.visit when positive, else position + 1', + () { + final steps = >[ + step( + stage: 's', + sequence: 1, + visit: 0, + artifacts: >[artifact('a')], + ), + step( + stage: 's', + sequence: 2, + visit: 0, + artifacts: >[artifact('b')], + ), + ]; + expect(artifactGroups(steps).map((group) => group.visit), [1, 2]); + }, + ); + + test('equal sequences keep recorded order', () { + final steps = >[ + step( + stage: 's', + sequence: 1, + visit: 1, + artifacts: >[artifact('first')], + ), + step( + stage: 's', + sequence: 1, + visit: 2, + artifacts: >[artifact('second')], + ), + ]; + expect( + artifactGroups(steps).map((group) => group.artifacts.single.name), + ['first', 'second'], + ); + }); + + test('an absent stage visit is not fabricated', () { + final steps = >[ + step( + stage: 'a', + sequence: 1, + artifacts: >[artifact('a.png')], + ), + ]; + final groups = artifactGroups(steps); + expect(groups.single.stageKey, 'a'); + expect(groups.any((group) => group.stageKey == 'b'), isFalse); + }); + }); + + group('identity', () { + test('the same file name in different visits remains two groups', () { + final steps = >[ + step( + stage: 'implementer', + sequence: 1, + visit: 1, + artifacts: >[ + artifact('report.md', url: '/artifacts/1/1/report.md'), + ], + ), + step( + stage: 'implementer', + sequence: 2, + visit: 2, + artifacts: >[ + artifact('report.md', url: '/artifacts/1/2/report.md'), + ], + ), + ]; + final groups = artifactGroups(steps); + expect(groups.length, 2); + expect(groups.map((group) => group.artifacts.single.url), [ + '/artifacts/1/1/report.md', + '/artifacts/1/2/report.md', + ]); + }); + + test('duplicate names in one visit are kept with their recorded urls', () { + final steps = >[ + step( + stage: 's', + sequence: 1, + artifacts: >[ + artifact('shot.png', url: '/artifacts/1/1/shot-a.png'), + artifact('shot.png', url: '/artifacts/1/1/shot-b.png'), + ], + ), + ]; + final artifacts = artifactGroups(steps).single.artifacts; + expect(artifacts.length, 2); + expect(artifacts.map((record) => record.url), [ + '/artifacts/1/1/shot-a.png', + '/artifacts/1/1/shot-b.png', + ]); + }); + + test('the retired session.md is hidden but session.html is retained', () { + final steps = >[ + step( + stage: 's', + sequence: 1, + artifacts: >[ + artifact('session.md'), + artifact('session.html'), + artifact('report.md'), + ], + ), + ]; + // session.html is retained as system evidence, but neither it nor the + // retired session.md is stage output, so the gallery shows only the report. + expect( + artifactGroups(steps).single.artifacts.map((record) => record.name), + ['report.md'], + ); + expect( + systemArtifacts(steps.single).map((record) => record.name), + ['session.html'], + ); + }); + }); + + group('shared public files', () { + test('a public file is attributed to the visit that first recorded it', () { + final steps = >[ + step( + stage: 'a', + sequence: 1, + artifacts: >[ + artifact('input.md'), + artifact('public/a.txt'), + ], + ), + step( + stage: 'b', + sequence: 2, + artifacts: >[ + artifact('output.md'), + artifact('public/a.txt'), + artifact('public/b.txt'), + ], + ), + ]; + final groups = artifactGroups(steps); + expect( + groups.map( + (group) => group.artifacts.map((record) => record.name).toList(), + ), + >[ + ['public/a.txt'], + ['public/b.txt'], + ], + ); + expect( + visitArtifacts(steps[1], steps).map((record) => record.name), + ['public/b.txt'], + ); + }); + + test( + 'visitArtifacts keeps a repeated non-public name in a later visit', + () { + final steps = >[ + step( + stage: 'a', + sequence: 1, + artifacts: >[ + artifact('report.md', url: '/artifacts/1/1/report.md'), + ], + ), + step( + stage: 'a', + sequence: 2, + artifacts: >[ + artifact('report.md', url: '/artifacts/1/2/report.md'), + ], + ), + ]; + expect( + visitArtifacts(steps[1], steps).map((record) => record.url), + ['/artifacts/1/2/report.md'], + ); + }, + ); + + test('a public file repeated inside one visit is recorded once', () { + final steps = >[ + step( + stage: 'a', + sequence: 1, + artifacts: >[ + artifact('public/a.txt'), + artifact('public/a.txt'), + ], + ), + ]; + expect(artifactGroups(steps).single.artifacts.length, 1); + }); + }); + + group('unavailable and empty captures', () { + test('unavailable, null and empty visits yield no group', () { + final steps = >[ + step(stage: 'a', sequence: 1, includeArtifacts: false), + step(stage: 'a', sequence: 2, artifacts: null), + step(stage: 'a', sequence: 3, artifacts: const []), + step( + stage: 'b', + sequence: 4, + artifacts: >[artifact('only.png')], + ), + ]; + final groups = artifactGroups(steps); + expect(groups.length, 1); + expect(groups.single.stageKey, 'b'); + expect(groups.single.visit, 1); + }); + + test('a visit with only utility or retired files yields no group', () { + final steps = >[ + step( + stage: 'a', + sequence: 1, + artifacts: >[ + artifact('input.md'), + artifact('session.md'), + artifact('session.html'), + ], + ), + ]; + expect(artifactGroups(steps), isEmpty); + }); + + test('an empty run yields no groups', () { + expect(artifactGroups(const []), isEmpty); + }); + }); +} diff --git a/app/test/features/artifacts/domain/artifact_kind_test.dart b/app/test/features/artifacts/domain/artifact_kind_test.dart new file mode 100644 index 00000000..a95ccfab --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_kind_test.dart @@ -0,0 +1,110 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_kind.dart'; + +void main() { + test('classifies images and videos from their recorded content type', () { + expect(artifactKind('image/png', 'shot.png'), ArtifactKind.image); + expect( + artifactKind('image/svg+xml; charset=utf-8', 'plot'), + ArtifactKind.image, + ); + expect(artifactKind('video/mp4', 'clip.mp4'), ArtifactKind.video); + }); + + test('matches the web client file-kind vocabulary by MIME and name', () { + const cases = <(String, String, ArtifactKind)>[ + ('audio/mpeg', 'sound.mp3', ArtifactKind.audio), + ('application/pdf', 'report', ArtifactKind.pdf), + ('application/octet-stream', 'data.pdf', ArtifactKind.pdf), + ('application/json', 'payload', ArtifactKind.json), + ('text/plain', 'config.json', ArtifactKind.json), + ('application/zip', 'bundle', ArtifactKind.archive), + ('text/plain', 'backup.tar.gz', ArtifactKind.archive), + ('text/csv', 'rows', ArtifactKind.spreadsheet), + ('application/octet-stream', 'sheet.xlsx', ArtifactKind.spreadsheet), + ('text/plain', 'run.log', ArtifactKind.log), + ('application/xml', 'layout', ArtifactKind.code), + ('text/plain', 'main.go', ArtifactKind.code), + ('text/html; charset=utf-8', 'session.html', ArtifactKind.document), + ('text/plain', 'notes.txt', ArtifactKind.document), + ('application/octet-stream', 'blob.bin', ArtifactKind.other), + ('', '', ArtifactKind.other), + ('application/x-unknown-thing', 'report.unknownext', ArtifactKind.other), + ]; + for (final (contentType, name, kind) in cases) { + expect( + artifactKind(contentType, name), + kind, + reason: '$contentType $name', + ); + } + }); + + test('names every kind in prose, with File as the unknown fallback', () { + expect(artifactKindLabel(ArtifactKind.image), 'Image'); + expect(artifactKindLabel(ArtifactKind.video), 'Video'); + expect(artifactKindLabel(ArtifactKind.audio), 'Audio'); + expect(artifactKindLabel(ArtifactKind.pdf), 'PDF'); + expect(artifactKindLabel(ArtifactKind.json), 'JSON'); + expect(artifactKindLabel(ArtifactKind.archive), 'Archive'); + expect(artifactKindLabel(ArtifactKind.spreadsheet), 'Spreadsheet'); + expect(artifactKindLabel(ArtifactKind.log), 'Log'); + expect(artifactKindLabel(ArtifactKind.code), 'Code'); + expect(artifactKindLabel(ArtifactKind.document), 'Document'); + expect(artifactKindLabel(ArtifactKind.other), 'File'); + }); + + test('formats recorded bytes like the web client', () { + expect(humanBytes(0), '0 B'); + expect(humanBytes(999), '999 B'); + expect(humanBytes(1024), '1.0 KiB'); + expect(humanBytes(1536), '1.5 KiB'); + expect(humanBytes(2 * 1024 * 1024), '2.0 MiB'); + expect(humanBytes(3 * 1024 * 1024 * 1024), '3.0 GiB'); + }); + + test('markdown and viewer artifacts use the shared classification', () { + const markdown = <(String, String)>[ + ('text/markdown', 'plan'), + ('text/markdown; charset=utf-8', 'plan'), + ('text/plain', 'notes'), + ('application/octet-stream', 'input.md'), + ('', 'memory.markdown'), + ('', 'output.txt'), + ]; + for (final (contentType, name) in markdown) { + expect(isMarkdownArtifact(contentType, name), isTrue, reason: name); + } + for (final (contentType, name) in <(String, String)>[ + ('text/html', 'session.html'), + ('text/csv', 'rows.csv'), + ('application/json', 'payload.json'), + ('text/x-python', 'main.py'), + ('application/xml', 'shot.png.xml'), + ('', ''), + ]) { + expect(isMarkdownArtifact(contentType, name), isFalse, reason: name); + } + + for (final (contentType, name) in <(String, String)>[ + ('image/png', 'shot.png'), + ('video/mp4', 'clip.mp4'), + ('text/markdown', 'input.md'), + ('text/plain', 'memory.txt'), + ('', 'output.md'), + ]) { + expect(isViewerArtifact(contentType, name), isTrue, reason: name); + } + for (final (contentType, name) in <(String, String)>[ + ('text/html', 'session.html'), + ('text/csv', 'rows.csv'), + ('application/json', 'payload.json'), + ('text/x-python', 'main.py'), + ('text/plain', 'run.log'), + ('application/octet-stream', 'blob.bin'), + ('', ''), + ]) { + expect(isViewerArtifact(contentType, name), isFalse, reason: name); + } + }); +} diff --git a/app/test/features/artifacts/domain/artifact_selection_test.dart b/app/test/features/artifacts/domain/artifact_selection_test.dart new file mode 100644 index 00000000..d65bdcb7 --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_selection_test.dart @@ -0,0 +1,154 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_selection.dart'; + +import 'artifact_fixtures.dart'; + +void main() { + group('record preservation', () { + test('keeps size, content type, url and unknown fields verbatim', () { + final recorded = ArtifactRecord.fromJson( + artifact( + 'shot.png', + url: '/artifacts/7/3/shot.png', + contentType: 'image/png', + sizeBytes: 1536, + extra: { + 'sha256': 'abc', + 'capture': {'source': 'stage'}, + }, + ), + ); + + expect(recorded.name, 'shot.png'); + expect(recorded.url, '/artifacts/7/3/shot.png'); + expect(recorded.contentType, 'image/png'); + expect(recorded.sizeBytes, 1536); + expect(recorded.raw['sha256'], 'abc'); + expect((recorded.raw['capture'] as Map)['source'], 'stage'); + }); + + test('never invents a missing name, url, type or size', () { + final recorded = ArtifactRecord.fromJson(const {}); + expect(recorded.name, ''); + expect(recorded.url, ''); + expect(recorded.contentType, ''); + expect(recorded.sizeBytes, 0); + expect(recorded.hasUrl, isFalse); + }); + + test('the raw record is read-only, including nested values', () { + final recorded = ArtifactRecord.fromJson( + artifact( + 'a.txt', + extra: { + 'nested': {'x': 1}, + }, + ), + ); + expect( + () => recorded.raw['nested'] = {}, + throwsUnsupportedError, + ); + expect( + () => (recorded.raw['nested'] as Map)['x'] = 2, + throwsUnsupportedError, + ); + }); + }); + + group('retired and utility files', () { + test( + 'hides session.md from presented artifacts but keeps session.html', + () { + final records = [ + ArtifactRecord.fromJson(artifact('shot.png')), + ArtifactRecord.fromJson(artifact(legacySessionMarkdownArtifact)), + ArtifactRecord.fromJson(artifact('session.html')), + ]; + + expect( + presentedArtifacts(records).map((record) => record.name), + ['shot.png', 'session.html'], + ); + }, + ); + + test('utility files are system evidence, not stage output', () { + expect(systemArtifactNames, [ + 'input.md', + 'memory.md', + 'output.md', + 'session.html', + ]); + for (final name in systemArtifactNames) { + expect(isSystemArtifactName(name), isTrue, reason: name); + } + expect(isSystemArtifactName('public/input.md'), isFalse); + expect(isSystemArtifactName('session.md'), isFalse); + expect(isSystemArtifactName('shot.png'), isFalse); + }); + + test('stage artifacts exclude utility files and repair exports', () { + final recorded = step( + artifacts: [ + artifact('input.md'), + artifact('memory.md'), + artifact('output.md'), + artifact('session.html'), + artifact('repaired.html'), + artifact('public/input.md'), + artifact('shot.png'), + ].cast>(), + repairs: >[ + {'html': 'repaired.html'}, + ], + ); + + expect(stageArtifacts(recorded).map((record) => record.name), [ + 'public/input.md', + 'shot.png', + ]); + expect(systemArtifacts(recorded).map((record) => record.name), [ + 'input.md', + 'memory.md', + 'output.md', + 'session.html', + 'repaired.html', + ]); + }); + + test('a missing or malformed artifact list records no artifacts', () { + expect(artifactsOf(step(includeArtifacts: false)), isEmpty); + expect(artifactsOf(step(artifacts: null)), isEmpty); + expect(artifactsOf(step(artifacts: const [])), isEmpty); + expect( + artifactsOf({'artifacts': 'not a list'}), + isEmpty, + ); + }); + + test('duplicate names are records, not identities to dedupe', () { + final records = [ + ArtifactRecord.fromJson( + artifact('shot.png', url: '/artifacts/1/1/a.png'), + ), + ArtifactRecord.fromJson( + artifact('shot.png', url: '/artifacts/1/1/b.png'), + ), + ]; + expect( + stageArtifacts( + step( + artifacts: >[ + artifact('shot.png', url: '/artifacts/1/1/a.png'), + artifact('shot.png', url: '/artifacts/1/1/b.png'), + ], + ), + ).map((record) => record.url), + ['/artifacts/1/1/a.png', '/artifacts/1/1/b.png'], + ); + expect(records.length, 2); + }); + }); +} diff --git a/app/test/features/artifacts/domain/artifact_url_test.dart b/app/test/features/artifacts/domain/artifact_url_test.dart new file mode 100644 index 00000000..e7d9a961 --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_url_test.dart @@ -0,0 +1,148 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_url.dart'; + +void main() { + group('server-relative paths', () { + test( + 'resolve against the configured endpoint origin, dropping its path', + () { + final resolved = resolveArtifactUrl( + 'ws://example.test:8081/connect?token=x', + '/artifacts/a%20b?download=1', + ); + expect(resolved, isNotNull); + expect( + resolved!.uri.toString(), + 'http://example.test:8081/artifacts/a%20b?download=1', + ); + expect(resolved.external, isFalse); + }, + ); + + test('map wss to https and omit the default port', () { + final resolved = resolveArtifactUrl( + 'wss://example.test/connect', + 'artifacts/shot.png', + ); + expect( + resolved!.uri.toString(), + 'https://example.test/artifacts/shot.png', + ); + expect(resolved.external, isFalse); + }); + + test('keep IPv6 brackets and encoded paths intact', () { + final resolved = resolveArtifactUrl( + 'ws://[::1]:8081/connect', + '/artifacts/a%2Fb?next=%2Fnext', + ); + expect( + resolved!.uri.toString(), + 'http://[::1]:8081/artifacts/a%2Fb?next=%2Fnext', + ); + expect(resolved.uri.host, '::1'); + }); + + test('a blank endpoint leaves a relative artifact unresolved', () { + expect(resolveArtifactUrl('', '/artifacts/a'), isNull); + expect(resolveArtifactUrl('not a url', '/artifacts/a'), isNull); + expect( + resolveArtifactUrl('https://example.test', '/artifacts/a'), + isNull, + ); + }); + }); + + group('absolute http(s) artifacts', () { + test('a same-origin absolute url stays internal', () { + final resolved = resolveArtifactUrl( + 'ws://example.test:8081/connect', + 'http://example.test:8081/artifacts/a%20b?download=1', + ); + expect( + resolved!.uri.toString(), + 'http://example.test:8081/artifacts/a%20b?download=1', + ); + expect(resolved.external, isFalse); + }); + + test('cross-host, cross-port and cross-scheme urls are external', () { + const configured = 'wss://example.test/connect'; + for (final url in [ + 'https://cdn.test/artifacts/a', + 'https://example.test:8443/artifacts/a', + 'http://example.test/artifacts/a', + ]) { + final resolved = resolveArtifactUrl(configured, url); + expect(resolved, isNotNull, reason: url); + expect(resolved!.external, isTrue, reason: url); + } + }); + + test('an absolute url without a usable configured origin is external', () { + final resolved = resolveArtifactUrl('', 'https://cdn.test/a%2Fb?q=1'); + expect(resolved!.uri.toString(), 'https://cdn.test/a%2Fb?q=1'); + expect(resolved.external, isTrue); + }); + }); + + group('unsafe urls', () { + test('rejects blank, protocol-relative and hostless urls', () { + for (final url in [ + '', + ' ', + '//evil.test/artifacts/a', + 'http:///artifacts/a', + 'http://', + 'https://?x=1', + ]) { + expect( + resolveArtifactUrl('ws://example.test:8081', url), + isNull, + reason: url, + ); + } + }); + + test('rejects credentials in any absolute url', () { + for (final url in [ + 'http://user:pass@example.test/artifacts/a', + 'https://user@example.test/artifacts/a', + 'http://example.test:8081@evil.test/artifacts/a', + ]) { + expect( + resolveArtifactUrl('ws://example.test:8081', url), + isNull, + reason: url, + ); + } + }); + + test('rejects unsafe and non-http schemes', () { + for (final url in [ + 'javascript:alert(1)', + 'data:text/html,hello', + 'file:///etc/passwd', + 'ftp://example.test/a', + 'intent://example.test/a#Intent;end', + 'mailto:ops@example.test', + ]) { + expect( + resolveArtifactUrl('ws://example.test:8081', url), + isNull, + reason: url, + ); + } + }); + + test('never produces a non-http(s) output', () { + final resolved = resolveArtifactUrl( + 'ws://example.test:8081/connect', + '/artifacts/a', + ); + expect(resolved!.uri.scheme, 'http'); + expect(resolved.uri.hasAuthority, isTrue); + expect(resolved.uri.userInfo, isEmpty); + }); + }); +} diff --git a/app/test/features/artifacts/domain/gallery_navigation_test.dart b/app/test/features/artifacts/domain/gallery_navigation_test.dart new file mode 100644 index 00000000..af8b72ed --- /dev/null +++ b/app/test/features/artifacts/domain/gallery_navigation_test.dart @@ -0,0 +1,197 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart'; +import 'package:pipelines_app/features/artifacts/domain/gallery_navigation.dart'; + +import 'artifact_fixtures.dart'; + +ArtifactRecord record(String name, {String contentType = '', String? url}) => + ArtifactRecord.fromJson(artifact(name, contentType: contentType, url: url)); + +void main() { + group('filtered gallery order', () { + test('pages viewer artifacts group by group, in recorded order', () { + final groups = [ + ArtifactGroup( + stageKey: 'reviewer', + visit: 1, + artifacts: [ + record('session.html', contentType: 'text/html'), + record('input.md', contentType: 'text/markdown'), + ], + ), + ArtifactGroup( + stageKey: 'implementer', + visit: 2, + artifacts: [ + record('run.log', contentType: 'text/plain'), + record('shot.png', contentType: 'image/png'), + record('main.py', contentType: 'text/x-python'), + record('clip.mp4', contentType: 'video/mp4'), + record('memory.txt', contentType: 'text/plain'), + record('rows.csv', contentType: 'text/csv'), + record('output.md', contentType: 'application/octet-stream'), + ], + ), + ]; + + expect(pagedArtifacts(groups).map((page) => page.artifact.name), [ + 'input.md', + 'shot.png', + 'clip.mp4', + 'memory.txt', + 'output.md', + ]); + expect(pagedArtifacts(const []), isEmpty); + }); + + test('a page keeps the stage visit it belongs to', () { + final groups = artifactGroups(>[ + step( + stage: 'a', + sequence: 1, + visit: 3, + artifacts: >[ + artifact('a.png', contentType: 'image/png'), + ], + ), + step( + stage: 'b', + sequence: 2, + visit: 5, + artifacts: >[ + artifact('b.png', contentType: 'image/png'), + ], + ), + ]); + final pages = pagedArtifacts(groups); + expect(pages.map((page) => '${page.stageKey}/${page.visit}'), [ + 'a/3', + 'b/5', + ]); + expect(pages.map((page) => page.pageIndex), [0, 1]); + }); + }); + + group('identity', () { + test('duplicate names with different urls get distinct viewer indices', () { + final groups = artifactGroups(>[ + step( + stage: 'a', + sequence: 1, + visit: 1, + artifacts: >[ + artifact( + 'shot.png', + url: '/artifacts/1/1/shot.png', + contentType: 'image/png', + ), + ], + ), + step( + stage: 'a', + sequence: 2, + visit: 2, + artifacts: >[ + artifact( + 'shot.png', + url: '/artifacts/1/2/shot.png', + contentType: 'image/png', + ), + ], + ), + ]); + final index = viewerIndexByUrl(groups); + expect(index, { + '/artifacts/1/1/shot.png': 0, + '/artifacts/1/2/shot.png': 1, + }); + expect(pagedArtifacts(groups).map((page) => page.identity), [ + '/artifacts/1/1/shot.png', + '/artifacts/1/2/shot.png', + ]); + }); + + test('a repeated url maps to its first occurrence only', () { + final groups = artifactGroups(>[ + step( + stage: 'a', + sequence: 1, + artifacts: >[ + artifact( + 'a.png', + url: '/artifacts/1/1/a.png', + contentType: 'image/png', + ), + artifact( + 'a.png', + url: '/artifacts/1/1/a.png', + contentType: 'image/png', + ), + ], + ), + ]); + final index = viewerIndexByUrl(groups); + expect(index, {'/artifacts/1/1/a.png': 0}); + expect(pagedArtifacts(groups).length, 2); + }); + + test('artifacts without a url keep distinct fallback identities', () { + final groups = artifactGroups(>[ + step( + stage: 'a', + sequence: 1, + visit: 2, + artifacts: >[ + artifact('shot.png', url: '', contentType: 'image/png'), + artifact('shot.png', url: '', contentType: 'image/png'), + ], + ), + ]); + final pages = pagedArtifacts(groups); + expect(pages.map((page) => page.identity).toSet().length, 2); + expect(viewerIndexByUrl(groups), isEmpty); + }); + + test('non-viewer artifacts never get a viewer identity', () { + final groups = artifactGroups(>[ + step( + stage: 'a', + sequence: 1, + artifacts: >[ + artifact('session.html', contentType: 'text/html'), + artifact('main.py', contentType: 'text/x-python'), + artifact('run.log', contentType: 'text/plain'), + ], + ), + ]); + expect(pagedArtifacts(groups), isEmpty); + expect(viewerIndexByUrl(groups), isEmpty); + }); + }); + + group('paging', () { + test('previous and next clamp at both ends without wrapping', () { + expect(pagedIndex(0, -1, 3), 0); + expect(pagedIndex(1, -1, 3), 0); + expect(pagedIndex(1, 1, 3), 2); + expect(pagedIndex(2, 1, 3), 2); + expect(pagedIndex(0, 0, 0), 0); + expect(pagedIndex(0, 0, 1), 0); + expect(pagedIndex(9, -3, 0), 0); + }); + + test('the position label trims the content type and falls back', () { + expect( + artifactViewerPositionLabel(0, 3, 'image/png'), + '1 of 3 · image/png', + ); + expect( + artifactViewerPositionLabel(1, 3, 'image/png; charset=binary'), + '2 of 3 · image/png', + ); + expect(artifactViewerPositionLabel(4, 5, ''), '5 of 5 · artifact'); + expect(artifactViewerPositionLabel(0, 1, ' '), '1 of 1 · artifact'); + }); + }); +} diff --git a/app/test/features/artifacts/ui/artifact_visit_list_fixture.dart b/app/test/features/artifacts/ui/artifact_visit_list_fixture.dart new file mode 100644 index 00000000..a781a34d --- /dev/null +++ b/app/test/features/artifacts/ui/artifact_visit_list_fixture.dart @@ -0,0 +1,87 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_visit_list.dart'; + +import '../domain/artifact_fixtures.dart'; + +/// A recorded name long enough to wrap at large text sizes. +const longArtifactName = + 'a-very-long-recorded-artifact-file-name-that-must-wrap-across-' + 'several-lines-at-large-text-sizes.csv'; + +/// The non-breaking space the row inserts between a size value and its unit. +const nonBreakingSpace = '\u00a0'; + +/// One recorded artifact. An empty [url] falls back to the fixture's url; use +/// [unaddressedArtifact] for a record the server sent without one. +ArtifactRecord recordedArtifact( + String name, { + String url = '', + String contentType = '', + int sizeBytes = 0, +}) { + return ArtifactRecord.fromJson( + artifact( + name, + url: url.isEmpty ? null : url, + contentType: contentType, + sizeBytes: sizeBytes, + ), + ); +} + +/// A record with no recorded url or content type, never completed locally. +/// +/// [name] defaults to empty, so the record is otherwise entirely unaddressed. +ArtifactRecord unaddressedArtifact({String name = ''}) { + return ArtifactRecord.fromJson({ + 'name': name, + 'url': '', + 'content_type': '', + 'size_bytes': 0, + }); +} + +ArtifactGroup visitGroup({ + String stageKey = 'review', + int visit = 1, + List artifacts = const [], +}) { + return ArtifactGroup(stageKey: stageKey, visit: visit, artifacts: artifacts); +} + +/// The list under the native host it is composed into, with the optional +/// grouped page colour a gallery must supply. +Widget artifactListHost({ + required bool cupertino, + required List groups, + String? selectedIdentity, + ArtifactSelected? onSelected, + double textScale = 1, +}) { + final list = ArtifactVisitList( + groups: groups, + selectedIdentity: selectedIdentity, + onSelected: onSelected, + ); + Widget scaled(BuildContext context, Widget? child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: child ?? const SizedBox.shrink(), + ); + return cupertino + ? CupertinoApp( + builder: scaled, + home: CupertinoPageScaffold( + backgroundColor: CupertinoColors.systemGroupedBackground, + child: list, + ), + ) + : MaterialApp( + builder: scaled, + home: Scaffold(body: list), + ); +} diff --git a/app/test/features/artifacts/ui/artifact_visit_list_semantics_test.dart b/app/test/features/artifacts/ui/artifact_visit_list_semantics_test.dart new file mode 100644 index 00000000..8e18f58b --- /dev/null +++ b/app/test/features/artifacts/ui/artifact_visit_list_semantics_test.dart @@ -0,0 +1,170 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/semantics.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_visit_list.dart'; + +import 'artifact_visit_list_fixture.dart'; + +List _threeGroups() => [ + visitGroup( + stageKey: 'build', + visit: 1, + artifacts: [ + recordedArtifact(longArtifactName, url: '/artifacts/7/3/long.xlsx'), + ], + ), + visitGroup( + visit: 1, + artifacts: [ + recordedArtifact('result.csv', url: '/artifacts/7/1/result.csv'), + recordedArtifact('notes.md', url: '/artifacts/7/1/notes.md'), + ], + ), + visitGroup( + visit: 2, + artifacts: [ + recordedArtifact('result.csv', url: '/artifacts/7/2/result.csv'), + ], + ), +]; + +void main() { + testWidgets('every group heading is a header node under both hosts', ( + tester, + ) async { + final handle = tester.ensureSemantics(); + + for (final cupertino in [false, true]) { + await tester.pumpWidget( + artifactListHost(cupertino: cupertino, groups: _threeGroups()), + ); + for (final label in [ + 'build · visit 1', + 'review · visit 1', + 'review · visit 2', + ]) { + expect( + tester.getSemantics(find.text(label)), + isSemantics(label: label, isHeader: true), + reason: + '${cupertino ? 'Cupertino' : 'Material'} must expose $label as a ' + 'heading', + ); + } + } + handle.dispose(); + }); + + testWidgets('a Cupertino heading stays separate from its single row', ( + tester, + ) async { + final handle = tester.ensureSemantics(); + final group = visitGroup( + visit: 2, + artifacts: [ + recordedArtifact( + 'result.csv', + url: '/artifacts/7/2/result.csv', + contentType: 'text/csv', + sizeBytes: 4096, + ), + ], + ); + await tester.pumpWidget( + artifactListHost(cupertino: true, groups: [group], onSelected: (_, _) {}), + ); + + final heading = tester.getSemantics(find.text('review · visit 2')); + expect(heading, isSemantics(label: 'review · visit 2', isHeader: true)); + expect( + heading.getSemanticsData().hasAction(SemanticsAction.tap), + isFalse, + reason: 'a heading must never activate the artifact below it', + ); + + final button = tester.getSemantics(find.byType(CupertinoButton)); + expect(button, isSemantics(isButton: true, hasTapAction: true)); + expect(button.label, contains('result.csv')); + expect( + button.label, + isNot(contains('review · visit 2')), + reason: 'the row accessible name must not repeat the group heading', + ); + + final headingRect = tester.getRect(find.text('review · visit 2')); + final rowRect = tester.getRect(find.byType(CupertinoButton)); + expect( + rowRect.top, + greaterThanOrEqualTo(headingRect.bottom), + reason: 'the row must not cover the heading', + ); + handle.dispose(); + }); + + testWidgets('rows without a callback expose no tap action under both hosts', ( + tester, + ) async { + final handle = tester.ensureSemantics(); + final group = visitGroup( + artifacts: [ + recordedArtifact('result.csv', url: '/artifacts/7/1/result.csv'), + ], + ); + + for (final cupertino in [false, true]) { + await tester.pumpWidget( + artifactListHost(cupertino: cupertino, groups: [group]), + ); + final row = tester.getSemantics(find.text('result.csv')); + expect( + row.getSemanticsData().hasAction(SemanticsAction.tap), + isFalse, + reason: 'without onSelected the row is read-only', + ); + expect( + row, + isSemantics(isButton: false), + reason: 'a read-only row must not expose a button role', + ); + await tester.tap(find.text('result.csv')); + expect(tester.takeException(), isNull); + } + handle.dispose(); + }); + + testWidgets('the selected row carries the selected semantics state', ( + tester, + ) async { + final handle = tester.ensureSemantics(); + final first = visitGroup( + visit: 1, + artifacts: [recordedArtifact('result.csv', url: '/artifacts/7/1/a.csv')], + ); + final second = visitGroup( + visit: 2, + artifacts: [recordedArtifact('result.csv', url: '/artifacts/7/2/b.csv')], + ); + await tester.pumpWidget( + artifactListHost( + cupertino: true, + groups: [first, second], + selectedIdentity: artifactVisitIdentity( + second, + second.artifacts.single, + ), + onSelected: (_, _) {}, + ), + ); + + expect( + tester.getSemantics(find.text('result.csv').last), + isSemantics(isSelected: true), + ); + expect( + tester.getSemantics(find.text('result.csv').first), + isSemantics(isSelected: false), + ); + handle.dispose(); + }); +} diff --git a/app/test/features/artifacts/ui/artifact_visit_list_test.dart b/app/test/features/artifacts/ui/artifact_visit_list_test.dart new file mode 100644 index 00000000..b9fb9585 --- /dev/null +++ b/app/test/features/artifacts/ui/artifact_visit_list_test.dart @@ -0,0 +1,230 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_visit_list.dart'; + +import 'artifact_visit_list_fixture.dart'; + +void main() { + test('a shared filename in two visits has distinct identities', () { + const url = '/artifacts/7/result.csv'; + final first = visitGroup( + visit: 1, + artifacts: [ + recordedArtifact('result.csv', url: url, contentType: 'text/csv'), + ], + ); + final second = visitGroup( + visit: 2, + artifacts: [ + recordedArtifact('result.csv', url: url, contentType: 'text/csv'), + ], + ); + + expect( + artifactVisitIdentity(first, first.artifacts.single), + isNot(artifactVisitIdentity(second, second.artifacts.single)), + ); + expect( + artifactVisitIdentity(first, first.artifacts.single), + artifactVisitIdentity(first, first.artifacts.single), + ); + }); + + test('an unaddressed record is identified by its recorded name', () { + final addressed = visitGroup( + visit: 1, + artifacts: [ + recordedArtifact('result.csv', url: '/artifacts/7/1/result.csv'), + ], + ); + final unaddressed = visitGroup( + visit: 1, + artifacts: [unaddressedArtifact(name: 'result.csv')], + ); + + expect( + artifactVisitIdentity(unaddressed, unaddressed.artifacts.single), + 'review\u00001\u0000result.csv', + ); + expect( + artifactVisitIdentity(unaddressed, unaddressed.artifacts.single), + isNot(artifactVisitIdentity(addressed, addressed.artifacts.single)), + ); + }); + + testWidgets('Material rows show recorded visit, MIME and size', ( + tester, + ) async { + final first = visitGroup( + visit: 1, + artifacts: [ + recordedArtifact( + 'result.csv', + url: '/artifacts/7/1/result.csv', + contentType: 'text/csv', + sizeBytes: 2048, + ), + ], + ); + final second = visitGroup( + visit: 2, + artifacts: [ + recordedArtifact( + 'result.csv', + url: '/artifacts/7/2/result.csv', + contentType: 'text/csv; charset=utf-8', + sizeBytes: 4096, + ), + ], + ); + ArtifactGroup? pickedGroup; + ArtifactRecord? pickedArtifact; + await tester.pumpWidget( + artifactListHost( + cupertino: false, + groups: [first, second], + selectedIdentity: artifactVisitIdentity( + second, + second.artifacts.single, + ), + onSelected: (selectedGroup, selectedArtifact) { + pickedGroup = selectedGroup; + pickedArtifact = selectedArtifact; + }, + ), + ); + + expect(find.text('review · visit 1'), findsOneWidget); + expect(find.text('review · visit 2'), findsOneWidget); + expect(find.text('result.csv'), findsNWidgets(2)); + expect(find.text('text/csv · 2.0${nonBreakingSpace}KiB'), findsOneWidget); + expect(find.text('text/csv · 4.0${nonBreakingSpace}KiB'), findsOneWidget); + expect(find.byIcon(Icons.check), findsOneWidget); + + await tester.tap(find.text('result.csv').first); + expect(pickedGroup, same(first)); + expect(pickedArtifact, same(first.artifacts.single)); + + await tester.tap(find.text('result.csv').last); + expect(pickedGroup, same(second)); + expect(pickedArtifact!.url, '/artifacts/7/2/result.csv'); + }); + + testWidgets('Cupertino uses grouped native controls and selects per visit', ( + tester, + ) async { + final first = visitGroup( + visit: 1, + artifacts: [ + recordedArtifact('result.csv', url: '/artifacts/7/1/result.csv'), + ], + ); + final second = visitGroup( + visit: 2, + artifacts: [ + recordedArtifact('result.csv', url: '/artifacts/7/2/result.csv'), + ], + ); + ArtifactGroup? pickedGroup; + await tester.pumpWidget( + artifactListHost( + cupertino: true, + groups: [first, second], + selectedIdentity: artifactVisitIdentity(first, first.artifacts.single), + onSelected: (selectedGroup, _) => pickedGroup = selectedGroup, + ), + ); + + expect(find.byType(CupertinoListSection), findsNWidgets(2)); + expect(find.byType(CupertinoButton), findsNWidgets(2)); + expect(find.byType(ListTile), findsNothing); + expect(find.byIcon(CupertinoIcons.check_mark), findsOneWidget); + + await tester.tap(find.text('result.csv').last); + expect(pickedGroup, same(second)); + }); + + testWidgets('long names wrap at 2x under both native hosts', (tester) async { + tester.view.devicePixelRatio = 2; + tester.view.physicalSize = const Size(780, 1560); + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final withLongName = visitGroup( + visit: 3, + artifacts: [ + recordedArtifact( + longArtifactName, + url: '/artifacts/7/3/$longArtifactName', + contentType: + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + sizeBytes: 123456, + ), + ], + ); + + for (final cupertino in [false, true]) { + await tester.pumpWidget( + artifactListHost( + cupertino: cupertino, + groups: [withLongName], + textScale: 2, + onSelected: (_, _) {}, + ), + ); + expect(tester.takeException(), isNull); + final name = tester.renderObject(find.text(longArtifactName)); + expect( + name.size.height, + greaterThan(120), + reason: 'the recorded name must wrap over several lines, not one', + ); + expect( + find.text( + 'application/vnd.openxmlformats-officedocument.' + 'spreadsheetml.sheet · 120.6${nonBreakingSpace}KiB', + ), + findsOneWidget, + ); + } + }); + + testWidgets('a missing name and content type stay explicit', (tester) async { + final group = visitGroup( + artifacts: [ + unaddressedArtifact(), + recordedArtifact( + 'notes.md', + url: '/artifacts/7/1/notes.md', + contentType: 'text/markdown', + sizeBytes: 812, + ), + ], + ); + await tester.pumpWidget( + artifactListHost(cupertino: false, groups: [group]), + ); + + expect(find.text('(unnamed artifact)'), findsOneWidget); + expect( + find.text('type not recorded · 0${nonBreakingSpace}B'), + findsOneWidget, + ); + expect(find.text('notes.md'), findsOneWidget); + expect( + find.text('text/markdown · 812${nonBreakingSpace}B'), + findsOneWidget, + ); + expect(find.byIcon(Icons.check), findsNothing); + }); + + testWidgets('empty groups keep the honest empty wording', (tester) async { + await tester.pumpWidget( + artifactListHost(cupertino: false, groups: const []), + ); + expect(find.text('No stage artifacts recorded.'), findsOneWidget); + expect(find.byType(ListTile), findsNothing); + }); +} diff --git a/app/test/features/changes/changes_viewer_test.dart b/app/test/features/changes/changes_viewer_test.dart new file mode 100644 index 00000000..5278e84b --- /dev/null +++ b/app/test/features/changes/changes_viewer_test.dart @@ -0,0 +1,473 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/changes/changes.dart'; + +import 'fixtures.dart'; +import 'widget_hosts.dart'; + +void main() { + testWidgets( + 'a missing capture is an evidence gap, not an observed no-change', + (tester) async { + await tester.pumpWidget( + materialHost(ChangesViewer(steps: [stepFixture(fileChanges: null)])), + ); + expect(find.text('Changes · not recorded for this run'), findsOneWidget); + expect(find.text('Capture unavailable'), findsOneWidget); + expect(find.text(missingCaptureDetail), findsOneWidget); + expect(find.text(emptyCaptureDetail), findsNothing); + expect(find.text('No changes observed'), findsNothing); + }, + ); + + testWidgets('a running step with no capture is pending, not unavailable', ( + tester, + ) async { + await tester.pumpWidget( + materialHost( + ChangesViewer( + steps: [stepFixture(status: 'running', fileChanges: null)], + ), + ), + ); + expect(find.text('Changes · capture pending'), findsOneWidget); + expect(find.text('Capture pending'), findsOneWidget); + expect(find.text(pendingCaptureDetail), findsOneWidget); + expect(find.text('Capture unavailable'), findsNothing); + }); + + testWidgets('a differently cased running status agrees with the header', ( + tester, + ) async { + await tester.pumpWidget( + materialHost( + ChangesViewer( + steps: [stepFixture(status: 'Running', fileChanges: null)], + ), + ), + ); + expect(find.text('Changes · capture pending'), findsOneWidget); + expect(find.text('Capture pending'), findsOneWidget); + expect(find.text('Capture unavailable'), findsNothing); + }); + + testWidgets('an empty complete capture says the workspace was unchanged', ( + tester, + ) async { + await tester.pumpWidget( + materialHost( + ChangesViewer(steps: [stepFixture(fileChanges: captureFixture())]), + ), + ); + expect(find.text('Changes · no changes observed'), findsOneWidget); + expect(find.text('No changes observed'), findsOneWidget); + expect(find.text(emptyCaptureDetail), findsOneWidget); + expect(find.text(missingCaptureDetail), findsNothing); + }); + + testWidgets('an unavailable capture never claims there were no changes', ( + tester, + ) async { + await tester.pumpWidget( + materialHost( + ChangesViewer( + steps: [ + stepFixture( + fileChanges: captureFixture( + status: 'unavailable', + diagnostic: + 'Workspace snapshot unavailable; changes could not be ' + 'compared.', + ), + ), + ], + ), + ), + ); + expect(find.text('Changes · capture unavailable'), findsOneWidget); + expect(find.textContaining('Workspace snapshot unavailable'), findsWidgets); + expect(find.text(emptyCaptureDetail), findsNothing); + }); + + testWidgets('stage/visit sections keep partial status, counters and scope', ( + tester, + ) async { + final diagnostic = 'Excluded protected files.'; + await tester.pumpWidget( + materialHost( + ChangesViewer( + steps: [ + stepFixture( + stage: 'implementer', + fileChanges: captureFixture( + status: 'partial', + skipped: 1, + omitted: 2, + diagnostic: diagnostic, + files: [ + fileChangeFixture(path: 'lib/a.dart', patch: multiHunkPatch), + ], + ), + ), + stepFixture( + stage: 'reviewer', + sequence: 2, + status: 'failed', + fileChanges: null, + ), + ], + ), + ), + ); + expect(find.text('implementer'), findsOneWidget); + expect(find.text('Visit 1 · completed'), findsOneWidget); + // The reviewer's first visit is Visit 1, not the run-wide step ordinal 2. + expect(find.text('Visit 1 · failed'), findsOneWidget); + expect(find.text('Visit 2 · failed'), findsNothing); + expect( + find.text( + 'partial (1 files), 1 skipped, 2 omitted · Excluded protected files.', + ), + findsOneWidget, + ); + expect( + find.text('Scope: Git tracked and nonignored files in the run directory'), + findsOneWidget, + ); + expect(find.text('reviewer'), findsOneWidget); + expect(find.text(missingCaptureDetail), findsOneWidget); + expect(find.textContaining('partial capture'), findsWidgets); + }); + + testWidgets( + 'repeated stages number their own visits and honour control.visit', + (tester) async { + // Tall enough that the lazy list builds every section. + tester.view.physicalSize = const Size(800, 1400); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + materialHost( + ChangesViewer( + steps: [ + stepFixture( + stage: 'implementer', + sequence: 1, + fileChanges: captureFixture(), + ), + stepFixture( + stage: 'reviewer', + sequence: 2, + fileChanges: captureFixture(), + ), + stepFixture( + stage: 'implementer', + sequence: 3, + fileChanges: captureFixture(), + ), + stepFixture( + stage: 'reviewer', + sequence: 4, + visit: 6, + fileChanges: captureFixture(), + ), + ], + ), + ), + ); + // Both stages' first recorded visits are Visit 1; the run-wide step + // ordinals (1-4) must not leak into the label. + expect(find.text('Visit 1 · completed'), findsNWidgets(2)); + expect(find.text('Visit 2 · completed'), findsOneWidget); + // The resumed reviewer visit records control.visit 6. + expect(find.text('Visit 6 · completed'), findsOneWidget); + expect(find.text('Visit 3 · completed'), findsNothing); + expect(find.text('Visit 4 · completed'), findsNothing); + }, + ); + + testWidgets('filtering changed filenames keeps matching rows and says so', ( + tester, + ) async { + await tester.pumpWidget( + materialHost( + ChangesViewer( + steps: [ + stepFixture( + fileChanges: captureFixture( + files: [ + fileChangeFixture(path: 'assets/logo.bin', binary: true), + fileChangeFixture( + path: 'lib/feature.dart', + patch: multiHunkPatch, + ), + fileChangeFixture( + path: 'docs/notes.md', + kind: 'added', + patch: '@@ -0,0 +1 @@\n+x', + ), + ], + ), + ), + ], + ), + ), + ); + expect(find.text('assets/logo.bin'), findsOneWidget); + expect(find.text('lib/feature.dart'), findsOneWidget); + + await tester.enterText(find.byType(TextField), 'feature'); + await tester.pump(); + expect(find.text('lib/feature.dart'), findsOneWidget); + expect(find.text('assets/logo.bin'), findsNothing); + expect(find.text('docs/notes.md'), findsNothing); + expect(find.text('1 of 3 changed paths match'), findsOneWidget); + + await tester.enterText(find.byType(TextField), 'nothing-here'); + await tester.pump(); + expect( + find.text('No changed filenames match "nothing-here".'), + findsOneWidget, + ); + + await tester.enterText(find.byType(TextField), ''); + await tester.pump(); + expect(find.text('assets/logo.bin'), findsOneWidget); + expect(find.textContaining('changed files match'), findsNothing); + }); + + testWidgets( + 'opening a file shows the rendered patch and copies exact bytes', + (tester) async { + final calls = []; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, (call) async { + if (call.method == 'Clipboard.setData') calls.add(call); + return null; + }); + addTearDown( + () => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, null), + ); + await tester.pumpWidget( + materialHost( + ChangesViewer( + steps: [ + stepFixture( + fileChanges: captureFixture( + files: [ + fileChangeFixture( + path: 'lib/feature.dart', + patch: multiHunkPatch, + ), + ], + ), + ), + ], + ), + ), + ); + + await tester.tap(find.byKey(const ValueKey('change-1-lib/feature.dart'))); + await tester.pumpAndSettle(); + expect(find.byType(Dialog), findsOneWidget); + expect(find.text('Rendered'), findsOneWidget); + expect(find.text('Raw patch'), findsOneWidget); + final rendered = tester + .widgetList(find.byType(RichText)) + .map((rich) => rich.text.toPlainText()) + .join('\n'); + expect(rendered, contains('+ new line')); + expect(rendered, contains('- old line')); + expect(rendered, contains('@@ -20,3 +21,2 @@')); + + await tester.tap(find.text('Raw patch')); + await tester.pumpAndSettle(); + final raw = tester.widget(find.text(multiHunkPatch)); + expect(raw.data, multiHunkPatch); + expect(raw.softWrap, isFalse); + + await tester.tap(find.text('Copy patch')); + await tester.pump(); + expect(calls, hasLength(1)); + expect(calls.single.arguments, {'text': multiHunkPatch}); + expect(find.text('Copied'), findsOneWidget); + + await tester.tap(find.byTooltip('Close diff')); + await tester.pumpAndSettle(); + expect(find.byType(Dialog), findsNothing); + }, + ); + + testWidgets('binary, truncated and mode-only entries explain the missing diff', ( + tester, + ) async { + await tester.pumpWidget( + materialHost( + SingleChildScrollView( + child: Column( + children: [ + SizedBox( + height: 300, + child: FileDiffViewer( + file: FileChange( + path: 'assets/logo.bin', + kind: ChangeKind.modified, + binary: true, + ), + ), + ), + SizedBox( + height: 300, + child: FileDiffViewer( + file: FileChange( + path: 'logs/build.log', + kind: ChangeKind.modified, + patch: '@@ -1 +1 @@\n-a\n+b', + truncated: true, + ), + ), + ), + SizedBox( + height: 300, + child: FileDiffViewer( + file: FileChange( + path: 'scripts/run.sh', + kind: ChangeKind.modified, + beforeMode: '0644', + afterMode: '0755', + ), + ), + ), + ], + ), + ), + ), + ); + expect(find.text(binaryDiffMessage), findsOneWidget); + expect(find.text(truncatedPatchNote), findsOneWidget); + expect( + find.text( + "Only the file's mode changed (0644→0755); the server recorded no text " + 'diff.', + ), + findsOneWidget, + ); + final copyButtons = []; + for (var index = 0; index < 3; index++) { + final button = find + .ancestor( + of: find.text('Copy patch').at(index), + matching: find.byWidgetPredicate((widget) => widget is TextButton), + ) + .first; + copyButtons.add(tester.widget(button)); + } + // Binary and mode-only have nothing to copy; the truncated patch still can. + expect( + copyButtons.where((button) => button.onPressed == null), + hasLength(2), + ); + expect( + copyButtons.where((button) => button.onPressed != null), + hasLength(1), + ); + }); + + testWidgets( + 'Cupertino uses native list tiles, search field and segmented control', + (tester) async { + await tester.pumpWidget( + cupertinoHost( + ChangesViewer( + steps: [ + stepFixture( + fileChanges: captureFixture( + files: [ + fileChangeFixture( + path: 'lib/feature.dart', + patch: multiHunkPatch, + ), + ], + ), + ), + ], + ), + ), + ); + expect(find.byType(CupertinoListTile), findsOneWidget); + expect(find.byType(CupertinoSearchTextField), findsOneWidget); + expect(find.byType(TextField), findsNothing); + + await tester.tap(find.byKey(const ValueKey('change-1-lib/feature.dart'))); + await tester.pumpAndSettle(); + expect( + find.byType(CupertinoSlidingSegmentedControl), + findsOneWidget, + ); + expect(find.text('Rendered'), findsOneWidget); + expect(find.text('Raw patch'), findsOneWidget); + + await tester.tap(find.byIcon(CupertinoIcons.xmark)); + await tester.pumpAndSettle(); + expect( + find.byType(CupertinoSlidingSegmentedControl), + findsNothing, + ); + }, + ); + + testWidgets('narrow viewport and large text keep every control reachable', ( + tester, + ) async { + tester.view.physicalSize = const Size(320, 720); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + materialHost( + ChangesViewer( + steps: [ + stepFixture( + fileChanges: captureFixture( + files: [ + fileChangeFixture( + path: 'lib/a_rather_long_feature_file_name.dart', + patch: multiHunkPatch, + ), + fileChangeFixture(path: 'assets/logo.bin', binary: true), + ], + ), + ), + ], + ), + scaler: const TextScaler.linear(2), + ), + ); + expect(tester.takeException(), isNull); + expect( + find.text('lib/a_rather_long_feature_file_name.dart'), + findsOneWidget, + ); + + // The viewer itself at the same narrow width and 2x text: every action + // stays on screen and the patch body scrolls instead of overflowing. + await tester.pumpWidget( + materialHost( + FileDiffViewer( + file: FileChange( + path: 'lib/a_rather_long_feature_file_name.dart', + kind: ChangeKind.modified, + patch: multiHunkPatch, + ), + ), + scaler: const TextScaler.linear(2), + ), + ); + expect(tester.takeException(), isNull); + expect(find.text('Rendered'), findsOneWidget); + expect(find.text('Copy patch'), findsOneWidget); + expect(find.byTooltip('Close diff'), findsOneWidget); + }); +} diff --git a/app/test/features/changes/diff_presentation_test.dart b/app/test/features/changes/diff_presentation_test.dart new file mode 100644 index 00000000..77dad873 --- /dev/null +++ b/app/test/features/changes/diff_presentation_test.dart @@ -0,0 +1,206 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/changes/changes.dart'; +import 'package:pipelines_app/features/changes/widgets/change_style.dart'; + +import 'fixtures.dart'; +import 'widget_hosts.dart'; + +/// The patch has one short context line and one much longer added line, so a +/// text-width tint and a full-hunk-width tint are visibly different sizes. +const _raggedPatch = + '@@ -1,4 +1,4 @@\n' + ' short\n' + '+this added line is much longer than every other recorded line here\n' + '-x\n' + ' tail\n'; + +void main() { + test( + 'patch typography preserves the native host style without overrides', + () { + const native = TextStyle(fontSize: 19, fontFamily: 'host-font'); + expect(nativeDiffText(native), same(native)); + }, + ); + + testWidgets( + 'light and dark themes give additions and removals distinct hues', + (tester) async { + for (final brightness in [Brightness.light, Brightness.dark]) { + await tester.pumpWidget( + materialHost(const SizedBox.shrink(), brightness: brightness), + ); + final context = tester.element(find.byType(Scaffold)); + final add = diffLineColors(context, ChangeLineKind.add); + final remove = diffLineColors(context, ChangeLineKind.remove); + expect(add.background, isNull); + expect(remove.background, isNull); + expect(add.text, isNot(remove.text), reason: '$brightness text'); + expect(add.text, Theme.of(context).colorScheme.primary); + expect(remove.text, Theme.of(context).colorScheme.error); + } + }, + ); + + testWidgets('every diff line shares the hunk width, not its own text width', ( + tester, + ) async { + await tester.pumpWidget( + materialHost( + SizedBox( + height: 400, + child: FileDiffViewer( + file: FileChange( + path: 'lib/ragged.dart', + kind: ChangeKind.modified, + patch: _raggedPatch, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final widths = [ + for (var index = 0; index < 4; index++) + tester.getSize(find.byKey(ValueKey('diff-line-$index'))).width, + ]; + for (final width in widths) { + expect(width, closeTo(widths.first, 0.01)); + } + // The widest recorded line sets the hunk width, well beyond a short line. + expect(widths.first, greaterThan(300)); + }); + + testWidgets('the stat line colours additions and removals apart', ( + tester, + ) async { + await tester.pumpWidget( + materialHost( + SizedBox( + height: 400, + child: FileDiffViewer( + file: FileChange( + path: 'lib/feature.dart', + kind: ChangeKind.modified, + patch: multiHunkPatch, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final stat = tester.widgetList(find.byType(RichText)).firstWhere(( + rich, + ) { + final span = rich.text; + return span is TextSpan && + span.children != null && + span.toPlainText() == '+2 -2'; + }); + final root = (stat.text as TextSpan).children!.single as TextSpan; + final spans = root.children!.cast(); + final added = spans.firstWhere((span) => span.text == '+2'); + final removed = spans.firstWhere((span) => span.text == '-2'); + expect(added.style!.color, isNot(removed.style!.color)); + }); + + testWidgets('the raw view scrolls long lines instead of wrapping them', ( + tester, + ) async { + await tester.pumpWidget( + materialHost( + SizedBox( + height: 400, + child: FileDiffViewer( + file: FileChange( + path: 'lib/feature.dart', + kind: ChangeKind.modified, + patch: multiHunkPatch, + ), + ), + ), + ), + ); + await tester.tap(find.text('Raw patch')); + await tester.pumpAndSettle(); + expect(find.text(multiHunkPatch), findsOneWidget); + expect( + find.ancestor( + of: find.text(multiHunkPatch), + matching: find.byWidgetPredicate( + (widget) => + widget is SingleChildScrollView && + widget.scrollDirection == Axis.horizontal, + ), + ), + findsOneWidget, + ); + }); + + testWidgets('a Cupertino row wraps its recorded path instead of clipping it', ( + tester, + ) async { + tester.view.physicalSize = const Size(320, 720); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + const path = + 'lib/features/changes/domain/a_rather_long_unified_patch_file_name.dart'; + await tester.pumpWidget( + cupertinoHost( + ChangesViewer( + steps: [ + stepFixture( + fileChanges: captureFixture( + files: [fileChangeFixture(path: path, patch: multiHunkPatch)], + ), + ), + ], + ), + ), + ); + final rich = tester + .widgetList(find.byType(RichText)) + .firstWhere((widget) => widget.text.toPlainText() == path); + // CupertinoListTile caps a title at one ellipsized line; the row must lift + // that cap so the filename stays visible. + expect(rich.maxLines, isNull); + expect(rich.overflow, TextOverflow.visible); + expect(tester.getSize(find.text(path)).height, greaterThan(30)); + expect(tester.takeException(), isNull); + }); + + testWidgets('a Cupertino phone dialog is inset from the screen edge', ( + tester, + ) async { + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + cupertinoHost( + ChangesViewer( + steps: [ + stepFixture( + fileChanges: captureFixture( + files: [ + fileChangeFixture( + path: 'lib/feature.dart', + patch: multiHunkPatch, + ), + ], + ), + ), + ], + ), + ), + ); + await tester.tap(find.byKey(const ValueKey('change-1-lib/feature.dart'))); + await tester.pumpAndSettle(); + final rect = tester.getRect(find.byType(CupertinoPopupSurface)); + expect(rect.width, lessThanOrEqualTo(390 - 24)); + expect(rect.left, greaterThan(8)); + expect(rect.right, lessThan(382)); + expect(tester.takeException(), isNull); + }); +} diff --git a/app/test/features/changes/fixtures.dart b/app/test/features/changes/fixtures.dart new file mode 100644 index 00000000..f3badfa3 --- /dev/null +++ b/app/test/features/changes/fixtures.dart @@ -0,0 +1,67 @@ +import 'package:pipelines_app/core/api_gateway.dart'; + +/// Server-shaped fixtures shared by the Changes tests. These mirror the JSON +/// `internal/protocol.StageFileChanges` / `FileChange` writer, including quoted +/// unified headers and optional fields. +const multiHunkPatch = + '--- "a/lib/feature.dart"\n' + '+++ "b/lib/feature.dart"\n' + '@@ -1,4 +1,5 @@\n' + ' context one\n' + '-old line\n' + '+new line\n' + '+added line\n' + ' context two\n' + ' context three\n' + '@@ -20,3 +21,2 @@\n' + ' context twenty\n' + '-removed line\n' + ' context twenty-two\n'; + +JsonMap fileChangeFixture({ + required String path, + String kind = 'modified', + String patch = '', + bool binary = false, + bool truncated = false, + String? beforeMode, + String? afterMode, +}) => { + 'path': path, + 'kind': kind, + 'patch': patch, + if (binary) 'binary': true, + if (truncated) 'truncated': true, + 'before_mode': ?beforeMode, + 'after_mode': ?afterMode, +}; + +JsonMap captureFixture({ + String status = 'complete', + List files = const [], + int skipped = 0, + int omitted = 0, + String diagnostic = '', + String scope = 'Git tracked and nonignored files in the run directory', +}) => { + 'status': status, + 'scope': scope, + 'files': files, + 'skipped': skipped, + 'omitted': omitted, + 'diagnostic': diagnostic, +}; + +JsonMap stepFixture({ + String stage = 'implementer', + int sequence = 1, + String status = 'completed', + JsonMap? fileChanges, + int? visit, +}) => { + 'stage': stage, + 'sequence': sequence, + 'status': status, + 'file_changes': fileChanges, + if (visit != null) 'control': {'visit': visit}, +}; diff --git a/app/test/features/changes/run_changes_test.dart b/app/test/features/changes/run_changes_test.dart new file mode 100644 index 00000000..384c1170 --- /dev/null +++ b/app/test/features/changes/run_changes_test.dart @@ -0,0 +1,624 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/changes/domain/change_capture.dart'; +import 'package:pipelines_app/features/changes/domain/change_kind.dart'; +import 'package:pipelines_app/features/changes/domain/change_wording.dart'; +import 'package:pipelines_app/features/changes/domain/file_change.dart'; +import 'package:pipelines_app/features/changes/domain/run_changes.dart'; + +import 'fixtures.dart'; + +// Thin map-override wrappers over the shared server-shaped fixtures; the +// canonical field shapes live in fixtures.dart. +JsonMap file(JsonMap overrides) => { + ...fileChangeFixture(path: 'a.txt'), + ...overrides, +}; + +JsonMap step(JsonMap overrides) => {...stepFixture(stage: 's'), ...overrides}; + +JsonMap capture({ + String status = 'complete', + List files = const [], + int skipped = 0, + int omitted = 0, + String diagnostic = '', + String scope = 'Git tracked and nonignored files in the run directory', +}) => captureFixture( + status: status, + files: files, + skipped: skipped, + omitted: omitted, + diagnostic: diagnostic, + scope: scope, +); + +void main() { + test( + 'a null capture is pending while running/waiting, otherwise missing', + () { + final running = runChanges([ + step({'status': 'running'}), + step({'status': 'waiting'}), + ]); + expect(running.pending, isTrue); + expect(running.missingCaptures, 0); + expect(running.stepsWithChanges, 0); + + final missing = runChanges([ + step({'status': 'completed'}), + step({'status': 'failed'}), + ]); + expect(missing.pending, isFalse); + expect(missing.missingCaptures, 2); + expect(missing.stepsWithChanges, 0); + }, + ); + + test('a non-null malformed capture is unavailable, not a no-change', () { + final changes = runChanges([ + step({'file_changes': 'not-an-object'}), + ]); + expect(changes.stepsWithChanges, 1); + expect(changes.missingCaptures, 0); + expect(changes.unavailable, isTrue); + expect(changes.files, isEmpty); + expect(runChangesHeader(changes), 'Changes · capture unavailable'); + expect(runChangesNote(changes), malformedCaptureDetail); + }); + + test('a present capture with no files is a captured no-change', () { + final changes = runChanges([ + step({'stage': 'a', 'file_changes': capture()}), + ]); + expect(changes.stepsWithChanges, 1); + expect(changes.files, isEmpty); + expect(changes.partial, isFalse); + expect(runChangesHeader(changes), 'Changes · no changes observed'); + expect(noChangeDetail(changes), emptyCaptureDetail); + }); + + test('a later visit wins the kind, including an unrecognised later kind', () { + final changes = runChanges([ + step({ + 'stage': 'a', + 'file_changes': capture( + files: [ + file({'path': 'x', 'kind': 'modified'}), + ], + ), + }), + step({ + 'stage': 'b', + 'file_changes': capture( + files: [ + file({'path': 'x', 'kind': 'added'}), + ], + ), + }), + ]); + expect(changes.files.single.kind, ChangeKind.added); + expect(changes.files.single.steps, ['a', 'b']); + + final unknown = runChanges([ + step({ + 'stage': 'a', + 'file_changes': capture( + files: [ + file({'path': 'x', 'kind': 'added'}), + ], + ), + }), + step({ + 'stage': 'b', + 'file_changes': capture( + files: [ + file({'path': 'x', 'kind': 'copied'}), + ], + ), + }), + ]); + expect(unknown.files.single.kind, ChangeKind.other); + }); + + test('three visits report only the last visit facts', () { + final changes = runChanges([ + step({ + 'stage': 'a', + 'sequence': 1, + 'file_changes': capture( + files: [ + file({ + 'path': 'x', + 'kind': 'modified', + 'patch': '@@ -1 +1 @@\n-old\n+one', + 'before_mode': '0644', + 'after_mode': '0644', + }), + ], + ), + }), + step({ + 'stage': 'b', + 'sequence': 2, + 'file_changes': capture( + files: [ + file({ + 'path': 'x', + 'patch': '@@ -1 +1 @@\n-one\n+two', + 'before_mode': '0644', + 'after_mode': '0644', + }), + ], + ), + }), + step({ + 'stage': 'c', + 'sequence': 3, + 'file_changes': capture( + files: [ + file({ + 'path': 'x', + 'kind': 'added', + 'patch': '@@ -1 +2 @@\n-two\n+three\n+four', + 'before_mode': '0755', + 'after_mode': '0600', + }), + ], + ), + }), + ]); + final entry = changes.files.single; + expect(entry.kind, ChangeKind.added); + expect(entry.added, 2); + expect(entry.removed, 1); + expect(entry.patch, '@@ -1 +2 @@\n-two\n+three\n+four'); + expect(entry.beforeMode, '0755'); + expect(entry.afterMode, '0600'); + expect(entry.modeChanged, isTrue); + expect(entry.steps, ['a', 'b', 'c']); + expect(changeRowMeta(entry), 'changed by a → b → c · mode 0755→0600'); + expect(changes.added, 2); + expect(changes.removed, 1); + }); + + test('later binary/truncated flags replace earlier rows', () { + final changes = runChanges([ + step({ + 'stage': 'a', + 'file_changes': capture( + files: [ + file({ + 'path': 'x', + 'patch': '@@ -1 +1 @@\n-old\n+new', + 'binary': true, + 'truncated': true, + 'before_mode': '0644', + 'after_mode': '0755', + }), + ], + ), + }), + step({ + 'stage': 'b', + 'file_changes': capture( + files: [ + file({ + 'path': 'x', + 'patch': '', + 'binary': false, + 'truncated': false, + 'before_mode': '0755', + 'after_mode': '0755', + }), + ], + ), + }), + ]); + final entry = changes.files.single; + expect(entry.binary, isFalse); + expect(entry.truncated, isFalse); + expect(entry.patch, isNull); + expect(entry.modeChanged, isFalse); + expect(entry.added, 0); + expect(entry.removed, 0); + // A truncated row anywhere in the run still makes the capture partial. + expect(changes.partial, isTrue); + }); + + test('paths keep first-seen order while ordering follows sequence', () { + final changes = runChanges([ + step({ + 'stage': 'c', + 'sequence': 3, + 'file_changes': capture( + files: [ + file({'path': 'y'}), + ], + ), + }), + step({ + 'stage': 'a', + 'sequence': 1, + 'file_changes': capture( + files: [ + file({'path': 'y'}), + ], + ), + }), + step({ + 'stage': 'b', + 'sequence': 2, + 'file_changes': capture( + files: [ + file({'path': 'x'}), + ], + ), + }), + ]); + expect(changes.files.map((entry) => entry.path), ['y', 'x']); + expect(changes.files.first.kind, ChangeKind.modified); + expect(changes.files.first.steps, ['a', 'c']); + expect(changeRowMeta(changes.files.first), 'changed by a → c'); + }); + + test( + 'stage names are deduped in run order; blank names/paths are handled', + () { + final changes = runChanges([ + step({ + 'stage': 'implementer', + 'file_changes': capture( + files: [ + file({'path': 'x'}), + ], + ), + }), + step({ + 'stage': 'reviewer', + 'file_changes': capture( + files: [ + file({'path': 'x'}), + ], + ), + }), + step({ + 'stage': 'implementer', + 'file_changes': capture( + files: [ + file({'path': 'x'}), + file({'path': ' '}), + ], + ), + }), + ]); + expect(changes.files.single.steps, ['implementer', 'reviewer']); + + final blank = runChanges([ + step({ + 'stage': ' ', + 'file_changes': capture( + files: [ + file({'path': 'x'}), + ], + ), + }), + ]); + expect(blank.files.single.steps, ['stage']); + }, + ); + + test('partial is OR-ed from status, a truncated file or omitted count', () { + expect( + runChanges([ + step({'file_changes': capture(status: 'partial')}), + ]).partial, + isTrue, + ); + expect( + runChanges([ + step({ + 'file_changes': capture( + files: [ + file({'truncated': true}), + ], + ), + }), + ]).partial, + isTrue, + ); + expect( + runChanges([ + step({'file_changes': capture(omitted: 2)}), + ]).partial, + isTrue, + ); + }); + + test('diagnostics from several captures are deduped and joined', () { + final changes = runChanges([ + step({'file_changes': capture(status: 'partial', diagnostic: 'why one')}), + step({'file_changes': capture(status: 'partial', diagnostic: 'why one')}), + step({'file_changes': capture(status: 'partial', diagnostic: 'why two')}), + ]); + expect(changes.diagnostic, 'why one why two'); + expect(changes.stepsWithChanges, 3); + }); + + test( + 'stageCaptures keeps every visit, including a missing one, in order', + () { + final visits = stageCaptures([ + step({'stage': 'reviewer', 'sequence': 2, 'file_changes': capture()}), + step({'stage': 'implementer', 'sequence': 1, 'file_changes': null}), + ]); + expect(visits.map((visit) => visit.stage), ['implementer', 'reviewer']); + expect(visits.first.missing, isTrue); + expect(visits.last.capture?.status, 'complete'); + }, + ); + + test( + 'visit is control.visit when positive, else the position in its stage', + () { + final visits = stageCaptures([ + stepFixture(stage: 'implementer', sequence: 1), + stepFixture(stage: 'reviewer', sequence: 2), + stepFixture(stage: 'implementer', sequence: 3), + stepFixture(stage: 'implementer', sequence: 4, visit: 7), + stepFixture(stage: 'reviewer', sequence: 5, visit: 0), + ]); + expect(visits.map((visit) => '${visit.stage}:${visit.visit}'), [ + 'implementer:1', + 'reviewer:1', + 'implementer:2', + 'implementer:7', + 'reviewer:2', + ]); + }, + ); + + test('equal sequences keep their input order for stage positions', () { + final visits = stageCaptures([ + stepFixture(stage: 's', sequence: 1), + stepFixture(stage: 's', sequence: 1), + stepFixture(stage: 'other', sequence: 0), + ]); + expect(visits.map((visit) => '${visit.stage}:${visit.visit}'), [ + 'other:1', + 's:1', + 's:2', + ]); + }); + + test('capture parsing keeps scope, counters and diagnostic', () { + final parsed = ChangeCapture.fromJson( + capture( + status: 'partial', + skipped: 2, + omitted: 1, + diagnostic: 'Excluded protected files.', + files: [ + file({'path': 'x'}), + file({'path': ''}), + ], + ), + ); + expect(parsed.scope, contains('Git tracked')); + expect(parsed.skipped, 2); + expect(parsed.omitted, 1); + expect(parsed.diagnostic, 'Excluded protected files.'); + expect(parsed.files.map((entry) => entry.path), ['x']); + expect( + fileChangesSummary(parsed), + 'partial (1 files), 2 skipped, 1 omitted · Excluded protected files.', + ); + }); + + test('header covers every empty-capture variant', () { + expect( + runChangesHeader(_run(unavailable: true, files: const [])), + 'Changes · capture unavailable', + ); + expect(runChangesHeader(_run(pending: true)), 'Changes · capture pending'); + expect( + runChangesHeader(_run(partial: true, stepsWithChanges: 1)), + 'Changes · partial capture', + ); + expect(runChangesHeader(_run()), 'Changes · not recorded for this run'); + expect( + runChangesHeader(_run(stepsWithChanges: 1, missingCaptures: 1)), + 'Changes · capture incomplete', + ); + expect( + runChangesHeader(_run(stepsWithChanges: 2)), + 'Changes · no changes observed', + ); + }); + + test('note spells partial, missing and unavailable wording', () { + expect( + runChangesNote(_run(unavailable: true)), + 'The workspace snapshot could not be compared; the changes below may be ' + 'incomplete.', + ); + expect( + runChangesNote(_run(unavailable: true, diagnostic: 'server says so')), + 'server says so', + ); + expect( + runChangesNote( + _run( + partial: true, + skipped: 8, + diagnostic: 'Excluded protected files.', + missingCaptures: 1, + ), + ), + 'Partial capture: some changes may be missing. (8 files skipped) ' + 'Excluded protected files. Missing capture: 1 stage did not record ' + 'changes.', + ); + expect( + runChangesNote( + _run( + partial: true, + omitted: 3, + missingCaptures: 2, + files: [ + FileChange(path: 'x', kind: ChangeKind.modified, truncated: true), + FileChange(path: 'y', kind: ChangeKind.modified, truncated: true), + ], + ), + ), + 'Partial capture: some changes may be missing. (3 omitted, 2 truncated) ' + 'Missing capture: 2 stages did not record changes.', + ); + expect(runChangesNote(_run()), ''); + }); + + test('tags, row meta and unavailable reasons are exact', () { + final binary = FileChange( + path: 'x', + kind: ChangeKind.modified, + binary: true, + truncated: false, + beforeMode: '0644', + afterMode: '0755', + steps: const ['a'], + ); + expect(changeEntryTags(binary), ['binary']); + expect(changeRowMeta(binary), 'changed by a · binary'); + + final truncated = FileChange( + path: 'x', + kind: ChangeKind.modified, + truncated: true, + steps: const ['a', 'b'], + ); + expect(changeEntryTags(truncated), ['truncated']); + expect(changeRowMeta(truncated), 'changed by a → b · truncated'); + + final modeOnly = FileChange( + path: 'x', + kind: ChangeKind.modified, + beforeMode: '0644', + afterMode: '0755', + steps: const ['a'], + ); + expect(changeEntryTags(modeOnly), ['mode change']); + expect( + changeRowMeta(modeOnly), + 'changed by a · mode change · mode 0644→0755', + ); + expect( + patchUnavailableReason(modeOnly), + "Only the file's mode changed (0644→0755); the server recorded no text " + 'diff.', + ); + expect( + patchUnavailableReason(truncated), + "The server truncated this file's patch at its capture limit; no diff " + 'text was recorded.', + ); + expect( + patchUnavailableReason(FileChange(path: 'x', kind: ChangeKind.modified)), + 'The server recorded this change without a patch.', + ); + }); + + test('changed filenames filter is case-insensitive and preserves order', () { + final files = [ + FileChange(path: 'lib/Changes_Viewer.dart', kind: ChangeKind.modified), + FileChange(path: 'docs/notes.md', kind: ChangeKind.added), + FileChange(path: 'lib/file_diff_viewer.dart', kind: ChangeKind.added), + ]; + expect(filterFileChanges(files, 'VIEWER').map((file) => file.path), [ + 'lib/Changes_Viewer.dart', + 'lib/file_diff_viewer.dart', + ]); + expect(filterFileChanges(files, ' '), files); + expect(filterFileChanges(files, 'absent'), isEmpty); + }); + + test('a real-shaped partial run aggregates once and keeps the gap visible', () { + const diagnostic = + 'Excluded protected, symlinked, oversized or unreadable files; this is ' + 'not a complete workspace diff.'; + final changes = runChanges([ + step({ + 'stage': 'implementer', + 'sequence': 1, + 'file_changes': capture( + status: 'partial', + skipped: 2, + diagnostic: diagnostic, + files: [ + file({ + 'path': 'docs/notes.md', + 'kind': 'added', + 'patch': '@@ -0,0 +1 @@\n+notes', + }), + file({ + 'path': 'internal/server/retry_test.go', + 'patch': '@@ -1 +1 @@\n-old\n+new', + }), + ], + ), + }), + step({ + 'stage': 'reviewer', + 'sequence': 2, + 'file_changes': capture( + status: 'partial', + skipped: 2, + diagnostic: diagnostic, + ), + }), + step({'stage': 'ui_reviewer', 'sequence': 3}), + ]); + expect(changes.files, hasLength(2)); + expect(changes.stepsWithChanges, 2); + expect(changes.missingCaptures, 1); + expect(changes.partial, isTrue); + expect(changes.skipped, 4); + expect( + runChangesHeader(changes), + '2 files changed · +2 -1 · partial capture', + ); + expect( + runChangesNote(changes), + 'Partial capture: some changes may be missing. (4 files skipped) ' + '$diagnostic Missing capture: 1 stage did not record changes.', + ); + expect( + runChangesHeader(_run(unavailable: true, files: changes.files)), + 'Changes · capture unavailable', + ); + }); +} + +RunChanges _run({ + List files = const [], + bool partial = false, + bool unavailable = false, + bool pending = false, + int stepsWithChanges = 0, + int missingCaptures = 0, + int skipped = 0, + int omitted = 0, + String diagnostic = '', +}) => RunChanges( + files: files, + stepsWithChanges: stepsWithChanges, + stepsPending: 0, + added: files.fold(0, (sum, file) => sum + file.added), + removed: files.fold(0, (sum, file) => sum + file.removed), + partial: partial, + unavailable: unavailable, + pending: pending, + missingCaptures: missingCaptures, + skipped: skipped, + omitted: omitted, + diagnostic: diagnostic, +); diff --git a/app/test/features/changes/unified_patch_test.dart b/app/test/features/changes/unified_patch_test.dart new file mode 100644 index 00000000..00cdd48a --- /dev/null +++ b/app/test/features/changes/unified_patch_test.dart @@ -0,0 +1,176 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/changes/domain/unified_patch.dart'; + +void main() { + test('a blank or absent patch parses to an empty result', () { + for (final blank in ['', ' ', '\n', null]) { + final parsed = parseUnifiedPatch(blank); + expect(parsed.raw, ''); + expect(parsed.headerLines, isEmpty); + expect(parsed.hunks, isEmpty); + expect(parsed.added, 0); + expect(parsed.removed, 0); + } + }); + + test('a single hunk is numbered and counted', () { + final patch = [ + '--- "a/x.txt"', + '+++ "b/x.txt"', + '@@ -1,3 +1,3 @@', + ' ctx', + '-old', + '+new', + ' tail', + ].join('\n'); + final parsed = parseUnifiedPatch(patch); + expect(parsed.raw, patch); + expect(parsed.headerLines, ['--- "a/x.txt"', '+++ "b/x.txt"']); + expect(parsed.hunks, hasLength(1)); + final hunk = parsed.hunks.single; + expect(hunk.header, '@@ -1,3 +1,3 @@'); + expect( + [hunk.oldStart, hunk.oldCount, hunk.newStart, hunk.newCount], + [1, 3, 1, 3], + ); + expect( + [ + for (final line in hunk.lines) + [line.kind, line.text, line.oldLine, line.newLine], + ], + [ + [ChangeLineKind.context, 'ctx', 1, 1], + [ChangeLineKind.remove, 'old', 2, 0], + [ChangeLineKind.add, 'new', 0, 2], + [ChangeLineKind.context, 'tail', 3, 3], + ], + ); + expect(parsed.added, 1); + expect(parsed.removed, 1); + }); + + test('a missing count defaults to 1', () { + final hunk = parseUnifiedPatch('@@ -5 +7 @@\n-old\n+new').hunks.single; + expect( + [hunk.oldStart, hunk.oldCount, hunk.newStart, hunk.newCount], + [5, 1, 7, 1], + ); + }); + + test('a multi-hunk patch keeps each hunk header and its own numbering', () { + final parsed = parseUnifiedPatch( + [ + '--- "a/lib/x.dart"', + '+++ "b/lib/x.dart"', + '@@ -1,2 +1,3 @@', + ' one', + '+two', + ' three', + '@@ -40,3 +41,2 @@', + ' forty', + '-forty-one', + ' forty-two', + ].join('\n'), + ); + expect(parsed.hunks, hasLength(2)); + expect(parsed.hunks[0].lines.map((line) => line.newLine), [1, 2, 3]); + expect(parsed.hunks[1].lines.map((line) => line.oldLine), [40, 41, 42]); + expect(parsed.added, 1); + expect(parsed.removed, 1); + expect(parsed.headerLines, ['--- "a/lib/x.dart"', '+++ "b/lib/x.dart"']); + }); + + test('a no-newline marker is shown verbatim and never numbered', () { + final lines = parseUnifiedPatch( + [ + '@@ -1 +1 @@', + '-one', + r'\ No newline at end of file', + '+two', + ].join('\n'), + ).hunks.single.lines; + expect(lines[1].noNewlineMarker, isTrue); + expect(lines[1].text, r'\ No newline at end of file'); + expect(lines[1].oldLine, 0); + expect(lines[1].newLine, 0); + expect(lines[1].kind, ChangeLineKind.context); + }); + + test('a second file header closes the current hunk', () { + final parsed = parseUnifiedPatch( + [ + '--- "a/x"', + '+++ "b/x"', + '@@ -1 +1 @@', + '-old', + '+new', + '--- "a/y"', + '+++ "b/y"', + '@@ -1 +1 @@', + '-alt', + '+neu', + ].join('\n'), + ); + expect(parsed.hunks, hasLength(2)); + expect(parsed.hunks[0].lines.map((line) => line.text), ['old', 'new']); + expect(parsed.hunks[1].lines.map((line) => line.text), ['alt', 'neu']); + expect( + parsed.headerLines.where((line) => line.startsWith('--- ')), + hasLength(2), + ); + expect(parsed.added, 2); + expect(parsed.removed, 2); + }); + + test('metadata before a hunk is kept; a truncated tail is unnumbered', () { + final parsed = parseUnifiedPatch( + [ + 'index abc..def 100644', + '--- "a/x"', + '+++ "b/x"', + '@@ -1 +1 @@', + '-old', + '+new', + 'trailing trunc', + ].join('\n'), + ); + expect(parsed.headerLines.first, 'index abc..def 100644'); + final tail = parsed.hunks.single.lines.last; + expect(tail.kind, ChangeLineKind.context); + expect(tail.text, 'trailing trunc'); + expect([tail.oldLine, tail.newLine], [0, 0]); + }); + + test('a trailing newline becomes a numbered empty context line', () { + final lines = parseUnifiedPatch('@@ -1 +1 @@\n ctx\n').hunks.single.lines; + expect(lines, hasLength(2)); + expect([lines[1].text, lines[1].oldLine, lines[1].newLine], ['', 2, 2]); + }); + + test('gutter width, gutter text, symbols and stat match the web wording', () { + expect( + gutterWidth( + const PatchHunk( + header: 'h', + oldStart: 0, + oldCount: 0, + newStart: 0, + newCount: 0, + lines: [], + ), + ), + 1, + ); + final hunk = parseUnifiedPatch('@@ -9,1 +12,1 @@\n-a\n+b').hunks.single; + expect(gutterWidth(hunk), 2); + expect(gutterText(0, 2), ' '); + expect(gutterText(7, 2), ' 7'); + expect(diffLineSymbol(ChangeLineKind.add), '+'); + expect(diffLineSymbol(ChangeLineKind.remove), '-'); + expect(diffLineSymbol(ChangeLineKind.context), ' '); + expect(changeStat(3, 2), '+3 -2'); + expect(changeStat(3, 0), '+3'); + expect(changeStat(0, 2), '-2'); + expect(changeStat(0, 0), ''); + }); +} diff --git a/app/test/features/changes/widget_hosts.dart b/app/test/features/changes/widget_hosts.dart new file mode 100644 index 00000000..f6b8144a --- /dev/null +++ b/app/test/features/changes/widget_hosts.dart @@ -0,0 +1,41 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +/// The two platform hosts the Changes widget tests share: Material for +/// Android/desktop/web and Cupertino for iOS/macOS. They state the platform +/// explicitly instead of mutating a global debug override. +Widget materialHost( + Widget child, { + TextScaler scaler = TextScaler.noScaling, + Brightness brightness = Brightness.light, +}) { + return MaterialApp( + theme: ThemeData(brightness: brightness), + builder: (context, app) => MediaQuery( + data: MediaQuery.of(context).copyWith(textScaler: scaler), + child: app!, + ), + home: Scaffold(body: child), + ); +} + +Widget cupertinoHost( + Widget child, { + TextScaler scaler = TextScaler.noScaling, + Brightness brightness = Brightness.light, +}) { + return CupertinoApp( + theme: CupertinoThemeData(brightness: brightness), + builder: (context, app) => Theme( + // The real app selects Cupertino by platform; the test host states it + // explicitly without changing a global debug override. The Theme wraps + // the Navigator so dialogs opened later resolve the same platform. + data: ThemeData(platform: TargetPlatform.iOS), + child: MediaQuery( + data: MediaQuery.of(context).copyWith(textScaler: scaler), + child: app!, + ), + ), + home: CupertinoPageScaffold(child: SafeArea(child: child)), + ); +} diff --git a/app/test/features/chat/chat_foundation_test.dart b/app/test/features/chat/chat_foundation_test.dart new file mode 100644 index 00000000..fd7b7b6a --- /dev/null +++ b/app/test/features/chat/chat_foundation_test.dart @@ -0,0 +1,316 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/data/chat_repository.dart'; +import 'package:pipelines_app/features/chat/domain/chat_sessions.dart'; +import 'package:pipelines_app/features/chat/domain/chat_transcript.dart'; + +class RecordingGateway implements ApiGateway { + final calls = <({String type, JsonMap fields})>[]; + JsonMap reply = {}; + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add((type: type, fields: fields)); + return reply; + } + + @override + Stream get frames => const Stream.empty(); +} + +void main() { + group('chat domain', () { + test( + 'filters/groups in server order and keeps server usage unknowns unavailable', + () { + final sessions = [ + {'id': 'a', 'directory': '/work', 'title': 'First'}, + {'id': 'b', 'directory': '/else', 'title': 'Second'}, + {'id': 'c', 'directory': '/work', 'title': 'Third'}, + ]; + expect(filterChatSessions(sessions, 'ELSE').single['id'], 'b'); + expect(groupChatSessions(sessions).map((g) => g.directory), [ + '/work', + '/else', + ]); + expect(chatSessionActivity(running: true, unseen: true), 'streaming'); + expect( + chatUsageSnapshot({ + 'total_tokens': 3, + 'context_window': 'unknown', + })!['context_window'], + isNull, + ); + expect(chatUsageSnapshot({'legacy_tokens': 9}), isNull); + }, + ); + + test( + 'merges pages by id, retains idless events, replaces authority, and folds parts', + () { + final first = mergeChatHistory({}, { + 'messages': [ + { + 'id': 'a', + 'role': 'assistant', + 'parts': [ + {'type': 'reasoning', 'text': 'think'}, + ], + }, + { + 'role': 'assistant', + 'parts': [ + {'type': 'future_part', 'payload': 4}, + ], + }, + {'id': 'u', 'role': 'user', 'text': 'hello', 'operation_id': 'op'}, + ], + 'nextCursor': 'opaque/1', + 'hasMore': true, + }); + final older = mergeChatHistory(first, { + 'messages': [ + { + 'id': 'a', + 'role': 'assistant', + 'parts': [ + {'type': 'text', 'text': 'final'}, + ], + }, + ], + 'nextCursor': '', + 'hasMore': false, + }, older: true); + expect(older['nextCursor'], ''); + final msgs = older['messages'] as List; + expect(msgs.map((m) => m['id']), ['a', null, 'u']); + expect( + (transcriptRows(msgs).first['parts'] as List).map((p) => p['type']), + ['text', 'future_part'], + ); + expect( + reconcileChatUser(msgs, { + 'id': 'remote', + 'role': 'user', + 'operation_id': 'op', + }).where((m) => m['operation_id'] == 'op').length, + 1, + ); + }, + ); + + test( + 'send queue is session-scoped and operation IDs deduplicate retries', + () { + final queue = ChatSendQueue(); + final send = QueuedChatSend( + operationId: 'stable', + text: ' prompt ', + files: ['/tmp/a'], + ); + expect(queue.enqueue('s1', send), isTrue); + expect(queue.enqueue('s1', send.retry()), isFalse); + expect(queue.enqueue('s2', send.retry()), isTrue); + expect(queue.takeNext('s1')!.operationId, 'stable'); + expect(queue.takeNext('s1'), isNull); + expect(queue.forSession('s2').single.files, ['/tmp/a']); + }, + ); + + test( + 'live text/reasoning append, tool snapshots merge, and steps settle only activity', + () { + var thread = { + 'sessionId': 's', + 'messages': [], + }; + thread = applyChatEvent(thread, { + 'kind': 'text', + 'session_id': 's', + 'message_id': 'a', + 'part': {'id': 'p'}, + 'delta': 'one', + }); + thread = applyChatEvent(thread, { + 'kind': 'text', + 'session_id': 's', + 'message_id': 'a', + 'part': {'id': 'p'}, + 'delta': ' two', + }); + thread = applyChatEvent(thread, { + 'kind': 'reasoning', + 'session_id': 's', + 'message_id': 'a', + 'part': {'id': 'r'}, + 'delta': 'hidden', + }); + thread = applyChatEvent(thread, { + 'kind': 'tool', + 'session_id': 's', + 'message_id': 'a', + 'part': { + 'id': 't', + 'type': 'tool', + 'state': {'input': 'x'}, + }, + }); + thread = applyChatEvent(thread, { + 'kind': 'tool', + 'session_id': 's', + 'message_id': 'a', + 'part': { + 'id': 't', + 'type': 'tool', + 'state': {'status': 'completed'}, + }, + }); + final parts = + ((thread['messages'] as List).single as JsonMap)['parts'] + as List; + expect(parts[0]['text'], 'one two'); + expect(parts[1]['text'], 'hidden'); + expect(parts[2]['state'], {'input': 'x', 'status': 'completed'}); + expect(thread['running'], true); + thread = applyChatEvent(thread, { + 'kind': 'step', + 'session_id': 's', + 'step': {'status': 'ended', 'turn_id': 'turn'}, + }); + expect(thread['running'], false); + expect( + applyChatEvent(thread, {'kind': 'text', 'session_id': 'other'}), + same(thread), + ); + }, + ); + }); + + group('chat wire adapter', () { + late RecordingGateway gateway; + late ChatRepository repo; + setUp(() { + gateway = RecordingGateway(); + repo = ChatRepository(gateway); + }); + test('uses web envelopes and opaque history cursor', () async { + gateway.reply = { + 'chat_history': { + 'messages': [ + {'id': 'm', 'role': 'user'}, + ], + 'next_cursor': 'opaque', + 'has_more': true, + }, + }; + final page = await repo.history('s', cursor: 'before', limit: 17); + expect(page['nextCursor'], 'opaque'); + expect(gateway.calls.last.type, 'chat_messages'); + expect(gateway.calls.last.fields, { + 'chat_query': {'session_id': 's', 'cursor': 'before', 'limit': 17}, + }); + await repo.subscribe('s'); + expect(gateway.calls.last.fields, { + 'chat_subscribe': {'session_id': 's'}, + }); + }); + test( + 'sends stable operation id, omits empty files, and builds action envelopes', + () async { + await repo.prompt('s', ' hi ', operationId: 'same'); + expect(gateway.calls.last.fields, { + 'chat_prompt': { + 'session_id': 's', + 'text': 'hi', + 'operation_id': 'same', + 'native_message_id': 'msg_same', + }, + }); + await repo.answerForm('s', 'f', {'choice': 'yes'}, action: 'submit'); + expect(gateway.calls.last.fields, { + 'chat_answer': { + 'session_id': 's', + 'form_id': 'f', + 'answers': {'choice': 'yes'}, + 'action': 'submit', + }, + }); + await repo.replyPermission('s', 'r', 'once', message: ' approved '); + expect(gateway.calls.last.fields, { + 'chat_reply': { + 'session_id': 's', + 'request_id': 'r', + 'decision': 'once', + 'client': 'Web', + 'message': 'approved', + }, + }); + await repo.create(title: 'New', directory: '~', operationId: 'create'); + expect(gateway.calls.last.fields, { + 'chat_create': { + 'title': 'New', + 'directory': '~', + 'operation_id': 'create', + }, + }); + await repo.selectModel('s', 'provider', 'model'); + expect(gateway.calls.last.type, 'chat_model'); + }, + ); + test('rejects invalid permissions and prompts before sending', () async { + expect( + () => repo.prompt(' ', 'hello', operationId: 'x'), + throwsArgumentError, + ); + expect( + () => repo.prompt('s', ' ', operationId: 'x'), + throwsArgumentError, + ); + expect( + () => repo.replyPermission('s', 'r', 'approve'), + throwsArgumentError, + ); + expect(gateway.calls, isEmpty); + }); + test( + 'uses the server model catalog object and default history limit', + () async { + gateway.reply = { + 'chat_models': { + 'providers': { + 'p': ['m'], + }, + }, + }; + expect((await repo.models('s'))['providers'], { + 'p': ['m'], + }); + expect(gateway.calls.single.fields, { + 'chat_query': {'session_id': 's'}, + }); + gateway.calls.clear(); + await repo.history('s'); + expect(gateway.calls.single.fields['chat_query']['limit'], 200); + }, + ); + test( + 'reads exact directory/backend catalog envelopes without inventing fallback', + () async { + gateway.reply = { + 'chat_directories': ['~', '/work'], + }; + expect(await repo.directories(), ['~', '/work']); + expect(gateway.calls.last.type, 'chat_directories'); + expect(gateway.calls.last.fields, isEmpty); + gateway.reply = { + 'chat_backends': ['opencode', 'claude'], + }; + expect(await repo.backends(), ['opencode', 'claude']); + expect(gateway.calls.last.type, 'chat_backends'); + expect(gateway.calls.last.fields, isEmpty); + gateway.reply = {}; + await expectLater(repo.directories(), throwsStateError); + await expectLater(repo.backends(), throwsStateError); + }, + ); + }); +} diff --git a/app/test/features/chat/ui/sessions/chat_create_dialog_test.dart b/app/test/features/chat/ui/sessions/chat_create_dialog_test.dart new file mode 100644 index 00000000..0b1b8b2e --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_create_dialog_test.dart @@ -0,0 +1,217 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; + +import 'chat_test_harness.dart'; +import 'fake_chat_gateway.dart'; + +void main() { + testWidgets( + 'material create dialog retains the draft through a delayed catalog failure and retry', + (tester) async { + final gateway = FakeChatGateway(); + final directories = Completer(); + gateway.directoriesHandler = () => directories.future; + JsonMap? opened; + await pumpMaterialChat( + tester, + gateway, + onOpen: (session) => opened = session, + ); + + await tester.tap(find.byKey(const Key('chat-new-chat-fab'))); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + expect(find.text('Loading directories…'), findsOneWidget); + + await tester.enterText( + find.byKey(const Key('chat-create-name')), + 'Draft chat', + ); + await tester.enterText( + find.byKey(const Key('chat-create-instructions')), + 'Keep me', + ); + + directories.completeError( + StateError('Server did not return chat directories.'), + ); + await tester.pump(); + await tester.pump(); + expect( + find.textContaining('Unable to load chat options'), + findsOneWidget, + ); + expect(find.text('Draft chat'), findsOneWidget); + expect(find.text('Keep me'), findsOneWidget); + + gateway.directoriesHandler = () async => { + 'chat_directories': ['/work'], + }; + await tester.tap(find.text('Retry')); + await tester.pumpAndSettle(); + expect(find.textContaining('Unable to load chat options'), findsNothing); + expect( + find.byKey(const Key('chat-create-server-directory')), + findsOneWidget, + ); + expect( + find.text('New chats use the server default model.'), + findsOneWidget, + ); + + await tester.enterText(find.byKey(const Key('chat-create-name')), ''); + await tester.tap(find.text('Create')); + await tester.pump(); + expect(find.text('Enter a name and server directory.'), findsOneWidget); + expect(gateway.count('chat_create'), 0); + + await tester.enterText( + find.byKey(const Key('chat-create-name')), + 'Draft chat', + ); + await tester.tap(find.text('Create')); + await tester.pumpAndSettle(); + + final fields = + gateway.lastFields('chat_create')!['chat_create']! as JsonMap; + expect(fields['title'], 'Draft chat'); + expect(fields['directory'], '/work'); + expect(fields.containsKey('backend'), isFalse); + expect(fields['instructions'], 'Keep me'); + expect(fields.containsKey('operation_id'), isTrue); + expect(opened?['id'], 'created'); + }, + ); + + testWidgets('Cupertino create dialog keeps the draft when catalogs fail', ( + tester, + ) async { + final gateway = FakeChatGateway(); + gateway.directoriesHandler = () => + Future.error(StateError('Server did not return chat directories.')); + await pumpCupertinoChat(tester, gateway); + + await tester.tap(find.byKey(const Key('chat-new-chat'))); + await tester.pumpAndSettle(); + expect(find.textContaining('Unable to load chat options'), findsOneWidget); + + await tester.enterText( + find.byKey(const Key('chat-create-name')), + 'Cupertino draft', + ); + await tester.enterText( + find.byKey(const Key('chat-create-instructions')), + 'Keep me too', + ); + expect(find.text('Cupertino draft'), findsOneWidget); + expect(find.text('Keep me too'), findsOneWidget); + + gateway.directoriesHandler = () async => { + 'chat_directories': ['/work'], + }; + await tester.tap(find.text('Retry')); + await tester.pumpAndSettle(); + expect(find.textContaining('Unable to load chat options'), findsNothing); + expect(find.text('Cupertino draft'), findsOneWidget); + expect(find.text('Keep me too'), findsOneWidget); + }); + + testWidgets('material create dialog reports an empty catalog', ( + tester, + ) async { + final gateway = FakeChatGateway(); + gateway.directoriesHandler = () async => {'chat_directories': []}; + await pumpMaterialChat(tester, gateway); + + await tester.tap(find.byKey(const Key('chat-new-chat-fab'))); + await tester.pumpAndSettle(); + expect( + find.text('The server has no chat directories or backends available.'), + findsOneWidget, + ); + }); + + testWidgets('Cupertino create dialog uses native selectors and fields', ( + tester, + ) async { + final gateway = FakeChatGateway(); + JsonMap? opened; + await pumpCupertinoChat( + tester, + gateway, + onOpen: (session) => opened = session, + ); + + await tester.tap(find.byKey(const Key('chat-new-chat'))); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.text('Server directory: /work'), findsOneWidget); + expect(find.text('Backend: opencode'), findsOneWidget); + + await tester.tap(find.byKey(const Key('chat-create-backend'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('codex')); + await tester.pumpAndSettle(); + expect(find.text('Backend: codex'), findsOneWidget); + + await tester.tap(find.byKey(const Key('chat-create-server-directory'))); + await tester.pumpAndSettle(); + expect(find.text('/archive'), findsOneWidget); + await tester.tap(find.text('/archive')); + await tester.pumpAndSettle(); + expect(find.text('Server directory: /archive'), findsOneWidget); + + await tester.enterText( + find.byKey(const Key('chat-create-name')), + 'Cupertino draft', + ); + await tester.enterText( + find.byKey(const Key('chat-create-instructions')), + 'Be careful', + ); + await tester.tap(find.text('Create')); + await tester.pumpAndSettle(); + + final fields = + gateway.lastFields('chat_create')!['chat_create']! as JsonMap; + expect(fields['title'], 'Cupertino draft'); + expect(fields['directory'], '/archive'); + expect(fields['backend'], 'codex'); + expect(fields['instructions'], 'Be careful'); + expect(opened?['id'], 'created'); + }); + + testWidgets('a created chat opens before the list refresh completes', ( + tester, + ) async { + final gateway = FakeChatGateway(); + JsonMap? opened; + await pumpMaterialChat( + tester, + gateway, + onOpen: (session) => opened = session, + ); + + final refresh = Completer(); + gateway.pendingSessions.add(refresh); + await tester.tap(find.byKey(const Key('chat-new-chat-fab'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Create')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + + expect(gateway.count('chat_create'), 1); + expect(gateway.count('chat_sessions'), 2); + expect( + opened?['id'], + 'created', + reason: 'a slow listing must not hold up opening the new chat', + ); + + refresh.complete({'chat_sessions': []}); + await tester.pumpAndSettle(); + }); +} diff --git a/app/test/features/chat/ui/sessions/chat_cupertino_theme_test.dart b/app/test/features/chat/ui/sessions/chat_cupertino_theme_test.dart new file mode 100644 index 00000000..b16bcc73 --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_cupertino_theme_test.dart @@ -0,0 +1,91 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'chat_test_harness.dart'; +import 'fake_chat_gateway.dart'; + +/// The message card is also mounted under a bare `MaterialApp` (the screen's +/// iOS/macOS path). Without its own style, `Text` inherits MaterialApp's +/// "missing Material" fallback: 48px, red, monospace with a double underline. +void main() { + testWidgets('Cupertino empty message under MaterialApp uses normal text', ( + tester, + ) async { + usePhoneSurface(tester); + await pumpIosMaterialChat(tester, FakeChatGateway()); + + expect(find.byType(CupertinoPageScaffold), findsOneWidget); + expect(find.byType(Scaffold), findsNothing); + + const message = 'No chat sessions on this server yet.'; + expect(find.text(message), findsOneWidget); + expectNormalTextStyle(tester, message); + }); + + testWidgets('Cupertino no-match message under MaterialApp wraps normally', ( + tester, + ) async { + usePhoneSurface(tester); + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + await pumpIosMaterialChat(tester, gateway); + + await tester.enterText( + find.byType(CupertinoSearchTextField), + 'zzz-no-match-with-a-long-query', + ); + await tester.pumpAndSettle(); + + const message = 'No chats match "zzz-no-match-with-a-long-query".'; + expect(find.text(message), findsOneWidget); + expectNormalTextStyle(tester, message); + expect( + tester.renderObject(find.text(message)).size.height, + greaterThan(30), + reason: 'the query message must wrap instead of being cut to one line', + ); + expect( + find.widgetWithText(CupertinoButton, 'Clear search'), + findsOneWidget, + ); + }); + + testWidgets('Cupertino load error under MaterialApp uses normal text', ( + tester, + ) async { + usePhoneSurface(tester); + final gateway = FakeChatGateway() + ..sessionsHandler = () => Future.error( + StateError( + 'server unavailable while listing chat sessions for this operator', + ), + ); + await pumpIosMaterialChat(tester, gateway); + + const message = + 'Bad state: server unavailable while listing chat sessions ' + 'for this operator'; + expect(find.text(message), findsOneWidget); + expectNormalTextStyle(tester, message); + expect(find.text('No chat sessions on this server yet.'), findsNothing); + expect(find.widgetWithText(CupertinoButton, 'Retry'), findsOneWidget); + }); +} + +/// Resolves the style actually painted for [message] and checks it is the +/// ordinary Cupertino body style rather than MaterialApp's fallback style. +void expectNormalTextStyle(WidgetTester tester, String message) { + final paragraph = tester.renderObject(find.text(message)); + final style = paragraph.text.style!; + expect( + style.fontSize, + const CupertinoThemeData().textTheme.textStyle.fontSize, + reason: 'message should not use MaterialApp\'s 48px fallback style', + ); + expect(style.fontFamily, isNot('monospace')); + expect(style.fontWeight, isNot(FontWeight.w900)); + expect(style.decoration, isNot(TextDecoration.underline)); + expect(style.color, isNot(const Color(0xD0FF0000))); +} diff --git a/app/test/features/chat/ui/sessions/chat_session_actions_test.dart b/app/test/features/chat/ui/sessions/chat_session_actions_test.dart new file mode 100644 index 00000000..363b9768 --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_session_actions_test.dart @@ -0,0 +1,174 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; + +import 'chat_test_harness.dart'; +import 'fake_chat_gateway.dart'; + +void main() { + testWidgets('material row star, rename, close confirm and reopen', ( + tester, + ) async { + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + await pumpMaterialChat(tester, gateway); + + await tester.tap(find.byKey(const Key('chat-star-s2'))); + await tester.pumpAndSettle(); + expect(gateway.lastFields('chat_star'), { + 'chat_query': {'session_id': 's2', 'starred': true}, + }); + + await tester.tap(find.byKey(const Key('chat-actions-s2'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Rename…')); + await tester.pumpAndSettle(); + await tester.enterText( + find.byKey(const Key('chat-rename-field')), + ' Renamed chat ', + ); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + expect(gateway.lastFields('chat_rename'), { + 'chat_rename': {'session_id': 's2', 'title': 'Renamed chat'}, + }); + + await tester.tap(find.byKey(const Key('chat-actions-s2'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Close chat…')); + await tester.pumpAndSettle(); + expect(find.text('Close chat?'), findsOneWidget); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + expect(gateway.count('chat_close'), 0); + + await tester.tap(find.byKey(const Key('chat-actions-s2'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Close chat…')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Close chat')); + await tester.pumpAndSettle(); + expect(gateway.lastFields('chat_close'), { + 'chat_query': {'session_id': 's2'}, + }); + + await tester.ensureVisible(find.byKey(const Key('chat-actions-s4'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('chat-actions-s4'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Reopen')); + await tester.pumpAndSettle(); + expect(gateway.lastFields('chat_reopen'), { + 'chat_query': {'session_id': 's4'}, + }); + }); + + testWidgets('Cupertino close confirmation uses the action sheet flow', ( + tester, + ) async { + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + await pumpCupertinoChat(tester, gateway); + + await tester.tap(find.byKey(const Key('chat-actions-s2'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Close chat…')); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect( + find.textContaining('marks it closed on every device'), + findsOneWidget, + ); + + await tester.tap(find.text('Close chat')); + await tester.pumpAndSettle(); + expect(gateway.lastFields('chat_close'), { + 'chat_query': {'session_id': 's2'}, + }); + }); + + testWidgets('material rename disables Save while the name is blank', ( + tester, + ) async { + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + await pumpMaterialChat(tester, gateway); + + await tester.tap(find.byKey(const Key('chat-actions-s2'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Rename…')); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(const Key('chat-rename-field')), ' '); + await tester.pump(); + + final save = tester.widget( + find.widgetWithText(FilledButton, 'Save'), + ); + expect(save.onPressed, isNull); + expect(gateway.count('chat_rename'), 0); + }); + + testWidgets('Cupertino rename disables Save while the name is blank', ( + tester, + ) async { + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + await pumpCupertinoChat(tester, gateway); + + await tester.tap(find.byKey(const Key('chat-actions-s2'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Rename…')); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(const Key('chat-rename-field')), ' '); + await tester.pump(); + + final save = tester.widget( + find.widgetWithText(CupertinoDialogAction, 'Save'), + ); + expect(save.onPressed, isNull); + expect(gateway.count('chat_rename'), 0); + }); + + testWidgets('material rename helper wraps instead of truncating at 2x', ( + tester, + ) async { + usePhoneSurface(tester); + tester.platformDispatcher.textScaleFactorTestValue = 2; + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + await pumpMaterialChat(tester, gateway); + + await tester.tap(find.byKey(const Key('chat-actions-s2'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Rename…')); + await tester.pumpAndSettle(); + + const helper = 'This name is shared with every device.'; + expect(find.text(helper), findsOneWidget); + expect( + tester.widget(find.text(helper)).maxLines, + 2, + reason: 'helperMaxLines defaults to one, which truncates the sentence', + ); + expect(tester.takeException(), isNull); + }); + + testWidgets('opening a row calls onOpen with the server session', ( + tester, + ) async { + JsonMap? opened; + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + await pumpMaterialChat( + tester, + gateway, + onOpen: (session) => opened = session, + ); + + await tester.tap(find.byKey(const Key('chat-row-s2'))); + await tester.pumpAndSettle(); + expect(opened?['id'], 's2'); + }); +} diff --git a/app/test/features/chat/ui/sessions/chat_sessions_lifecycle_test.dart b/app/test/features/chat/ui/sessions/chat_sessions_lifecycle_test.dart new file mode 100644 index 00000000..c2df3dad --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_sessions_lifecycle_test.dart @@ -0,0 +1,76 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_screen.dart'; + +import 'fake_chat_gateway.dart'; + +void main() { + testWidgets('a stale refresh reply never replaces the latest listing', ( + tester, + ) async { + final gateway = FakeChatGateway(); + final first = Completer(); + final second = Completer(); + gateway.pendingSessions.addAll([first, second]); + + await tester.pumpWidget( + MaterialApp( + home: ChatSessionsScreen(gateway: gateway, onOpen: (_) {}), + ), + ); + await tester.pump(); + + await tester.tap(find.byKey(const Key('chat-refresh'))); + await tester.pump(); + expect(gateway.count('chat_sessions'), 2); + + second.complete({ + 'chat_sessions': [ + {'id': 'new', 'title': 'Newest chat'}, + ], + }); + await tester.pump(); + await tester.pump(); + expect(find.text('Newest chat'), findsOneWidget); + + first.complete({ + 'chat_sessions': [ + {'id': 'old', 'title': 'Older chat'}, + ], + }); + await tester.pump(); + await tester.pump(); + expect(find.text('Older chat'), findsNothing); + expect(find.text('Newest chat'), findsOneWidget); + }); + + testWidgets('a reply completing after dispose changes nothing', ( + tester, + ) async { + final gateway = FakeChatGateway(); + final pending = Completer(); + gateway.pendingSessions.add(pending); + + await tester.pumpWidget( + MaterialApp( + home: ChatSessionsScreen(gateway: gateway, onOpen: (_) {}), + ), + ); + await tester.pump(); + + await tester.pumpWidget(const MaterialApp(home: SizedBox())); + pending.complete({ + 'chat_sessions': [ + {'id': 'late', 'title': 'Late chat'}, + ], + }); + await tester.pump(); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(find.text('Late chat'), findsNothing); + }); +} diff --git a/app/test/features/chat/ui/sessions/chat_sessions_screen_test.dart b/app/test/features/chat/ui/sessions/chat_sessions_screen_test.dart new file mode 100644 index 00000000..dae24df2 --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_sessions_screen_test.dart @@ -0,0 +1,213 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'chat_test_harness.dart'; +import 'fake_chat_gateway.dart'; + +void main() { + testWidgets( + 'material list keeps closed starred rows once and groups directories once', + (tester) async { + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + await pumpMaterialChat(tester, gateway); + + expect(find.text('Starred'), findsOneWidget); + expect(find.text('Chats'), findsNWidgets(2)); + expect(find.text('Closed'), findsOneWidget); + expect(find.text('Starred chat'), findsOneWidget); + expect(find.text('Starred closed'), findsOneWidget); + expect(find.text('Open chat'), findsOneWidget); + expect(find.byIcon(Icons.folder_outlined), findsNWidgets(4)); + expect(find.byType(Scaffold), findsOneWidget); + }, + ); + + testWidgets('material search distinguishes no-match and clears back', ( + tester, + ) async { + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + await pumpMaterialChat(tester, gateway); + + await tester.enterText(find.byType(TextField), 'zzz'); + await tester.pumpAndSettle(); + expect(find.text('No chats match "zzz".'), findsOneWidget); + expect(find.text('Open chat'), findsNothing); + + await tester.tap(find.text('Clear search')); + await tester.pumpAndSettle(); + expect(find.text('Open chat'), findsOneWidget); + }); + + testWidgets('material empty server shows the distinct empty message', ( + tester, + ) async { + final gateway = FakeChatGateway(); + await pumpMaterialChat(tester, gateway); + expect(find.text('No chat sessions on this server yet.'), findsOneWidget); + expect(find.textContaining('No chats match'), findsNothing); + }); + + testWidgets( + 'Cupertino app renders standard controls, groups and renames without Material', + (tester) async { + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + await pumpCupertinoChat(tester, gateway); + + expect(find.byType(CupertinoPageScaffold), findsOneWidget); + expect(find.byType(CupertinoSearchTextField), findsOneWidget); + expect(find.byType(Scaffold), findsNothing); + expect( + tester.getTopLeft(find.byType(CupertinoSearchTextField)).dy, + greaterThanOrEqualTo( + tester.getBottomLeft(find.byType(CupertinoNavigationBar)).dy, + ), + ); + expect(find.text('Chats · /work'), findsOneWidget); + expect(find.text('Chats · /else'), findsOneWidget); + + await tester.tap(find.byKey(const Key('chat-star-s2'))); + await tester.pumpAndSettle(); + expect(gateway.lastFields('chat_star'), { + 'chat_query': {'session_id': 's2', 'starred': true}, + }); + + await tester.tap(find.byKey(const Key('chat-actions-s2'))); + await tester.pumpAndSettle(); + expect(find.text('Rename…'), findsOneWidget); + await tester.tap(find.text('Rename…')); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + + await tester.enterText( + find.byKey(const Key('chat-rename-field')), + 'Renamed on Cupertino', + ); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + expect(gateway.lastFields('chat_rename'), { + 'chat_rename': {'session_id': 's2', 'title': 'Renamed on Cupertino'}, + }); + + await tester.tap(find.byKey(const Key('chat-actions-s4'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Reopen')); + await tester.pumpAndSettle(); + expect(gateway.lastFields('chat_reopen'), { + 'chat_query': {'session_id': 's4'}, + }); + }, + ); + + testWidgets( + 'Cupertino no-match message wraps and Clear search is its own button', + (tester) async { + usePhoneSurface(tester); + final semantics = tester.ensureSemantics(); + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + await pumpCupertinoChat(tester, gateway); + + const query = 'zzz-no-match-with-a-long-query'; + await tester.enterText(find.byType(CupertinoSearchTextField), query); + await tester.pumpAndSettle(); + + const message = 'No chats match "zzz-no-match-with-a-long-query".'; + expect(find.text(message), findsOneWidget); + expect(find.text('Open chat'), findsNothing); + final messageBox = tester.renderObject(find.text(message)); + expect( + messageBox.size.height, + greaterThan(30), + reason: 'the query message must wrap instead of being cut to one line', + ); + + final clear = find.bySemanticsLabel('Clear search'); + expect(clear, findsOneWidget); + expect(tester.getSemantics(clear).label, 'Clear search'); + + await tester.tap(find.text('Clear search')); + await tester.pumpAndSettle(); + expect(find.text('Open chat'), findsOneWidget); + semantics.dispose(); + }, + ); + + testWidgets( + 'Cupertino load failure wraps the reason and hides the empty message', + (tester) async { + usePhoneSurface(tester); + final gateway = FakeChatGateway() + ..sessionsHandler = () => Future.error( + StateError( + 'server unavailable while listing chat sessions for this operator', + ), + ); + await pumpCupertinoChat(tester, gateway); + + const message = + 'Bad state: server unavailable while listing chat sessions ' + 'for this operator'; + expect(find.text(message), findsOneWidget); + expect(find.text('No chat sessions on this server yet.'), findsNothing); + final messageBox = tester.renderObject(find.text(message)); + expect( + messageBox.size.height, + greaterThan(30), + reason: 'the server reason must wrap instead of being cut to one line', + ); + expect(find.widgetWithText(CupertinoButton, 'Retry'), findsOneWidget); + }, + ); + + testWidgets('Cupertino no-match message survives 2x text scaling', ( + tester, + ) async { + usePhoneSurface(tester); + tester.platformDispatcher.textScaleFactorTestValue = 2; + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + await pumpCupertinoChat(tester, gateway); + + await tester.enterText( + find.byType(CupertinoSearchTextField), + 'zzz-no-match-with-a-long-query', + ); + await tester.pumpAndSettle(); + + expect( + find.text('No chats match "zzz-no-match-with-a-long-query".'), + findsOneWidget, + ); + expect(find.text('Clear search'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('duplicate Cupertino titles disambiguate the action labels', ( + tester, + ) async { + final semantics = tester.ensureSemantics(); + final gateway = FakeChatGateway() + ..sessionsReply = { + 'chat_sessions': [ + {'id': 'd1', 'title': 'New chat', 'directory': '/work'}, + {'id': 'd2', 'title': 'New chat', 'directory': '/work'}, + ], + }; + await pumpCupertinoChat(tester, gateway); + + expect( + tester.getSemantics(find.byKey(const Key('chat-actions-d1'))).label, + 'Chat actions for New chat (d1)', + ); + expect( + tester.getSemantics(find.byKey(const Key('chat-actions-d2'))).label, + 'Chat actions for New chat (d2)', + ); + semantics.dispose(); + }); +} diff --git a/app/test/features/chat/ui/sessions/chat_test_harness.dart b/app/test/features/chat/ui/sessions/chat_test_harness.dart new file mode 100644 index 00000000..d56e3b81 --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_test_harness.dart @@ -0,0 +1,77 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_screen.dart'; + +import 'fake_chat_gateway.dart'; + +List sampleSessions() => [ + {'id': 's1', 'title': 'Starred chat', 'directory': '/work', 'starred': true}, + {'id': 's2', 'title': 'Open chat', 'directory': '/work'}, + {'id': 's3', 'title': 'Elsewhere chat', 'directory': '/else'}, + { + 'id': 's4', + 'title': 'Closed chat', + 'directory': '/else', + 'closed_at': '2026-01-01', + }, + { + 'id': 's5', + 'title': 'Starred closed', + 'directory': '/work', + 'starred': true, + 'closed_at': '2026-01-02', + }, +]; + +Future pumpMaterialChat( + WidgetTester tester, + FakeChatGateway gateway, { + ValueChanged? onOpen, +}) async { + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + home: ChatSessionsScreen(gateway: gateway, onOpen: onOpen ?? (_) {}), + ), + ); + await tester.pumpAndSettle(); +} + +Future pumpCupertinoChat( + WidgetTester tester, + FakeChatGateway gateway, { + ValueChanged? onOpen, +}) async { + await tester.pumpWidget( + CupertinoApp( + home: ChatSessionsScreen(gateway: gateway, onOpen: onOpen ?? (_) {}), + ), + ); + await tester.pumpAndSettle(); +} + +/// The screen's iOS/macOS path: Cupertino controls under the app's ordinary +/// `MaterialApp` root, with no Material or CupertinoTheme ancestor. +Future pumpIosMaterialChat( + WidgetTester tester, + FakeChatGateway gateway, { + ValueChanged? onOpen, +}) async { + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.iOS), + home: ChatSessionsScreen(gateway: gateway, onOpen: onOpen ?? (_) {}), + ), + ); + await tester.pumpAndSettle(); +} + +/// Narrows the test surface to a phone so long messages must wrap. +void usePhoneSurface(WidgetTester tester) { + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); +} diff --git a/app/test/features/chat/ui/sessions/fake_chat_gateway.dart b/app/test/features/chat/ui/sessions/fake_chat_gateway.dart new file mode 100644 index 00000000..6fa13aca --- /dev/null +++ b/app/test/features/chat/ui/sessions/fake_chat_gateway.dart @@ -0,0 +1,56 @@ +import 'dart:async'; +import 'dart:collection'; + +import 'package:pipelines_app/core/api_gateway.dart'; + +/// Scripted gateway for session-browser widget tests. +class FakeChatGateway implements ApiGateway { + final calls = <({String type, JsonMap fields})>[]; + final pendingSessions = Queue>(); + JsonMap sessionsReply = const {'chat_sessions': []}; + Future Function()? sessionsHandler; + JsonMap createReply = const { + 'chat_session': {'id': 'created', 'title': 'New chat'}, + }; + Future Function()? directoriesHandler; + Future Function()? backendsHandler; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) { + calls.add((type: type, fields: fields)); + switch (type) { + case 'chat_sessions': + if (pendingSessions.isNotEmpty) { + return pendingSessions.removeFirst().future; + } + if (sessionsHandler != null) return sessionsHandler!(); + return Future.value(sessionsReply); + case 'chat_directories': + return directoriesHandler?.call() ?? + Future.value(const { + 'chat_directories': ['/work', '/archive'], + }); + case 'chat_backends': + return backendsHandler?.call() ?? + Future.value(const { + 'chat_backends': ['opencode', 'codex'], + }); + case 'chat_create': + return Future.value(createReply); + default: + return Future.value(const {}); + } + } + + int count(String type) => calls.where((call) => call.type == type).length; + + JsonMap? lastFields(String type) { + for (final call in calls.reversed) { + if (call.type == type) return call.fields; + } + return null; + } +} diff --git a/app/test/features/graph/domain/graph_definition_test.dart b/app/test/features/graph/domain/graph_definition_test.dart new file mode 100644 index 00000000..deb13d62 --- /dev/null +++ b/app/test/features/graph/domain/graph_definition_test.dart @@ -0,0 +1,229 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; + +import 'graph_fixtures.dart'; + +void main() { + group('outcome and edge order', () { + test('success first, other outcomes alphabetical, error last', () { + expect( + stageOutcomes( + stage( + 'a', + edges: { + 'error': '#', + 'rejected': 'a', + 'success': 'b', + 'approved': 'b', + 'retry': 'a', + }, + ), + ), + ['success', 'approved', 'rejected', 'retry', 'error'], + ); + expect(stageOutcomes({}), isEmpty); + expect(stageOutcomes(null), isEmpty); + }); + + test('edgeLabel marks only an implicit fallback error route', () { + expect( + edgeLabel({'fallback_error': true}, 'error'), + 'error*', + ); + expect( + edgeLabel({'fallback_error': false}, 'error'), + 'error', + ); + expect( + edgeLabel({'fallback_error': true}, 'success'), + 'success', + ); + expect(edgeLabel({}, 'rejected'), 'rejected'); + }); + }); + + group('linear definition', () { + test('edges keep stage and outcome order with contiguous ids', () { + final edges = graphEdges(linearGraph()); + expect(edges.map((edge) => edge.id), [1, 2, 3, 4, 5]); + expect(edges.map((edge) => edge.source), [ + 'plan', + 'plan', + 'build', + 'ship', + 'ship', + ]); + expect(edges.map((edge) => edge.outcome), [ + 'success', + 'error', + 'success', + 'success', + 'error', + ]); + expect(edges.map((edge) => edge.target), [ + 'build', + '#failure', + 'ship', + '#success', + '#failure', + ]); + expect(edges.map((edge) => edge.label), [ + 'success', + 'error*', + 'success', + 'success', + 'error', + ]); + expect(edges.where((edge) => edge.fallback).map((edge) => edge.id), [ + 2, + ]); + expect(edges.every((edge) => edge.knownTarget), isTrue); + }); + + test('nodes are declaration order plus failure then success terminals', () { + final nodes = graphNodes(linearGraph()); + expect(nodes.map((node) => node.key), [ + 'plan', + 'build', + 'ship', + failureEnd, + successEnd, + ]); + expect(nodes.map((node) => node.stageIndex), [0, 1, 2, null, null]); + expect(nodes.map((node) => node.terminal), [ + false, + false, + false, + true, + true, + ]); + expect(nodes[3].label, 'Failure'); + expect(nodes[3].shortLabel, 'FAILURE'); + expect(nodes[4].label, 'Success'); + expect(nodes[4].shortLabel, 'SUCCESS'); + }); + }); + + group('diamond definition', () { + test('keeps every converging edge distinct in stable order', () { + final edges = graphEdges(diamondGraph()); + expect( + edges.map((edge) => '${edge.source}/${edge.outcome}->${edge.target}'), + [ + 'a/success->b', + 'a/approved->c', + 'a/error->#failure', + 'b/success->d', + 'c/success->d', + 'd/success->#success', + ], + ); + expect(edges.every((edge) => edge.knownTarget), isTrue); + }); + }); + + group('self loops', () { + test('a self edge is one edge and never duplicates node identity', () { + final graph = selfLoopGraph(); + final edges = graphEdges(graph); + expect( + edges.map((edge) => '${edge.source}/${edge.outcome}->${edge.target}'), + [ + 'a/success->b', + 'a/retry->a', + 'b/success->#success', + 'b/error->#failure', + ], + ); + expect(edges[1].source, edges[1].target); + expect(edges[1].knownTarget, isTrue); + + final nodes = graphNodes(graph); + expect(nodes.map((node) => node.key), [ + 'a', + 'b', + failureEnd, + successEnd, + ]); + expect(nodes.where((node) => node.key == 'a'), hasLength(1)); + }); + + test( + 'a stage declared twice keeps one node and one set of edges per key', + () { + final graph = { + 'stages': [ + stage('a', edges: {'retry': 'a'}), + stage('a', edges: {'success': '#success'}), + ], + }; + expect(graphNodes(graph).map((node) => node.key), [ + 'a', + failureEnd, + successEnd, + ]); + // Both declarations are still definition data, with unique edge ids. + expect(graphEdges(graph).map((edge) => edge.id), [1, 2]); + }, + ); + }); + + group('missing and unknown targets', () { + test( + 'an absent edge declares nothing; empty and unknown targets stay honest', + () { + final edges = graphEdges(incompleteGraph()); + expect(edges.map((edge) => edge.id), [1, 2, 3, 4]); + expect(edges.map((edge) => edge.outcome), [ + 'blocked', + 'retry', + 'error', + 'success', + ]); + expect(edges[0].target, ''); + expect(edges[0].knownTarget, isFalse); + expect(edges[1].target, 'ghost'); + expect(edges[1].knownTarget, isFalse); + expect(edges[2].target, failureEnd); + expect(edges[2].fallback, isTrue); + expect(edges[3].target, successEnd); + }, + ); + + test('an unknown target does not become a node or a terminal', () { + final graph = { + 'stages': [ + stage('a', edges: {'retry': 'ghost'}), + ], + }; + expect(graphNodes(graph).map((node) => node.key), ['a']); + expect(graphEdges(graph).single.knownTarget, isFalse); + }); + + test('a graph with no stages has no nodes or edges', () { + expect(graphNodes({}), isEmpty); + expect(graphEdges({'stages': null}), isEmpty); + expect(graphNodes(null), isEmpty); + }); + }); + + test( + 'definition nodes ignore run evidence even when the graph map carries it', + () { + final graph = { + 'stages': [ + stage('a', edges: {'success': 'b'}), + stage('b'), + ], + 'steps': [ + step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'), + ], + 'visited_stages': ['a', 'b'], + }; + final nodes = graphNodes(graph); + expect(nodes.map((node) => node.key), ['a', 'b']); + expect(nodes.every((node) => !node.terminal), isTrue); + }, + ); +} diff --git a/app/test/features/graph/domain/graph_fixtures.dart b/app/test/features/graph/domain/graph_fixtures.dart new file mode 100644 index 00000000..3a074221 --- /dev/null +++ b/app/test/features/graph/domain/graph_fixtures.dart @@ -0,0 +1,96 @@ +import 'package:pipelines_app/core/api_gateway.dart'; + +/// Small, server-shaped fixtures shared by the graph domain tests. + +JsonMap step({ + int sequence = 0, + String stage = '', + String status = 'completed', + String outcome = '', + String target = '', + String startedAt = '', + Map? control, +}) { + return { + 'sequence': sequence, + 'stage': stage, + 'status': status, + 'outcome': outcome, + 'target': target, + if (startedAt.isNotEmpty) 'started_at': startedAt, + 'control': ?control, + }; +} + +JsonMap stage( + String key, { + Map edges = const {}, + bool fallbackError = false, + String type = 'model', +}) { + return { + 'key': key, + 'type': type, + 'edges': edges, + if (fallbackError) 'fallback_error': true, + }; +} + +/// plan -> build -> ship, with an implicit failure fallback on plan and an +/// explicit terminal pair on ship. +JsonMap linearGraph() => { + 'stages': [ + stage( + 'plan', + edges: {'success': 'build', 'error': '#'}, + fallbackError: true, + ), + stage('build', edges: {'success': 'ship'}), + stage( + 'ship', + edges: {'success': '#success', 'error': '#failure'}, + ), + ], +}; + +/// a fans out to b/c and both converge on d. +JsonMap diamondGraph() => { + 'stages': [ + stage( + 'a', + edges: {'success': 'b', 'approved': 'c', 'error': '#'}, + fallbackError: true, + ), + stage('b', edges: {'success': 'd'}), + stage('c', edges: {'success': 'd'}), + stage('d', edges: {'success': '#success'}), + ], +}; + +/// a retries itself and can still succeed into b; terminal pair on b. +JsonMap selfLoopGraph() => { + 'stages': [ + stage('a', edges: {'success': 'b', 'retry': 'a'}), + stage( + 'b', + edges: {'success': '#success', 'error': '#failure'}, + ), + ], +}; + +/// A definition with an absent edge, an empty target and an unknown target. +JsonMap incompleteGraph() => { + 'stages': [ + stage( + 'a', + edges: { + 'success': null, + 'blocked': '', + 'retry': 'ghost', + 'error': '#', + }, + fallbackError: true, + ), + stage('b', edges: {'success': '#success'}), + ], +}; diff --git a/app/test/features/graph/domain/graph_protocol_test.dart b/app/test/features/graph/domain/graph_protocol_test.dart new file mode 100644 index 00000000..972fc77e --- /dev/null +++ b/app/test/features/graph/domain/graph_protocol_test.dart @@ -0,0 +1,56 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; + +void main() { + group('terminal target normalization', () { + test('a bare # resolves by outcome exactly like the web protocol', () { + expect(resolveTarget('error', '#'), failureEnd); + expect(resolveTarget('success', '#'), successEnd); + expect(resolveTarget('approved', '#'), successEnd); + expect(resolveTarget('', '#'), successEnd); + }); + + test('explicit, empty and unknown targets are preserved verbatim', () { + expect(resolveTarget('success', successEnd), successEnd); + expect(resolveTarget('error', failureEnd), failureEnd); + expect(resolveTarget('success', 'review'), 'review'); + expect(resolveTarget('blocked', ''), ''); + expect(resolveTarget('retry', 'ghost'), 'ghost'); + expect(resolveTarget('success', ' #success'), ' #success'); + }); + + test( + 'a missing target stays missing instead of fabricating a terminal', + () { + expect(resolveTarget('success', null), isNull); + expect(resolveTarget(null, null), isNull); + }, + ); + + test('only the explicit terminal keys are terminals', () { + expect(isTerminalTarget(successEnd), isTrue); + expect(isTerminalTarget(failureEnd), isTrue); + expect(isTerminalTarget('#'), isFalse); + expect(isTerminalTarget('review'), isFalse); + expect(isTerminalTarget(''), isFalse); + expect(isTerminalTarget(null), isFalse); + }); + }); + + group('terminal labels', () { + test('TUI labels are SUCCESS and FAILURE', () { + expect(nodeLabel(successEnd), 'SUCCESS'); + expect(nodeLabel(failureEnd), 'FAILURE'); + expect(nodeLabel('implementer'), 'implementer'); + expect(nodeLabel(''), ''); + expect(nodeLabel(null), ''); + }); + + test('display labels title-case the terminals and keep stage keys', () { + expect(nodeDisplayLabel(successEnd), 'Success'); + expect(nodeDisplayLabel(failureEnd), 'Failure'); + expect(nodeDisplayLabel('implementer'), 'implementer'); + expect(nodeDisplayLabel(null), ''); + }); + }); +} diff --git a/app/test/features/graph/domain/run_graph_state_live_test.dart b/app/test/features/graph/domain/run_graph_state_live_test.dart new file mode 100644 index 00000000..18244107 --- /dev/null +++ b/app/test/features/graph/domain/run_graph_state_live_test.dart @@ -0,0 +1,91 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/run_graph_state.dart'; + +import 'graph_fixtures.dart'; + +void main() { + group('current stage fallback', () { + test('the run current stage wins over the last recorded visit', () { + final state = runGraphState({ + 'current_stage': 'committer', + 'steps': [step(sequence: 1, stage: 'review')], + }); + expect(state.currentStage, 'committer'); + }); + + test('a blank current stage falls back to the last visit, else null', () { + final fallback = runGraphState({ + 'current_stage': ' ', + 'steps': [ + step(sequence: 1, stage: 'a'), + step(sequence: 2, stage: 'b'), + ], + }); + expect(fallback.currentStage, 'b'); + + final blankLast = runGraphState({ + 'steps': [step(sequence: 1)], + }); + expect(blankLast.currentStage, isNull); + }); + }); + + group('active stage and start', () { + test('a live run exposes its running visit start', () { + final state = runGraphState({ + 'executing': true, + 'current_stage': 'review', + 'steps': [ + step( + sequence: 1, + stage: 'review', + status: 'running', + startedAt: '2026-01-01T00:00:00Z', + ), + ], + }); + expect(state.executing, isTrue); + expect(state.activeStage, 'review'); + expect(state.currentStageStartedAt, '2026-01-01T00:00:00Z'); + }); + + test('a finished run has no active stage or start', () { + final state = runGraphState({ + 'executing': false, + 'current_stage': 'review', + 'steps': [ + step( + sequence: 1, + stage: 'review', + status: 'running', + startedAt: '2026-01-01T00:00:00Z', + ), + ], + }); + expect(state.activeStage, isNull); + expect(state.currentStageStartedAt, isNull); + }); + + test('only an exact running status with a non-blank start is used', () { + final state = runGraphState({ + 'executing': true, + 'current_stage': 'review', + 'steps': [ + step( + sequence: 1, + stage: 'review', + status: 'Running', + startedAt: '2026-01-01T00:00:00Z', + ), + step( + sequence: 2, + stage: 'review', + status: 'running', + startedAt: ' ', + ), + ], + }); + expect(state.currentStageStartedAt, isNull); + }); + }); +} diff --git a/app/test/features/graph/domain/run_graph_state_test.dart b/app/test/features/graph/domain/run_graph_state_test.dart new file mode 100644 index 00000000..3af43777 --- /dev/null +++ b/app/test/features/graph/domain/run_graph_state_test.dart @@ -0,0 +1,170 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/domain/run_graph_state.dart'; + +import 'graph_fixtures.dart'; + +void main() { + group('linear run evidence', () { + test('visits and routes follow the recorded visits', () { + final state = runGraphState({ + 'executing': false, + 'steps': [ + step(sequence: 1, stage: 'plan', outcome: 'success', target: 'build'), + step(sequence: 2, stage: 'build', outcome: 'success', target: 'ship'), + step( + sequence: 3, + stage: 'ship', + outcome: 'success', + target: '#success', + ), + ], + }); + expect(state.visitedStages, [ + 'plan', + 'build', + 'ship', + successEnd, + ]); + expect(state.takenRoutes, [ + 'plan\u0000success\u0000build', + 'build\u0000success\u0000ship', + 'ship\u0000success\u0000#success', + ]); + expect(state.currentStage, 'ship'); + expect(state.executing, isFalse); + expect(state.currentStageStartedAt, isNull); + expect(state.activeStage, isNull); + }); + }); + + group('diamond run evidence', () { + test('repeated visits keep one identity and loop routes stay distinct', () { + final state = runGraphState({ + 'executing': false, + 'steps': [ + step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'), + step(sequence: 2, stage: 'b', outcome: 'success', target: 'd'), + step(sequence: 3, stage: 'd', outcome: 'rejected', target: 'b'), + step(sequence: 4, stage: 'b', outcome: 'success', target: 'd'), + step(sequence: 5, stage: 'd', outcome: 'success', target: '#success'), + ], + }); + expect(state.visitedStages, ['a', 'b', 'd', successEnd]); + expect(state.visitedStages.where((key) => key == 'b'), hasLength(1)); + expect(state.takenRoutes, [ + 'a\u0000success\u0000b', + 'b\u0000success\u0000d', + 'd\u0000rejected\u0000b', + 'd\u0000success\u0000#success', + ]); + }); + + test('different outcomes to the same target stay separate routes', () { + final state = runGraphState({ + 'executing': false, + 'steps': [ + step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'), + step(sequence: 2, stage: 'a', outcome: 'approved', target: 'b'), + step(sequence: 3, stage: 'a', outcome: 'success', target: 'b'), + ], + }); + expect(state.visitedStages, ['a']); + expect(state.takenRoutes, [ + 'a\u0000success\u0000b', + 'a\u0000approved\u0000b', + ]); + }); + }); + + group('self edges', () { + test('a self edge is evidence, not a second visit or recursion', () { + final state = runGraphState({ + 'executing': false, + 'steps': [ + step(sequence: 1, stage: 'a', outcome: 'retry', target: 'a'), + step(sequence: 2, stage: 'a', outcome: 'success', target: 'b'), + ], + }); + expect(state.visitedStages, ['a']); + expect(state.takenRoutes, [ + 'a\u0000retry\u0000a', + 'a\u0000success\u0000b', + ]); + }); + }); + + group('terminals', () { + test('a bare # resolves to failure on error and success otherwise', () { + final failed = runGraphState({ + 'steps': [ + step(sequence: 1, stage: 'impl', outcome: 'error', target: '#'), + ], + }); + expect(failed.visitedStages, ['impl', failureEnd]); + expect(failed.visitedStages, isNot(contains(successEnd))); + expect(failed.isRouteTaken('impl', 'error', '#'), isTrue); + + final succeeded = runGraphState({ + 'steps': [ + step(sequence: 1, stage: 'impl', outcome: 'done', target: '#'), + ], + }); + expect(succeeded.visitedStages, ['impl', successEnd]); + expect(succeeded.visitedStages, isNot(contains(failureEnd))); + }); + + test('a non-terminal target is not visited until a step lands on it', () { + final state = runGraphState({ + 'steps': [ + step( + sequence: 1, + stage: 'impl', + outcome: 'success', + target: 'review', + ), + ], + }); + expect(state.visitedStages, ['impl']); + expect(state.isStageVisited('review'), isFalse); + expect(state.isRouteTaken('impl', 'success', 'review'), isTrue); + }); + + test('blank outcome or target records no route and no terminal visit', () { + final state = runGraphState({ + 'steps': [ + step(sequence: 1, stage: 'impl', outcome: 'success', target: ''), + step(sequence: 2, stage: 'impl', outcome: '', target: '#success'), + ], + }); + expect(state.visitedStages, ['impl']); + expect(state.takenRoutes, isEmpty); + }); + }); + + group('missing evidence', () { + test('absent run or steps fabricates no visits', () { + for (final run in [ + null, + {}, + {'steps': null}, + {'steps': []}, + ]) { + final state = runGraphState(run); + expect(state.visitedStages, isEmpty); + expect(state.takenRoutes, isEmpty); + expect(state.currentStage, isNull); + expect(state.executing, isFalse); + expect(state.currentStageStartedAt, isNull); + } + }); + + test('malformed step entries are ignored, not invented', () { + final state = runGraphState({ + 'steps': ['nope', 42, null], + }); + expect(state.visitedStages, isEmpty); + expect(state.takenRoutes, isEmpty); + }); + }); +} diff --git a/app/test/features/graph/domain/stage_visits_test.dart b/app/test/features/graph/domain/stage_visits_test.dart new file mode 100644 index 00000000..dcf77840 --- /dev/null +++ b/app/test/features/graph/domain/stage_visits_test.dart @@ -0,0 +1,150 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/stage_visits.dart'; + +import 'graph_fixtures.dart'; + +void main() { + group('ordered stage visits', () { + test('repeated visits are ordered by sequence, not input order', () { + final steps = [ + step( + sequence: 5, + stage: 'review', + outcome: 'rejected', + target: 'implementer', + control: {'visit': 2}, + ), + step(sequence: 3, stage: 'implementer'), + step( + sequence: 2, + stage: 'review', + outcome: 'success', + target: 'done', + control: {'visit': 1}, + ), + ].cast>(); + + final byStage = visitsByStage(steps); + expect(byStage.keys, ['review', 'implementer']); + expect(byStage['review']!.map((visit) => visit['sequence']), [2, 5]); + expect(byStage['review']!.map((visit) => visit['outcome']), [ + 'success', + 'rejected', + ]); + expect(displayVisit(byStage['review']![0], 0), 1); + expect(displayVisit(byStage['review']![1], 1), 2); + }); + + test('equal sequences keep their recorded order', () { + final steps = [ + step(sequence: 1, stage: 'a', outcome: 'first'), + step(sequence: 1, stage: 'a', outcome: 'second'), + ].cast>(); + expect( + visitsByStage(steps)['a']!.map((visit) => visit['outcome']), + ['first', 'second'], + ); + }); + + test('a missing control visit falls back to the position', () { + final steps = [ + step(sequence: 1, stage: 'a'), + step(sequence: 2, stage: 'a'), + ].cast>(); + final visits = visitsByStage(steps)['a']!; + expect(displayVisit(visits[0], 0), 1); + expect(displayVisit(visits[1], 1), 2); + }); + + test( + 'a non-positive or malformed control visit falls back to position', + () { + expect( + displayVisit(step(control: {'visit': 0}), 2), + 3, + ); + expect( + displayVisit(step(control: {'visit': -1}), 2), + 3, + ); + expect( + displayVisit(step(control: {'visit': '3'}), 0), + 3, + ); + expect(displayVisit(step(), 4), 5); + }, + ); + }); + + group('clamping', () { + test('keeps a valid index and handles an empty list', () { + expect(clampVisitIndex(0, 3), 0); + expect(clampVisitIndex(2, 3), 2); + expect(clampVisitIndex(99, 3), 2); + expect(clampVisitIndex(-4, 3), 0); + expect(clampVisitIndex(5, 0), 0); + }); + }); + + group('selection', () { + List> repeatedVisits() => [ + step(sequence: 5, stage: 'review', outcome: 'rejected'), + step(sequence: 2, stage: 'review', outcome: 'success'), + ].cast>(); + + test('no requested visit selects the stage most recent recorded visit', () { + final selection = selectStageVisit(repeatedVisits(), 'review'); + expect(selection.hasVisit, isTrue); + expect(selection.index, 1); + expect(selection.step!['sequence'], 5); + expect(selection.visitNumber, 2); + }); + + test('an explicit visit selects that recorded visit', () { + final selection = selectStageVisit( + repeatedVisits(), + 'review', + visitIndex: 0, + ); + expect(selection.step!['sequence'], 2); + expect(selection.visitNumber, 1); + }); + + test('out-of-range indexes clamp to the nearest recorded visit', () { + final late = selectStageVisit(repeatedVisits(), 'review', visitIndex: 99); + expect(late.index, 1); + expect(late.step!['sequence'], 5); + expect(late.correctedRequest(99), isTrue); + + final early = selectStageVisit( + repeatedVisits(), + 'review', + visitIndex: -4, + ); + expect(early.index, 0); + expect(early.step!['sequence'], 2); + expect(early.correctedRequest(-4), isTrue); + expect(early.correctedRequest(null), isFalse); + }); + + test('a stage with no recorded visit returns no fabricated step', () { + final selection = selectStageVisit(repeatedVisits(), 'never-ran'); + expect(selection.hasVisit, isFalse); + expect(selection.step, isNull); + expect(selection.index, 0); + expect(selection.visitNumber, 0); + + final empty = selectStageVisit(const >[], 'review'); + expect(empty.hasVisit, isFalse); + expect(empty.step, isNull); + }); + + test('an absent capture for one stage does not hide another stage', () { + final steps = [ + step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'), + ].cast>(); + expect(selectStageVisit(steps, 'a').hasVisit, isTrue); + expect(selectStageVisit(steps, 'b').hasVisit, isFalse); + }); + }); +} diff --git a/app/test/features/graph/layout/graph_layout_validation_test.dart b/app/test/features/graph/layout/graph_layout_validation_test.dart new file mode 100644 index 00000000..dd70f7ee --- /dev/null +++ b/app/test/features/graph/layout/graph_layout_validation_test.dart @@ -0,0 +1,96 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/layout/graph_node_layout.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; + +import 'layout_fixtures.dart'; + +/// Invalid and boundary input for the pure layout engine. +void main() { + test('an empty definition yields empty padded bounds', () { + final layout = layoutGraphNodes( + nodes: const [], + edges: const [], + extents: const {}, + config: layoutConfig(columnGap: 30, rowGap: 10, padding: 6), + ); + + expect(layout.isEmpty, isTrue); + expect(layout.rankCount, 0); + expect(layout.width, 12); + expect(layout.height, 12); + expect(layout.ranks, isEmpty); + }); + + test('missing measurements are reported rather than invented', () { + final graph = linearGraphFixture(); + final nodes = graphNodes(graph); + final extents = uniformExtents(nodes)..remove('build'); + + expect( + () => layoutGraphNodes( + nodes: nodes, + edges: graphEdges(graph), + extents: extents, + config: layoutConfig(), + ), + throwsArgumentError, + ); + }); + + test('extra measurements are ignored because they cannot become nodes', () { + final graph = linearGraphFixture(); + final nodes = graphNodes(graph); + final extents = uniformExtents(nodes) + ..['ghost'] = NodeExtent(width: 20, height: 20); + + final layout = layoutGraphNodes( + nodes: nodes, + edges: graphEdges(graph), + extents: extents, + config: layoutConfig(), + ); + + expect(layout.nodeFor('ghost'), isNull); + expect(layout.nodes.length, nodes.length); + }); + + test('duplicate or empty node keys are rejected', () { + const stageNode = GraphNode(key: 'a', terminal: false, stageIndex: 0); + expect( + () => layoutGraphNodes( + nodes: const [stageNode, stageNode], + edges: const [], + extents: {'a': NodeExtent(width: 10, height: 10)}, + config: layoutConfig(), + ), + throwsArgumentError, + ); + expect( + () => layoutGraphNodes( + nodes: const [ + GraphNode(key: '', terminal: false, stageIndex: 0), + ], + edges: const [], + extents: const {}, + config: layoutConfig(), + ), + throwsArgumentError, + ); + }); + + test('invalid gaps and extents are rejected', () { + expect( + () => GraphLayoutConfig(columnGap: -1, rowGap: 8), + throwsArgumentError, + ); + expect( + () => GraphLayoutConfig(columnGap: 8, rowGap: double.nan), + throwsArgumentError, + ); + expect( + () => NodeExtent(width: double.infinity, height: 10), + throwsArgumentError, + ); + }); +} diff --git a/app/test/features/graph/layout/graph_node_layout_test.dart b/app/test/features/graph/layout/graph_node_layout_test.dart new file mode 100644 index 00000000..bbaf2408 --- /dev/null +++ b/app/test/features/graph/layout/graph_node_layout_test.dart @@ -0,0 +1,228 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/layout/graph_node_layout.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; + +import 'layout_fixtures.dart'; + +GraphLayout _layout( + Map graph, { + Map? extents, + GraphLayoutConfig? config, +}) { + final nodes = graphNodes(graph); + return layoutGraphNodes( + nodes: nodes, + edges: graphEdges(graph), + extents: extents ?? uniformExtents(nodes), + config: config ?? layoutConfig(), + ); +} + +void _expectWithinBounds(GraphLayout layout) { + for (final box in layout.nodes) { + expect(box.x, greaterThanOrEqualTo(0), reason: '${box.key} left'); + expect(box.y, greaterThanOrEqualTo(0), reason: '${box.key} top'); + expect( + box.right, + lessThanOrEqualTo(layout.width), + reason: '${box.key} right inside width', + ); + expect( + box.bottom, + lessThanOrEqualTo(layout.height), + reason: '${box.key} bottom inside height', + ); + } +} + +void _expectSeparated(GraphLayout layout) { + for (var first = 0; first < layout.nodes.length; first += 1) { + for (var second = first + 1; second < layout.nodes.length; second += 1) { + final a = layout.nodes[first]; + final b = layout.nodes[second]; + final separated = + a.right <= b.x || + b.right <= a.x || + a.bottom <= b.y || + b.bottom <= a.y; + expect(separated, isTrue, reason: '${a.key} overlaps ${b.key}'); + } + } +} + +void main() { + test('linear nodes keep declaration order and terminal identity', () { + final layout = _layout(linearGraphFixture()); + + expect(layout.rankCount, 4); + expect(layout.nodes.map((box) => box.key), [ + 'plan', + 'build', + 'ship', + failureEnd, + successEnd, + ]); + expect(layout.ranks, { + 'plan': 0, + 'build': 1, + 'ship': 2, + failureEnd: 3, + successEnd: 3, + }); + expect(layout.nodeFor('plan')!.stageIndex, 0); + expect(layout.nodeFor('build')!.stageIndex, 1); + expect(layout.nodeFor('ship')!.stageIndex, 2); + expect(layout.nodeFor(failureEnd)!.terminal, isTrue); + expect(layout.nodeFor(failureEnd)!.stageIndex, isNull); + expect(layout.nodeFor(successEnd)!.terminal, isTrue); + expect( + layout.nodeFor(successEnd)!.y - layout.nodeFor(failureEnd)!.bottom, + layoutConfig().rowGap, + ); + expect(layout.nodeFor(failureEnd)!.x, layout.nodeFor(successEnd)!.x); + expect(layout.nodeFor('plan')!.x, layoutConfig().padding); + expect(layout.nodeFor('plan')!.y, layoutConfig().padding); + expect( + layout.nodeFor('build')!.x - layout.nodeFor('plan')!.right, + layoutConfig().columnGap, + ); + expect(layout.width, 560); + expect(layout.height, 140); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('diamond ranks place siblings in one column', () { + final layout = _layout(diamondGraphFixture()); + + final b = layout.nodeFor('b')!; + final c = layout.nodeFor('c')!; + expect(b.rank, 1); + expect(c.rank, 1); + expect(b.x, c.x); + expect(c.y - b.bottom, layoutConfig().rowGap); + expect(layout.nodeFor('d')!.rank, 2); + expect(layout.nodeFor('d')!.x, greaterThan(b.right)); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('cycles share a column and terminals still follow them', () { + final layout = _layout(cycleGraph()); + + final a = layout.nodeFor('a')!; + final b = layout.nodeFor('b')!; + expect(a.rank, 0); + expect(b.rank, 0); + expect(b.y - a.bottom, layoutConfig().rowGap); + expect(layout.nodeFor(failureEnd)!.rank, 1); + expect(layout.nodeFor(successEnd)!.rank, 1); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('self loops and disconnected stages stay finite and separate', () { + final selfLoop = _layout(selfLoopGraphFixture()); + expect(selfLoop.nodeFor('a')!.rank, 0); + expect(selfLoop.nodeFor('b')!.rank, 1); + + final disconnected = _layout(disconnectedGraph()); + expect(disconnected.nodeFor('a')!.rank, 0); + expect(disconnected.nodeFor('b')!.rank, 0); + expect(disconnected.nodeFor('c')!.rank, 0); + expect( + disconnected.nodeFor('b')!.y, + greaterThan(disconnected.nodeFor('a')!.bottom), + ); + _expectWithinBounds(selfLoop); + _expectSeparated(selfLoop); + _expectWithinBounds(disconnected); + _expectSeparated(disconnected); + }); + + test('unknown edge targets add no node and no column', () { + final graph = incompleteGraphFixture(); + final layout = _layout(graph); + + expect( + layout.nodes.map((box) => box.key), + graphNodes(graph).map((node) => node.key), + ); + expect(layout.nodeFor('ghost'), isNull); + expect(layout.ranks.containsKey('ghost'), isFalse); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('heterogeneous measured widths stay inside their columns', () { + final layout = _layout( + diamondGraphFixture(), + extents: heterogeneousExtents(), + ); + + for (final entry in heterogeneousExtents().entries) { + final box = layout.nodeFor(entry.key)!; + expect(box.width, entry.value.width, reason: '${entry.key} width'); + expect(box.height, entry.value.height, reason: '${entry.key} height'); + } + final b = layout.nodeFor('b')!; + final c = layout.nodeFor('c')!; + expect(b.rank, c.rank); + expect(b.x + b.width / 2, c.x + c.width / 2); + expect(c.y - b.bottom, layoutConfig().rowGap); + expect(layout.width, greaterThan(0)); + expect(layout.width, 770); + expect(layout.height, 236); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('expanded text extents grow the canvas without overlap or clipping', () { + final base = _layout( + diamondGraphFixture(), + extents: heterogeneousExtents(), + ); + final expandedExtents = scaledExtents(heterogeneousExtents(), 2.6); + final expanded = _layout(diamondGraphFixture(), extents: expandedExtents); + + expect(expanded.width, greaterThan(base.width)); + expect(expanded.height, greaterThan(base.height)); + for (final entry in expandedExtents.entries) { + final box = expanded.nodeFor(entry.key)!; + expect(box.width, entry.value.width, reason: '${entry.key} width'); + expect(box.height, entry.value.height, reason: '${entry.key} height'); + } + _expectWithinBounds(expanded); + _expectSeparated(expanded); + }); + + test('the same input produces the same immutable layout', () { + final graph = diamondGraphFixture(); + final nodes = graphNodes(graph); + final edges = graphEdges(graph); + final extents = uniformExtents(nodes, width: 133, height: 77); + + final first = layoutGraphNodes( + nodes: nodes, + edges: edges, + extents: extents, + config: layoutConfig(), + ); + final second = layoutGraphNodes( + nodes: nodes, + edges: edges, + extents: extents, + config: layoutConfig(), + ); + + expect(second.nodes, first.nodes); + expect(second.ranks, first.ranks); + expect(second.width, first.width); + expect(second.height, first.height); + expect(second.rankCount, first.rankCount); + expect(() => second.nodes.add(first.nodes.first), throwsUnsupportedError); + expect(() => second.ranks['a'] = 99, throwsUnsupportedError); + }); +} diff --git a/app/test/features/graph/layout/graph_ranks_test.dart b/app/test/features/graph/layout/graph_ranks_test.dart new file mode 100644 index 00000000..320ba287 --- /dev/null +++ b/app/test/features/graph/layout/graph_ranks_test.dart @@ -0,0 +1,116 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/layout/graph_ranks.dart'; + +import 'layout_fixtures.dart'; + +GraphRanks _ranksFor(Map graph) { + return assignGraphRanks(graphNodes(graph), graphEdges(graph)); +} + +void main() { + test('linear definitions rank one stage per column', () { + final ranks = _ranksFor(linearGraphFixture()); + + expect(ranks.rankOf, { + 'plan': 0, + 'build': 1, + 'ship': 2, + failureEnd: 3, + successEnd: 3, + }); + expect(ranks.rankCount, 4); + expect(ranks.components, >[ + ['plan'], + ['build'], + ['ship'], + [failureEnd], + [successEnd], + ]); + }); + + test('diamond fan-out shares a rank and converges after it', () { + final ranks = _ranksFor(diamondGraphFixture()); + + expect(ranks.rankOf['a'], 0); + expect(ranks.rankOf['b'], ranks.rankOf['c']); + expect(ranks.rankOf['b'], 1); + expect(ranks.rankOf['d'], 2); + expect(ranks.rankOf[failureEnd], 1); + expect(ranks.rankOf[successEnd], 3); + expect(ranks.rankCount, 4); + }); + + test('a cycle collapses to one shared rank instead of recursing', () { + final ranks = _ranksFor(cycleGraph()); + + expect(ranks.rankOf['a'], 0); + expect(ranks.rankOf['b'], 0); + expect(ranks.rankOf[failureEnd], 1); + expect(ranks.rankOf[successEnd], 1); + expect(ranks.rankCount, 2); + expect(ranks.components, contains(equals(['a', 'b']))); + }); + + test('a self edge stays inside its own component and adds no rank', () { + final ranks = _ranksFor(selfLoopGraphFixture()); + + expect(ranks.rankOf, { + 'a': 0, + 'b': 1, + failureEnd: 2, + successEnd: 2, + }); + expect(ranks.components, contains(equals(['a']))); + expect(ranks.components, contains(equals(['b']))); + }); + + test('disconnected stages stay at rank zero', () { + final ranks = _ranksFor(disconnectedGraph()); + + expect(ranks.rankOf['a'], 0); + expect(ranks.rankOf['b'], 0); + expect(ranks.rankOf['c'], 0); + expect(ranks.rankOf[failureEnd], 1); + expect(ranks.rankOf[successEnd], 1); + expect(ranks.rankCount, 2); + }); + + test('unknown and empty edge targets never become ranks or nodes', () { + final graph = incompleteGraphFixture(); + final nodes = graphNodes(graph); + final ranks = assignGraphRanks(nodes, graphEdges(graph)); + + expect(nodes.map((node) => node.key), isNot(contains('ghost'))); + expect(ranks.rankOf.containsKey('ghost'), isFalse); + expect(ranks.rankOf.containsKey(''), isFalse); + expect(ranks.rankOf['a'], 0); + expect(ranks.rankOf['b'], 0); + expect(ranks.rankOf[failureEnd], 1); + expect(ranks.rankOf[successEnd], 1); + }); + + test('ranks are stable across repeated assignments', () { + final graph = diamondGraphFixture(); + final nodes = graphNodes(graph); + final edges = graphEdges(graph); + + final first = assignGraphRanks(nodes, edges); + final second = assignGraphRanks(nodes, edges); + + expect(second.rankOf, first.rankOf); + expect(second.rankCount, first.rankCount); + expect(second.components, first.components); + }); + + test('a long chain is walked iteratively without overflow', () { + const length = 2000; + final ranks = _ranksFor(chainGraph(length)); + + expect(ranks.rankCount, length + 1); + expect(ranks.rankOf['s0'], 0); + expect(ranks.rankOf['s${length - 1}'], length - 1); + expect(ranks.rankOf[successEnd], length); + }); +} diff --git a/app/test/features/graph/layout/layout_fixtures.dart b/app/test/features/graph/layout/layout_fixtures.dart new file mode 100644 index 00000000..e67a6051 --- /dev/null +++ b/app/test/features/graph/layout/layout_fixtures.dart @@ -0,0 +1,102 @@ +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; + +import '../domain/graph_fixtures.dart' as domain; + +/// Small definitions and measured extents shared by the layout tests. + +GraphLayoutConfig layoutConfig({ + double columnGap = 24, + double rowGap = 12, + double padding = 4, +}) { + return GraphLayoutConfig( + columnGap: columnGap, + rowGap: rowGap, + padding: padding, + ); +} + +/// One measured size for every node, optionally scaled to simulate text growth. +Map uniformExtents( + Iterable nodes, { + double width = 120, + double height = 60, + double scale = 1, +}) { + return { + for (final node in nodes) + node.key: NodeExtent(width: width * scale, height: height * scale), + }; +} + +Map scaledExtents( + Map base, + double scale, +) { + return { + for (final entry in base.entries) + entry.key: NodeExtent( + width: entry.value.width * scale, + height: entry.value.height * scale, + ), + }; +} + +/// Deliberately uneven measured boxes for the diamond definition. +Map heterogeneousExtents() { + return { + 'a': NodeExtent(width: 210, height: 84), + 'b': NodeExtent(width: 92, height: 44), + 'c': NodeExtent(width: 148, height: 126), + 'd': NodeExtent(width: 104, height: 58), + failureEnd: NodeExtent(width: 72, height: 34), + successEnd: NodeExtent(width: 228, height: 96), + }; +} + +/// Two stages in a cycle; both terminals are reached from inside the cycle. +Map cycleGraph() => { + 'stages': [ + domain.stage( + 'a', + edges: {'success': 'b', 'error': '#'}, + fallbackError: true, + ), + domain.stage( + 'b', + edges: {'success': 'a', 'error': '#success'}, + ), + ], +}; + +/// Two independent routes and a stage with no edges at all. +Map disconnectedGraph() => { + 'stages': [ + domain.stage('a', edges: {'success': '#success'}), + domain.stage('b', edges: {'success': '#failure'}), + domain.stage('c'), + ], +}; + +Map linearGraphFixture() => domain.linearGraph(); + +Map diamondGraphFixture() => domain.diamondGraph(); + +Map selfLoopGraphFixture() => domain.selfLoopGraph(); + +Map incompleteGraphFixture() => domain.incompleteGraph(); + +/// A long chain, used to prove the iterative rank walk cannot overflow. +Map chainGraph(int length) => { + 'stages': [ + for (var index = 0; index < length; index += 1) + domain.stage( + 's$index', + edges: { + 'success': index + 1 < length ? 's${index + 1}' : '#success', + }, + ), + ], +}; diff --git a/app/test/features/graph/painting/edge_layer_fixtures.dart b/app/test/features/graph/painting/edge_layer_fixtures.dart new file mode 100644 index 00000000..50cc9d00 --- /dev/null +++ b/app/test/features/graph/painting/edge_layer_fixtures.dart @@ -0,0 +1,41 @@ +import 'package:flutter/material.dart'; +import 'package:pipelines_app/features/graph/routing/route_models.dart'; + +/// Shared hand-built routes for the edge-layer painting tests. + +EdgeRoute edgeRoute({ + required List points, + RouteKind kind = RouteKind.forward, + RoutePortSide targetSide = RoutePortSide.left, + double portX = 0, + double portY = 0, +}) { + final start = points.isEmpty ? RoutePoint(portX, portY) : points.first; + final end = points.isEmpty ? RoutePoint(portX, portY) : points.last; + return EdgeRoute( + id: 1, + source: 'a', + outcome: 'success', + target: 'b', + label: 'success', + fallback: false, + kind: kind, + straight: false, + sourcePort: RoutePort(side: RoutePortSide.right, point: start), + targetPort: RoutePort(side: targetSide, point: end), + points: points, + ); +} + +Offset routeOffset(RoutePoint point) => Offset(point.x, point.y); + +/// The direction of the route's last non-degenerate segment. +Offset arrival(EdgeRoute route) { + final points = route.points; + final end = points.last; + for (var index = points.length - 2; index >= 0; index -= 1) { + final delta = Offset(end.x - points[index].x, end.y - points[index].y); + if (delta != Offset.zero) return delta / delta.distance; + } + return Offset.zero; +} diff --git a/app/test/features/graph/painting/graph_edge_geometry_test.dart b/app/test/features/graph/painting/graph_edge_geometry_test.dart new file mode 100644 index 00000000..18ef42de --- /dev/null +++ b/app/test/features/graph/painting/graph_edge_geometry_test.dart @@ -0,0 +1,240 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/painting/graph_edge_layer.dart'; +import 'package:pipelines_app/features/graph/routing/route_models.dart'; + +import '../routing/routing_fixtures.dart'; +import 'edge_layer_fixtures.dart'; + +void main() { + const color = Colors.black87; + final straight = edgeRoute( + points: const [RoutePoint(10, 20), RoutePoint(90, 20)], + ); + final wrapping = edgeRoute( + points: const [ + RoutePoint(10, 20), + RoutePoint(40, 20), + RoutePoint(40, 60), + RoutePoint(80, 60), + RoutePoint(80, 50), + ], + ); + + group('path', () { + test('keeps every orthogonal vertex of the supplied route', () { + final painter = GraphEdgePainter( + routes: [wrapping], + color: color, + strokeWidth: 2, + ); + final path = painter.linePath(wrapping); + final metric = path.computeMetrics().single; + expect(metric.length, closeTo(30 + 40 + 40 + 10, 0.001)); + expect( + metric.getTangentForOffset(0)!.position, + routeOffset(wrapping.points.first), + ); + expect( + metric.getTangentForOffset(metric.length)!.position, + routeOffset(wrapping.points.last), + ); + expect(path.getBounds(), const Rect.fromLTRB(10, 20, 80, 60)); + }); + + test('a straight route is the exact port-to-port segment', () { + final painter = GraphEdgePainter( + routes: [straight], + color: color, + strokeWidth: 1, + ); + final metric = painter.linePath(straight).computeMetrics().single; + expect(metric.length, 80); + expect(metric.getTangentForOffset(40)!.vector, const Offset(1, 0)); + }); + + test('zero- and one-point routes produce an empty path', () { + final painter = GraphEdgePainter( + routes: const [], + color: color, + strokeWidth: 1, + ); + final empty = edgeRoute(points: const []); + final single = edgeRoute(points: const [RoutePoint(5, 5)]); + for (final route in [empty, single]) { + final path = painter.linePath(route); + expect(path.getBounds().isEmpty, isTrue); + expect(path.computeMetrics().isEmpty, isTrue); + } + }); + }); + + group('arrow', () { + test('points into a forward target port', () { + final painter = GraphEdgePainter( + routes: [straight], + color: color, + strokeWidth: 2, + ); + final arrow = painter.arrowPath(straight); + final tip = routeOffset(straight.points.last); + expect( + arrow.computeMetrics().first.getTangentForOffset(0)!.position, + tip, + ); + // 12 long and 8 wide for a 2px stroke, pointing right. + expect(arrow.getBounds(), const Rect.fromLTRB(78, 16, 90, 24)); + expect(arrow.contains(tip.translate(-5, 0)), isTrue); + expect(arrow.contains(tip.translate(2, 0)), isFalse); + expect(arrow.contains(tip.translate(-14, 0)), isFalse); + }); + + test('follows self-loop arrival instead of assuming a rightward edge', () { + final routing = routeFor(selfLoopGraphFixture()); + final loop = routing.routes.singleWhere( + (route) => route.kind == RouteKind.selfLoop, + ); + final painter = GraphEdgePainter( + routes: routing.routes, + color: color, + strokeWidth: 2, + ); + final direction = arrival(loop); + final tip = routeOffset(loop.points.last); + final arrow = painter.arrowPath(loop); + + expect(loop.targetPort.side, RoutePortSide.right); + expect(direction.dx, -1); + expect(arrow.getBounds().left, tip.dx); + expect(arrow.contains(tip.translate(5, 0)), isTrue); + expect(arrow.contains(tip.translate(-2, 0)), isFalse); + }); + + test('a backward route keeps its leftward arrival into a right port', () { + final back = edgeRoute( + kind: RouteKind.back, + targetSide: RoutePortSide.right, + points: const [ + RoutePoint(120, 20), + RoutePoint(140, 20), + RoutePoint(140, 60), + RoutePoint(80, 60), + ], + ); + final painter = GraphEdgePainter( + routes: [back], + color: color, + strokeWidth: 2, + ); + final arrow = painter.arrowPath(back); + final tip = routeOffset(back.points.last); + + expect(back.kind, RouteKind.back); + expect(arrow.getBounds().left, tip.dx); + expect(arrow.contains(tip.translate(5, 0)), isTrue); + expect(arrow.contains(tip.translate(-2, 0)), isFalse); + }); + + test('keeps the routed arrival direction for every cycle edge', () { + final routing = routeFor(cycleGraphFixture()); + final painter = GraphEdgePainter( + routes: routing.routes, + color: color, + strokeWidth: 2, + ); + expect(routing.routes, isNotEmpty); + for (final route in routing.routes) { + final direction = arrival(route); + final tip = routeOffset(route.points.last); + final arrow = painter.arrowPath(route); + expect( + arrow.computeMetrics().first.getTangentForOffset(0)!.position, + tip, + ); + expect(arrow.contains(tip - direction * 5), isTrue); + expect(arrow.contains(tip + direction * 2), isFalse); + } + }); + + test('a routed forward edge ends exactly at its target port', () { + final routing = routeFor(chainGraphFixture()); + final painter = GraphEdgePainter( + routes: routing.routes, + color: color, + strokeWidth: 2, + ); + expect(routing.routes, isNotEmpty); + for (final route in routing.routes) { + expect(route.points.last, route.targetPort.point); + final arrow = painter.arrowPath(route); + expect( + arrow.computeMetrics().first.getTangentForOffset(0)!.position, + routeOffset(route.targetPort.point), + ); + } + }); + + test('anchors the tip at the target port, not the last route point', () { + final route = EdgeRoute( + id: 7, + source: 'a', + outcome: 'success', + target: 'b', + label: 'success', + fallback: false, + kind: RouteKind.forward, + straight: true, + sourcePort: const RoutePort( + side: RoutePortSide.right, + point: RoutePoint(10, 20), + ), + targetPort: const RoutePort( + side: RoutePortSide.left, + point: RoutePoint(85, 20), + ), + points: const [RoutePoint(10, 20), RoutePoint(80, 20)], + ); + final arrow = GraphEdgePainter( + routes: [route], + color: color, + strokeWidth: 2, + ).arrowPath(route); + expect( + arrow.computeMetrics().first.getTangentForOffset(0)!.position, + const Offset(85, 20), + ); + }); + + test('scales with the caller stroke width', () { + final small = GraphEdgePainter( + routes: [straight], + color: color, + strokeWidth: 1, + ).arrowPath(straight); + final large = GraphEdgePainter( + routes: [straight], + color: color, + strokeWidth: 4, + ).arrowPath(straight); + expect(small.getBounds().width, 6); + expect(small.getBounds().height, 4); + expect(large.getBounds().width, 24); + expect(large.getBounds().height, 16); + }); + + test('falls back to the port inward normal for a degenerate tail', () { + final route = edgeRoute( + points: const [RoutePoint(50, 50), RoutePoint(50, 50)], + targetSide: RoutePortSide.top, + ); + final arrow = GraphEdgePainter( + routes: [route], + color: color, + strokeWidth: 2, + ).arrowPath(route); + final tip = routeOffset(route.points.last); + expect(arrow.getBounds(), const Rect.fromLTRB(46, 38, 54, 50)); + expect(arrow.contains(tip.translate(0, -5)), isTrue); + }); + }); +} diff --git a/app/test/features/graph/painting/graph_edge_layer_test.dart b/app/test/features/graph/painting/graph_edge_layer_test.dart new file mode 100644 index 00000000..aa46bfad --- /dev/null +++ b/app/test/features/graph/painting/graph_edge_layer_test.dart @@ -0,0 +1,190 @@ +import 'dart:ui' as ui; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/painting/graph_edge_layer.dart'; +import 'package:pipelines_app/features/graph/routing/route_models.dart'; + +import 'edge_layer_fixtures.dart'; + +void main() { + const color = Colors.black87; + final straight = edgeRoute( + points: const [RoutePoint(10, 20), RoutePoint(90, 20)], + ); + final wrapping = edgeRoute( + points: const [ + RoutePoint(10, 20), + RoutePoint(40, 20), + RoutePoint(40, 60), + RoutePoint(80, 60), + RoutePoint(80, 50), + ], + ); + + test('draws one stroke and one filled arrow per route, clipped', () { + final canvas = TestRecordingCanvas(); + GraphEdgePainter( + routes: [straight, wrapping], + color: color, + strokeWidth: 2, + ).paint(canvas, const Size(120, 80)); + + final calls = canvas.invocations + .where((call) => call.invocation.memberName == #drawPath) + .toList(); + expect(calls.length, 4); + final paints = [ + for (final call in calls) + call.invocation.positionalArguments.last as Paint, + ]; + expect(paints[0].style, PaintingStyle.stroke); + expect(paints[1].style, PaintingStyle.stroke); + expect(paints[2].style, PaintingStyle.fill); + expect(paints[3].style, PaintingStyle.fill); + expect( + paints.every((paint) => paint.color.toARGB32() == color.toARGB32()), + isTrue, + ); + + final clip = canvas.invocations.singleWhere( + (call) => call.invocation.memberName == #clipRect, + ); + expect( + clip.invocation.positionalArguments.first, + const Rect.fromLTWH(0, 0, 120, 80), + ); + }); + + test('paints nothing for an empty route list', () { + final canvas = TestRecordingCanvas(); + GraphEdgePainter( + routes: const [], + color: color, + strokeWidth: 2, + ).paint(canvas, const Size(120, 80)); + expect(canvas.invocations, isEmpty); + }); + + test('reports every canvas point as a miss', () { + final painter = GraphEdgePainter( + routes: [straight], + color: color, + strokeWidth: 2, + ); + expect(painter.hitTest(const Offset(50, 20)), isFalse); + expect(painter.hitTest(const Offset(500, 500)), isFalse); + }); + + testWidgets('clips painted geometry to the canvas bounds', (tester) async { + final recorder = ui.PictureRecorder(); + GraphEdgePainter( + routes: [ + edgeRoute(points: const [RoutePoint(-30, 10), RoutePoint(60, 10)]), + ], + color: Colors.black, + strokeWidth: 6, + ).paint(Canvas(recorder), const Size(20, 20)); + final data = await tester.runAsync(() async { + final image = await recorder.endRecording().toImage(80, 40); + final bytes = await image.toByteData(format: ui.ImageByteFormat.rawRgba); + image.dispose(); + return bytes; + }); + expect(data, isNotNull); + final bytes = data!.buffer.asUint8List(); + int alphaAt(int x, int y) => bytes[(y * 80 + x) * 4 + 3]; + expect(alphaAt(10, 10), 255, reason: 'inside the clip is painted'); + expect(alphaAt(40, 10), 0, reason: 'the route continues past the clip'); + expect(alphaAt(10, 35), 0, reason: 'below the canvas stays empty'); + }); + + testWidgets('lets taps through to a sibling below the canvas', ( + tester, + ) async { + var taps = 0; + Widget harness(List routes) => MaterialApp( + home: Center( + child: SizedBox( + width: 200, + height: 100, + child: Stack( + children: [ + Positioned.fill( + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => taps += 1, + ), + ), + GraphEdgeLayer( + routes: routes, + canvasSize: const Size(200, 100), + color: color, + strokeWidth: 2, + ), + ], + ), + ), + ), + ); + for (final routes in >[ + const [], + [straight], + ]) { + await tester.pumpWidget(harness(routes)); + final origin = tester.getTopLeft(find.byType(GraphEdgeLayer)); + final before = taps; + await tester.tapAt(origin + const Offset(50, 20)); + await tester.tapAt(origin + const Offset(150, 80)); + expect(taps, before + 2, reason: 'routes=$routes'); + } + }); + + test('repaints on route, color or stroke changes only', () { + final painter = GraphEdgePainter( + routes: [straight], + color: color, + strokeWidth: 2, + ); + GraphEdgePainter copy({ + List? routes, + Color? color, + double? strokeWidth, + }) => GraphEdgePainter( + routes: routes ?? [straight], + color: color ?? Colors.black87, + strokeWidth: strokeWidth ?? 2, + ); + + expect(painter.shouldRepaint(copy()), isFalse); + expect(painter.shouldRepaint(copy(color: Colors.red)), isTrue); + expect(painter.shouldRepaint(copy(strokeWidth: 3)), isTrue); + expect( + painter.shouldRepaint( + copy( + routes: [ + edgeRoute(points: const [RoutePoint(10, 20), RoutePoint(90, 30)]), + ], + ), + ), + isTrue, + ); + }); + + testWidgets('lays out at the supplied canvas size', (tester) async { + await tester.pumpWidget( + MaterialApp( + home: Center( + child: GraphEdgeLayer( + routes: [wrapping], + canvasSize: const Size(120, 80), + color: color, + strokeWidth: 2, + ), + ), + ), + ); + expect(tester.getSize(find.byType(GraphEdgeLayer)), const Size(120, 80)); + expect(tester.takeException(), isNull); + }); +} diff --git a/app/test/features/graph/routing/graph_edge_routing_test.dart b/app/test/features/graph/routing/graph_edge_routing_test.dart new file mode 100644 index 00000000..59ee4922 --- /dev/null +++ b/app/test/features/graph/routing/graph_edge_routing_test.dart @@ -0,0 +1,191 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/routing/route_models.dart'; + +import '../layout/layout_fixtures.dart' as layout; +import 'routing_assertions.dart'; +import 'routing_fixtures.dart'; + +void main() { + test('chain routes keep identities and use straight forward runs', () { + final graph = chainGraphFixture(); + final layoutBox = layoutFor(graph); + final edges = graphEdges(graph); + final labels = labelsFor(edges); + final routing = routeFor(graph, labels: labels); + + expect(routing.skipped, isEmpty); + expect( + routing.routes.map((route) => route.id), + edges.map((edge) => edge.id), + ); + for (var index = 0; index < edges.length; index += 1) { + final edge = edges[index]; + final route = routing.routes[index]; + expect(route.source, edge.source); + expect(route.outcome, edge.outcome); + expect(route.target, edge.target); + expect(route.label, edge.label); + expect(route.fallback, edge.fallback); + expect(route.kind, RouteKind.forward); + expect(route.straight, isTrue); + expect(route.points.length, 2); + expect(route.sourcePort.side, RoutePortSide.right); + expect(route.targetPort.side, RoutePortSide.left); + } + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('diamond fan-out and fan-in avoid every node interior', () { + final graph = diamondGraphFixture(); + final layoutBox = layoutFor(graph); + final labels = labelsFor(graphEdges(graph)); + final routing = routeFor(graph, labels: labels); + + expect(routing.skipped, isEmpty); + expect(routing.routes.length, graphEdges(graph).length); + final fromA = routing.routes.where((route) => route.source == 'a'); + expect(fromA.length, 3); + expect( + fromA.where((route) => route.straight).length, + greaterThanOrEqualTo(1), + ); + final longForward = fromA.singleWhere( + (route) => route.target == failureEnd, + ); + expect(longForward.kind, RouteKind.forward); + expect(longForward.straight, isFalse); + expect(longForward.points.length, greaterThan(4)); + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('parallel outcomes to one target get separate corridors and labels', () { + final graph = parallelOutcomesGraph(); + final layoutBox = layoutFor(graph); + final labels = labelsFor(graphEdges(graph)); + final routing = routeFor(graph, labels: labels); + + final parallel = routing.routes + .where((route) => route.source == 'a' && route.target == 'b') + .toList(); + expect(parallel.length, 3); + final ports = { + for (final route in parallel) + '${route.sourcePort.point.y}/${route.targetPort.point.y}', + }; + expect(ports.length, 3, reason: 'each outcome has its own port pair'); + final labelBoxes = [ + for (final route in parallel) routing.labelFor(route.id)!, + ]; + expect(labelBoxes.map((box) => box.y).toSet().length, greaterThan(1)); + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('a same-rank cycle uses distinct lanes around both members', () { + final graph = cycleGraphFixture(); + final layoutBox = layoutFor(graph); + final labels = labelsFor(graphEdges(graph)); + final routing = routeFor(graph, labels: labels); + + final sameRank = routing.routes + .where((route) => route.kind == RouteKind.sameRank) + .toList(); + expect(sameRank.length, 2); + expect(sameRank.map((route) => route.target).toSet(), {'a', 'b'}); + for (final route in sameRank) { + expect(route.straight, isFalse); + expect(route.sourcePort.side, RoutePortSide.right); + expect(route.targetPort.side, RoutePortSide.right); + expect( + route.points.map((point) => point.y).toSet().length, + greaterThan(2), + ); + } + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('a self loop expands bounds and keeps both ports on its border', () { + final graph = selfLoopOnlyGraph(); + final layoutBox = layoutFor(graph); + final labels = labelsFor(graphEdges(graph)); + final routing = routeFor(graph, labels: labels); + + final route = routing.routes.single; + expect(route.kind, RouteKind.selfLoop); + expect(route.straight, isFalse); + expect(route.points.length, greaterThanOrEqualTo(4)); + expect(route.sourcePort.side, RoutePortSide.right); + expect(route.targetPort.side, RoutePortSide.right); + expect(route.sourcePort.point.y, isNot(route.targetPort.point.y)); + expect(routing.width, greaterThan(layoutBox.width)); + expect(routing.height, greaterThan(layoutBox.height)); + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('disconnected stages route only their declared edges', () { + final graph = disconnectedGraphFixture(); + final layoutBox = layoutFor(graph); + final labels = labelsFor(graphEdges(graph)); + final routing = routeFor(graph, labels: labels); + + expect(routing.skipped, isEmpty); + expect(routing.routes.length, 2); + expect(routing.routes.map((route) => route.source).toSet(), { + 'a', + 'b', + }); + expect(layoutBox.nodeFor('c'), isNotNull); + expect(routing.routes.any((route) => route.source == 'c'), isFalse); + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('heterogeneous and expanded text sizes stay valid and grow bounds', () { + final graph = diamondGraphFixture(); + final baseLayout = layoutFor(graph, extents: layout.heterogeneousExtents()); + final expandedExtents = layout.scaledExtents( + layout.heterogeneousExtents(), + 2.6, + ); + final expandedLayout = layoutFor(graph, extents: expandedExtents); + final edges = graphEdges(graph); + final labels = fixedLabels(edges); + + final base = routeFor( + graph, + extents: layout.heterogeneousExtents(), + labels: labels, + ); + final expanded = routeFor(graph, extents: expandedExtents, labels: labels); + + expectValidRouting(base, baseLayout, extents: labels); + expectValidRouting(expanded, expandedLayout, extents: labels); + expect(expanded.width, greaterThan(base.width)); + expect(expanded.height, greaterThan(base.height)); + }); + + test('unknown and missing targets are skipped with their identity', () { + final graph = incompleteGraphFixture(); + final layoutBox = layoutFor(graph); + final edges = graphEdges(graph); + final labels = labelsFor(edges); + final routing = routeFor(graph, labels: labels); + + expect(routing.skipped.length, 2); + final skipped = routing.skipped.toList(); + expect(skipped.map((item) => item.reason), [ + RouteSkipReason.unknownTarget, + RouteSkipReason.unknownTarget, + ]); + expect(skipped.map((item) => item.id), [1, 2]); + expect(skipped[0].source, 'a'); + expect(skipped[0].outcome, 'blocked'); + expect(skipped[0].target, ''); + expect(skipped[1].target, 'ghost'); + expect(routing.routes.map((route) => route.id), [3, 4]); + expect(routing.routeFor(1), isNull); + expect(routing.routeFor(2), isNull); + expect(layoutBox.nodeFor('ghost'), isNull); + expectValidRouting(routing, layoutBox, extents: labels); + }); +} diff --git a/app/test/features/graph/routing/graph_routing_geometry_test.dart b/app/test/features/graph/routing/graph_routing_geometry_test.dart new file mode 100644 index 00000000..2fce067a --- /dev/null +++ b/app/test/features/graph/routing/graph_routing_geometry_test.dart @@ -0,0 +1,161 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; +import 'package:pipelines_app/features/graph/routing/graph_edge_routing.dart'; +import 'package:pipelines_app/features/graph/routing/route_models.dart'; + +import 'routing_assertions.dart'; +import 'routing_fixtures.dart'; +import '../layout/layout_fixtures.dart' as layout; + +void main() { + test( + 'wide measured labels move outside the drawing instead of covering it', + () { + final graph = chainGraphFixture(); + final layoutBox = layoutFor(graph); + final edges = graphEdges(graph); + final labels = fixedLabels(edges, width: 400, height: 40); + final routing = routeFor(graph, labels: labels); + + expect(routing.labels.length, edges.length); + for (final label in routing.labels) { + expect(label.y, greaterThanOrEqualTo(layoutBox.height)); + expect(label.right, lessThanOrEqualTo(routing.width)); + expect(label.bottom, lessThanOrEqualTo(routing.height)); + } + expect(routing.height, greaterThan(layoutBox.height)); + expectValidRouting(routing, layoutBox, extents: labels); + }, + ); + + test('tight gaps and expanded extents keep the same guarantees', () { + for (final gap in [8, 24, 80]) { + for (final scale in [1, 2.6]) { + final extents = layout.scaledExtents( + layout.heterogeneousExtents(), + scale, + ); + final layoutBox = layoutFor( + diamondGraphFixture(), + extents: extents, + config: routingLayoutConfig(columnGap: gap, rowGap: 16), + ); + final edges = graphEdges(diamondGraphFixture()); + final labels = labelsFor(edges); + final routing = routeFor( + diamondGraphFixture(), + extents: extents, + labels: labels, + layoutConfig: routingLayoutConfig(columnGap: gap, rowGap: 16), + ); + expectValidRouting(routing, layoutBox, extents: labels); + } + } + }); + + test('a three-stage cycle keeps every same-rank corridor distinct', () { + final graph = cycleThreeGraph(); + final layoutBox = layoutFor( + graph, + config: routingLayoutConfig(columnGap: 8), + ); + final edges = graphEdges(graph); + final labels = labelsFor(edges); + final routing = routeFor( + graph, + labels: labels, + layoutConfig: routingLayoutConfig(columnGap: 8), + ); + + expect(routing.routes.length, 3); + expect( + routing.routes.every((route) => route.kind == RouteKind.sameRank), + isTrue, + ); + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('a caller-supplied backward rank routes around the target column', () { + final layoutBox = GraphLayout( + nodes: [ + const GraphNodeBox( + key: 'a', + terminal: false, + stageIndex: 0, + rank: 1, + x: 208, + y: 8, + width: 120, + height: 60, + ), + const GraphNodeBox( + key: 'b', + terminal: false, + stageIndex: 1, + rank: 0, + x: 8, + y: 8, + width: 120, + height: 60, + ), + ], + ranks: {'a': 1, 'b': 0}, + rankCount: 2, + width: 336, + height: 76, + ); + final edge = GraphEdge( + id: 1, + source: 'a', + outcome: 'success', + target: 'b', + label: 'success', + fallback: false, + knownTarget: true, + ); + final labels = {1: LabelExtent(width: 52, height: 18)}; + final routing = routeGraphEdges( + layout: layoutBox, + edges: [edge], + labelExtents: labels, + config: routingConfig(), + ); + + final route = routing.routes.single; + expect(route.kind, RouteKind.back); + expect(route.sourcePort.side, RoutePortSide.right); + expect(route.targetPort.side, RoutePortSide.right); + expect(route.straight, isFalse); + expect(route.points.length, greaterThan(4)); + expect(routing.width, greaterThan(layoutBox.width)); + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('a self loop and forward routes share one valid layout', () { + final graph = selfLoopGraphFixture(); + final layoutBox = layoutFor(graph); + final labels = labelsFor(graphEdges(graph)); + final routing = routeFor(graph, labels: labels); + + expect(routing.routes.length, 4); + expect(routing.routes.map((route) => route.kind).toSet(), { + RouteKind.forward, + RouteKind.selfLoop, + }); + final loop = routing.routes.singleWhere( + (route) => route.kind == RouteKind.selfLoop, + ); + expect(loop.source, 'a'); + expect(loop.target, 'a'); + expect(loop.sourcePort.point.y, isNot(loop.targetPort.point.y)); + expect( + routing.routes + .where((route) => route.target == successEnd) + .every((route) => route.targetPort.side == RoutePortSide.left), + isTrue, + ); + expectValidRouting(routing, layoutBox, extents: labels); + }); +} diff --git a/app/test/features/graph/routing/graph_routing_validation_test.dart b/app/test/features/graph/routing/graph_routing_validation_test.dart new file mode 100644 index 00000000..7d548748 --- /dev/null +++ b/app/test/features/graph/routing/graph_routing_validation_test.dart @@ -0,0 +1,222 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/routing/graph_edge_routing.dart'; +import 'package:pipelines_app/features/graph/routing/route_models.dart'; + +import 'routing_fixtures.dart'; + +GraphEdge _edge({ + int id = 1, + String source = 'a', + String target = 'b', + String outcome = 'success', + bool knownTarget = true, +}) { + return GraphEdge( + id: id, + source: source, + outcome: outcome, + target: target, + label: outcome, + fallback: false, + knownTarget: knownTarget, + ); +} + +void main() { + test('an empty graph has empty routes and the layout bounds', () { + final layoutBox = layoutFor({'stages': []}); + final routing = routeGraphEdges( + layout: layoutBox, + edges: const [], + labelExtents: const {}, + config: routingConfig(), + ); + + expect(routing.isEmpty, isTrue); + expect(routing.routes, isEmpty); + expect(routing.labels, isEmpty); + expect(routing.skipped, isEmpty); + expect(routing.width, layoutBox.width + routingConfig().boundsPadding); + expect(routing.height, layoutBox.height + routingConfig().boundsPadding); + }); + + test('unknown endpoints become diagnostics, never invented nodes', () { + final layoutBox = layoutFor(chainGraphFixture()); + final edges = [ + _edge(id: 1, source: 'missing', target: 's0'), + _edge(id: 2, source: 's0', target: 'ghost'), + _edge(id: 3, source: 's0', target: '', knownTarget: false), + ]; + final routing = routeGraphEdges( + layout: layoutBox, + edges: edges, + labelExtents: const {}, + config: routingConfig(), + ); + + expect(routing.routes, isEmpty); + expect(routing.skipped.map((item) => item.reason), [ + RouteSkipReason.unknownSource, + RouteSkipReason.unknownTarget, + RouteSkipReason.unknownTarget, + ]); + expect(routing.skipped.map((item) => item.id), [1, 2, 3]); + expect(layoutBox.nodeFor('missing'), isNull); + expect(layoutBox.nodeFor('ghost'), isNull); + }); + + test('routed edges require measured label extents', () { + final graph = diamondGraphFixture(); + final layoutBox = layoutFor(graph); + final edges = graphEdges(graph); + final labels = labelsFor(edges)..remove(edges.first.id); + + expect( + () => routeGraphEdges( + layout: layoutBox, + edges: edges, + labelExtents: labels, + config: routingConfig(), + ), + throwsArgumentError, + ); + }); + + test('extra label extents are ignored and duplicate ids are rejected', () { + final graph = diamondGraphFixture(); + final layoutBox = layoutFor(graph); + final edges = graphEdges(graph); + final labels = labelsFor(edges)..[999] = LabelExtent(width: 10, height: 10); + final routing = routeGraphEdges( + layout: layoutBox, + edges: edges, + labelExtents: labels, + config: routingConfig(), + ); + expect(routing.routes.length, edges.length); + expect(routing.labelFor(999), isNull); + + expect( + () => routeGraphEdges( + layout: layoutBox, + edges: [edges.first, edges.first], + labelExtents: labelsFor(edges), + config: routingConfig(), + ), + throwsArgumentError, + ); + }); + + test('invalid configuration and label extents are rejected', () { + expect( + () => RoutingConfig( + nodeClearance: -1, + laneSpacing: 10, + corridorSpacing: 10, + portSpacing: 8, + labelGap: 2, + ), + throwsArgumentError, + ); + expect( + () => RoutingConfig( + nodeClearance: 2, + laneSpacing: 0, + corridorSpacing: 10, + portSpacing: 8, + labelGap: 2, + ), + throwsArgumentError, + ); + expect( + () => RoutingConfig( + nodeClearance: 2, + laneSpacing: 10, + corridorSpacing: double.nan, + portSpacing: 8, + labelGap: 2, + ), + throwsArgumentError, + ); + expect( + () => LabelExtent(width: double.infinity, height: 10), + throwsArgumentError, + ); + expect(() => LabelExtent(width: 10, height: -1), throwsArgumentError); + }); + + test('the same input produces equal immutable results', () { + final graph = diamondGraphFixture(); + final layoutBox = layoutFor(graph); + final edges = graphEdges(graph); + final labels = labelsFor(edges); + final config = routingConfig(); + + final first = routeGraphEdges( + layout: layoutBox, + edges: edges, + labelExtents: labels, + config: config, + ); + final second = routeGraphEdges( + layout: layoutBox, + edges: edges, + labelExtents: labels, + config: config, + ); + + expect(first.routes, second.routes); + expect(first.labels, second.labels); + expect(first.skipped, second.skipped); + expect(first.width, second.width); + expect(first.height, second.height); + expect(() => first.routes.add(first.routes.first), throwsUnsupportedError); + expect( + () => first.routes.first.points.add(const RoutePoint(0, 0)), + throwsUnsupportedError, + ); + expect(() => first.labels.add(first.labels.first), throwsUnsupportedError); + expect( + () => first.skipped.add( + const RouteDiagnostic( + id: 1, + source: 'a', + outcome: 'success', + target: 'b', + reason: RouteSkipReason.unknownTarget, + message: '', + ), + ), + throwsUnsupportedError, + ); + }); + + test('edges are routed in definition id order regardless of input order', () { + final graph = diamondGraphFixture(); + final layoutBox = layoutFor(graph); + final edges = graphEdges(graph); + final labels = labelsFor(edges); + final forward = routeGraphEdges( + layout: layoutBox, + edges: edges, + labelExtents: labels, + config: routingConfig(), + ); + final reversed = routeGraphEdges( + layout: layoutBox, + edges: edges.reversed.toList(), + labelExtents: labels, + config: routingConfig(), + ); + + expect(reversed.routes, forward.routes); + expect(reversed.labels, forward.labels); + expect(reversed.width, forward.width); + expect(reversed.height, forward.height); + expect( + forward.routes.map((route) => route.id), + edges.map((edge) => edge.id), + ); + }); +} diff --git a/app/test/features/graph/routing/routing_assertions.dart b/app/test/features/graph/routing/routing_assertions.dart new file mode 100644 index 00000000..c524fa30 --- /dev/null +++ b/app/test/features/graph/routing/routing_assertions.dart @@ -0,0 +1,215 @@ +import 'dart:math' as math; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; +import 'package:pipelines_app/features/graph/routing/route_models.dart'; + +const double _epsilon = 1e-9; + +/// Checks the routing guarantees every fixture must satisfy. +void expectValidRouting( + GraphRouting routing, + GraphLayout layout, { + Map? extents, +}) { + expect(routing.width.isFinite, isTrue); + expect(routing.height.isFinite, isTrue); + expect(routing.width, greaterThan(0)); + expect(routing.height, greaterThan(0)); + + for (final route in routing.routes) { + _expectRoute(route, layout, routing.width, routing.height); + _expectNoNodeInterior(route, layout); + } + expectDistinctCorridors(routing.routes); + + final byId = { + for (final label in routing.labels) label.edgeId: label, + }; + expect(byId.length, routing.labels.length, reason: 'one label per edge'); + for (final route in routing.routes) { + final label = byId[route.id]; + expect(label, isNotNull, reason: 'edge ${route.id} has a label'); + final extent = extents?[route.id]; + if (extent != null) { + expect(label!.width, extent.width); + expect(label.height, extent.height); + } + expect(label!.x, greaterThanOrEqualTo(-_epsilon)); + expect(label.y, greaterThanOrEqualTo(-_epsilon)); + expect(label.right, lessThanOrEqualTo(routing.width + _epsilon)); + expect(label.bottom, lessThanOrEqualTo(routing.height + _epsilon)); + for (final node in layout.nodes) { + expect( + _overlaps( + label.x, + label.y, + label.width, + label.height, + node.x, + node.y, + node.width, + node.height, + ), + isFalse, + reason: 'label for edge ${route.id} overlaps node ${node.key}', + ); + } + } + for (var first = 0; first < routing.labels.length; first += 1) { + for (var second = first + 1; second < routing.labels.length; second += 1) { + final a = routing.labels[first]; + final b = routing.labels[second]; + expect( + _overlaps(a.x, a.y, a.width, a.height, b.x, b.y, b.width, b.height), + isFalse, + reason: 'labels for edges ${a.edgeId} and ${b.edgeId} overlap', + ); + } + } + + for (final skipped in routing.skipped) { + expect(routing.routeFor(skipped.id), isNull); + expect(routing.labelFor(skipped.id), isNull); + } +} + +void expectDistinctCorridors(List routes) { + for (var first = 0; first < routes.length; first += 1) { + for (var second = first + 1; second < routes.length; second += 1) { + final a = routes[first]; + final b = routes[second]; + for (var ai = 1; ai < a.points.length; ai += 1) { + final a0 = a.points[ai - 1]; + final a1 = a.points[ai]; + for (var bi = 1; bi < b.points.length; bi += 1) { + final b0 = b.points[bi - 1]; + final b1 = b.points[bi]; + if (a0.x == a1.x && b0.x == b1.x && a0.x == b0.x) { + final aLo = math.min(a0.y, a1.y); + final aHi = math.max(a0.y, a1.y); + final bLo = math.min(b0.y, b1.y); + final bHi = math.max(b0.y, b1.y); + expect( + aLo < bHi - _epsilon && bLo < aHi - _epsilon, + isFalse, + reason: 'edges ${a.id} and ${b.id} share a vertical corridor', + ); + } + if (a0.y == a1.y && b0.y == b1.y && a0.y == b0.y) { + final aLo = math.min(a0.x, a1.x); + final aHi = math.max(a0.x, a1.x); + final bLo = math.min(b0.x, b1.x); + final bHi = math.max(b0.x, b1.x); + expect( + aLo < bHi - _epsilon && bLo < aHi - _epsilon, + isFalse, + reason: 'edges ${a.id} and ${b.id} share a horizontal run', + ); + } + } + } + } + } +} + +void _expectRoute( + EdgeRoute route, + GraphLayout layout, + double width, + double height, +) { + expect(route.points.length, greaterThanOrEqualTo(2)); + expect(route.points.first, route.sourcePort.point); + expect(route.points.last, route.targetPort.point); + for (var index = 0; index < route.points.length; index += 1) { + final point = route.points[index]; + expect(point.x.isFinite, isTrue); + expect(point.y.isFinite, isTrue); + expect(point.x, greaterThanOrEqualTo(-_epsilon)); + expect(point.y, greaterThanOrEqualTo(-_epsilon)); + expect(point.x, lessThanOrEqualTo(width + _epsilon)); + expect(point.y, lessThanOrEqualTo(height + _epsilon)); + if (index > 0) { + final previous = route.points[index - 1]; + expect( + previous.x == point.x || previous.y == point.y, + isTrue, + reason: 'edge ${route.id} segment ${index - 1} is not orthogonal', + ); + expect(previous, isNot(point), reason: 'zero-length segment'); + } + } + _expectPort(route.sourcePort, layout.nodeFor(route.source)!); + _expectPort(route.targetPort, layout.nodeFor(route.target)!); +} + +void _expectPort(RoutePort port, GraphNodeBox box) { + switch (port.side) { + case RoutePortSide.right: + expect(port.point.x, closeTo(box.right, _epsilon)); + expect(port.point.y, greaterThanOrEqualTo(box.y - _epsilon)); + expect(port.point.y, lessThanOrEqualTo(box.bottom + _epsilon)); + case RoutePortSide.left: + expect(port.point.x, closeTo(box.x, _epsilon)); + expect(port.point.y, greaterThanOrEqualTo(box.y - _epsilon)); + expect(port.point.y, lessThanOrEqualTo(box.bottom + _epsilon)); + case RoutePortSide.top: + expect(port.point.y, closeTo(box.y, _epsilon)); + expect(port.point.x, greaterThanOrEqualTo(box.x - _epsilon)); + expect(port.point.x, lessThanOrEqualTo(box.right + _epsilon)); + case RoutePortSide.bottom: + expect(port.point.y, closeTo(box.bottom, _epsilon)); + expect(port.point.x, greaterThanOrEqualTo(box.x - _epsilon)); + expect(port.point.x, lessThanOrEqualTo(box.right + _epsilon)); + } +} + +void _expectNoNodeInterior(EdgeRoute route, GraphLayout layout) { + for (var index = 1; index < route.points.length; index += 1) { + final a = route.points[index - 1]; + final b = route.points[index]; + for (final node in layout.nodes) { + if (a.y == b.y) { + final left = math.min(a.x, b.x); + final right = math.max(a.x, b.x); + final crosses = + a.y > node.y + _epsilon && + a.y < node.bottom - _epsilon && + right > node.x + _epsilon && + left < node.right - _epsilon; + expect( + crosses, + isFalse, + reason: 'edge ${route.id} crosses node ${node.key} horizontally', + ); + } else { + final top = math.min(a.y, b.y); + final bottom = math.max(a.y, b.y); + final crosses = + a.x > node.x + _epsilon && + a.x < node.right - _epsilon && + bottom > node.y + _epsilon && + top < node.bottom - _epsilon; + expect( + crosses, + isFalse, + reason: 'edge ${route.id} crosses node ${node.key} vertically', + ); + } + } + } +} + +bool _overlaps( + double ax, + double ay, + double aw, + double ah, + double bx, + double by, + double bw, + double bh, +) { + return ax < bx + bw && ax + aw > bx && ay < by + bh && ay + ah > by; +} diff --git a/app/test/features/graph/routing/routing_fixtures.dart b/app/test/features/graph/routing/routing_fixtures.dart new file mode 100644 index 00000000..7a155b03 --- /dev/null +++ b/app/test/features/graph/routing/routing_fixtures.dart @@ -0,0 +1,143 @@ +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/layout/graph_node_layout.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; +import 'package:pipelines_app/features/graph/routing/graph_edge_routing.dart'; +import 'package:pipelines_app/features/graph/routing/route_models.dart'; + +import '../layout/layout_fixtures.dart' as layout; +import '../domain/graph_fixtures.dart' as domain; + +/// Definitions, measured extents and configs shared by the routing tests. + +GraphLayoutConfig routingLayoutConfig({ + double columnGap = 80, + double rowGap = 16, + double padding = 8, +}) { + return GraphLayoutConfig( + columnGap: columnGap, + rowGap: rowGap, + padding: padding, + ); +} + +RoutingConfig routingConfig({ + double nodeClearance = 8, + double laneSpacing = 28, + double corridorSpacing = 20, + double portSpacing = 12, + double labelGap = 4, + double boundsPadding = 4, +}) { + return RoutingConfig( + nodeClearance: nodeClearance, + laneSpacing: laneSpacing, + corridorSpacing: corridorSpacing, + portSpacing: portSpacing, + labelGap: labelGap, + boundsPadding: boundsPadding, + ); +} + +GraphLayout layoutFor( + Map graph, { + Map? extents, + GraphLayoutConfig? config, +}) { + final nodes = graphNodes(graph); + return layoutGraphNodes( + nodes: nodes, + edges: graphEdges(graph), + extents: extents ?? layout.uniformExtents(nodes), + config: config ?? routingLayoutConfig(), + ); +} + +/// Measured label boxes sized from their text, as a renderer would supply them. +Map labelsFor( + Iterable edges, { + double charWidth = 7, + double padding = 12, + double height = 18, +}) { + return { + for (final edge in edges) + edge.id: LabelExtent( + width: edge.label.length * charWidth + padding, + height: height, + ), + }; +} + +/// One box per edge at an explicit size, used for wide-label checks. +Map fixedLabels( + Iterable edges, { + double width = 52, + double height = 18, +}) { + return { + for (final edge in edges) + edge.id: LabelExtent(width: width, height: height), + }; +} + +GraphRouting routeFor( + Map graph, { + Map? extents, + Map? labels, + GraphLayoutConfig? layoutConfig, + RoutingConfig? config, +}) { + final layout = layoutFor(graph, extents: extents, config: layoutConfig); + final edges = graphEdges(graph); + return routeGraphEdges( + layout: layout, + edges: edges, + labelExtents: labels ?? labelsFor(edges), + config: config ?? routingConfig(), + ); +} + +/// Three outcomes from `a` to the same target `b`, then `b` to Success. +Map parallelOutcomesGraph() => { + 'stages': [ + domain.stage( + 'a', + edges: { + 'success': 'b', + 'approved': 'b', + 'rejected': 'b', + }, + ), + domain.stage('b', edges: {'success': '#success'}), + ], +}; + +/// A single stage that retries itself and has no terminal pair. +Map selfLoopOnlyGraph() => { + 'stages': [ + domain.stage('a', edges: {'retry': 'a'}), + ], +}; + +Map chainGraphFixture() => layout.chainGraph(4); + +Map diamondGraphFixture() => layout.diamondGraphFixture(); + +Map cycleGraphFixture() => layout.cycleGraph(); + +Map selfLoopGraphFixture() => layout.selfLoopGraphFixture(); + +Map disconnectedGraphFixture() => layout.disconnectedGraph(); + +Map incompleteGraphFixture() => + layout.incompleteGraphFixture(); + +/// Three stages in one strongly connected component with no terminals. +Map cycleThreeGraph() => { + 'stages': [ + domain.stage('a', edges: {'success': 'b'}), + domain.stage('b', edges: {'success': 'c'}), + domain.stage('c', edges: {'success': 'a'}), + ], +}; diff --git a/app/test/features/graph/widgets/graph_stage_node_render_test.dart b/app/test/features/graph/widgets/graph_stage_node_render_test.dart new file mode 100644 index 00000000..113a09ae --- /dev/null +++ b/app/test/features/graph/widgets/graph_stage_node_render_test.dart @@ -0,0 +1,210 @@ +import 'dart:typed_data'; +import 'dart:ui' as ui; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart'; + +const _stage = GraphNode(key: 'build', terminal: false, stageIndex: 1); +const _long = GraphNode( + key: 'implementer-with-an-unshortened-stage-label', + terminal: false, + stageIndex: 2, +); +const _longLabel = 'implementer-with-an-unshortened-stage-label'; + +Widget _material(Widget child) => MaterialApp( + home: Scaffold(body: Center(child: child)), +); + +Widget _cupertino(Widget child) => CupertinoApp( + home: CupertinoPageScaffold(child: Center(child: child)), +); + +/// The node centred on an opaque page, inside its own repaint boundary so the +/// painted result can be read back as pixels. +Widget _framed(Key key, Widget Function(Widget) wrap, Widget child) => wrap( + RepaintBoundary( + key: key, + child: ColoredBox( + color: const Color(0xFFFFFFFF), + child: Center(child: child), + ), + ), +); + +Finder get _materialSurface => + find.descendant(of: find.byType(Card), matching: find.byType(Material)); + +Finder _visual(String label) => find.byWidgetPredicate( + (widget) => widget is Text && widget.data?.replaceAll('\u200B', '') == label, +); + +final class _Shot { + _Shot(this.bytes, this.size, this.origin); + + final Uint8List bytes; + final Size size; + final Offset origin; + + Color at(Offset global) { + final x = (global.dx - origin.dx).round(); + final y = (global.dy - origin.dy).round(); + expect(x, inInclusiveRange(0, size.width.round() - 1)); + expect(y, inInclusiveRange(0, size.height.round() - 1)); + final i = (y * size.width.round() + x) * 4; + return Color.fromARGB(bytes[i + 3], bytes[i], bytes[i + 1], bytes[i + 2]); + } +} + +Future<_Shot> _shot(WidgetTester tester, Key key) async { + final boundary = tester.renderObject(find.byKey(key)); + final image = (await tester.runAsync(() => boundary.toImage()))!; + final data = (await tester.runAsync( + () => image.toByteData(format: ui.ImageByteFormat.rawRgba), + ))!; + image.dispose(); + return _Shot( + data.buffer.asUint8List(), + tester.getSize(find.byKey(key)), + tester.getTopLeft(find.byKey(key)), + ); +} + +double _distance(Color a, Color b) => [ + (a.r - b.r).abs() * 255, + (a.g - b.g).abs() * 255, + (a.b - b.b).abs() * 255, +].reduce((value, next) => value > next ? value : next); + +void main() { + testWidgets('material node paints a rounded surface, not a stadium', ( + tester, + ) async { + await tester.pumpWidget( + _material(GraphStageNode(node: _stage, onSelected: (_) {})), + ); + final material = tester.widget(_materialSurface); + expect( + material.shape, + isA(), + reason: + 'Material button shapes are stadiums; a stadium border cuts into a ' + 'wrapped label the way the reviewed 2x control did', + ); + }); + + testWidgets('wrapped glyph boxes stay inside the painted material surface', ( + tester, + ) async { + for (final scale in [1.0, 2.0]) { + await tester.pumpWidget( + _material( + Builder( + builder: (context) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(scale)), + child: SizedBox( + width: 150, + child: GraphStageNode(node: _long, onSelected: (_) {}), + ), + ), + ), + ), + ); + expect(tester.takeException(), isNull); + + final rect = tester.getRect(_materialSurface); + final shape = tester.widget(_materialSurface).shape!; + final path = shape.getOuterPath(Offset.zero & rect.size); + final paragraph = tester.renderObject( + _visual(_longLabel), + ); + final boxes = paragraph.getBoxesForSelection( + TextSelection( + baseOffset: 0, + extentOffset: paragraph.text.toPlainText().length, + ), + ); + expect(boxes, isNotEmpty); + for (final box in boxes) { + final corners = [ + Offset(box.left, box.top), + Offset(box.right, box.top), + Offset(box.left, box.bottom), + Offset(box.right, box.bottom), + ]; + for (final corner in corners) { + final local = paragraph.localToGlobal(corner) - rect.topLeft; + expect( + path.contains(local), + isTrue, + reason: + 'at ${scale}x a glyph box corner at $local escapes the ' + 'painted control boundary $rect', + ); + } + } + } + }); + + testWidgets('unselected cupertino node paints a visible container', ( + tester, + ) async { + final key = GlobalKey(); + await tester.pumpWidget( + _framed( + key, + _cupertino, + GraphStageNode(node: _stage, onSelected: (_) {}), + ), + ); + final shot = await _shot(tester, key); + final rect = tester.getRect(find.byType(CupertinoButton)); + // Just inside the left edge of the control, clear of the label's inset. + final body = shot.at(rect.centerLeft + const Offset(4, 0)); + final page = shot.at(const Offset(4, 4)); + expect( + _distance(body, page), + greaterThan(24), + reason: 'an unselected cupertino node needs its own visible surface', + ); + }); + + testWidgets('selected state changes the painted surface in both hosts', ( + tester, + ) async { + for (final wrap in [_material, _cupertino]) { + final colors = {}; + for (final selected in [false, true]) { + final key = GlobalKey(); + await tester.pumpWidget( + _framed( + key, + wrap, + GraphStageNode( + node: _stage, + selected: selected, + onSelected: (_) {}, + ), + ), + ); + final shot = await _shot(tester, key); + final rect = tester.getRect(find.byType(GraphStageNode)); + colors[selected] = shot.at(rect.centerLeft + const Offset(4, 0)); + } + expect( + _distance(colors[false]!, colors[true]!), + greaterThan(16), + reason: + 'selection must be visible, not only announced: the surface fill ' + 'and the outlined border change together', + ); + } + }); +} diff --git a/app/test/features/graph/widgets/graph_stage_node_test.dart b/app/test/features/graph/widgets/graph_stage_node_test.dart new file mode 100644 index 00000000..3d2ade29 --- /dev/null +++ b/app/test/features/graph/widgets/graph_stage_node_test.dart @@ -0,0 +1,235 @@ +import 'dart:ui' show Tristate; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart'; + +const _stage = GraphNode(key: 'build', terminal: false, stageIndex: 1); +const _success = GraphNode(key: '#success', terminal: true); +const _failure = GraphNode(key: '#failure', terminal: true); + +Widget _material(Widget child) => MaterialApp( + home: Scaffold(body: Center(child: child)), +); + +Widget _cupertino(Widget child) => CupertinoApp( + home: CupertinoPageScaffold(child: Center(child: child)), +); + +/// Applies a 2x text scale below the app so the fixture renders as a real +/// scale-2 layout rather than a test-only text property. +Widget _scaled(Widget child) => Builder( + builder: (context) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: const TextScaler.linear(2)), + child: child, + ), +); + +/// The merged accessibility node a screen reader receives for one node. +SemanticsData _semantics(WidgetTester tester) => + tester.getSemantics(find.byType(MergeSemantics)).getSemanticsData(); + +void _expectSelectable(WidgetTester tester, {required bool selected}) { + final data = _semantics(tester); + expect(data.flagsCollection.isButton, isTrue); + expect(data.flagsCollection.isSelected == Tristate.isTrue, selected); + expect(data.actions & SemanticsAction.tap.index, isNot(0)); +} + +/// Finds the visual line for [label], ignoring its invisible break chars. +Finder _visual(String label) => find.byWidgetPredicate( + (widget) => widget is Text && widget.data?.replaceAll('\u200B', '') == label, +); + +void main() { + testWidgets('selection callback carries the exact definition key', ( + tester, + ) async { + final picked = []; + await tester.pumpWidget( + _material(GraphStageNode(node: _success, onSelected: picked.add)), + ); + + await tester.tap(find.byType(GraphStageNode)); + await tester.pump(); + + expect(picked, ['#success']); + _expectSelectable(tester, selected: false); + expect(_semantics(tester).label, 'Success'); + }); + + testWidgets('selected node is announced selected in both native hosts', ( + tester, + ) async { + await tester.pumpWidget( + _material( + GraphStageNode(node: _stage, selected: true, onSelected: (_) {}), + ), + ); + expect(find.byType(Card), findsOneWidget); + expect(find.byType(InkWell), findsOneWidget); + _expectSelectable(tester, selected: true); + + await tester.pumpWidget( + _cupertino( + GraphStageNode(node: _stage, selected: true, onSelected: (_) {}), + ), + ); + expect(find.byType(CupertinoButton), findsOneWidget); + expect(find.byType(Card), findsNothing); + _expectSelectable(tester, selected: true); + }); + + testWidgets('unselected node is not announced selected', (tester) async { + await tester.pumpWidget( + _material(GraphStageNode(node: _stage, onSelected: (_) {})), + ); + expect(find.byType(Card), findsOneWidget); + _expectSelectable(tester, selected: false); + }); + + testWidgets('keyboard activation selects the node', (tester) async { + for (final wrap in [_material, _cupertino]) { + final picked = []; + await tester.pumpWidget( + wrap(GraphStageNode(node: _stage, onSelected: picked.add)), + ); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.pumpAndSettle(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect(picked, ['build']); + } + }); + + testWidgets('keyboard selection keeps focus inside the material node', ( + tester, + ) async { + var selected = false; + await tester.pumpWidget( + _material( + StatefulBuilder( + builder: (context, setState) => GraphStageNode( + node: _stage, + selected: selected, + onSelected: (_) => setState(() => selected = true), + ), + ), + ), + ); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.pumpAndSettle(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect(selected, isTrue); + + final focused = FocusManager.instance.primaryFocus; + expect(focused?.context, isNotNull); + expect( + focused?.context?.findAncestorWidgetOfExactType(), + isNotNull, + reason: 'switching card emphasis must not drop keyboard focus', + ); + }); + + testWidgets('long label wraps unshortened in a narrow 2x layout', ( + tester, + ) async { + const label = 'implementer-with-an-unshortened-stage-label'; + const node = GraphNode(key: label, terminal: false, stageIndex: 0); + for (final wrap in [_material, _cupertino]) { + await tester.pumpWidget( + wrap( + _scaled( + SizedBox( + width: 150, + child: GraphStageNode(node: node, onSelected: (_) {}), + ), + ), + ), + ); + + expect(tester.takeException(), isNull); + final text = tester.widget(_visual(label)); + expect(text.data!.replaceAll('\u200B', ''), label); + expect(text.maxLines, isNull); + expect(text.overflow, isNull); + final paragraph = tester.renderObject(_visual(label)); + expect(paragraph.size.width, lessThanOrEqualTo(150)); + expect( + paragraph.size.height, + greaterThan(50), + reason: 'the 2x label must occupy more than one 2x text line', + ); + // No glyph may paint outside the paragraph: every laid-out line, + // including a hyphen-broken segment, fits the width the control gave it. + final painter = TextPainter( + text: paragraph.text, + textDirection: paragraph.textDirection, + textScaler: paragraph.textScaler, + textAlign: paragraph.textAlign, + )..layout(maxWidth: paragraph.size.width); + expect( + painter.computeLineMetrics().every( + (line) => line.width <= paragraph.size.width + 0.5, + ), + isTrue, + reason: 'an unshortened label must wrap, not paint over the control', + ); + } + }); + + testWidgets('terminal shows its definition label and no invented status', ( + tester, + ) async { + for (final node in [_success, _failure]) { + await tester.pumpWidget( + _material(GraphStageNode(node: node, onSelected: (_) {})), + ); + final texts = tester + .widgetList(find.byType(Text)) + .map((text) => text.data?.replaceAll('\u200B', '')) + .toList(); + expect(texts, [node.label]); + expect(texts.join(' ').toLowerCase(), isNot(contains('executed'))); + expect(texts.join(' ').toLowerCase(), isNot(contains('visited'))); + expect(_semantics(tester).label, node.label); + expect(_semantics(tester).label, isNot(contains('\u200B'))); + } + }); + + testWidgets('a recorded status is shown verbatim', (tester) async { + await tester.pumpWidget( + _cupertino( + GraphStageNode( + node: _stage, + recordedStatus: 'failed', + onSelected: (_) {}, + ), + ), + ); + expect(_visual('build'), findsOneWidget); + expect(_visual('failed'), findsOneWidget); + final label = _semantics(tester).label; + expect(label, contains('build')); + expect(label, contains('failed')); + expect(label, isNot(contains('\u200B'))); + }); + + testWidgets('a blank recorded status adds no line', (tester) async { + await tester.pumpWidget( + _material( + GraphStageNode(node: _stage, recordedStatus: ' ', onSelected: (_) {}), + ), + ); + expect(find.byType(Text), findsOneWidget); + expect(_semantics(tester).label, 'build'); + }); +} diff --git a/app/test/features/runs/actions/cancel_action_test.dart b/app/test/features/runs/actions/cancel_action_test.dart new file mode 100644 index 00000000..e50a6eea --- /dev/null +++ b/app/test/features/runs/actions/cancel_action_test.dart @@ -0,0 +1,192 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/cancel_eligibility.dart'; +import 'package:pipelines_app/features/runs/actions/cancel_wording.dart'; + +import 'cancel_test_support.dart'; + +void main() { + test('cancel eligibility matches the web canCancel exactly', () { + final cases = <(String, JsonMap, bool)>[ + ('executing run', executingRun(), true), + ( + 'waiting while a session export is pending', + executingRun(executing: false, status: 'waiting', exportPending: 2), + true, + ), + ( + 'waiting with no pending export', + executingRun(executing: false, status: 'waiting'), + false, + ), + ( + 'status says running but the run is not executing', + executingRun(executing: false), + false, + ), + ( + 'cancellation already requested', + executingRun(cancelRequested: true), + false, + ), + ('cleanup unconfirmed', executingRun(cleanupUnconfirmed: true), false), + ( + 'completed run', + executingRun(executing: false, status: 'succeeded'), + false, + ), + ('failed run', executingRun(executing: false, status: 'failed'), false), + ]; + for (final (label, run, expected) in cases) { + expect(canCancelRun(run), expected, reason: label); + } + expect(canCancelRun(null), isFalse); + }); + + testWidgets( + 'material cancel asks first, Keep sends nothing, then sends the envelope', + (tester) async { + final accepted = acceptedCancelRun(); + final gateway = FakeCancelGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await tester.pumpWidget( + cancelApp( + CancelHost( + gateway: gateway, + initial: executingRun(), + changed: changed, + ), + cupertino: false, + ), + ); + + expect(find.byKey(cancelActionKey), findsOneWidget); + expect(find.byType(FilledButton), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text(cancelDialogTitle(7)), findsOneWidget); + expect(find.text(cancelDialogMessage), findsOneWidget); + expect(find.text(cancelKeepLabel), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(cancelKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(cancelActionKey), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(cancelConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['cancel_run']); + expect(gateway.calls.single.fields, {'run_id': 7}); + expect(changed.single, equals(accepted)); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(cancelActionKey), findsNothing); + }, + ); + + testWidgets( + 'cupertino cancel uses a native prompt and sends only on confirm', + (tester) async { + final accepted = acceptedCancelRun(); + final gateway = FakeCancelGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await tester.pumpWidget( + cancelApp( + CancelHost( + gateway: gateway, + initial: executingRun(), + changed: changed, + ), + cupertino: true, + ), + ); + + expect(find.byKey(cancelActionKey), findsOneWidget); + expect(find.byType(CupertinoButton), findsOneWidget); + expect(find.byType(FilledButton), findsNothing); + + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.byType(AlertDialog), findsNothing); + expect(find.text(cancelDialogTitle(7)), findsOneWidget); + expect(find.text(cancelDialogMessage), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(cancelKeepKey)); + await tester.pumpAndSettle(); + expect(gateway.calls, isEmpty); + expect(find.byType(CupertinoAlertDialog), findsNothing); + + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(cancelConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['cancel_run']); + expect(gateway.calls.single.fields, {'run_id': 7}); + expect(changed.single, equals(accepted)); + expect(find.byType(CupertinoAlertDialog), findsNothing); + expect(find.byKey(cancelActionKey), findsNothing); + }, + ); + + testWidgets('the action is absent for runs the web does not cancel', ( + tester, + ) async { + final gateway = FakeCancelGateway( + (type, fields) async => {'run_detail': executingRun()}, + ); + final changed = []; + final cases = <(String, JsonMap, bool)>[ + ('executing', executingRun(), true), + ( + 'export wait', + executingRun(executing: false, status: 'waiting', exportPending: 1), + true, + ), + ( + 'no export wait', + executingRun(executing: false, status: 'waiting'), + false, + ), + ('stale running status', executingRun(executing: false), false), + ('already stopping', executingRun(cancelRequested: true), false), + ('cleanup unconfirmed', executingRun(cleanupUnconfirmed: true), false), + ('finished', executingRun(executing: false, status: 'succeeded'), false), + ]; + for (final (label, run, visible) in cases) { + await tester.pumpWidget( + cancelApp( + CancelHost( + key: ValueKey(label), + gateway: gateway, + initial: run, + changed: changed, + ), + cupertino: false, + ), + ); + expect( + find.byKey(cancelActionKey), + visible ? findsOneWidget : findsNothing, + reason: label, + ); + } + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + }); +} diff --git a/app/test/features/runs/actions/cancel_resilience_test.dart b/app/test/features/runs/actions/cancel_resilience_test.dart new file mode 100644 index 00000000..675c58b2 --- /dev/null +++ b/app/test/features/runs/actions/cancel_resilience_test.dart @@ -0,0 +1,271 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/runs/actions/cancel_wording.dart'; + +import 'cancel_test_support.dart'; + +Future _pump( + WidgetTester tester, + FakeCancelGateway gateway, + List changed, { + bool cupertino = false, + double textScale = 1, + JsonMap? run, +}) async { + await tester.pumpWidget( + cancelApp( + CancelHost( + gateway: gateway, + initial: run ?? executingRun(), + changed: changed, + ), + cupertino: cupertino, + textScale: textScale, + ), + ); +} + +Future _openAndConfirm(WidgetTester tester) async { + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(cancelConfirmKey)); +} + +void main() { + testWidgets('a refusal stays visible and delivers the resynced run', ( + tester, + ) async { + const refusal = 'run 7 already completed; nothing to cancel'; + final refreshed = executingRun(executing: false, status: 'succeeded'); + final gateway = FakeCancelGateway((type, fields) async { + if (type == 'cancel_run') throw const ProtocolError(refusal); + expect(type, 'get_run'); + return {'run_detail': refreshed}; + }); + final changed = []; + await _pump(tester, gateway, changed); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['cancel_run', 'get_run']); + expect(gateway.calls.first.fields, {'run_id': 7}); + expect(gateway.calls.last.fields, {'run_id': 7}); + expect(find.text(refusal), findsOneWidget); + expect(find.byKey(cancelErrorKey), findsOneWidget); + expect(find.byType(AlertDialog), findsOneWidget); + expect(changed.single, equals(refreshed)); + expect(find.byKey(cancelActionKey), findsNothing); + }); + + testWidgets('a failed resync never hides the refusal or invents a run', ( + tester, + ) async { + const refusal = 'server refused to stop the run'; + final gateway = FakeCancelGateway((type, fields) async { + if (type == 'cancel_run') throw const ProtocolError(refusal); + throw const NotConnectedError(); + }); + final changed = []; + await _pump(tester, gateway, changed); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['cancel_run', 'get_run']); + expect(find.text(refusal), findsOneWidget); + expect(find.byType(AlertDialog), findsOneWidget); + expect(changed, isEmpty); + expect(find.byKey(cancelActionKey), findsOneWidget); + }); + + testWidgets('a refusal and Keep do not wait for the resync', (tester) async { + const refusal = 'run 7 is already stopping'; + final resync = Completer(); + final gateway = FakeCancelGateway((type, fields) { + if (type == 'cancel_run') throw const ProtocolError(refusal); + return resync.future; + }); + final changed = []; + await _pump(tester, gateway, changed); + + await _openAndConfirm(tester); + await tester.pump(); + + expect(find.text(refusal), findsOneWidget); + expect( + tester.widget(find.byKey(cancelKeepKey)).onPressed, + isNotNull, + ); + expect( + tester.widget(find.byKey(cancelConfirmKey)).onPressed, + isNull, + ); + expect(changed, isEmpty); + + await tester.tap(find.byKey(cancelKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + + resync.complete({ + 'run_detail': executingRun(executing: false, status: 'succeeded'), + }); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed.single['status'], 'succeeded'); + }); + + testWidgets('a late resync after disposal is ignored safely', (tester) async { + final resync = Completer(); + final gateway = FakeCancelGateway((type, fields) { + if (type == 'cancel_run') throw const ProtocolError('already stopped'); + return resync.future; + }); + final changed = []; + await _pump(tester, gateway, changed); + + await _openAndConfirm(tester); + await tester.pump(); + expect(gateway.calls.map((call) => call.type), ['cancel_run', 'get_run']); + + await tester.pumpWidget(const SizedBox()); + resync.complete({'run_detail': acceptedCancelRun()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('an ineligible resync disables confirm but keeps the refusal', ( + tester, + ) async { + const refusal = 'run 7 already completed; nothing to cancel'; + final finished = executingRun(executing: false, status: 'succeeded'); + final gateway = FakeCancelGateway((type, fields) async { + if (type == 'cancel_run') throw const ProtocolError(refusal); + return {'run_detail': finished}; + }); + final changed = []; + await _pump(tester, gateway, changed); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['cancel_run', 'get_run']); + expect(find.text(refusal), findsOneWidget); + expect( + tester.widget(find.byKey(cancelConfirmKey)).onPressed, + isNull, + ); + expect( + tester.widget(find.byKey(cancelKeepKey)).onPressed, + isNotNull, + ); + + await tester.tap(find.byKey(cancelConfirmKey)); + await tester.pump(); + expect(gateway.calls.map((call) => call.type), ['cancel_run', 'get_run']); + + await tester.tap(find.byKey(cancelKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(cancelActionKey), findsNothing); + expect(changed.single, equals(finished)); + }); + + testWidgets( + 'confirm cannot submit twice while the cancellation is in flight', + (tester) async { + final reply = Completer(); + final gateway = FakeCancelGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + final confirm = find.byKey(cancelConfirmKey); + await tester.tap(confirm); + await tester.tap(confirm); + await tester.pump(); + + expect( + gateway.calls.where((call) => call.type == 'cancel_run'), + hasLength(1), + ); + expect( + tester.widget(find.byKey(cancelConfirmKey)).onPressed, + isNull, + ); + expect( + tester.widget(find.byKey(cancelKeepKey)).onPressed, + isNull, + ); + expect(find.byType(AlertDialog), findsOneWidget); + + reply.complete({'run_detail': acceptedCancelRun()}); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(changed, hasLength(1)); + }, + ); + + testWidgets('a late reply after disposal is ignored safely', (tester) async { + final reply = Completer(); + final gateway = FakeCancelGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + + await _openAndConfirm(tester); + await tester.pump(); + expect(gateway.calls, hasLength(1)); + + await tester.pumpWidget(const SizedBox()); + reply.complete({'run_detail': acceptedCancelRun()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('both prompts fit 2x text at a narrow width', (tester) async { + tester.view.physicalSize = const Size(320, 480); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + for (final cupertino in [false, true]) { + final gateway = FakeCancelGateway( + (type, fields) async => {'run_detail': acceptedCancelRun()}, + ); + await _pump( + tester, + gateway, + [], + cupertino: cupertino, + textScale: 2, + ); + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino'); + expect(find.text(cancelDialogTitle(7)), findsOneWidget); + expect(find.text(cancelDialogMessage), findsOneWidget); + expect( + cupertino + ? find.byType(CupertinoAlertDialog) + : find.byType(AlertDialog), + findsOneWidget, + ); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(cancelKeepKey)); + await tester.pumpAndSettle(); + } + }); +} diff --git a/app/test/features/runs/actions/cancel_test_support.dart b/app/test/features/runs/actions/cancel_test_support.dart new file mode 100644 index 00000000..7acee8d9 --- /dev/null +++ b/app/test/features/runs/actions/cancel_test_support.dart @@ -0,0 +1,101 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/cancel_run_action.dart'; + +typedef CancelHandler = Future Function(String type, JsonMap fields); + +/// A fake gateway that records every request and never owns a socket. +class FakeCancelGateway implements ApiGateway { + FakeCancelGateway(this.handler); + + final CancelHandler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap executingRun({ + num id = 7, + bool executing = true, + String status = 'running', + int exportPending = 0, + bool cancelRequested = false, + bool cleanupUnconfirmed = false, +}) => { + 'id': id, + 'title': 'Nightly build', + 'status': status, + 'executing': executing, + 'export_pending_sequence': exportPending, + 'cancel_requested': cancelRequested, + 'cleanup_unconfirmed': cleanupUnconfirmed, +}; + +JsonMap acceptedCancelRun() => + executingRun(executing: false, status: 'canceled', cancelRequested: true); + +/// Owns the run like a run-detail screen would, so the callback's returned +/// server detail is what the action renders next. +class CancelHost extends StatefulWidget { + const CancelHost({ + super.key, + required this.gateway, + required this.initial, + required this.changed, + }); + + final FakeCancelGateway gateway; + final JsonMap initial; + final List changed; + + @override + State createState() => _CancelHostState(); +} + +class _CancelHostState extends State { + late JsonMap _run = widget.initial; + + @override + Widget build(BuildContext context) { + return CancelRunAction( + run: _run, + gateway: widget.gateway, + onRunChanged: (run) { + widget.changed.add(run); + setState(() => _run = run); + }, + ); + } +} + +Widget cancelApp( + Widget child, { + required bool cupertino, + double textScale = 1, +}) { + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + if (cupertino) { + return CupertinoApp( + builder: media, + home: CupertinoPageScaffold(child: Center(child: child)), + ); + } + return MaterialApp( + builder: media, + home: Scaffold(body: Center(child: child)), + ); +} diff --git a/app/test/features/runs/actions/decision_action_test.dart b/app/test/features/runs/actions/decision_action_test.dart new file mode 100644 index 00000000..b756db79 --- /dev/null +++ b/app/test/features/runs/actions/decision_action_test.dart @@ -0,0 +1,265 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/decision_action.dart'; +import 'package:pipelines_app/features/runs/actions/decision_wording.dart'; + +typedef _Handler = Future Function(String type, JsonMap fields); + +class _FakeGateway implements ApiGateway { + _FakeGateway(this.handler); + + final _Handler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap _waitingRun({ + String status = 'waiting', + int exportPending = 0, + String type = 'human', + List options = const ['go', 'skip'], +}) => { + 'id': 7, + 'title': 'Report', + 'name': 'Build', + 'status': status, + 'current_stage': 'human', + 'export_pending_sequence': exportPending, + 'graph': { + 'stages': [ + { + 'key': 'human', + 'type': type, + 'prompt': 'Graph prompt', + 'edges': {'go': '#', 'skip': 'finish'}, + }, + ], + }, + 'steps': [ + { + 'sequence': 1, + 'status': 'waiting', + 'stage': 'human', + 'output': {'prompt': 'Ship it?', 'options': options}, + }, + ], +}; + +JsonMap _decided() => { + ..._waitingRun(), + 'status': 'succeeded', + 'steps': const [], +}; + +Widget _app(Widget child, {required bool cupertino, double textScale = 1}) { + if (cupertino) { + return CupertinoApp( + builder: (context, app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ), + home: CupertinoPageScaffold(child: Center(child: child)), + ); + } + return MaterialApp( + builder: (context, app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ), + home: Scaffold(body: Center(child: child)), + ); +} + +Future _pump( + WidgetTester tester, + _FakeGateway gateway, + JsonMap run, { + required bool cupertino, + required List changed, + double textScale = 1, +}) async { + await tester.pumpWidget( + _app( + HumanDecisionAction( + run: run, + gateway: gateway, + onRunChanged: changed.add, + ), + cupertino: cupertino, + textScale: textScale, + ), + ); +} + +Future _open(WidgetTester tester) async { + await tester.tap(find.byKey(decisionActionKey)); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets( + 'material decision waits for option and confirm, then sends exact fields', + (tester) async { + final gateway = _FakeGateway( + (type, fields) async => { + 'run_detail': type == 'decide_run' ? _decided() : _waitingRun(), + }, + ); + final changed = []; + await _pump( + tester, + gateway, + _waitingRun(), + cupertino: false, + changed: changed, + ); + + expect(find.byKey(decisionActionKey), findsOneWidget); + expect(find.byType(FilledButton), findsOneWidget); + expect(gateway.calls, isEmpty); + + await _open(tester); + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text(decisionWaitingTitle), findsOneWidget); + expect(find.text('Ship it?'), findsOneWidget); + expect(find.text('→ SUCCESS'), findsOneWidget); + expect(gateway.calls, isEmpty); + + final confirm = find.widgetWithText(FilledButton, decisionConfirmLabel); + expect(tester.widget(confirm).onPressed, isNull); + + await tester.tap(find.text('go')); + await tester.pump(); + expect(gateway.calls, isEmpty); + expect(tester.widget(confirm).onPressed, isNotNull); + + await tester.enterText(find.byKey(decisionFeedbackKey), ' looks good '); + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['decide_run']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'stage': 'human', + 'option': 'go', + 'feedback': 'looks good', + }); + expect(changed.single['status'], 'succeeded'); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(decisionActionKey), findsNothing); + }, + ); + + testWidgets( + 'cupertino decision uses a native dialog and omits empty feedback', + (tester) async { + final gateway = _FakeGateway( + (type, fields) async => { + 'run_detail': type == 'decide_run' ? _decided() : _waitingRun(), + }, + ); + final changed = []; + await _pump( + tester, + gateway, + _waitingRun(), + cupertino: true, + changed: changed, + ); + + expect(find.byKey(decisionActionKey), findsOneWidget); + expect(find.byType(FilledButton), findsNothing); + await _open(tester); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.text(decisionWaitingTitle), findsOneWidget); + expect(gateway.calls, isEmpty); + + final confirm = find.widgetWithText( + CupertinoDialogAction, + decisionConfirmLabel, + ); + expect(tester.widget(confirm).onPressed, isNull); + await tester.tap(find.text('skip')); + await tester.pump(); + expect(gateway.calls, isEmpty); + + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['decide_run']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'stage': 'human', + 'option': 'skip', + }); + expect(changed.single['status'], 'succeeded'); + expect(find.byType(CupertinoAlertDialog), findsNothing); + }, + ); + + testWidgets('Cancel dismisses the draft without sending anything', ( + tester, + ) async { + final gateway = _FakeGateway( + (type, fields) async => {'run_detail': _decided()}, + ); + final changed = []; + await _pump( + tester, + gateway, + _waitingRun(), + cupertino: false, + changed: changed, + ); + + await _open(tester); + await tester.tap(find.text('go')); + await tester.pump(); + await tester.enterText(find.byKey(decisionFeedbackKey), 'not sent'); + await tester.tap(find.widgetWithText(TextButton, decisionCancelLabel)); + await tester.pumpAndSettle(); + + expect(find.byType(AlertDialog), findsNothing); + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + expect(find.byKey(decisionActionKey), findsOneWidget); + }); + + testWidgets('the action is absent unless a run is genuinely waiting', ( + tester, + ) async { + final gateway = _FakeGateway( + (type, fields) async => {'run_detail': _waitingRun()}, + ); + final changed = []; + for (final (label, run) in [ + ('not waiting', _waitingRun(status: 'running')), + ('export pending', _waitingRun(exportPending: 2)), + ('model stage', _waitingRun(type: 'model')), + ]) { + await _pump(tester, gateway, run, cupertino: false, changed: changed); + expect( + find.byKey(decisionActionKey), + findsNothing, + reason: '$label must not offer a decision', + ); + } + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + }); +} diff --git a/app/test/features/runs/actions/decision_resilience_test.dart b/app/test/features/runs/actions/decision_resilience_test.dart new file mode 100644 index 00000000..e755ddc5 --- /dev/null +++ b/app/test/features/runs/actions/decision_resilience_test.dart @@ -0,0 +1,351 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/runs/actions/decision_action.dart'; +import 'package:pipelines_app/features/runs/actions/decision_wording.dart'; + +typedef _Handler = Future Function(String type, JsonMap fields); + +class _FakeGateway implements ApiGateway { + _FakeGateway(this.handler); + + final _Handler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap _waitingRun() => { + 'id': 7, + 'title': 'Report', + 'status': 'waiting', + 'current_stage': 'human', + 'graph': { + 'stages': [ + { + 'key': 'human', + 'type': 'human', + 'prompt': 'Graph prompt', + 'edges': {'go': '#', 'skip': 'finish'}, + }, + ], + }, + 'steps': [ + { + 'sequence': 1, + 'status': 'waiting', + 'stage': 'human', + 'output': { + 'prompt': 'Ship it?', + 'options': ['go', 'skip'], + }, + }, + ], +}; + +JsonMap _decided() => { + ..._waitingRun(), + 'status': 'succeeded', + 'steps': const [], +}; + +Widget _app(Widget child, {required bool cupertino, double textScale = 1}) { + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + if (cupertino) { + return CupertinoApp( + builder: media, + home: CupertinoPageScaffold(child: Center(child: child)), + ); + } + return MaterialApp( + builder: media, + home: Scaffold(body: Center(child: child)), + ); +} + +Future _pump( + WidgetTester tester, + _FakeGateway gateway, + List changed, { + bool cupertino = false, + double textScale = 1, +}) async { + await tester.pumpWidget( + _app( + HumanDecisionAction( + run: _waitingRun(), + gateway: gateway, + onRunChanged: changed.add, + ), + cupertino: cupertino, + textScale: textScale, + ), + ); +} + +Future _chooseGo(WidgetTester tester, {String feedback = ''}) async { + await tester.tap(find.byKey(decisionActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.text('go')); + await tester.pump(); + if (feedback.isNotEmpty) { + await tester.enterText(find.byKey(decisionFeedbackKey), feedback); + } +} + +void main() { + testWidgets('a refusal stays visible and keeps the selected draft', ( + tester, + ) async { + const refusal = 'option "go" is not a valid outcome; choose one of: skip'; + final gateway = _FakeGateway((type, fields) async { + if (type == 'decide_run') throw const ProtocolError(refusal); + expect(type, 'get_run'); + return { + 'run_detail': { + ..._waitingRun(), + 'status': 'failed', + 'steps': const [], + }, + }; + }); + final changed = []; + await _pump(tester, gateway, changed); + await _chooseGo(tester, feedback: ' keep me '); + + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['decide_run', 'get_run']); + expect(gateway.calls.last.fields, {'run_id': 7}); + expect(find.text(refusal), findsOneWidget); + expect(find.byType(AlertDialog), findsOneWidget); + expect( + tester + .widget>(find.byType(RadioGroup)) + .groupValue, + 'go', + ); + expect( + tester + .widget(find.byKey(decisionFeedbackKey)) + .controller + ?.text, + ' keep me ', + ); + expect(changed.single['status'], 'failed'); + expect(find.byKey(decisionActionKey), findsNothing); + }); + + testWidgets('a refusal is shown before the resync keeps the draft', ( + tester, + ) async { + const refusal = 'option "go" is no longer valid'; + final resync = Completer(); + final gateway = _FakeGateway((type, fields) { + if (type == 'decide_run') throw const ProtocolError(refusal); + return resync.future; + }); + final changed = []; + await _pump(tester, gateway, changed); + await _chooseGo(tester, feedback: ' keep me '); + + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pump(); + + expect(find.text(refusal), findsOneWidget); + expect(find.byType(AlertDialog), findsOneWidget); + expect( + tester + .widget>(find.byType(RadioGroup)) + .groupValue, + 'go', + ); + expect( + tester + .widget(find.byKey(decisionFeedbackKey)) + .controller + ?.text, + ' keep me ', + ); + expect( + tester + .widget( + find.widgetWithText(TextButton, decisionCancelLabel), + ) + .onPressed, + isNotNull, + ); + expect(changed, isEmpty); + + resync.complete({'run_detail': _decided()}); + await tester.pumpAndSettle(); + + expect(find.text(refusal), findsOneWidget); + expect( + tester + .widget( + find.widgetWithText(FilledButton, decisionConfirmLabel), + ) + .onPressed, + isNull, + ); + expect(changed.single['status'], 'succeeded'); + }); + + testWidgets('a failed resync keeps the draft and allows a retry', ( + tester, + ) async { + const refusal = 'server refused the decision'; + final gateway = _FakeGateway((type, fields) async { + if (type == 'decide_run') throw const ProtocolError(refusal); + throw const NotConnectedError(); + }); + final changed = []; + await _pump(tester, gateway, changed); + await _chooseGo(tester, feedback: ' keep me '); + + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['decide_run', 'get_run']); + expect(find.text(refusal), findsOneWidget); + expect( + tester + .widget>(find.byType(RadioGroup)) + .groupValue, + 'go', + ); + expect( + tester + .widget( + find.widgetWithText(FilledButton, decisionConfirmLabel), + ) + .onPressed, + isNotNull, + ); + expect(changed, isEmpty); + }); + + testWidgets('a late resync after disposal is ignored safely', (tester) async { + final resync = Completer(); + final gateway = _FakeGateway((type, fields) { + if (type == 'decide_run') throw const ProtocolError('no longer waiting'); + return resync.future; + }); + final changed = []; + await _pump(tester, gateway, changed); + await _chooseGo(tester); + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pump(); + expect(gateway.calls.map((call) => call.type), ['decide_run', 'get_run']); + + await tester.pumpWidget(const SizedBox()); + resync.complete({'run_detail': _decided()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('confirm cannot submit twice while the decision is in flight', ( + tester, + ) async { + final reply = Completer(); + final gateway = _FakeGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + await _chooseGo(tester); + + final confirm = find.text(decisionConfirmLabel); + await tester.tap(confirm); + await tester.tap(confirm); + await tester.pump(); + + expect( + gateway.calls.where((call) => call.type == 'decide_run'), + hasLength(1), + ); + expect(find.text(decisionSendingLabel), findsOneWidget); + expect( + tester + .widget( + find.widgetWithText(TextButton, decisionCancelLabel), + ) + .onPressed, + isNull, + ); + + reply.complete({'run_detail': _decided()}); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(changed, hasLength(1)); + }); + + testWidgets('a late reply after disposal is ignored safely', (tester) async { + final reply = Completer(); + final gateway = _FakeGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + await _chooseGo(tester); + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pump(); + expect(gateway.calls, hasLength(1)); + + await tester.pumpWidget(const SizedBox()); + reply.complete({'run_detail': _decided()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('both prompts fit 2x text at a narrow width', (tester) async { + tester.view.physicalSize = const Size(320, 480); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + for (final cupertino in [false, true]) { + final gateway = _FakeGateway( + (type, fields) async => {'run_detail': _decided()}, + ); + await _pump( + tester, + gateway, + [], + cupertino: cupertino, + textScale: 2, + ); + await tester.tap(find.byKey(decisionActionKey)); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino'); + expect(find.text(decisionWaitingTitle), findsOneWidget); + expect(find.text('Ship it?'), findsOneWidget); + expect( + cupertino + ? find.byType(CupertinoAlertDialog) + : find.byType(AlertDialog), + findsOneWidget, + ); + } + }); +} diff --git a/app/test/features/runs/actions/retry_action_test.dart b/app/test/features/runs/actions/retry_action_test.dart new file mode 100644 index 00000000..ca11fa8b --- /dev/null +++ b/app/test/features/runs/actions/retry_action_test.dart @@ -0,0 +1,245 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/retry_eligibility.dart'; +import 'package:pipelines_app/features/runs/actions/retry_intent.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; + +import 'retry_test_support.dart'; + +void main() { + test('retry eligibility matches the web canRetry exactly', () { + final cases = <(String, JsonMap, bool)>[ + ('failed and stopped', failedRun(), true), + ('failed but still executing', failedRun(executing: true), false), + ('running', failedRun(status: 'running'), false), + ('waiting', failedRun(status: 'waiting'), false), + ('succeeded', failedRun(status: 'succeeded'), false), + ('canceled', failedRun(status: 'canceled'), false), + ]; + for (final (label, run, expected) in cases) { + expect(canRetryRun(run), expected, reason: label); + } + expect(canRetryRun(null), isFalse); + expect(retryRunId(failedRun()), 7); + expect(retryRunId({'id': '7'}), isNull); + }); + + test('a generated retry key is bounded, run-scoped and fresh', () { + final first = newRetryRequestKey(7); + final second = newRetryRequestKey(7); + + expect(first, startsWith('app-retry-7-')); + expect(first.length, lessThanOrEqualTo(128)); + expect(second.length, lessThanOrEqualTo(128)); + expect(first, isNot(second)); + expect( + newRetryRequestKey(7, now: DateTime.utc(2026, 1, 1), random: 36), + 'app-retry-7-${DateTime.utc(2026, 1, 1).microsecondsSinceEpoch}-10', + ); + }); + + testWidgets( + 'material retry asks first, Keep sends nothing, then omits retry_mode', + (tester) async { + final accepted = retriedRun(); + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + expect(find.byKey(retryActionKey), findsOneWidget); + expect(find.byType(FilledButton), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text(retryDialogTitle(7)), findsOneWidget); + expect(find.text(retryDialogMessage), findsOneWidget); + expect( + find.descendant( + of: find.byType(AlertDialog), + matching: find.text(retryConfirmLabel), + ), + findsOneWidget, + ); + expect(find.text(restartConfirmLabel), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(retryActionKey), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(1)); + final fields = gateway.retries.single.fields; + expect(fields.keys, containsAll(['run_id', 'request_key'])); + expect(fields.containsKey('retry_mode'), isFalse); + expect(fields['run_id'], 7); + expect(fields['request_key'], startsWith('app-retry-7-')); + expect(fields['request_key'].length, lessThanOrEqualTo(128)); + expect(changed.single, equals(accepted)); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(retryActionKey), findsNothing); + }, + ); + + testWidgets( + 'material restart has its own confirmation and sends retry_mode', + (tester) async { + final accepted = retriedRun(); + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + + expect(find.text(restartDialogTitle(7)), findsOneWidget); + expect(find.text(restartDialogMessage), findsOneWidget); + expect(find.text(retryDialogTitle(7)), findsNothing); + expect(find.text(retryDialogMessage), findsNothing); + expect(find.text(restartConfirmLabel), findsOneWidget); + expect(find.byKey(retryRestartKey), findsNothing); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(1)); + final fields = gateway.retries.single.fields; + expect(fields['run_id'], 7); + expect(fields['retry_mode'], 'restart'); + expect(fields['request_key'], startsWith('app-retry-7-')); + expect(changed.single, equals(accepted)); + expect(find.byType(AlertDialog), findsNothing); + }, + ); + + testWidgets( + 'cupertino retry uses a native prompt and sends only on confirm', + (tester) async { + final accepted = retriedRun(); + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await pumpRetry( + tester, + gateway: gateway, + changed: changed, + cupertino: true, + ); + + expect(find.byKey(retryActionKey), findsOneWidget); + expect(find.byType(CupertinoButton), findsOneWidget); + expect(find.byType(FilledButton), findsNothing); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.byType(AlertDialog), findsNothing); + expect(find.text(retryDialogTitle(7)), findsOneWidget); + expect(find.text(retryDialogMessage), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(gateway.calls, isEmpty); + expect(find.byType(CupertinoAlertDialog), findsNothing); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(1)); + final fields = gateway.retries.single.fields; + expect(fields['run_id'], 7); + expect(fields.containsKey('retry_mode'), isFalse); + expect(fields['request_key'], startsWith('app-retry-7-')); + expect(changed.single, equals(accepted)); + expect(find.byType(CupertinoAlertDialog), findsNothing); + }, + ); + + testWidgets('cupertino restart switches to the restart confirmation', ( + tester, + ) async { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + await pumpRetry( + tester, + gateway: gateway, + changed: [], + cupertino: true, + ); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.text(restartDialogTitle(7)), findsOneWidget); + expect(find.text(restartDialogMessage), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + expect(gateway.retries.single.fields['retry_mode'], 'restart'); + }); + + testWidgets('the action is absent for runs the web does not retry', ( + tester, + ) async { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + final changed = []; + final cases = <(String, JsonMap, bool)>[ + ('failed', failedRun(), true), + ('executing', failedRun(executing: true), false), + ('running', failedRun(status: 'running'), false), + ('waiting', failedRun(status: 'waiting'), false), + ('succeeded', failedRun(status: 'succeeded'), false), + ('canceled', failedRun(status: 'canceled'), false), + ]; + for (final cupertino in [false, true]) { + for (final (label, run, visible) in cases) { + await tester.pumpWidget( + retryApp( + RetryHost( + key: ValueKey('$label-$cupertino'), + gateway: gateway, + initial: run, + changed: changed, + ), + cupertino: cupertino, + ), + ); + expect( + find.byKey(retryActionKey), + visible ? findsOneWidget : findsNothing, + reason: '$label cupertino=$cupertino', + ); + } + } + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + }); +} diff --git a/app/test/features/runs/actions/retry_resilience_test.dart b/app/test/features/runs/actions/retry_resilience_test.dart new file mode 100644 index 00000000..26053426 --- /dev/null +++ b/app/test/features/runs/actions/retry_resilience_test.dart @@ -0,0 +1,223 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/runs/actions/retry_eligibility.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; + +import 'retry_test_support.dart'; + +Future _openAndConfirm(WidgetTester tester) async { + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); +} + +void main() { + testWidgets('a refusal is shown at once and Keep does not wait for resync', ( + tester, + ) async { + const refusal = 'run 7 is still executing; wait for it to stop completely'; + final resync = Completer(); + final gateway = FakeRetryGateway((type, fields) { + if (type == 'retry_run') throw const ProtocolError(refusal); + return resync.future; + }); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await _openAndConfirm(tester); + await tester.pump(); + + expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']); + expect(find.text(refusal), findsOneWidget); + expect(find.byKey(retryErrorKey), findsOneWidget); + expect( + tester.widget(find.byKey(retryKeepKey)).onPressed, + isNotNull, + ); + expect( + tester.widget(find.byKey(retryConfirmKey)).onPressed, + isNull, + ); + expect(changed, isEmpty); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + + resync.complete({'run_detail': failedRun(status: 'succeeded')}); + await tester.pump(); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed.single['status'], 'succeeded'); + expect(find.byKey(retryActionKey), findsNothing); + }); + + testWidgets('server truth that is ineligible blocks a repeat action', ( + tester, + ) async { + const refusal = 'only failed runs can be retried'; + final finished = failedRun(status: 'succeeded'); + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'retry_run') throw const ProtocolError(refusal); + return {'run_detail': finished}; + }); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']); + expect(find.text(refusal), findsOneWidget); + expect( + tester.widget(find.byKey(retryConfirmKey)).onPressed, + isNull, + ); + expect( + tester.widget(find.byKey(retryKeepKey)).onPressed, + isNotNull, + ); + + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pump(); + expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(retryActionKey), findsNothing); + expect(changed.single, equals(finished)); + expect(canRetryRun(changed.single), isFalse); + }); + + testWidgets('a failed recheck keeps the same key for the uncertain request', ( + tester, + ) async { + const refusal = 'connection dropped while retrying'; + var attempts = 0; + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'get_run') throw const NotConnectedError(); + attempts += 1; + if (attempts == 1) throw const ProtocolError(refusal); + return {'run_detail': retriedRun()}; + }); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(find.text(refusal), findsOneWidget); + expect( + tester.widget(find.byKey(retryConfirmKey)).onPressed, + isNotNull, + ); + expect(gateway.retries, hasLength(1)); + + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(2)); + expect( + gateway.retries.last.fields['request_key'], + gateway.retries.first.fields['request_key'], + ); + expect( + gateway.retries.every((call) => !call.fields.containsKey('retry_mode')), + isTrue, + ); + expect(changed.single, equals(retriedRun())); + expect(find.byType(AlertDialog), findsNothing); + }); + + testWidgets('a restart retry keeps the mode and key across uncertainty', ( + tester, + ) async { + var attempts = 0; + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'get_run') throw const NotConnectedError(); + attempts += 1; + if (attempts == 1) throw const ProtocolError('network lost'); + return {'run_detail': retriedRun()}; + }); + await pumpRetry(tester, gateway: gateway, changed: []); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(2)); + expect(gateway.retries.first.fields['retry_mode'], 'restart'); + expect(gateway.retries.last.fields['retry_mode'], 'restart'); + expect( + gateway.retries.last.fields['request_key'], + gateway.retries.first.fields['request_key'], + ); + }); + + testWidgets('a deliberate reopen sends a fresh request key', (tester) async { + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'get_run') throw const NotConnectedError(); + throw const ProtocolError('server did not answer'); + }); + await pumpRetry(tester, gateway: gateway, changed: []); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(2)); + expect( + gateway.retries.first.fields['request_key'], + isNot(gateway.retries.last.fields['request_key']), + ); + }); + + testWidgets('a restart after a dismissed resume uses a fresh key', ( + tester, + ) async { + var attempts = 0; + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'get_run') throw const NotConnectedError(); + attempts += 1; + if (attempts == 1) throw const ProtocolError('resume refused'); + return {'run_detail': retriedRun()}; + }); + await pumpRetry(tester, gateway: gateway, changed: []); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + // A refusal leaves the prompt open; keep the mode frozen and dismiss. + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(2)); + expect(gateway.retries.first.fields.containsKey('retry_mode'), isFalse); + expect(gateway.retries.last.fields['retry_mode'], 'restart'); + expect( + gateway.retries.first.fields['request_key'], + isNot(gateway.retries.last.fields['request_key']), + ); + }); +} diff --git a/app/test/features/runs/actions/retry_safety_test.dart b/app/test/features/runs/actions/retry_safety_test.dart new file mode 100644 index 00000000..df9e7e88 --- /dev/null +++ b/app/test/features/runs/actions/retry_safety_test.dart @@ -0,0 +1,133 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; + +import 'retry_test_support.dart'; + +void main() { + testWidgets('confirm cannot submit twice while the retry is in flight', ( + tester, + ) async { + final reply = Completer(); + final gateway = FakeRetryGateway((type, fields) => reply.future); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + final confirm = find.byKey(retryConfirmKey); + await tester.tap(confirm); + await tester.tap(confirm); + await tester.pump(); + + expect(gateway.retries, hasLength(1)); + expect( + tester.widget(find.byKey(retryConfirmKey)).onPressed, + isNull, + ); + expect( + tester.widget(find.byKey(retryKeepKey)).onPressed, + isNull, + ); + expect(find.byType(AlertDialog), findsOneWidget); + + reply.complete({'run_detail': retriedRun()}); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(changed, hasLength(1)); + }); + + testWidgets('a late retry reply after disposal is ignored safely', ( + tester, + ) async { + final reply = Completer(); + final gateway = FakeRetryGateway((type, fields) => reply.future); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pump(); + expect(gateway.retries, hasLength(1)); + + await tester.pumpWidget(const SizedBox()); + reply.complete({'run_detail': retriedRun()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('a late resync after disposal is ignored safely', (tester) async { + final resync = Completer(); + final gateway = FakeRetryGateway((type, fields) { + if (type == 'retry_run') throw const ProtocolError('refused'); + return resync.future; + }); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pump(); + expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']); + + await tester.pumpWidget(const SizedBox()); + resync.complete({'run_detail': retriedRun()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('both confirmations fit 2x text at a narrow width', ( + tester, + ) async { + tester.view.physicalSize = const Size(320, 480); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + for (final cupertino in [false, true]) { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + await pumpRetry( + tester, + gateway: gateway, + changed: [], + cupertino: cupertino, + textScale: 2, + ); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino'); + expect(find.text(retryDialogTitle(7)), findsOneWidget); + expect(find.text(retryDialogMessage), findsOneWidget); + expect( + cupertino + ? find.byType(CupertinoAlertDialog) + : find.byType(AlertDialog), + findsOneWidget, + ); + + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull, reason: 'restart=$cupertino'); + expect(find.text(restartDialogTitle(7)), findsOneWidget); + expect(find.text(restartDialogMessage), findsOneWidget); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(gateway.calls, isEmpty); + } + }); +} diff --git a/app/test/features/runs/actions/retry_test_support.dart b/app/test/features/runs/actions/retry_test_support.dart new file mode 100644 index 00000000..67556d05 --- /dev/null +++ b/app/test/features/runs/actions/retry_test_support.dart @@ -0,0 +1,112 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/retry_action.dart'; + +typedef RetryHandler = Future Function(String type, JsonMap fields); + +/// A fake gateway that records every request and never owns a socket. +class FakeRetryGateway implements ApiGateway { + FakeRetryGateway(this.handler); + + final RetryHandler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); + + Iterable<({String type, JsonMap fields})> get retries => + calls.where((call) => call.type == 'retry_run'); +} + +JsonMap failedRun({ + num id = 7, + bool executing = false, + String status = 'failed', + String title = 'Nightly build', +}) => {'id': id, 'title': title, 'status': status, 'executing': executing}; + +JsonMap retriedRun({num id = 8}) => + failedRun(id: id, status: 'running', executing: true, title: 'Retry of 7'); + +/// Owns the run like a run-detail screen would, so the callback's returned +/// server detail is what the action renders next. +class RetryHost extends StatefulWidget { + const RetryHost({ + super.key, + required this.gateway, + required this.initial, + required this.changed, + }); + + final FakeRetryGateway gateway; + final JsonMap initial; + final List changed; + + @override + State createState() => _RetryHostState(); +} + +class _RetryHostState extends State { + late JsonMap _run = widget.initial; + + @override + Widget build(BuildContext context) { + return RetryRunAction( + run: _run, + gateway: widget.gateway, + onRunChanged: (run) { + widget.changed.add(run); + setState(() => _run = run); + }, + ); + } +} + +Widget retryApp(Widget child, {required bool cupertino, double textScale = 1}) { + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + if (cupertino) { + return CupertinoApp( + builder: media, + home: CupertinoPageScaffold(child: Center(child: child)), + ); + } + return MaterialApp( + builder: media, + home: Scaffold(body: Center(child: child)), + ); +} + +Future pumpRetry( + WidgetTester tester, { + required FakeRetryGateway gateway, + required List changed, + bool cupertino = false, + double textScale = 1, + JsonMap? run, +}) async { + await tester.pumpWidget( + retryApp( + RetryHost( + gateway: gateway, + initial: run ?? failedRun(), + changed: changed, + ), + cupertino: cupertino, + textScale: textScale, + ), + ); +} diff --git a/app/test/features/runs/actions/title_action_test.dart b/app/test/features/runs/actions/title_action_test.dart new file mode 100644 index 00000000..110fda20 --- /dev/null +++ b/app/test/features/runs/actions/title_action_test.dart @@ -0,0 +1,244 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/runs/actions/title_action.dart'; +import 'package:pipelines_app/features/runs/actions/title_wording.dart'; + +import 'title_test_support.dart'; + +String _materialFieldText(WidgetTester tester) => + tester.widget(find.byKey(runTitleFieldKey)).controller!.text; + +String _cupertinoFieldText(WidgetTester tester) => tester + .widget(find.byKey(runTitleFieldKey)) + .controller! + .text; + +void main() { + testWidgets( + 'material rename starts from the stored title, typing sends nothing, ' + 'Cancel sends nothing and Save sends the exact text', + (tester) async { + final accepted = renamedRun(title: 'Release build'); + final gateway = FakeTitleGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await tester.pumpWidget( + titleApp( + TitleHost(gateway: gateway, initial: titledRun(), changed: changed), + cupertino: false, + ), + ); + + expect(find.byKey(runTitleActionKey), findsOneWidget); + expect(find.byType(OutlinedButton), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text(runTitleDialogTitle), findsWidgets); + expect(find.text(runTitleFieldLabel), findsOneWidget); + expect(_materialFieldText(tester), 'Nightly build'); + + await tester.enterText( + find.byKey(runTitleFieldKey), + ' 发布 🚀 — nightly ', + ); + await tester.pump(); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Nightly build', + ); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(_materialFieldText(tester), 'Nightly build'); + await tester.enterText( + find.byKey(runTitleFieldKey), + ' 发布 🚀 — nightly ', + ); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['set_run_title']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'title': ' 发布 🚀 — nightly ', + }); + expect(changed.single, equals(accepted)); + expect(find.byType(AlertDialog), findsNothing); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Release build', + ); + }, + ); + + testWidgets('cupertino rename is native and sends only on Save', ( + tester, + ) async { + final accepted = renamedRun(title: 'Release build'); + final gateway = FakeTitleGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await tester.pumpWidget( + titleApp( + TitleHost(gateway: gateway, initial: titledRun(), changed: changed), + cupertino: true, + ), + ); + + expect(find.byKey(runTitleActionKey), findsOneWidget); + expect(find.byType(CupertinoButton), findsOneWidget); + expect(find.byType(OutlinedButton), findsNothing); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.byType(AlertDialog), findsNothing); + expect(_cupertinoFieldText(tester), 'Nightly build'); + + await tester.enterText(find.byKey(runTitleFieldKey), 'Typed only'); + await tester.pump(); + expect(gateway.calls, isEmpty); + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsNothing); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(runTitleFieldKey), 'Release build'); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['set_run_title']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'title': 'Release build', + }); + expect(changed.single, equals(accepted)); + expect(find.byType(CupertinoAlertDialog), findsNothing); + }); + + testWidgets('a blank title is sent exactly and the server refusal is shown', ( + tester, + ) async { + const refusal = 'title must not be blank'; + final gateway = FakeTitleGateway( + (type, fields) async => throw const ProtocolError(refusal), + ); + final changed = []; + await tester.pumpWidget( + titleApp( + TitleHost(gateway: gateway, initial: titledRun(), changed: changed), + cupertino: false, + ), + ); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(runTitleFieldKey), ''); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.single.fields, {'run_id': 7, 'title': ''}); + expect(find.text(refusal), findsOneWidget); + expect(find.byKey(runTitleErrorKey), findsOneWidget); + expect(_materialFieldText(tester), ''); + expect(find.byType(AlertDialog), findsOneWidget); + expect(changed, isEmpty); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Nightly build', + ); + expect( + tester.widget(find.byKey(runTitleSaveKey)).onPressed, + isNotNull, + ); + }); + + testWidgets('the prompt is seeded from the stored title, never the prompt', ( + tester, + ) async { + final gateway = FakeTitleGateway( + (type, fields) async => {'run_detail': titledRun()}, + ); + final changed = []; + + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: titledRun( + title: 'Stored title', + prompt: 'prompt fallback must not appear', + ), + changed: changed, + ), + cupertino: false, + ), + ); + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(_materialFieldText(tester), 'Stored title'); + expect(find.text('prompt fallback must not appear'), findsNothing); + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: titledRun(title: null, prompt: 'prompt is not a title'), + changed: changed, + ), + cupertino: false, + ), + ); + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(_materialFieldText(tester), ''); + expect(find.text('prompt is not a title'), findsNothing); + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + }); + + testWidgets('a malformed run has no rename entry point', (tester) async { + final gateway = FakeTitleGateway( + (type, fields) async => {'run_detail': titledRun()}, + ); + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: {'title': 'No id'}, + changed: [], + ), + cupertino: false, + ), + ); + + expect(find.byKey(runTitleActionKey), findsNothing); + expect(gateway.calls, isEmpty); + expect(runTitleId({'title': 'No id'}), isNull); + expect(storedRunTitle({'title': 'Kept'}), 'Kept'); + expect(storedRunTitle({}), ''); + }); +} diff --git a/app/test/features/runs/actions/title_resilience_test.dart b/app/test/features/runs/actions/title_resilience_test.dart new file mode 100644 index 00000000..32a566c3 --- /dev/null +++ b/app/test/features/runs/actions/title_resilience_test.dart @@ -0,0 +1,243 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/runs/actions/title_wording.dart'; + +import 'title_test_support.dart'; + +Future _pump( + WidgetTester tester, + FakeTitleGateway gateway, + List changed, { + bool cupertino = false, + double textScale = 1, + JsonMap? run, +}) async { + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: run ?? titledRun(), + changed: changed, + ), + cupertino: cupertino, + textScale: textScale, + ), + ); +} + +Future _open(WidgetTester tester) async { + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); +} + +String _fieldText(WidgetTester tester, {required bool cupertino}) { + if (cupertino) { + return tester + .widget(find.byKey(runTitleFieldKey)) + .controller! + .text; + } + return tester + .widget(find.byKey(runTitleFieldKey)) + .controller! + .text; +} + +void main() { + testWidgets('a failed save keeps the prompt open with the draft intact', ( + tester, + ) async { + const refusal = 'rename refused: the run is locked'; + final gateway = FakeTitleGateway( + (type, fields) async => throw const ProtocolError(refusal), + ); + final changed = []; + await _pump(tester, gateway, changed); + + await _open(tester); + await tester.enterText(find.byKey(runTitleFieldKey), ' Renamed draft '); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['set_run_title']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'title': ' Renamed draft ', + }); + expect(find.text(refusal), findsOneWidget); + expect(find.byKey(runTitleErrorKey), findsOneWidget); + expect(_fieldText(tester, cupertino: false), ' Renamed draft '); + expect(find.byType(AlertDialog), findsOneWidget); + expect(changed, isEmpty); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Nightly build', + ); + }); + + testWidgets('a transport failure keeps the server words and the draft', ( + tester, + ) async { + final gateway = FakeTitleGateway( + (type, fields) async => throw const NotConnectedError(), + ); + final changed = []; + await _pump(tester, gateway, changed, cupertino: true); + + await _open(tester); + await tester.enterText(find.byKey(runTitleFieldKey), 'Unsent title'); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(find.byKey(runTitleErrorKey), findsOneWidget); + expect(_fieldText(tester, cupertino: true), 'Unsent title'); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(changed, isEmpty); + }); + + testWidgets('Save cannot send twice while the rename is in flight', ( + tester, + ) async { + final reply = Completer(); + final gateway = FakeTitleGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + + await _open(tester); + await tester.enterText(find.byKey(runTitleFieldKey), 'One title'); + final save = find.byKey(runTitleSaveKey); + await tester.tap(save); + await tester.tap(save); + await tester.pump(); + + expect( + gateway.calls.where((call) => call.type == 'set_run_title'), + hasLength(1), + ); + expect(tester.widget(save).onPressed, isNull); + expect( + tester.widget(find.byKey(runTitleCancelKey)).onPressed, + isNull, + ); + expect(find.byType(AlertDialog), findsOneWidget); + + reply.complete({'run_detail': renamedRun(title: 'One title')}); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(changed, hasLength(1)); + expect(changed.single['title'], 'One title'); + }); + + testWidgets('a late reply after disposal is ignored safely', (tester) async { + final reply = Completer(); + final gateway = FakeTitleGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + + await _open(tester); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pump(); + expect(gateway.calls, hasLength(1)); + + await tester.pumpWidget(const SizedBox()); + reply.complete({'run_detail': renamedRun()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('a reply for a run the widget no longer owns is not delivered', ( + tester, + ) async { + final reply = Completer(); + final gateway = FakeTitleGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + + await _open(tester); + await tester.enterText(find.byKey(runTitleFieldKey), 'Run seven title'); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pump(); + + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: titledRun(id: 8, title: 'Another run'), + changed: changed, + ), + cupertino: false, + ), + ); + await tester.pump(); + reply.complete({'run_detail': renamedRun(title: 'Run seven title')}); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'title': 'Run seven title', + }); + expect(changed, isEmpty); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Another run', + ); + }); + + testWidgets('both prompts fit 2x text at a narrow width', (tester) async { + tester.view.physicalSize = const Size(320, 480); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + const refusal = 'the title is too long for this run; shorten it'; + for (final cupertino in [false, true]) { + final gateway = FakeTitleGateway( + (type, fields) async => throw const ProtocolError(refusal), + ); + await _pump( + tester, + gateway, + [], + cupertino: cupertino, + textScale: 2, + ); + await _open(tester); + + expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino'); + expect( + cupertino + ? find.byType(CupertinoAlertDialog) + : find.byType(AlertDialog), + findsOneWidget, + ); + expect(find.text(runTitleFieldLabel), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.enterText( + find.byKey(runTitleFieldKey), + 'A deliberately long title that must scroll rather than overflow', + ); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino'); + expect(find.text(refusal), findsOneWidget); + expect( + _fieldText(tester, cupertino: cupertino), + 'A deliberately long title that must scroll rather than overflow', + ); + + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byType(CupertinoAlertDialog), findsNothing); + } + }); +} diff --git a/app/test/features/runs/actions/title_test_support.dart b/app/test/features/runs/actions/title_test_support.dart new file mode 100644 index 00000000..b566a2d8 --- /dev/null +++ b/app/test/features/runs/actions/title_test_support.dart @@ -0,0 +1,110 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/title_action.dart'; + +typedef TitleHandler = Future Function(String type, JsonMap fields); + +/// A fake gateway that records every request and never owns a socket. +class FakeTitleGateway implements ApiGateway { + FakeTitleGateway(this.handler); + + final TitleHandler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap titledRun({ + num id = 7, + String? title = 'Nightly build', + String status = 'succeeded', + String prompt = 'the submitted prompt', +}) => { + 'id': id, + 'title': title, + 'status': status, + 'input': {'prompt': prompt}, +}; + +JsonMap renamedRun({num id = 7, String title = 'Release build'}) => + titledRun(id: id, title: title, status: 'succeeded'); + +/// Owns the run like a run-detail screen would, so the callback's returned +/// server detail is what the action renders next. Re-pumping with a different +/// initial run updates the action in place, as a refreshed detail does. +class TitleHost extends StatefulWidget { + const TitleHost({ + super.key, + required this.gateway, + required this.initial, + required this.changed, + }); + + final FakeTitleGateway gateway; + final JsonMap initial; + final List changed; + + @override + State createState() => _TitleHostState(); +} + +class _TitleHostState extends State { + late JsonMap _run = widget.initial; + + @override + void didUpdateWidget(covariant TitleHost oldWidget) { + super.didUpdateWidget(oldWidget); + if (!identical(oldWidget.initial, widget.initial)) { + _run = widget.initial; + } + } + + @override + Widget build(BuildContext context) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('${_run['title'] ?? ''}', key: titleHostTitleKey), + RunTitleAction( + run: _run, + gateway: widget.gateway, + onRunChanged: (run) { + widget.changed.add(run); + setState(() => _run = run); + }, + ), + ], + ); + } +} + +const titleHostTitleKey = ValueKey('rename-host-title'); + +Widget titleApp(Widget child, {required bool cupertino, double textScale = 1}) { + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + final body = Center(child: child); + if (cupertino) { + return CupertinoApp( + builder: media, + home: CupertinoPageScaffold(child: body), + ); + } + return MaterialApp( + builder: media, + home: Scaffold(body: body), + ); +} diff --git a/app/test/features/runs/run_decisions_test.dart b/app/test/features/runs/run_decisions_test.dart new file mode 100644 index 00000000..2cb47b1c --- /dev/null +++ b/app/test/features/runs/run_decisions_test.dart @@ -0,0 +1,87 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/domain/run_decisions.dart'; +import 'package:pipelines_app/features/runs/domain/run_events.dart'; +import 'package:pipelines_app/features/runs/domain/run_models.dart'; + +void main() { + test( + 'scheduled origin is immutable and export pending blocks attention/decision', + () { + final rows = [ + { + 'id': 5, + 'status': 'waiting', + 'scheduled': true, + 'schedule_id': 12, + 'schedule_name': 'Nightly', + }, + ]; + final changed = foldRunEvent(rows, { + 'run_id': 5, + 'status': 'waiting', + 'scheduled': false, + 'schedule_id': 99, + 'schedule_name': 'Other', + 'export_pending_sequence': 4, + }); + expect(changed.runs.single['schedule_id'], 12); + expect(changed.runs.single['schedule_name'], 'Nightly'); + expect(changed.runs.single['scheduled'], true); + expect(orderAttention(changed.runs), isEmpty); + expect( + pendingDecision({ + ...changed.runs.single, + 'current_stage': 'human', + 'steps': [], + }), + isNull, + ); + }, + ); + + test( + 'pending decision uses recorded options then graph fallback and target labels', + () { + final run = { + 'id': 7, + 'status': 'waiting', + 'current_stage': 'human', + 'name': 'Build', + 'graph': { + 'stages': [ + { + 'key': 'human', + 'type': 'human', + 'prompt': 'Graph prompt', + 'edges': {'go': '#', 'error': '#', 'skip': 'finish'}, + }, + ], + }, + 'steps': [ + { + 'sequence': 1, + 'status': 'waiting', + 'stage': 'human', + 'output': { + 'prompt': 'Recorded prompt', + 'options': ['go'], + }, + }, + ], + }; + final decision = pendingDecision(run)!; + expect(decision.instructions, 'Recorded prompt'); + expect(decision.options.map((option) => option.key), ['go']); + expect(decision.options.single.target, 'SUCCESS'); + final fallback = pendingDecision({ + ...run, + 'steps': [ + {'status': 'waiting', 'stage': 'human', 'output': {}}, + ], + })!; + expect(fallback.instructions, 'Graph prompt'); + expect(fallback.options.map((option) => option.key), ['go', 'skip']); + }, + ); +} diff --git a/app/test/features/runs/runs_foundation_test.dart b/app/test/features/runs/runs_foundation_test.dart new file mode 100644 index 00000000..df77eca0 --- /dev/null +++ b/app/test/features/runs/runs_foundation_test.dart @@ -0,0 +1,189 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/domain/run_events.dart'; + +void main() { + group('event fold', () { + test('terminal status and resource wait reset are monotonic', () { + final initial = [ + { + 'id': 1, + 'status': 'succeeded', + 'executing': false, + 'completed_steps': 4, + }, + ]; + final reset = foldRunEvent(initial, { + 'run_id': 1, + 'status': 'queued', + 'resource_wait_set': true, + 'resource_wait': null, + }); + expect(reset.runs.single['status'], 'succeeded'); + expect(reset.runs.single['executing'], false); + final competing = foldRunEvent(initial, { + 'run_id': 1, + 'status': 'failed', + 'resource_wait_set': true, + }); + expect(competing.runs.single['status'], 'succeeded'); + expect(competing.runs.single['resource_wait'], isNull); + }); + + test( + 'resource wait reset advances only nonterminal rows, even on stale status', + () { + final rows = [ + { + 'id': 2, + 'status': 'running', + 'executing': true, + 'resource_wait': {'resource': 'gpu'}, + 'completed_steps': 3, + }, + ]; + final result = foldRunEvent(rows, { + 'run_id': 2, + 'status': 'queued', + 'resource_wait_set': true, + 'resource_wait': null, + 'completed_steps': 1, + }); + expect(result.runs.single['status'], 'queued'); + expect(result.runs.single['resource_wait'], isNull); + expect(result.runs.single['completed_steps'], 3); + }, + ); + + test( + 'new waiting and terminal rows are not executing; identity-less frame resyncs', + () { + for (final status in ['waiting', 'succeeded']) { + final result = foldRunEvent([], { + 'run_id': 8, + 'pipeline_id': 4, + 'name': 'Build', + 'status': status, + }); + expect(result.runs.single['executing'], false); + } + expect( + foldRunEvent([], {'run_id': 9, 'status': 'running'}).needsResync, + isTrue, + ); + }, + ); + + test( + 'blank sparse step fields preserve graph evidence and terminal visit', + () { + final detail = { + 'id': 1, + 'status': 'running', + 'steps': [ + { + 'sequence': 2, + 'stage': 'review', + 'status': 'completed', + 'outcome': 'approve', + 'target': 'publish', + 'diagnostic': 'kept', + }, + ], + }; + final next = foldRunEventDetail(detail, { + 'run_id': 1, + 'status': 'running', + 'step': { + 'sequence': 2, + 'stage': '', + 'status': 'running', + 'outcome': ' ', + 'target': '', + 'diagnostic': '', + }, + })!; + final step = (next['steps'] as List).single as JsonMap; + expect(step, containsPair('stage', 'review')); + expect(step, containsPair('status', 'completed')); + expect(step, containsPair('outcome', 'approve')); + expect(step, containsPair('target', 'publish')); + expect(step, containsPair('diagnostic', 'kept')); + }, + ); + + test( + 'cancel and cleanup flags stick; resource wait can clear; terminal clears it', + () { + final rows = [ + { + 'id': 3, + 'status': 'running', + 'resource_wait': {'resource': 'gpu'}, + }, + ]; + final first = foldRunEvent(rows, { + 'run_id': 3, + 'status': 'running', + 'cancel_requested': true, + 'cleanup_unconfirmed': true, + }); + final second = foldRunEvent(first.runs, { + 'run_id': 3, + 'status': 'running', + 'cancel_requested': false, + 'cleanup_unconfirmed': false, + 'resource_wait_set': true, + 'resource_wait': null, + }); + expect(second.runs.single['cancel_requested'], true); + expect(second.runs.single['cleanup_unconfirmed'], true); + expect(second.runs.single['resource_wait'], isNull); + final terminal = foldRunEvent(second.runs, { + 'run_id': 3, + 'status': 'failed', + }); + expect(terminal.runs.single['resource_wait'], isNull); + }, + ); + + test( + 'full sync triggers and list/detail folds agree across stale and current frames', + () { + expect(runDetailNeedsFullSync({'status': 'waiting'}), true); + expect( + runDetailNeedsFullSync({ + 'status': 'running', + 'step': {'status': 'completed'}, + }), + true, + ); + final summary = [ + {'id': 1, 'status': 'running', 'completed_steps': 1}, + ]; + final frame = { + 'run_id': 1, + 'status': 'succeeded', + 'completed_steps': 2, + 'outcome': 'done', + }; + final list = foldRunEvent(summary, frame).runs.single; + final detail = foldRunEventDetail({ + 'id': 1, + 'status': 'running', + 'completed_steps': 1, + 'steps': [], + }, frame)!; + expect(list['status'], detail['status']); + expect(list['completed_steps'], detail['completed_steps']); + final old = foldRunEventDetail(detail, { + 'run_id': 1, + 'status': 'running', + 'outcome': '', + })!; + expect(old['status'], 'succeeded'); + expect(old['outcome'], 'done'); + }, + ); + }); +} diff --git a/app/test/features/runs/runs_repository_test.dart b/app/test/features/runs/runs_repository_test.dart new file mode 100644 index 00000000..e6ee2164 --- /dev/null +++ b/app/test/features/runs/runs_repository_test.dart @@ -0,0 +1,163 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/domain/run_models.dart'; + +class FakeGateway implements ApiGateway { + String? type; + JsonMap fields = {}; + JsonMap reply = {}; + Object? failure; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + this.type = type; + this.fields = Map.of(fields); + if (failure case final error?) throw error; + return reply; + } + + @override + Stream get frames => const Stream.empty(); +} + +void main() { + test( + 'run models match identity, filtering, sorting and null usage behavior', + () { + expect(runIdentity(' Report ', 'Build').label, 'Report'); + final rows = [ + { + 'id': 1, + 'pipeline_id': 2, + 'status': 'failed', + 'created_at': '2024-01-01T00:00:00Z', + 'finished_at': '2024-01-01T00:00:10Z', + }, + { + 'id': 2, + 'pipeline_id': 2, + 'status': 'running', + 'created_at': '2025-01-01T00:00:00Z', + }, + ]; + expect(filterRuns(rows, statuses: {'failed'}).single['id'], 1); + expect(sortRuns(rows).first['id'], 2); + expect(sortRuns(rows, sort: 'shortest_duration').first['id'], 1); + final scheduled = [ + { + 'id': 3, + 'scheduled': true, + 'schedule_id': 9, + 'created_at': '2025-03-10T12:00:00Z', + }, + {'id': 4, 'scheduled': false, 'created_at': '2025-03-10T12:00:00Z'}, + {'id': 5, 'created_at': '2025-03-10T12:00:00Z'}, + ]; + expect( + filterRuns(scheduled, scheduled: 'scheduled').map((run) => run['id']), + [3], + ); + expect( + filterRuns( + scheduled, + scheduled: 'unscheduled', + timeRange: 'today', + today: DateTime(2025, 3, 10), + ).map((run) => run['id']), + [4], + ); + expect( + runStatusLabel({'status': 'waiting', 'export_pending_sequence': 2}), + 'Waiting for session export', + ); + expect(RunListResult(const [], null).usage, isNull); + }, + ); + + test('repository sends exact action and launch requests', () async { + final gateway = FakeGateway() + ..reply = { + 'run_detail': {'id': 3}, + }; + final repo = RunsRepository(gateway); + gateway.reply = { + 'runs': [ + {'id': 1, 'status': 'running'}, + ], + 'usage': {'active': 1}, + }; + final listed = await repo.listRuns(); + expect(gateway.type, 'list_runs'); + expect(gateway.fields, isEmpty); + expect(listed.runs.single['id'], 1); + expect(listed.usage, {'active': 1}); + gateway.reply = { + 'run_detail': {'id': 3}, + }; + await repo.retryRun(3, requestKey: 'retry-1'); + expect(gateway.type, 'retry_run'); + expect(gateway.fields, {'run_id': 3, 'request_key': 'retry-1'}); + await repo.retryRun(3, requestKey: 'retry-2', mode: 'restart'); + expect(gateway.fields, { + 'run_id': 3, + 'request_key': 'retry-2', + 'retry_mode': 'restart', + }); + await repo.decideRun(3, stage: 'human', option: ' go ', feedback: ' yes '); + expect(gateway.fields, { + 'run_id': 3, + 'stage': 'human', + 'option': 'go', + 'feedback': 'yes', + }); + await repo.cancelRun(3); + expect(gateway.type, 'cancel_run'); + expect(gateway.fields, {'run_id': 3}); + await repo.setRunTitle(3, 'New'); + expect(gateway.type, 'set_run_title'); + expect(gateway.fields, {'run_id': 3, 'title': 'New'}); + await repo.startRun( + pipelineId: 4, + version: 2, + prompt: 'hello', + workspace: ' /work ', + requestKey: 'start-2', + title: ' Job ', + notifyMode: 'off', + outputFormat: 'json', + ); + expect(gateway.type, 'run_pipeline'); + expect(gateway.fields, { + 'pipeline_id': 4, + 'version': 2, + 'request_key': 'start-2', + 'workspace': '/work', + 'input': {'prompt': 'hello'}, + 'title': 'Job', + 'notify_mode': 'off', + 'output_format': 'json', + }); + }); + + test( + 'repository propagates server refusals and rejects missing detail', + () async { + final gateway = FakeGateway()..reply = {}; + final repo = RunsRepository(gateway); + await expectLater( + repo.getRun(3), + throwsA(isA()), + ); + await expectLater( + repo.decideRun(3, option: ' '), + throwsA(isA()), + ); + gateway.failure = const RunsRepositoryException('server refused'); + await expectLater( + repo.cancelRun(3), + throwsA(predicate((error) => '$error' == 'server refused')), + ); + }, + ); +} diff --git a/app/test/features/runs/ui/run_detail_widget_test.dart b/app/test/features/runs/ui/run_detail_widget_test.dart new file mode 100644 index 00000000..972b0692 --- /dev/null +++ b/app/test/features/runs/ui/run_detail_widget_test.dart @@ -0,0 +1,264 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_view.dart'; +import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; + +enum AppPlatform { material, cupertino } + +class FakeGateway implements ApiGateway { + FakeGateway(this.detail); + JsonMap detail; + Object? failure; + Completer? hold; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type != 'get_run') throw UnsupportedError(type); + if (hold != null) return hold!.future; + if (failure != null) return Future.error(failure!); + return Future.value({'run_detail': detail}); + } +} + +const prompt = ' keep\n\nspacing '; + +JsonMap runFixture({JsonMap? usage, int steps = 2}) { + final run = { + 'id': 7, + 'title': 'Nightly build', + 'name': 'release', + 'status': 'succeeded', + 'input': { + 'prompt': prompt, + 'nested': { + 'alpha': 1, + 'items': [1, 2], + }, + }, + 'output': { + 'result': {'ok': true}, + }, + 'steps': [ + for (var i = 0; i < steps; i++) + { + 'stage': i == 0 ? 'build' : 'test', + 'sequence': i + 3, + 'status': 'completed', + 'outcome': 'success', + 'target': '#success', + }, + ], + }; + if (usage != null) run['usage'] = usage; + return run; +} + +JsonMap usageFixture({int known = 1}) => { + 'stages': 1, + 'tokens_total': 0, + 'tokens_known_stages': known, + 'tokens_in': 0, + 'tokens_out': 0, + 'split_known': true, + 'cost_known_stages': known, +}; + +Future pumpDetail( + WidgetTester tester, + AppPlatform platform, + RunsController controller, { + VoidCallback? onBack, + bool settle = true, +}) async { + tester.view.physicalSize = const Size(390, 1600); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final view = RunDetailView(controller: controller, onBack: onBack ?? () {}); + final page = MediaQuery( + data: MediaQueryData.fromView( + tester.view, + ).copyWith(textScaler: const TextScaler.linear(2)), + child: view, + ); + await tester.pumpWidget( + platform == AppPlatform.material + ? MaterialApp(home: Scaffold(body: page)) + : CupertinoApp( + home: CupertinoPageScaffold(child: SafeArea(child: page)), + ), + ); + if (settle) { + await tester.pumpAndSettle(); + } else { + await tester.pump(); + } +} + +void mockClipboard( + WidgetTester tester, + List copied, { + bool Function()? denied, +}) { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method != 'Clipboard.setData') return null; + if (denied?.call() ?? false) { + throw PlatformException(code: 'clipboard-denied'); + } + copied.add((call.arguments as Map)['text'] as String); + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); +} + +void main() { + late FakeGateway gateway; + late RunsController controller; + + setUp(() { + gateway = FakeGateway(runFixture()); + controller = RunsController(RunsRepository(gateway)); + }); + tearDown(() => controller.dispose()); + + for (final platform in AppPlatform.values) { + testWidgets('${platform.name} detail at 390 with 2x text', (tester) async { + gateway.detail = runFixture(steps: 12); + await controller.select(1); + await pumpDetail(tester, platform, controller); + expect(tester.takeException(), isNull); + expect(find.text('Nightly build'), findsOneWidget); + expect(find.textContaining('Original prompt'), findsOneWidget); + if (platform == AppPlatform.material) { + expect(find.byType(Chip), findsOneWidget); + expect(find.byType(ExpansionTile), findsNWidgets(2)); + } else { + expect(find.byType(Material), findsNothing); + expect(find.byType(Chip), findsNothing); + expect(find.byType(CupertinoExpansionTile), findsNWidgets(2)); + } + + await tester.tap(find.text('Input')); + await tester.pumpAndSettle(); + expect(find.textContaining('"alpha": 1'), findsOneWidget); + await tester.scrollUntilVisible( + find.text('Output'), + 200, + scrollable: find.byType(Scrollable).first, + ); + await tester.tap(find.text('Output')); + await tester.pumpAndSettle(); + expect(find.textContaining('"ok": true'), findsOneWidget); + + await tester.scrollUntilVisible( + find.textContaining('build · visit 3'), + 200, + scrollable: find.byType(Scrollable).first, + ); + expect(find.textContaining('build · visit 3'), findsOneWidget); + expect(find.textContaining('test · visit 4'), findsOneWidget); + if (platform == AppPlatform.material) { + final scrollable = tester.state( + find.byType(Scrollable).first, + ); + final before = scrollable.position.pixels; + expect(before, greaterThan(0)); + gateway.detail = runFixture(steps: 13); + await controller.select(1); + await tester.pumpAndSettle(); + expect(scrollable.position.pixels, closeTo(before, 0.1)); + } + }); + + testWidgets('${platform.name} loading and error stay honest', ( + tester, + ) async { + gateway.hold = Completer(); + final pending = controller.select(1); + await pumpDetail(tester, platform, controller, settle: false); + expect(find.text('Loading run details…'), findsOneWidget); + expect( + find.byType( + platform == AppPlatform.material + ? CircularProgressIndicator + : CupertinoActivityIndicator, + ), + findsOneWidget, + ); + gateway.hold!.complete({'run_detail': runFixture()}); + await pending; + await tester.pumpAndSettle(); + expect(find.text('Nightly build'), findsOneWidget); + + controller.dispose(); + gateway = FakeGateway(runFixture()) + ..failure = StateError('server unavailable'); + controller = RunsController(RunsRepository(gateway)); + await controller.select(1); + var backs = 0; + await pumpDetail(tester, platform, controller, onBack: () => backs++); + expect(find.textContaining('server unavailable'), findsOneWidget); + await tester.tap(find.text('Back to list')); + expect(backs, 1); + }); + + testWidgets('${platform.name} copies the exact prompt and reports denial', ( + tester, + ) async { + final copied = []; + var denied = false; + mockClipboard(tester, copied, denied: () => denied); + final copy = platform == AppPlatform.material + ? find.byTooltip('Copy prompt') + : find.text('Copy prompt'); + await controller.select(1); + await pumpDetail(tester, platform, controller); + await tester.tap(copy); + await tester.pumpAndSettle(); + expect(copied.single, prompt); + expect(find.text('Prompt copied to clipboard.'), findsOneWidget); + if (platform == AppPlatform.material) { + await tester.pump(const Duration(seconds: 5)); + await tester.pumpAndSettle(); + } + denied = true; + await tester.tap(copy); + await tester.pumpAndSettle(); + expect(find.text('Could not copy prompt to clipboard.'), findsOneWidget); + }); + } + + testWidgets('reported zero and missing usage stay distinct', (tester) async { + gateway.detail = runFixture(usage: usageFixture()); + await controller.select(1); + await pumpDetail(tester, AppPlatform.material, controller); + await tester.tap(find.text('Metrics')); + await tester.pumpAndSettle(); + expect(find.text('Unavailable'), findsNothing); + expect(find.text('0'), findsNWidgets(3)); + expect(find.text('\$0.000000'), findsOneWidget); + + gateway.detail = runFixture(usage: usageFixture(known: 0)); + await controller.select(1); + await tester.pumpAndSettle(); + expect(find.text('Unavailable'), findsNWidgets(4)); + expect(find.text('0'), findsNothing); + }); +} diff --git a/app/test/features/runs/ui/runs_controller_test.dart b/app/test/features/runs/ui/runs_controller_test.dart new file mode 100644 index 00000000..0945f77b --- /dev/null +++ b/app/test/features/runs/ui/runs_controller_test.dart @@ -0,0 +1,344 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; + +class FakeGateway implements ApiGateway { + final framesController = StreamController.broadcast(); + final lists = >[]; + final details = >>{}; + int listCalls = 0; + @override + Stream get frames => framesController.stream; + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'list_runs') { + listCalls++; + final request = Completer(); + lists.add(request); + return request.future; + } + final id = fields['run_id'] as num; + final request = Completer(); + details.putIfAbsent(id, () => []).add(request); + return request.future; + } + + void listReply(int index, List runs) => + lists[index].complete({'runs': runs}); + void detailReply(num id, int index, JsonMap value) => + details[id]![index].complete({'run_detail': value}); +} + +void main() { + late FakeGateway gateway; + late RunsController controller; + var disposed = false; + setUp(() { + gateway = FakeGateway(); + controller = RunsController(RunsRepository(gateway)); + disposed = false; + }); + tearDown(() { + if (!disposed) controller.dispose(); + gateway.framesController.close(); + }); + + test('late selection response cannot replace latest selection', () async { + final first = controller.select(1); + final second = controller.select(2); + gateway.detailReply(2, 0, {'id': 2}); + await second; + gateway.detailReply(1, 0, {'id': 1}); + await first; + expect(controller.detail?['id'], 2); + }); + + test('pending load and selection futures are safe after dispose', () async { + final load = controller.load(); + final select = controller.select(1); + controller.dispose(); + disposed = true; + gateway.listReply(0, []); + gateway.detailReply(1, 0, {'id': 1}); + await Future.wait([load, select]); + }); + + test('Back cancels scheduled detail refresh', () async { + final select = controller.select(1); + gateway.detailReply(1, 0, {'id': 1, 'status': 'running'}); + await select; + controller.listen(gateway.frames); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 1, + 'status': 'succeeded', + }); + controller.back(); + await Future.delayed(const Duration(milliseconds: 220)); + expect(gateway.details[1], hasLength(1)); + expect(controller.detail, isNull); + }); + + test('unrelated run event does not refresh selected detail', () async { + final select = controller.select(1); + gateway.detailReply(1, 0, {'id': 1, 'status': 'running'}); + await select; + controller.listen(gateway.frames); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 2, + 'status': 'succeeded', + }); + await Future.delayed(const Duration(milliseconds: 220)); + expect(gateway.details[1], hasLength(1)); + }); + + test('identity-less event reloads list', () async { + controller.listen(gateway.frames); + gateway.framesController.add({'type': 'run_event', 'status': 'running'}); + await Future.delayed(Duration.zero); + expect(gateway.listCalls, 1); + gateway.listReply(0, [ + {'id': 3}, + ]); + await Future.delayed(Duration.zero); + expect(controller.runs.single['id'], 3); + expect(controller.loading, isFalse); + }); + + test( + 'full refresh is coalesced and keeps current detail until reply', + () async { + final select = controller.select(1); + gateway.detailReply(1, 0, {'id': 1, 'status': 'running'}); + await select; + controller.listen(gateway.frames); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 1, + 'status': 'succeeded', + }); + await Future.delayed(const Duration(milliseconds: 180)); + expect(controller.detail?['id'], 1); + expect(gateway.details[1], hasLength(2)); + gateway.detailReply(1, 1, {'id': 1, 'status': 'succeeded'}); + await Future.delayed(Duration.zero); + expect(controller.detail?['status'], 'succeeded'); + }, + ); + + test('load with initial id clears list and detail loading', () async { + final load = controller.load(7); + expect(controller.loading, isTrue); + gateway.listReply(0, [ + {'id': 7}, + {'id': 8}, + ]); + await Future.delayed(Duration.zero); + expect(gateway.details[7], hasLength(1)); + expect(controller.loading, isFalse); + expect(controller.detailLoading, isTrue); + gateway.detailReply(7, 0, {'id': 7}); + await load; + expect(controller.loading, isFalse); + expect(controller.detailLoading, isFalse); + expect(controller.detail?['id'], 7); + expect(controller.selectedRunId, 7); + }); + + test('newer list load wins when replies complete out of order', () async { + final first = controller.load(); + final second = controller.load(); + gateway.listReply(1, [ + {'id': 2}, + ]); + await second; + gateway.listReply(0, [ + {'id': 1}, + ]); + await first; + expect(controller.runs.single['id'], 2); + expect(controller.loading, isFalse); + }); + + test('list resync leaves the selected detail request valid', () async { + final select = controller.select(1); + gateway.detailReply(1, 0, {'id': 1, 'status': 'running'}); + await select; + controller.listen(gateway.frames); + gateway.framesController.add({'type': 'run_event', 'status': 'running'}); + await Future.delayed(Duration.zero); + expect(gateway.listCalls, 1); + gateway.listReply(0, [ + {'id': 1, 'status': 'running'}, + ]); + await Future.delayed(Duration.zero); + expect(controller.detail?['id'], 1); + expect(controller.selectedRunId, 1); + expect(gateway.details[1], hasLength(1)); + }); + + test('manual list load keeps an in-flight detail refresh valid', () async { + final select = controller.select(1); + gateway.detailReply(1, 0, {'id': 1, 'status': 'running'}); + await select; + controller.listen(gateway.frames); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 1, + 'status': 'succeeded', + }); + await Future.delayed(const Duration(milliseconds: 180)); + expect(gateway.details[1], hasLength(2)); + final load = controller.load(); + gateway.listReply(1, [ + {'id': 1}, + ]); + await load; + gateway.detailReply(1, 1, {'id': 1, 'status': 'succeeded'}); + await Future.delayed(Duration.zero); + expect(controller.detail?['status'], 'succeeded'); + expect(controller.detailLoading, isFalse); + gateway.listReply(0, [ + {'id': 1}, + ]); + }); + + test('event during a superseded resync still runs one followup', () async { + controller.listen(gateway.frames); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 9, + 'status': 'running', + }); + await Future.delayed(Duration.zero); + expect(gateway.listCalls, 1); + final load = controller.load(); + expect(gateway.listCalls, 2); + gateway.listReply(1, [ + {'id': 1}, + ]); + await load; + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 10, + 'status': 'running', + }); + await Future.delayed(Duration.zero); + expect(gateway.listCalls, 2); + gateway.listReply(0, [ + {'id': 1}, + ]); + await Future.delayed(Duration.zero); + expect(gateway.listCalls, 3); + gateway.listReply(2, [ + {'id': 1}, + {'id': 2}, + ]); + await Future.delayed(Duration.zero); + expect(controller.runs, hasLength(2)); + expect(controller.loading, isFalse); + }); + + test('unknown run events coalesce into one followup resync', () async { + controller.listen(gateway.frames); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 9, + 'status': 'running', + }); + await Future.delayed(Duration.zero); + expect(gateway.listCalls, 1); + expect(controller.loading, isTrue); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 10, + 'status': 'running', + }); + await Future.delayed(Duration.zero); + expect(gateway.listCalls, 1); + gateway.listReply(0, [ + {'id': 3}, + ]); + await Future.delayed(Duration.zero); + expect(gateway.listCalls, 2); + expect(controller.loading, isTrue); + gateway.listReply(1, [ + {'id': 3}, + {'id': 4}, + ]); + await Future.delayed(Duration.zero); + expect(gateway.listCalls, 2); + expect(controller.loading, isFalse); + expect(controller.runs, hasLength(2)); + }); + + test( + 'selected refresh coalesces and Back ignores the pending reply', + () async { + final select = controller.select(1); + gateway.detailReply(1, 0, {'id': 1, 'status': 'running'}); + await select; + controller.listen(gateway.frames); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 1, + 'status': 'succeeded', + }); + await Future.delayed(const Duration(milliseconds: 180)); + expect(gateway.details[1], hasLength(2)); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 1, + 'status': 'failed', + }); + await Future.delayed(Duration.zero); + expect(gateway.details[1], hasLength(2)); + gateway.detailReply(1, 1, {'id': 1, 'status': 'succeeded'}); + await Future.delayed(Duration.zero); + expect(gateway.details[1], hasLength(3)); + controller.back(); + gateway.detailReply(1, 2, {'id': 1, 'status': 'failed'}); + await Future.delayed(Duration.zero); + expect(controller.detail, isNull); + expect(controller.detailLoading, isFalse); + expect(controller.error, isNull); + }, + ); + + test('choosing another run does not display the previous detail', () async { + final first = controller.select(1); + gateway.detailReply(1, 0, {'id': 1}); + await first; + final second = controller.select(2); + expect(controller.detail, isNull); + expect(controller.selectedRunId, 2); + expect(controller.detailLoading, isTrue); + gateway.detailReply(2, 0, {'id': 2}); + await second; + expect(controller.detail?['id'], 2); + expect(controller.detailLoading, isFalse); + }); + + test('pending detail refresh is safe after dispose', () async { + final select = controller.select(1); + gateway.detailReply(1, 0, {'id': 1, 'status': 'running'}); + await select; + controller.listen(gateway.frames); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 1, + 'status': 'succeeded', + }); + await Future.delayed(const Duration(milliseconds: 180)); + expect(gateway.details[1], hasLength(2)); + controller.dispose(); + disposed = true; + gateway.detailReply(1, 1, {'id': 1, 'status': 'succeeded'}); + await Future.delayed(Duration.zero); + expect(controller.detail?['id'], 1); + }); +} diff --git a/app/test/features/runs/ui/runs_list_widget_test.dart b/app/test/features/runs/ui/runs_list_widget_test.dart new file mode 100644 index 00000000..2414cf78 --- /dev/null +++ b/app/test/features/runs/ui/runs_list_widget_test.dart @@ -0,0 +1,180 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; +import 'package:pipelines_app/features/runs/ui/runs_list.dart'; + +class _Gateway implements ApiGateway { + final framesController = StreamController.broadcast(); + JsonMap? reply; + Object? failure; + Completer? gate; + + @override + Stream get frames => framesController.stream; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + await gate?.future; + if (failure != null) throw failure!; + return reply ?? {'runs': []}; + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late _Gateway gateway; + late RunsController controller; + + setUp(() { + gateway = _Gateway(); + controller = RunsController(RunsRepository(gateway)); + }); + + tearDown(() async { + controller.dispose(); + await gateway.framesController.close(); + }); + + Future mount( + WidgetTester tester, { + required bool cupertino, + ValueChanged? onSelected, + }) async { + gateway.reply = { + 'runs': [ + {'id': 1, 'name': 'Alpha', 'status': 'running', 'scheduled': true}, + {'id': 2, 'name': 'Beta', 'status': 'failed', 'scheduled': false}, + ], + }; + await controller.load(); + final list = AnimatedBuilder( + animation: controller, + builder: (context, _) => + RunsList(controller: controller, onSelected: onSelected ?? (_) {}), + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp(home: CupertinoPageScaffold(child: list)) + : MaterialApp(home: Scaffold(body: list)), + ); + } + + testWidgets( + 'uses native search and filters runs in CupertinoApp', + (tester) async { + num? selectedRun; + await mount( + tester, + cupertino: true, + onSelected: (id) => selectedRun = id, + ); + + expect(find.byType(CupertinoSearchTextField), findsOneWidget); + expect(find.text('Alpha'), findsOneWidget); + await tester.enterText(find.byType(CupertinoSearchTextField), 'Beta'); + await tester.pumpAndSettle(); + expect(find.text('Beta'), findsNWidgets(2)); + expect(find.text('Alpha'), findsNothing); + await tester.tap(find.byType(CupertinoListTile)); + expect(selectedRun, 2); + await tester.enterText(find.byType(CupertinoSearchTextField), 'missing'); + await tester.pumpAndSettle(); + expect(find.text('No runs found.'), findsOneWidget); + await tester.enterText(find.byType(CupertinoSearchTextField), ''); + await tester.pumpAndSettle(); + await tester.tap(find.textContaining('Schedule:')); + await tester.pumpAndSettle(); + expect(find.text('Scheduled'), findsWidgets); + await tester.tap(find.text('Scheduled').last); + await tester.pumpAndSettle(); + expect(controller.scheduled, 'scheduled'); + }, + variant: TargetPlatformVariant.only(TargetPlatform.iOS), + ); + + testWidgets( + 'retains Material controls and handles large text on narrow layout', + (tester) async { + tester.view.devicePixelRatio = 2; + tester.view.physicalSize = const Size(780, 1560); + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + MaterialApp( + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: const TextScaler.linear(2)), + child: child!, + ), + home: Scaffold( + body: AnimatedBuilder( + animation: controller, + builder: (_, _) => + RunsList(controller: controller, onSelected: (_) {}), + ), + ), + ), + ); + gateway.reply = { + 'runs': [ + {'id': 1, 'name': 'Alpha', 'status': 'running', 'scheduled': true}, + {'id': 2, 'name': 'Beta', 'status': 'failed', 'scheduled': false}, + ], + }; + await controller.load(); + await tester.pumpAndSettle(); + expect(find.byType(TextField), findsOneWidget); + final layoutError = tester.takeException(); + expect( + layoutError, + isNull, + reason: layoutError is FlutterError + ? layoutError.toStringDeep() + : '$layoutError', + ); + }, + variant: TargetPlatformVariant.only(TargetPlatform.android), + ); + + testWidgets( + 'shows loading, error and server-empty states distinctly', + (tester) async { + gateway.failure = StateError('offline'); + gateway.gate = Completer(); + final loading = controller.load(); + await tester.pumpWidget( + CupertinoApp( + home: CupertinoPageScaffold( + child: AnimatedBuilder( + animation: controller, + builder: (_, child) => + RunsList(controller: controller, onSelected: (_) {}), + ), + ), + ), + ); + await tester.pump(); + expect(find.byType(CupertinoActivityIndicator), findsOneWidget); + gateway.gate!.complete(); + await loading; + await tester.pumpAndSettle(); + expect(find.textContaining('offline'), findsOneWidget); + expect(tester.takeException(), isNull); + gateway.failure = null; + gateway.gate = null; + gateway.reply = {'runs': []}; + await controller.load(); + await tester.pumpAndSettle(); + expect(find.text('No runs found.'), findsOneWidget); + expect(find.textContaining('offline'), findsNothing); + expect(tester.takeException(), isNull); + }, + variant: TargetPlatformVariant.only(TargetPlatform.iOS), + ); +} diff --git a/app/test/features/runs/ui/runs_screen_test.dart b/app/test/features/runs/ui/runs_screen_test.dart new file mode 100644 index 00000000..e66cdfb8 --- /dev/null +++ b/app/test/features/runs/ui/runs_screen_test.dart @@ -0,0 +1,247 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/screen.dart'; + +class _Gateway implements ApiGateway { + final framesController = StreamController.broadcast(); + final listRequests = >[]; + final detailRequests = >>{}; + + @override + Stream get frames => framesController.stream; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final request = Completer(); + if (type == 'list_runs') { + listRequests.add(request); + } else if (type == 'get_run') { + final id = fields['run_id'] as num; + detailRequests.putIfAbsent(id, () => []).add(request); + } else { + request.completeError(UnsupportedError(type)); + } + return request.future; + } + + void replyList(int index, List runs) => + listRequests[index].complete({'runs': runs}); + + void replyDetail(num id, int index, JsonMap detail) => + detailRequests[id]![index].complete({'run_detail': detail}); + + void failDetail(num id, int index, Object error) => + detailRequests[id]![index].completeError(error); +} + +const _runs = [ + {'id': 1, 'title': 'Alpha run', 'name': 'alpha', 'status': 'running'}, + {'id': 2, 'title': 'Beta run', 'name': 'beta', 'status': 'failed'}, +]; + +Widget _materialScreen( + _Gateway gateway, { + int? initialRunId, + int syncToken = 0, + ValueChanged? onRunSelected, + VoidCallback? onBack, +}) => MaterialApp( + home: Scaffold( + body: RunsScreen( + gateway: gateway, + initialRunId: initialRunId, + syncToken: syncToken, + onRunSelected: onRunSelected, + onBack: onBack, + ), + ), +); + +Future _mountList(WidgetTester tester, _Gateway gateway) async { + await tester.pump(); + gateway.replyList(0, _runs); + await tester.pump(); + await tester.pump(); +} + +void main() { + late _Gateway gateway; + + setUp(() => gateway = _Gateway()); + tearDown(() => gateway.framesController.close()); + + testWidgets('initial run opens a pending detail with Back available', ( + tester, + ) async { + await tester.pumpWidget(_materialScreen(gateway, initialRunId: 1)); + await _mountList(tester, gateway); + + expect(gateway.detailRequests[1], hasLength(1)); + expect(find.text('Loading run details…'), findsOneWidget); + expect(find.text('Back to list'), findsOneWidget); + expect(find.text('Alpha run'), findsNothing); + + await tester.tap(find.text('Back to list')); + await tester.pump(); + expect(find.text('Alpha run'), findsOneWidget); + expect(find.text('Beta run'), findsOneWidget); + + // A reply that lands after Back must not reopen the previous detail. + gateway.replyDetail(1, 0, {'id': 1, 'title': 'Alpha run'}); + await tester.pump(); + expect(find.text('Alpha run'), findsOneWidget); + expect(find.text('Loading run details…'), findsNothing); + }); + + testWidgets('initial run renders its detail after the reply', (tester) async { + await tester.pumpWidget(_materialScreen(gateway, initialRunId: 1)); + await _mountList(tester, gateway); + gateway.replyDetail(1, 0, { + 'id': 1, + 'title': 'Alpha run', + 'status': 'succeeded', + 'input': {'prompt': 'initial prompt'}, + }); + await tester.pump(); + + expect(find.text('Alpha run'), findsOneWidget); + expect(find.text('initial prompt'), findsOneWidget); + expect(find.text('Loading run details…'), findsNothing); + }); + + testWidgets('detail failure keeps Back and returns to the list', ( + tester, + ) async { + await tester.pumpWidget(_materialScreen(gateway, initialRunId: 2)); + await _mountList(tester, gateway); + gateway.failDetail(2, 0, StateError('server unavailable')); + await tester.pump(); + + expect(find.textContaining('server unavailable'), findsOneWidget); + expect(find.text('Back to list'), findsOneWidget); + + await tester.tap(find.text('Back to list')); + await tester.pump(); + expect(find.text('Alpha run'), findsOneWidget); + expect(find.textContaining('server unavailable'), findsNothing); + }); + + testWidgets('selecting a list row is driven by the controller selection', ( + tester, + ) async { + await tester.pumpWidget(_materialScreen(gateway)); + await _mountList(tester, gateway); + + await tester.tap(find.text('Beta run')); + await tester.pump(); + expect(gateway.detailRequests[2], hasLength(1)); + gateway.replyDetail(2, 0, {'id': 2, 'title': 'Beta run'}); + await tester.pump(); + expect(find.text('Beta run'), findsOneWidget); + expect(find.text('Back to list'), findsOneWidget); + }); + + testWidgets('selection and Back report route changes to the host', ( + tester, + ) async { + int? selected; + var backs = 0; + await tester.pumpWidget( + _materialScreen( + gateway, + onRunSelected: (id) => selected = id, + onBack: () => backs++, + ), + ); + await _mountList(tester, gateway); + + await tester.tap(find.text('Beta run')); + await tester.pump(); + expect(selected, 2); + gateway.replyDetail(2, 0, {'id': 2, 'title': 'Beta run'}); + await tester.pump(); + + await tester.tap(find.text('Back to list')); + await tester.pump(); + expect(backs, 1); + expect(find.text('Alpha run'), findsOneWidget); + }); + + testWidgets('a route change opens and closes the named run', (tester) async { + await tester.pumpWidget(_materialScreen(gateway, initialRunId: 2)); + await _mountList(tester, gateway); + expect(gateway.detailRequests[2], hasLength(1)); + gateway.replyDetail(2, 0, {'id': 2, 'title': 'Beta run'}); + await tester.pump(); + expect(find.text('Beta run'), findsOneWidget); + + await tester.pumpWidget(_materialScreen(gateway, initialRunId: 1)); + await tester.pump(); + expect(gateway.detailRequests[1], hasLength(1)); + gateway.replyDetail(1, 0, {'id': 1, 'title': 'Alpha run'}); + await tester.pump(); + expect(find.text('Alpha run'), findsOneWidget); + + await tester.pumpWidget(_materialScreen(gateway)); + await tester.pump(); + expect(find.text('Alpha run'), findsOneWidget); + expect(find.text('Beta run'), findsOneWidget); + expect(find.text('Back to list'), findsNothing); + }); + + testWidgets('a reconnect token refreshes the open detail in place', ( + tester, + ) async { + await tester.pumpWidget(_materialScreen(gateway, initialRunId: 2)); + await _mountList(tester, gateway); + gateway.replyDetail(2, 0, {'id': 2, 'title': 'Beta run'}); + await tester.pump(); + expect(find.text('Beta run'), findsOneWidget); + + await tester.pumpWidget( + _materialScreen(gateway, initialRunId: 2, syncToken: 1), + ); + await tester.pump(); + expect(gateway.listRequests, hasLength(2)); + gateway.replyList(1, _runs); + await tester.pump(); + await tester.pump(); + expect(gateway.detailRequests[2], hasLength(2)); + gateway.replyDetail(2, 1, { + 'id': 2, + 'title': 'Beta run', + 'status': 'succeeded', + }); + await tester.pump(); + expect(find.text('Beta run'), findsOneWidget); + expect(find.text('Back to list'), findsOneWidget); + }); + + testWidgets( + 'Cupertino host keeps exactly one navigation bar while pending', + (tester) async { + await tester.pumpWidget( + CupertinoApp( + home: CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar(middle: Text('Runs')), + child: SafeArea( + child: RunsScreen(gateway: gateway, initialRunId: 1), + ), + ), + ), + ); + await _mountList(tester, gateway); + + expect(find.byType(CupertinoPageScaffold), findsOneWidget); + expect(find.byType(CupertinoNavigationBar), findsOneWidget); + expect(find.text('Loading run details…'), findsOneWidget); + expect(find.byType(CupertinoActivityIndicator), findsOneWidget); + expect(find.text('Back to list'), findsOneWidget); + }, + variant: TargetPlatformVariant.only(TargetPlatform.iOS), + ); +} diff --git a/app/test/features/schedules/data/saved_schedule_record_test.dart b/app/test/features/schedules/data/saved_schedule_record_test.dart new file mode 100644 index 00000000..aef17fe6 --- /dev/null +++ b/app/test/features/schedules/data/saved_schedule_record_test.dart @@ -0,0 +1,101 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart'; + +import 'schedule_test_support.dart'; + +void main() { + test('saved schedule exposes run-configuration provenance', () { + final schedule = SavedSchedule(savedRecord()); + + expect(schedule.id, 8); + expect(schedule.revision, 3); + expect(schedule.pipelineId, 4); + expect(schedule.version, 2); + expect(schedule.name, 'Research batteries'); + expect(schedule.enabled, isTrue); + expect(schedule.prompt, 'Research batteries'); + expect(schedule.input['custom'], {'nested': 'kept'}); + expect(schedule.workspace, '/srv/research'); + expect(schedule.writePaths, ['reports/research.md']); + expect(schedule.allowTools, isTrue); + expect(schedule.model, 'openai/gpt-5'); + expect(schedule.stageModels, {'one': 'openai/gpt-5'}); + expect(schedule.notifyMode, 'off'); + expect(schedule.title, 'Battery research'); + expect(schedule.outputFormat, 'markdown'); + expect(schedule.rule.every, '24h'); + expect(schedule.rule.days, ['mon', 'wed']); + expect(schedule.rule.timezone, 'Europe/London'); + expect(schedule.rule.isClock, isFalse); + expect(schedule.nextDue, '2026-10-22T09:00:00Z'); + expect(schedule.createdAt, '2026-10-20T09:00:00Z'); + expect(schedule.updatedAt, '2026-10-21T09:00:00Z'); + }); + + test('unknown fields survive the typed view and pause copy', () { + final schedule = SavedSchedule(savedRecord()); + final paused = schedule.withEnabled(false); + + expect(paused.enabled, isFalse); + expect(paused.id, 8); + expect(paused.revision, 3); + expect(paused.toJson()['future_server_field'], { + 'nested': [ + 1, + 2, + {'deep': true}, + ], + }); + expect(paused.toJson()['input'], { + 'prompt': 'Research batteries', + 'custom': {'nested': 'kept'}, + }); + expect(paused.toJson()['rule'], savedRecord()['rule']); + + // The original snapshot is untouched and still enabled. + expect(schedule.enabled, isTrue); + expect(schedule.revision, 3); + }); + + test('toJson is a deep copy, not an alias of the server reply', () { + final source = savedRecord(); + final schedule = SavedSchedule(source); + + final first = schedule.toJson(); + ((first['future_server_field'] as Map)['nested'] as List).add('changed'); + final second = schedule.toJson(); + expect((second['future_server_field'] as Map)['nested'], [ + 1, + 2, + {'deep': true}, + ]); + + final promptInput = schedule.input; + promptInput['custom'] = 'changed'; + expect(schedule.input['custom'], {'nested': 'kept'}); + }); + + test('missing fields stay absent instead of being fabricated', () { + final schedule = SavedSchedule(const {}); + + expect(schedule.id, isNull); + expect(schedule.revision, isNull); + expect(schedule.pipelineId, isNull); + expect(schedule.version, isNull); + expect(schedule.enabled, isFalse); + expect(schedule.prompt, ''); + expect(schedule.workspace, ''); + expect(schedule.rule.every, ''); + expect(schedule.rule.times, isEmpty); + expect(schedule.writePaths, isEmpty); + expect(schedule.stageModels, isEmpty); + expect(schedule.toJson(), isEmpty); + }); + + test('a fractional revision is not truncated into a false token', () { + final schedule = SavedSchedule(const {'id': 8, 'revision': 3.5}); + + expect(schedule.id, 8); + expect(schedule.revision, isNull); + }); +} diff --git a/app/test/features/schedules/data/schedule_test_support.dart b/app/test/features/schedules/data/schedule_test_support.dart new file mode 100644 index 00000000..f80b852f --- /dev/null +++ b/app/test/features/schedules/data/schedule_test_support.dart @@ -0,0 +1,83 @@ +import 'dart:convert'; + +import 'package:pipelines_app/core/api_gateway.dart'; + +class RecordedCall { + const RecordedCall(this.type, this.fields); + final String type; + final JsonMap fields; +} + +/// Records the exact request built by the repository and replays queued +/// replies. Both are deep-copied, so a test can prove the repository neither +/// mutated its input nor depended on alias mutation of a reply. +class RecordingGateway implements ApiGateway { + final calls = []; + final replies = []; + Object? failure; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add(RecordedCall(type, deepCopy(fields))); + if (failure case final error?) throw error; + if (replies.isEmpty) throw StateError('No recorded reply for $type'); + return deepCopy(replies.removeAt(0)); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap deepCopy(JsonMap value) => jsonDecode(jsonEncode(value)) as JsonMap; + +/// A complete server record including fields this client does not interpret +/// yet, an unknown nested rule field and unknown input. +JsonMap savedRecord() => { + 'id': 8, + 'revision': 3, + 'name': 'Research batteries', + 'pipeline_id': 4, + 'version': 2, + 'enabled': true, + 'input': { + 'prompt': 'Research batteries', + 'custom': {'nested': 'kept'}, + }, + 'workspace': '/srv/research', + 'write_paths': ['reports/research.md'], + 'allow_tools': true, + 'model': 'openai/gpt-5', + 'stage_models': {'one': 'openai/gpt-5'}, + 'notify_mode': 'off', + 'title': 'Battery research', + 'output_format': 'markdown', + 'rule': { + 'every': '24h', + 'days': ['mon', 'wed'], + 'timezone': 'Europe/London', + 'future_rule_field': 'kept', + }, + 'next_due': '2026-10-22T09:00:00Z', + 'created_at': '2026-10-20T09:00:00Z', + 'updated_at': '2026-10-21T09:00:00Z', + 'future_server_field': { + 'nested': [ + 1, + 2, + {'deep': true}, + ], + }, +}; + +/// The create form of the record: id 0 is the server's create sentinel and no +/// revision has been issued yet. +JsonMap createRecord() => { + 'id': 0, + 'name': 'Research batteries', + 'pipeline_id': 4, + 'version': 2, + 'enabled': true, + 'input': {'prompt': 'Research batteries'}, + 'workspace': '/srv/research', + 'rule': {'every': '24h', 'timezone': 'Europe/London'}, +}; diff --git a/app/test/features/schedules/data/schedules_delete_test.dart b/app/test/features/schedules/data/schedules_delete_test.dart new file mode 100644 index 00000000..fc4f8d32 --- /dev/null +++ b/app/test/features/schedules/data/schedules_delete_test.dart @@ -0,0 +1,131 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/schedules/data/schedules_repository.dart'; + +import 'schedule_test_support.dart'; + +void main() { + test('delete sends the exact ID and expected revision', () async { + final gateway = RecordingGateway() + ..replies.add({'type': 'schedule_deleted', 'schedule_id': 8}); + final repository = SchedulesRepository(gateway); + + await repository.deleteSchedule(8, 3); + + expect(gateway.calls.single.type, 'delete_schedule'); + expect(gateway.calls.single.fields, { + 'schedule_id': 8, + 'expected_revision': 3, + }); + }); + + test('delete refuses a confirmation for anything else', () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + for (final reply in [ + {}, + {'type': 'pong'}, + {'type': 'schedule_deleted'}, + {'type': 'schedule_deleted', 'schedule_id': 9}, + ]) { + gateway.replies.add(reply); + await expectLater( + repository.deleteSchedule(8, 3), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server did not confirm deletion of this schedule.', + ), + ), + ); + } + }); + + test('server refusals and conflicts propagate verbatim', () async { + final conflict = const ProtocolError( + 'schedule revision conflict; reload before editing', + ); + final recording = RecordingGateway()..failure = conflict; + final conflicting = SchedulesRepository(recording); + await expectLater( + conflicting.saveSchedule(createRecord()), + throwsA(same(conflict)), + ); + await expectLater( + conflicting.deleteSchedule(8, 3), + throwsA(same(conflict)), + ); + + final unsupported = const ProtocolError( + 'unknown message type: list_schedules', + ); + recording.failure = unsupported; + await expectLater( + conflicting.listSchedules(pipelineId: 4), + throwsA(same(unsupported)), + ); + }); + + test('missing and empty list replies are different facts', () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + + gateway.replies.add({'type': 'schedules'}); + expect(await repository.listSchedules(), isEmpty); + + gateway.replies.add({'type': 'schedules', 'schedules': null}); + expect(await repository.listSchedules(), isEmpty); + + for (final reply in [ + {}, + {'type': 'pong'}, + {'type': 'schedules', 'schedules': {}}, + { + 'type': 'schedules', + 'schedules': ['not a record'], + }, + ]) { + gateway.replies.add(reply); + await expectLater( + repository.listSchedules(), + throwsA(isA()), + ); + } + }); + + test('save requires a saved schedule in the reply', () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + for (final reply in [ + {}, + {'type': 'schedule'}, + {'type': 'schedule', 'schedule': null}, + {'type': 'schedule', 'schedule': 'record'}, + ]) { + gateway.replies.add(reply); + await expectLater( + repository.saveSchedule(createRecord()), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned no saved schedule.', + ), + ), + ); + } + }); + + test('an empty schedule object is not turned into a fake identity', () async { + final gateway = RecordingGateway() + ..replies.add({'type': 'schedule', 'schedule': {}}); + final repository = SchedulesRepository(gateway); + + final saved = await repository.saveSchedule(createRecord()); + + expect(saved.id, isNull); + expect(saved.revision, isNull); + expect(saved.toJson(), isEmpty); + }); +} diff --git a/app/test/features/schedules/data/schedules_protocol_bounds_test.dart b/app/test/features/schedules/data/schedules_protocol_bounds_test.dart new file mode 100644 index 00000000..db39b164 --- /dev/null +++ b/app/test/features/schedules/data/schedules_protocol_bounds_test.dart @@ -0,0 +1,81 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/schedules/data/schedules_repository.dart'; + +import 'schedule_test_support.dart'; + +void main() { + test( + 'list rejects non-positive and unsafe pipeline IDs before sending', + () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + + for (final id in [0, -1, 9007199254740992]) { + await expectLater( + repository.listSchedules(pipelineId: id), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'A positive pipeline ID is required.', + ), + ), + ); + } + expect(gateway.calls, isEmpty); + }, + ); + + test( + 'delete rejects an inexact identity or revision before sending', + () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + + for (final pair in [ + (0, 1), + (-1, 1), + (8, 0), + (8, -1), + (8, 9007199254740992), + ]) { + await expectLater( + repository.deleteSchedule(pair.$1, pair.$2), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'An exact schedule ID and revision are required.', + ), + ), + ); + } + expect(gateway.calls, isEmpty); + }, + ); + + test( + 'request keys are bounded at 128 characters like the web client', + () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + + await expectLater( + repository.saveSchedule(createRecord(), requestKey: 'x' * 129), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'Schedule request keys must be strings of at most 128 characters.', + ), + ), + ); + expect(gateway.calls, isEmpty); + + final key = 'x' * 128; + gateway.replies.add({'type': 'schedule', 'schedule': savedRecord()}); + await repository.saveSchedule(createRecord(), requestKey: key); + expect(gateway.calls.single.fields['request_key'], key); + }, + ); +} diff --git a/app/test/features/schedules/data/schedules_repository_test.dart b/app/test/features/schedules/data/schedules_repository_test.dart new file mode 100644 index 00000000..8ac1ef4c --- /dev/null +++ b/app/test/features/schedules/data/schedules_repository_test.dart @@ -0,0 +1,132 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/schedules/data/schedules_repository.dart'; +import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart'; + +import 'schedule_test_support.dart'; + +void main() { + test( + 'lists with the exact web envelope and retains every record field', + () async { + final record = savedRecord(); + final gateway = RecordingGateway() + ..replies.add({ + 'type': 'schedules', + 'schedules': [record], + }); + final repository = SchedulesRepository(gateway); + + final listed = await repository.listSchedules(pipelineId: 4); + + expect(gateway.calls.single.type, 'list_schedules'); + expect(gateway.calls.single.fields, {'pipeline_id': 4}); + expect(listed.single.toJson(), record); + expect(listed.single.pipelineId, 4); + expect(listed.single.version, 2); + expect(listed.single.prompt, 'Research batteries'); + expect(listed.single.workspace, '/srv/research'); + expect(listed.single.enabled, isTrue); + expect(listed.single.rule.every, '24h'); + expect(listed.single.rule.days, ['mon', 'wed']); + expect(listed.single.rule.timezone, 'Europe/London'); + expect(listed.single.model, 'openai/gpt-5'); + expect(listed.single.notifyMode, 'off'); + expect(listed.single.toJson()['future_server_field'], { + 'nested': [ + 1, + 2, + {'deep': true}, + ], + }); + + gateway.replies.add({'type': 'schedules'}); + await repository.listSchedules(); + expect(gateway.calls.last.type, 'list_schedules'); + expect(gateway.calls.last.fields, isEmpty); + }, + ); + + test( + 'create sends the web sentinel record without inventing a revision', + () async { + final create = createRecord(); + final original = deepCopy(create); + final gateway = RecordingGateway() + ..replies.add({'type': 'schedule', 'schedule': savedRecord()}); + final repository = SchedulesRepository(gateway); + + final saved = await repository.saveSchedule(create); + + expect(gateway.calls.single.type, 'save_schedule'); + expect(gateway.calls.single.fields, {'schedule': create}); + expect(gateway.calls.single.fields.containsKey('request_key'), isFalse); + expect( + gateway.calls.single.fields.containsKey('expected_revision'), + isFalse, + ); + expect(create, original, reason: 'the caller record must be unchanged'); + expect(saved.id, 8); + expect(saved.revision, 3); + expect(saved.toJson(), savedRecord()); + }, + ); + + test( + 'a stable create key is forwarded exactly and blanks are omitted', + () async { + final create = createRecord(); + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + + gateway.replies.add({'type': 'schedule', 'schedule': savedRecord()}); + await repository.saveSchedule( + create, + requestKey: 'schedule:stable-editor-key', + ); + expect(gateway.calls.last.fields, { + 'schedule': create, + 'request_key': 'schedule:stable-editor-key', + }); + + gateway.replies.add({'type': 'schedule', 'schedule': savedRecord()}); + await repository.saveSchedule(create, requestKey: ''); + expect(gateway.calls.last.fields, {'schedule': create}); + }, + ); + + test('update reuses the read revision as the CAS token', () async { + final current = SavedSchedule(savedRecord()); + final paused = current.withEnabled(false); + expect(paused.id, 8); + expect(paused.revision, 3); + expect(paused.toJson()['future_server_field'], isNotNull); + + final gateway = RecordingGateway() + ..replies.add({ + 'type': 'schedule', + 'schedule': {...savedRecord(), 'enabled': false, 'revision': 4}, + }); + final repository = SchedulesRepository(gateway); + + final updated = await repository.saveSchedule(paused.toJson()); + + final body = gateway.calls.single.fields['schedule'] as Map; + expect(gateway.calls.single.type, 'save_schedule'); + expect(gateway.calls.single.fields.containsKey('request_key'), isFalse); + expect( + gateway.calls.single.fields.containsKey('expected_revision'), + isFalse, + ); + expect(body['id'], 8); + expect(body['revision'], 3); + expect(body['enabled'], isFalse); + expect(body['future_server_field'], isNotNull); + expect(updated.revision, 4); + expect(updated.enabled, isFalse); + + // The stale draft keeps its token: a conflict must not be papered over by + // silently adopting the reply revision. + expect(current.revision, 3); + expect(current.enabled, isTrue); + }); +} diff --git a/app/test/features/schedules/ui/list/schedule_list_controller_test.dart b/app/test/features/schedules/ui/list/schedule_list_controller_test.dart new file mode 100644 index 00000000..44be8b24 --- /dev/null +++ b/app/test/features/schedules/ui/list/schedule_list_controller_test.dart @@ -0,0 +1,182 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/schedules/data/schedules_repository.dart'; +import 'package:pipelines_app/features/schedules/ui/list/schedule_list_controller.dart'; + +import 'schedule_list_test_support.dart'; + +SchedulesController controllerFor(ApiGateway gateway, {int? pipelineId}) => + SchedulesController( + repository: SchedulesRepository(gateway), + pipelineId: pipelineId, + ); + +void main() { + test('lists schedules with the optional pipeline envelope', () async { + final gateway = FakeSchedulesGateway( + (type, fields) async => + schedulesReply([scheduleRecord(), pausedRecord()]), + ); + final controller = controllerFor(gateway, pipelineId: 4); + addTearDown(controller.dispose); + + await controller.refresh(); + + expect(gateway.calls.single.type, 'list_schedules'); + expect(gateway.calls.single.fields, {'pipeline_id': 4}); + expect(controller.schedules.map((schedule) => schedule.name), [ + 'Research batteries', + 'Nightly report', + ]); + expect(controller.hasLoaded, isTrue); + expect(controller.failure, isNull); + expect(controller.countLabel, '2 schedules'); + + final globalGateway = FakeSchedulesGateway( + (type, fields) async => schedulesReply([scheduleRecord()]), + ); + final global = controllerFor(globalGateway); + addTearDown(global.dispose); + await global.refresh(); + expect(globalGateway.calls.single.fields, isEmpty); + }); + + test('an empty reply is loaded empty, not an unsupported server', () async { + final gateway = FakeSchedulesGateway( + (type, fields) async => {'type': 'schedules'}, + ); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + await controller.refresh(); + + expect(controller.hasLoaded, isTrue); + expect(controller.schedules, isEmpty); + expect(controller.failure, isNull); + expect(controller.countLabel, '0 schedules'); + }); + + test('an unsupported envelope is distinct from empty and errors', () async { + final unsupported = controllerFor( + FakeSchedulesGateway((type, fields) async => {'type': 'runs'}), + ); + addTearDown(unsupported.dispose); + await unsupported.refresh(); + expect(unsupported.failure?.unsupported, isTrue); + expect(unsupported.failure?.message, contains('does not support')); + expect(unsupported.failure?.message, contains('Upgrade the server')); + expect(unsupported.hasLoaded, isFalse); + + final failed = controllerFor( + FakeSchedulesGateway( + (type, fields) async => throw StateError('socket closed'), + ), + ); + addTearDown(failed.dispose); + await failed.refresh(); + expect(failed.failure?.unsupported, isFalse); + expect(failed.failure?.message, contains('socket closed')); + expect(failed.hasLoaded, isFalse); + }); + + test( + 'an older server refusal gets the same upgrade guidance as web', + () async { + for (final text in [ + 'unknown request: list_schedules', + 'UNKNOWN COMMAND list_schedules', + 'Unsupported schedules command', + ]) { + final controller = controllerFor( + FakeSchedulesGateway( + (type, fields) async => throw SchedulesRepositoryException(text), + ), + ); + addTearDown(controller.dispose); + await controller.refresh(); + + expect(controller.failure?.unsupported, isTrue, reason: text); + expect(controller.failure?.message, contains('Upgrade the server')); + expect(controller.failure?.message, contains(text)); + } + + final unrelated = controllerFor( + FakeSchedulesGateway( + (type, fields) async => + throw const SchedulesRepositoryException('Permission denied.'), + ), + ); + addTearDown(unrelated.dispose); + await unrelated.refresh(); + expect(unrelated.failure?.unsupported, isFalse); + expect(unrelated.failure?.message, 'Permission denied.'); + }, + ); + + test('a failed refresh keeps the previously loaded schedules', () async { + var fail = false; + final gateway = FakeSchedulesGateway((type, fields) async { + if (fail) throw StateError('refresh failed'); + return schedulesReply([scheduleRecord()]); + }); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + await controller.refresh(); + fail = true; + await controller.refresh(); + + expect(controller.schedules.single.name, 'Research batteries'); + expect(controller.failure?.message, contains('refresh failed')); + expect(controller.isLoading, isFalse); + }); + + test('only the newest refresh may publish a reply', () async { + final gateway = ControlledSchedulesGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + final first = controller.refresh(); + final second = controller.refresh(); + expect(gateway.requests, hasLength(2)); + + gateway.complete(1, schedulesReply([scheduleRecord(name: 'Newest reply')])); + await second; + gateway.complete(0, schedulesReply([scheduleRecord(name: 'Stale reply')])); + await first; + + expect(controller.schedules.single.name, 'Newest reply'); + expect(controller.isLoading, isFalse); + }); + + test('a reply arriving after dispose is ignored safely', () async { + final gateway = ControlledSchedulesGateway(); + final controller = controllerFor(gateway); + var notifications = 0; + controller.addListener(() => notifications++); + + final pending = controller.refresh(); + expect(notifications, 1); + controller.dispose(); + gateway.complete(0, schedulesReply([scheduleRecord()])); + + await expectLater(pending, completes); + expect(notifications, 1); + }); + + test('missing server fields stay visible as unavailable values', () async { + final gateway = FakeSchedulesGateway( + (type, fields) async => schedulesReply([sparseRecord()]), + ); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + await controller.refresh(); + + final schedule = controller.schedules.single; + expect(schedule.name, isEmpty); + expect(schedule.pipelineId, isNull); + expect(schedule.version, isNull); + expect(schedule.workspace, isEmpty); + expect(schedule.nextDue, isEmpty); + }); +} diff --git a/app/test/features/schedules/ui/list/schedule_list_filter_test.dart b/app/test/features/schedules/ui/list/schedule_list_filter_test.dart new file mode 100644 index 00000000..9439f675 --- /dev/null +++ b/app/test/features/schedules/ui/list/schedule_list_filter_test.dart @@ -0,0 +1,87 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/schedules/data/schedules_repository.dart'; +import 'package:pipelines_app/features/schedules/ui/list/schedule_list_controller.dart'; + +import 'schedule_list_test_support.dart'; + +SchedulesController controllerFor(ApiGateway gateway) => + SchedulesController(repository: SchedulesRepository(gateway)); + +void main() { + test( + 'search covers name, prompt and pipeline; enabled filters rows', + () async { + final gateway = FakeSchedulesGateway( + (type, fields) async => + schedulesReply([scheduleRecord(), pausedRecord()]), + ); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + await controller.refresh(); + + controller.setQuery('research'); + expect(controller.visibleSchedules.single.name, 'Research batteries'); + + controller.setQuery('BATTERY CHEMISTRY'); + expect(controller.visibleSchedules.single.id, 8); + + controller.setQuery('pipeline 7'); + expect(controller.visibleSchedules.single.name, 'Nightly report'); + expect(controller.countLabel, '1 of 2 schedules'); + + controller.setQuery('pipeline unavailable'); + expect(controller.visibleSchedules, isEmpty); + + controller.clearQuery(); + controller.setFilter(ScheduleListFilter.enabled); + expect(controller.visibleSchedules.single.name, 'Research batteries'); + expect(controller.emptyMessage, 'No enabled schedules.'); + + await controller.refresh(); + expect(controller.filter, ScheduleListFilter.enabled); + expect(controller.visibleSchedules.single.name, 'Research batteries'); + + controller.setQuery('unmatched'); + expect(controller.visibleSchedules, isEmpty); + expect(controller.countLabel, '0 of 2 schedules'); + expect(controller.emptyMessage, 'No schedules match this search.'); + }, + ); + + test( + 'the filtered view is recomputed for query, filter and new replies', + () async { + var records = [scheduleRecord(), pausedRecord()]; + final gateway = FakeSchedulesGateway( + (type, fields) async => schedulesReply(records), + ); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + await controller.refresh(); + + expect(controller.visibleSchedules, hasLength(2)); + + controller.setQuery('nightly'); + expect(controller.visibleSchedules.single.name, 'Nightly report'); + + controller.clearQuery(); + controller.setFilter(ScheduleListFilter.enabled); + expect(controller.visibleSchedules.single.name, 'Research batteries'); + + records = [ + scheduleRecord(id: 20, name: 'Renamed', enabled: false), + scheduleRecord(id: 21, name: 'Fresh'), + ]; + await controller.refresh(); + expect(controller.visibleSchedules.single.name, 'Fresh'); + expect(controller.countLabel, '1 of 2 schedules'); + + controller.setFilter(ScheduleListFilter.all); + expect(controller.visibleSchedules.map((schedule) => schedule.name), [ + 'Renamed', + 'Fresh', + ]); + }, + ); +} diff --git a/app/test/features/schedules/ui/list/schedule_list_format_test.dart b/app/test/features/schedules/ui/list/schedule_list_format_test.dart new file mode 100644 index 00000000..6a4c6f24 --- /dev/null +++ b/app/test/features/schedules/ui/list/schedule_list_format_test.dart @@ -0,0 +1,72 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart'; +import 'package:pipelines_app/features/schedules/ui/list/schedule_list_format.dart'; + +import 'schedule_list_test_support.dart'; + +void main() { + test('formats complete server values', () { + final schedule = SavedSchedule(scheduleRecord()); + + expect(scheduleDisplayName(schedule), 'Research batteries'); + expect(scheduleStatusLabel(schedule), 'Enabled'); + expect(schedulePipelineVersionValue(schedule), 'Pipeline 4 · v2'); + expect(scheduleWorkspaceValue(schedule), '/srv/research'); + expect(scheduleTimerValue(schedule), 'Every 24h · mon, wed'); + expect(scheduleTimezoneValue(schedule), 'Europe/London'); + expect(scheduleNextDueValue(schedule), scheduleDueValue(schedule.nextDue)); + }); + + test('formats clock rules and the server timezone fallback', () { + final schedule = SavedSchedule(pausedRecord()); + + expect(scheduleStatusLabel(schedule), 'Paused'); + expect(scheduleTimerValue(schedule), '10:00, 18:30'); + expect(scheduleTimezoneValue(schedule), 'Server timezone'); + expect(scheduleNextDueValue(schedule), 'Paused'); + }); + + test('missing server values are honest, never invented', () { + final schedule = SavedSchedule(sparseRecord()); + + expect(scheduleDisplayName(schedule), 'Unnamed schedule'); + expect( + schedulePipelineVersionValue(schedule), + 'Pipeline unavailable · Version unavailable', + ); + expect(scheduleWorkspaceValue(schedule), 'Workspace unavailable'); + expect(scheduleTimerValue(schedule), 'Timer unavailable'); + expect(scheduleTimezoneValue(schedule), 'Server timezone'); + expect(scheduleNextDueValue(schedule), 'Paused'); + + final enabled = SavedSchedule(scheduleRecord(nextDue: null)); + expect(scheduleNextDueValue(enabled), 'Not scheduled'); + + final invalid = SavedSchedule(scheduleRecord(nextDue: 'tomorrow')); + expect(scheduleNextDueValue(invalid), 'Next time unavailable'); + }); + + test('due values are shown in local time and keep invalid input honest', () { + expect( + scheduleDueValue('2026-10-22T09:00:00'), + '2026-10-22 09:00 (your local time)', + ); + + final value = scheduleDueValue('2026-10-22T09:00:00Z'); + final local = DateTime.parse('2026-10-22T09:00:00Z').toLocal(); + String two(int part) => part.toString().padLeft(2, '0'); + expect( + value, + '${local.year}-${two(local.month)}-${two(local.day)} ' + '${two(local.hour)}:${two(local.minute)} (your local time)', + ); + expect(scheduleDueValue('not a date'), 'Next time unavailable'); + }); + + test('count wording covers single, plural, filtered and empty lists', () { + expect(scheduleCountLabel(1, 1), '1 schedule'); + expect(scheduleCountLabel(2, 2), '2 schedules'); + expect(scheduleCountLabel(1, 2), '1 of 2 schedules'); + expect(scheduleCountLabel(0, 0), '0 schedules'); + }); +} diff --git a/app/test/features/schedules/ui/list/schedule_list_test_support.dart b/app/test/features/schedules/ui/list/schedule_list_test_support.dart new file mode 100644 index 00000000..394f5d53 --- /dev/null +++ b/app/test/features/schedules/ui/list/schedule_list_test_support.dart @@ -0,0 +1,143 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; + +typedef ScheduleHandler = Future Function(String type, JsonMap fields); + +class RecordedScheduleCall { + const RecordedScheduleCall(this.type, this.fields); + final String type; + final JsonMap fields; +} + +/// Records every request and replays the handler's reply. No socket is opened. +class FakeSchedulesGateway implements ApiGateway { + FakeSchedulesGateway(this.handler); + + final ScheduleHandler handler; + final calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + calls.add(RecordedScheduleCall(type, Map.from(fields))); + return handler(type, Map.from(fields)); + } + + @override + Stream get frames => const Stream.empty(); +} + +/// Holds each request open so a test can complete replies out of order or after +/// the screen is gone. +class ControlledSchedulesGateway implements ApiGateway { + final calls = []; + final requests = >[]; + + @override + Future call(String type, [JsonMap fields = const {}]) { + calls.add(RecordedScheduleCall(type, Map.from(fields))); + final request = Completer(); + requests.add(request); + return request.future; + } + + void complete(int index, JsonMap reply) => requests[index].complete(reply); + + void fail(int index, Object error) => requests[index].completeError(error); + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap schedulesReply(List items) => { + 'type': 'schedules', + 'schedules': items, +}; + +JsonMap scheduleRecord({ + int? id = 8, + int? revision = 3, + String name = 'Research batteries', + int? pipelineId = 4, + int? version = 2, + bool enabled = true, + String prompt = 'Find battery chemistry sources', + String workspace = '/srv/research', + Map rule = const { + 'every': '24h', + 'days': ['mon', 'wed'], + 'timezone': 'Europe/London', + }, + String? nextDue = '2026-10-22T09:00:00Z', +}) => { + 'id': ?id, + 'revision': ?revision, + 'name': name, + 'pipeline_id': ?pipelineId, + 'version': ?version, + 'enabled': enabled, + 'input': {'prompt': prompt}, + 'workspace': workspace, + 'rule': rule, + 'next_due': ?nextDue, +}; + +JsonMap pausedRecord() => scheduleRecord( + id: 9, + revision: 1, + name: 'Nightly report', + pipelineId: 7, + version: 5, + enabled: false, + prompt: 'Summarise the open issues', + workspace: '/srv/reports', + rule: const { + 'times': ['10:00', '18:30'], + 'days': [], + 'timezone': 'Local', + }, + nextDue: null, +); + +JsonMap sparseRecord() => { + 'id': 11, + 'name': '', + 'enabled': false, + 'input': {}, + 'rule': {}, +}; + +List longScheduleList(int count) => [ + for (var index = 0; index < count; index++) + scheduleRecord( + id: 100 + index, + revision: 1, + name: 'Topic $index', + prompt: 'Prompt $index', + ), +]; + +Widget schedulesApp( + Widget child, { + required bool cupertino, + double textScale = 1, +}) { + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + if (cupertino) { + return CupertinoApp( + builder: media, + home: CupertinoPageScaffold(child: SafeArea(child: child)), + ); + } + return MaterialApp( + builder: media, + home: Scaffold(body: child), + ); +} diff --git a/app/test/features/schedules/ui/list/schedule_screen_harness.dart b/app/test/features/schedules/ui/list/schedule_screen_harness.dart new file mode 100644 index 00000000..607e90bb --- /dev/null +++ b/app/test/features/schedules/ui/list/schedule_screen_harness.dart @@ -0,0 +1,33 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart'; +import 'package:pipelines_app/features/schedules/screen.dart'; + +import 'schedule_list_test_support.dart'; + +Future pumpSchedules( + WidgetTester tester, { + required bool cupertino, + required ApiGateway gateway, + ValueChanged? onOpen, + double textScale = 1, + bool settle = true, +}) async { + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + schedulesApp( + SchedulesScreen(gateway: gateway, onOpen: onOpen ?? (_) {}), + cupertino: cupertino, + textScale: textScale, + ), + ); + if (settle) { + await tester.pumpAndSettle(); + } else { + await tester.pump(); + } +} diff --git a/app/test/features/schedules/ui/list/schedules_layout_test.dart b/app/test/features/schedules/ui/list/schedules_layout_test.dart new file mode 100644 index 00000000..374802c1 --- /dev/null +++ b/app/test/features/schedules/ui/list/schedules_layout_test.dart @@ -0,0 +1,79 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/schedules/ui/list/schedule_list_controller.dart'; +import 'package:pipelines_app/features/schedules/ui/list/schedule_list_toolbar.dart'; +import 'package:pipelines_app/features/schedules/ui/list/schedule_list_view.dart'; + +import 'schedule_list_test_support.dart'; +import 'schedule_screen_harness.dart'; + +void main() { + for (final cupertino in [false, true]) { + for (final textScale in [1.0, 2.0]) { + testWidgets('${cupertino ? 'Cupertino' : 'Material'} list at 390px and ' + '${textScale}x text shows server values with native controls', ( + tester, + ) async { + final gateway = FakeSchedulesGateway( + (type, fields) async => schedulesReply([ + scheduleRecord(nextDue: '2026-10-22T09:00:00'), + pausedRecord(), + ]), + ); + await pumpSchedules( + tester, + cupertino: cupertino, + gateway: gateway, + textScale: textScale, + ); + + expect(find.text('2 schedules'), findsOneWidget); + expect(find.textContaining('not pipeline definitions'), findsOneWidget); + expect(find.text('Research batteries'), findsOneWidget); + expect(find.text('Find battery chemistry sources'), findsOneWidget); + expect(find.text('Pipeline 4 · v2'), findsOneWidget); + expect(find.text('Workspace: /srv/research'), findsOneWidget); + expect(find.text('Timer: Every 24h · mon, wed'), findsOneWidget); + expect(find.text('Timezone: Europe/London'), findsOneWidget); + expect( + find.text('Next due: 2026-10-22 09:00 (your local time)'), + findsOneWidget, + ); + + await tester.scrollUntilVisible( + find.text('Nightly report'), + 300, + scrollable: find.descendant( + of: find.byKey(scheduleListKey), + matching: find.byType(Scrollable), + ), + ); + expect(find.text('Nightly report'), findsOneWidget); + expect(find.text('Pipeline 7 · v5'), findsOneWidget); + expect(find.text('Workspace: /srv/reports'), findsOneWidget); + expect(find.text('Timer: 10:00, 18:30'), findsOneWidget); + expect(find.text('Timezone: Server timezone'), findsOneWidget); + expect(find.text('Next due: Paused'), findsOneWidget); + + if (cupertino) { + expect(find.byType(CupertinoSearchTextField), findsOneWidget); + expect( + find.byType(CupertinoSlidingSegmentedControl), + findsOneWidget, + ); + expect(find.byType(CupertinoButton), findsWidgets); + expect(find.byType(TextField), findsNothing); + } else { + expect(find.byKey(scheduleSearchFieldKey), findsOneWidget); + expect( + find.byType(SegmentedButton), + findsOneWidget, + ); + expect(find.byType(TextField), findsOneWidget); + } + expect(tester.takeException(), isNull); + }); + } + } +} diff --git a/app/test/features/schedules/ui/list/schedules_refresh_test.dart b/app/test/features/schedules/ui/list/schedules_refresh_test.dart new file mode 100644 index 00000000..ffaea372 --- /dev/null +++ b/app/test/features/schedules/ui/list/schedules_refresh_test.dart @@ -0,0 +1,119 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/schedules/ui/list/schedule_list_toolbar.dart'; +import 'package:pipelines_app/features/schedules/ui/list/schedule_list_view.dart'; + +import 'schedule_list_test_support.dart'; +import 'schedule_screen_harness.dart'; + +void main() { + testWidgets('refresh keeps the search query and its filtered rows', ( + tester, + ) async { + final gateway = FakeSchedulesGateway( + (type, fields) async => + schedulesReply([scheduleRecord(), pausedRecord()]), + ); + await pumpSchedules(tester, cupertino: false, gateway: gateway); + + await tester.enterText( + find.byKey(scheduleSearchFieldKey), + 'battery chemistry', + ); + await tester.pump(); + expect(find.text('Research batteries'), findsOneWidget); + expect(find.text('Nightly report'), findsNothing); + + await tester.tap(find.byKey(scheduleRefreshKey)); + await tester.pumpAndSettle(); + + final field = tester.widget(find.byKey(scheduleSearchFieldKey)); + expect(field.controller?.text, 'battery chemistry'); + expect(find.text('Research batteries'), findsOneWidget); + expect(find.text('Nightly report'), findsNothing); + expect(gateway.calls, hasLength(2)); + expect( + gateway.calls.every((call) => call.type == 'list_schedules'), + isTrue, + ); + }); + + testWidgets('refresh preserves the list scroll offset', (tester) async { + final gateway = FakeSchedulesGateway( + (type, fields) async => schedulesReply(longScheduleList(30)), + ); + await pumpSchedules(tester, cupertino: false, gateway: gateway); + + final list = find.byKey(scheduleListKey); + await tester.drag(list, const Offset(0, -700)); + await tester.pumpAndSettle(); + final before = tester.widget(list).controller!.offset; + expect(before, greaterThan(0)); + + await tester.tap(find.byKey(scheduleRefreshKey)); + await tester.pumpAndSettle(); + + final after = tester.widget(list).controller!.offset; + expect(after, before); + expect(tester.takeException(), isNull); + }); + + testWidgets('a failed refresh keeps the scroll offset and the rows', ( + tester, + ) async { + var fail = false; + final gateway = FakeSchedulesGateway((type, fields) async { + if (fail) throw StateError('refresh failed'); + return schedulesReply(longScheduleList(30)); + }); + await pumpSchedules(tester, cupertino: false, gateway: gateway); + + final list = find.byKey(scheduleListKey); + await tester.drag(list, const Offset(0, -700)); + await tester.pumpAndSettle(); + final before = tester.widget(list).controller!.offset; + expect(before, greaterThan(0)); + + fail = true; + await tester.tap(find.byKey(scheduleRefreshKey)); + await tester.pumpAndSettle(); + + expect(find.textContaining('refresh failed'), findsOneWidget); + expect( + tester.widget(find.byKey(scheduleListKey)).controller!.offset, + before, + ); + + fail = false; + await tester.tap(find.byKey(scheduleRetryKey)); + await tester.pumpAndSettle(); + + expect(find.textContaining('refresh failed'), findsNothing); + expect( + tester.widget(find.byKey(scheduleListKey)).controller!.offset, + before, + ); + expect(tester.takeException(), isNull); + }); + + testWidgets('a failed refresh keeps rows and reports the error', ( + tester, + ) async { + var fail = false; + final gateway = FakeSchedulesGateway((type, fields) async { + if (fail) throw StateError('refresh failed'); + return schedulesReply([scheduleRecord(), pausedRecord()]); + }); + await pumpSchedules(tester, cupertino: false, gateway: gateway); + + fail = true; + await tester.tap(find.byKey(scheduleRefreshKey)); + await tester.pumpAndSettle(); + + expect(find.text('Research batteries'), findsOneWidget); + expect(find.text('Nightly report'), findsOneWidget); + expect(find.textContaining('refresh failed'), findsOneWidget); + expect(find.byKey(scheduleRetryKey), findsOneWidget); + expect(tester.takeException(), isNull); + }); +} diff --git a/app/test/features/schedules/ui/list/schedules_screen_test.dart b/app/test/features/schedules/ui/list/schedules_screen_test.dart new file mode 100644 index 00000000..da42963a --- /dev/null +++ b/app/test/features/schedules/ui/list/schedules_screen_test.dart @@ -0,0 +1,171 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart'; +import 'package:pipelines_app/features/schedules/ui/list/schedule_list_row.dart'; +import 'package:pipelines_app/features/schedules/ui/list/schedule_list_toolbar.dart'; +import 'package:pipelines_app/features/schedules/ui/list/schedule_list_view.dart'; + +import 'schedule_list_test_support.dart'; +import 'schedule_screen_harness.dart'; + +void main() { + testWidgets('search covers name, prompt and pipeline in both themes', ( + tester, + ) async { + for (final cupertino in [false, true]) { + final gateway = FakeSchedulesGateway( + (type, fields) async => + schedulesReply([scheduleRecord(), pausedRecord()]), + ); + await pumpSchedules(tester, cupertino: cupertino, gateway: gateway); + + await tester.enterText(find.byKey(scheduleSearchFieldKey), 'pipeline 7'); + await tester.pump(); + expect(find.text('Nightly report'), findsOneWidget); + expect(find.text('Research batteries'), findsNothing); + expect(find.text('1 of 2 schedules'), findsOneWidget); + + await tester.enterText( + find.byKey(scheduleSearchFieldKey), + 'battery chemistry', + ); + await tester.pump(); + expect(find.text('Research batteries'), findsOneWidget); + expect(find.text('Nightly report'), findsNothing); + + await tester.enterText(find.byKey(scheduleSearchFieldKey), 'no match'); + await tester.pump(); + expect(find.text('No schedules match this search.'), findsOneWidget); + expect(tester.takeException(), isNull); + } + }); + + testWidgets('enabled filter removes paused schedules in both themes', ( + tester, + ) async { + for (final cupertino in [false, true]) { + final gateway = FakeSchedulesGateway( + (type, fields) async => + schedulesReply([scheduleRecord(), pausedRecord()]), + ); + await pumpSchedules(tester, cupertino: cupertino, gateway: gateway); + + await tester.tap( + find.descendant( + of: find.byKey(scheduleFilterKey), + matching: find.text('Enabled'), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Research batteries'), findsOneWidget); + expect(find.text('Nightly report'), findsNothing); + expect(find.text('1 of 2 schedules'), findsOneWidget); + expect(tester.takeException(), isNull); + } + }); + + testWidgets('row selection opens the exact record and never mutates', ( + tester, + ) async { + final record = scheduleRecord(); + final gateway = FakeSchedulesGateway( + (type, fields) async => schedulesReply([record]), + ); + final opened = []; + await pumpSchedules( + tester, + cupertino: false, + gateway: gateway, + onOpen: opened.add, + ); + + expect(opened, isEmpty); + expect(find.text('Add schedule'), findsNothing); + expect(find.text('Edit'), findsNothing); + expect(find.text('Delete'), findsNothing); + expect(find.text('Pause'), findsNothing); + + await tester.tap(find.byType(ScheduleListRow)); + await tester.pumpAndSettle(); + + expect(opened, hasLength(1)); + expect(opened.single.raw, equals(record)); + expect(gateway.calls.map((call) => call.type), ['list_schedules']); + }); + + testWidgets('empty and unsupported or failed replies stay distinct', ( + tester, + ) async { + final empty = FakeSchedulesGateway( + (type, fields) async => {'type': 'schedules'}, + ); + await pumpSchedules(tester, cupertino: false, gateway: empty); + expect(find.text('No schedules yet.'), findsOneWidget); + expect(find.byKey(scheduleRetryKey), findsNothing); + + final unsupported = FakeSchedulesGateway( + (type, fields) async => {'type': 'runs'}, + ); + await pumpSchedules(tester, cupertino: false, gateway: unsupported); + expect( + find.textContaining('does not support saved schedules'), + findsOneWidget, + ); + expect(find.byKey(scheduleRetryKey), findsOneWidget); + expect(find.text('No schedules yet.'), findsNothing); + + final failed = FakeSchedulesGateway( + (type, fields) async => throw StateError('socket closed'), + ); + await pumpSchedules(tester, cupertino: false, gateway: failed); + expect(find.textContaining('socket closed'), findsOneWidget); + expect(find.byKey(scheduleRetryKey), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('an empty search with the enabled filter names the filter', ( + tester, + ) async { + final gateway = FakeSchedulesGateway( + (type, fields) async => schedulesReply([pausedRecord()]), + ); + await pumpSchedules(tester, cupertino: false, gateway: gateway); + + await tester.tap( + find.descendant( + of: find.byKey(scheduleFilterKey), + matching: find.text('Enabled'), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('0 of 1 schedules'), findsOneWidget); + expect(find.text('No enabled schedules.'), findsOneWidget); + expect(find.text('No schedules match this search.'), findsNothing); + + await tester.enterText(find.byKey(scheduleSearchFieldKey), 'nightly'); + await tester.pump(); + expect(find.text('No schedules match this search.'), findsOneWidget); + expect(find.text('No enabled schedules.'), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets('late reply after the screen is disposed does not throw', ( + tester, + ) async { + final gateway = ControlledSchedulesGateway(); + await pumpSchedules( + tester, + cupertino: false, + gateway: gateway, + settle: false, + ); + expect(find.byKey(scheduleRefreshKey), findsNothing); + + await tester.pumpWidget(const SizedBox.shrink()); + gateway.complete(0, schedulesReply([scheduleRecord()])); + await tester.pump(); + expect(tester.takeException(), isNull); + }); +} diff --git a/app/test/features/search/search_controller_failure_test.dart b/app/test/features/search/search_controller_failure_test.dart new file mode 100644 index 00000000..43f217c1 --- /dev/null +++ b/app/test/features/search/search_controller_failure_test.dart @@ -0,0 +1,90 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/search/domain/search_controller.dart'; +import 'package:pipelines_app/features/search/domain/search_query.dart'; +import 'search_test_support.dart'; + +void main() { + test('a server error is shown, and retry issues a fresh request', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('plan'); + await pumpEventQueue(); + gateway.fail(0, StateError('server is down')); + await pumpEventQueue(); + + expect(controller.bodyKind, SearchBodyKind.error); + expect(controller.error, contains('server is down')); + + final retry = controller.retry(); + await pumpEventQueue(); + expect(gateway.calls, hasLength(2)); + expect(gateway.lastSearch, {'query': 'plan', 'kind': '', 'limit': 0}); + + gateway.succeed( + 1, + envelope([ + { + 'kind': 'pipeline', + 'target': 'pipeline:7', + 'pipeline': {'id': 7}, + }, + ]), + ); + await retry; + expect(controller.error, isNull); + expect(controller.results, hasLength(1)); + expect(controller.bodyKind, SearchBodyKind.results); + }); + + test('a stale failure never replaces the newest query state', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('first'); + await pumpEventQueue(); + controller.updateQuery('second'); + await pumpEventQueue(); + + gateway.fail(0, StateError('stale failure')); + await pumpEventQueue(); + + expect(controller.error, isNull); + expect(controller.loading, isTrue); + expect(controller.bodyKind, SearchBodyKind.searching); + + gateway.succeed( + 1, + envelope([ + { + 'kind': 'pipeline', + 'target': 'pipeline:9', + 'pipeline': {'id': 9}, + }, + ]), + ); + await pumpEventQueue(); + expect(controller.error, isNull); + expect(controller.results.single['target'], 'pipeline:9'); + expect(controller.bodyKind, SearchBodyKind.results); + }); + + test( + 'a missing search_results payload reports the unsupported copy', + () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('plan'); + await pumpEventQueue(); + gateway.succeed(0, {'type': 'pong'}); + await pumpEventQueue(); + + expect(controller.bodyKind, SearchBodyKind.error); + expect(controller.error, unsupportedSearchCopy); + }, + ); +} diff --git a/app/test/features/search/search_controller_test.dart b/app/test/features/search/search_controller_test.dart new file mode 100644 index 00000000..f9d90fe3 --- /dev/null +++ b/app/test/features/search/search_controller_test.dart @@ -0,0 +1,240 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/search/domain/search_controller.dart'; +import 'package:pipelines_app/features/search/domain/search_models.dart'; +import 'search_test_support.dart'; + +void main() { + test('empty query with no kind is idle and sends no request', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery(' '); + await pumpEventQueue(); + + expect(gateway.calls, isEmpty); + expect(controller.bodyKind, SearchBodyKind.idle); + expect(controller.results, isEmpty); + expect(controller.loaded, isFalse); + expect(controller.loading, isFalse); + }); + + test('the request carries the parsed query, kind and limit 0', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('t:run Plan TYPE:artifact'); + await pumpEventQueue(); + + expect(gateway.calls, hasLength(1)); + expect(gateway.lastSearch, { + 'query': 'Plan', + 'kind': 'artifact', + 'limit': 0, + }); + }); + + test( + 'a kind selector change removes type tokens and sends at once', + () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('plan t:run'); + await pumpEventQueue(); + expect(gateway.lastSearch['kind'], 'run'); + + controller.selectKind(SearchKind.pipeline); + await pumpEventQueue(); + + expect(controller.query.trim(), 'plan'); + expect(controller.query, isNot(contains('t:run'))); + expect(controller.selectedKind, SearchKind.pipeline); + expect(gateway.calls, hasLength(2)); + expect(gateway.lastSearch, { + 'query': 'plan', + 'kind': 'pipeline', + 'limit': 0, + }); + }, + ); + + test( + 'kind-only browsing sends a blank query and reports the empty copy', + () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.selectKind(SearchKind.pipeline); + await pumpEventQueue(); + expect(gateway.lastSearch, {'query': '', 'kind': 'pipeline', 'limit': 0}); + expect(controller.bodyKind, SearchBodyKind.searching); + + gateway.succeed(0, envelope(const [])); + await pumpEventQueue(); + expect(controller.bodyKind, SearchBodyKind.empty); + expect(controller.emptyMessage, 'No pipelines yet.'); + }, + ); + + test('the latest query wins and a stale reply is dropped', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('first'); + await pumpEventQueue(); + controller.updateQuery('second'); + await pumpEventQueue(); + expect(gateway.calls, hasLength(2)); + + gateway.succeed( + 0, + envelope([ + { + 'kind': 'run', + 'target': 'run:1', + 'run': {'id': 1}, + }, + ]), + ); + await pumpEventQueue(); + expect(controller.results, isEmpty); + expect(controller.loading, isTrue); + expect(controller.bodyKind, SearchBodyKind.searching); + + gateway.succeed( + 1, + envelope([ + { + 'kind': 'run', + 'target': 'run:2', + 'run': {'id': 2}, + }, + ]), + ); + await pumpEventQueue(); + expect(controller.results.single['target'], 'run:2'); + expect(controller.loading, isFalse); + expect(controller.bodyKind, SearchBodyKind.results); + }); + + test('truncation and scan bounds come from the server envelope', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('plan'); + await pumpEventQueue(); + gateway.succeed( + 0, + envelope( + [ + { + 'kind': 'field', + 'target': 'run:11:4:output', + 'field': {'run_id': 11}, + }, + ], + truncated: true, + scannedSteps: 2000, + scannedBytes: 1048576, + cap: 50, + ), + ); + await pumpEventQueue(); + + expect(controller.truncated, isTrue); + expect(controller.scannedSteps, 2000); + expect(controller.scannedBytes, 1048576); + expect(controller.cap, 50); + expect(controller.boundsText, contains('truncated')); + expect(controller.boundsText, contains('cap 50')); + expect(controller.boundsText, contains('2000 steps')); + }); + + test( + 'a truncated empty reply reports the scan bound instead of a complete empty', + () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('needle'); + await pumpEventQueue(); + gateway.succeed( + 0, + envelope( + const [], + truncated: true, + scannedSteps: 2000, + scannedBytes: 1048576, + cap: 50, + ), + ); + await pumpEventQueue(); + + expect(controller.bodyKind, SearchBodyKind.empty); + expect( + controller.emptyMessage, + 'No matches for "needle" within the server\'s scan limit.', + ); + expect(controller.boundsText, contains('Results truncated')); + expect(controller.boundsText, contains('0 results')); + expect(controller.boundsText, contains('2000 steps')); + expect(controller.boundsText, contains('scan limit 1.0 MiB')); + }, + ); + + test( + 'a complete empty reply stays a plain empty with no bounds line', + () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('needle'); + await pumpEventQueue(); + gateway.succeed(0, envelope(const [])); + await pumpEventQueue(); + + expect(controller.bodyKind, SearchBodyKind.empty); + expect(controller.emptyMessage, 'No matches for "needle".'); + expect(controller.boundsText, isNull); + }, + ); + + test('in-hand kind narrowing keeps the list honest while loading', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('plan'); + await pumpEventQueue(); + gateway.succeed( + 0, + envelope([ + { + 'kind': 'run', + 'target': 'run:1', + 'run': {'id': 1}, + }, + { + 'kind': 'pipeline', + 'target': 'pipeline:7', + 'pipeline': {'id': 7}, + }, + ]), + ); + await pumpEventQueue(); + expect(controller.shownResults, hasLength(2)); + + controller.selectKind(SearchKind.run); + await pumpEventQueue(); + expect(controller.shownResults, hasLength(1)); + expect(controller.shownResults.single['target'], 'run:1'); + }); +} diff --git a/app/test/features/search/search_query_test.dart b/app/test/features/search/search_query_test.dart new file mode 100644 index 00000000..942a9b73 --- /dev/null +++ b/app/test/features/search/search_query_test.dart @@ -0,0 +1,118 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/search/domain/search_models.dart'; +import 'package:pipelines_app/features/search/domain/search_query.dart'; + +const unsupported = + 'This server does not support search. Update the Pipelines server, then try again.'; + +void main() { + test('kind vocabulary is exactly the server vocabulary, All kinds first', () { + expect(SearchKind.values.map((kind) => kind.wire), [ + '', + 'pipeline', + 'run', + 'step', + 'field', + 'artifact', + 'version', + ]); + expect(SearchKind.values.map((kind) => kind.label), [ + 'All kinds', + 'Pipelines', + 'Runs', + 'Steps', + 'Fields', + 'Artifacts', + 'Versions', + ]); + expect(SearchKind.fromWire('run'), SearchKind.run); + expect(SearchKind.fromWire(''), SearchKind.all); + expect(SearchKind.fromWire('prompts'), SearchKind.all); + expect(SearchKind.fromWire(null), SearchKind.all); + }); + + test('both type aliases and kinds are case insensitive', () { + for (final kind in SearchKind.values.where( + (kind) => kind != SearchKind.all, + )) { + for (final prefix in ['t', 'type', 'T', 'TyPe']) { + final parsed = parseSearchQuery( + '$prefix:${kind.wire.toUpperCase()} plan', + ); + expect(parsed.query, ' plan'); + expect(parsed.kind, kind); + expect(parsed.hasType, isTrue); + } + } + }); + + test('normal, quoted and unsupported text is preserved byte for byte', () { + const preserved = [ + ' ordinary text\twith\nspacing ', + '"t:pipeline" "hello world"', + "'type:artifact'", + '"escaped \\" t:run"', + '"unclosed t:run', + 't:prompt type:unknown t: t:PIPELINES', + 'not:t:run t:run,', + 'prefix"t:run"', + '\\t:run', + ]; + for (final query in preserved) { + final parsed = parseSearchQuery(query, SearchKind.field); + expect(parsed.query, query); + expect(parsed.kind, SearchKind.field); + expect(parsed.hasType, isFalse); + } + expect( + parseSearchQuery('t:artifact "t:pipeline" report').query, + ' "t:pipeline" report', + ); + }); + + test('last supported token wins over the selector; unknown tokens stay', () { + final parsed = parseSearchQuery( + 't:run plan TYPE:artifact t:unknown', + SearchKind.pipeline, + ); + expect(parsed.query, ' plan t:unknown'); + expect(parsed.kind, SearchKind.artifact); + expect(parsed.hasType, isTrue); + expect(parseSearchQuery('plan', SearchKind.step).kind, SearchKind.step); + }); + + test('type-only query is distinguishable from literal and blank input', () { + final typed = parseSearchQuery('t:pipeline'); + expect(typed.query, ''); + expect(typed.kind, SearchKind.pipeline); + expect(typed.hasType, isTrue); + final blank = parseSearchQuery(''); + expect(blank.query, ''); + expect(blank.kind, SearchKind.all); + expect(blank.hasType, isFalse); + }); + + test('blank text is sendable only with a supported nonempty kind', () { + for (final kind in SearchKind.values) { + expect(searchQuerySendable(' \n\t ', kind), kind != SearchKind.all); + } + expect(searchQuerySendable('', SearchKind.all), isFalse); + expect(searchQuerySendable('plan', SearchKind.all), isTrue); + expect(searchQuerySendable(' plan ', SearchKind.all), isTrue); + }); + + test( + 'failure copy distinguishes an unsupported server from a plain error', + () { + expect(searchFailureText(null), unsupported); + expect(searchFailureText(' '), unsupported); + expect(searchFailureText('unknown command: search'), unsupported); + expect(searchFailureText('unsupported command'), unsupported); + expect(searchFailureText('boom'), 'boom'); + expect( + searchFailureText('request timed out after 30000ms'), + 'request timed out after 30000ms', + ); + }, + ); +} diff --git a/app/test/features/search/search_repository_test.dart b/app/test/features/search/search_repository_test.dart new file mode 100644 index 00000000..1760b363 --- /dev/null +++ b/app/test/features/search/search_repository_test.dart @@ -0,0 +1,106 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/search/data/search_repository.dart'; +import 'package:pipelines_app/features/search/domain/search_models.dart'; + +class RecordingGateway implements ApiGateway { + String? type; + JsonMap fields = {}; + JsonMap reply = {}; + Object? failure; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + this.type = type; + this.fields = Map.of(fields); + if (failure case final error?) throw error; + return reply; + } + + @override + Stream get frames => const Stream.empty(); +} + +void main() { + test( + 'search sends exactly search/query/kind/limit and parses bounds', + () async { + final gateway = RecordingGateway() + ..reply = { + 'search_results': { + 'query': 'plan', + 'kind': 'run', + 'results': [ + { + 'kind': 'run', + 'target': 'run:11', + 'run': {'id': 11}, + }, + ], + 'truncated': true, + 'scanned_steps': 27, + 'scanned_bytes': 4096, + 'cap': 50, + 'scan_bound_bytes': 1048576, + }, + }; + final repository = SearchRepository(gateway); + + final response = await repository.search( + query: 'plan', + kind: SearchKind.run, + ); + + expect(gateway.type, 'search'); + expect(gateway.fields, { + 'search': {'query': 'plan', 'kind': 'run', 'limit': 0}, + }); + expect(response, isNotNull); + expect(response!.query, 'plan'); + expect(response.kind, SearchKind.run); + expect(response.results.single['target'], 'run:11'); + expect(response.truncated, isTrue); + expect(response.scannedSteps, 27); + expect(response.scannedBytes, 4096); + expect(response.cap, 50); + expect(response.scanBoundBytes, 1048576); + }, + ); + + test('all-kinds search still sends the empty kind field', () async { + final gateway = RecordingGateway() + ..reply = { + 'search_results': {'results': []}, + }; + await SearchRepository(gateway).search(query: 'plan', kind: SearchKind.all); + expect(gateway.fields, { + 'search': {'query': 'plan', 'kind': '', 'limit': 0}, + }); + }); + + test( + 'a reply without search_results is null, not an empty success', + () async { + final gateway = RecordingGateway()..reply = {'type': 'pong'}; + final response = await SearchRepository( + gateway, + ).search(query: 'plan', kind: SearchKind.all); + expect(response, isNull); + }, + ); + + test('server refusals propagate to the caller unchanged', () async { + final gateway = RecordingGateway() + ..failure = StateError('permission denied'); + await expectLater( + SearchRepository(gateway).search(query: 'plan', kind: SearchKind.all), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'permission denied', + ), + ), + ); + }); +} diff --git a/app/test/features/search/search_row_test.dart b/app/test/features/search/search_row_test.dart new file mode 100644 index 00000000..086f2246 --- /dev/null +++ b/app/test/features/search/search_row_test.dart @@ -0,0 +1,161 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/search/domain/search_row.dart'; + +JsonMap pipelineHit([JsonMap overrides = const {}]) => { + 'kind': 'pipeline', + 'target': 'pipeline:7', + 'pipeline': { + 'id': 7, + 'name': 'release', + 'version': 3, + 'stages': 4, + ...overrides, + }, +}; + +JsonMap versionHit() => { + 'kind': 'version', + 'target': 'pipeline:9:v2', + 'recency': '2026-01-01T00:00:00Z', + 'version': { + 'pipeline_id': 9, + 'version': 2, + 'content_hash': 'abc', + 'created_at': '2026-01-01T00:00:00Z', + }, +}; + +JsonMap runHit([JsonMap overrides = const {}]) => { + 'kind': 'run', + 'target': 'run:11', + 'run': { + 'id': 11, + 'pipeline_name': 'release', + 'status': 'succeeded', + 'created_at': '2026-01-01T00:00:00Z', + ...overrides, + }, +}; + +JsonMap stepHit([JsonMap overrides = const {}]) => { + 'kind': 'step', + 'target': 'run:11:4', + 'step': { + 'run_id': 11, + 'sequence': 4, + 'stage': 'builder', + 'visit': 2, + 'outcome': 'success', + ...overrides, + }, +}; + +JsonMap fieldHit([JsonMap overrides = const {}]) => { + 'kind': 'field', + 'target': 'run:11:4:output', + 'matched_field': 'output', + 'field': { + 'run_id': 11, + 'sequence': 4, + 'field': 'output', + 'snippet': 'the release is ready', + ...overrides, + }, +}; + +JsonMap artifactHit([JsonMap overrides = const {}]) => { + 'kind': 'artifact', + 'target': '/artifacts/11/4/notes.md', + 'artifact': { + 'run_id': 11, + 'sequence': 4, + 'name': 'notes.md', + 'content_type': 'text/markdown', + 'size_bytes': 2048, + ...overrides, + }, +}; + +void main() { + test('per-kind rows mirror the browser titles and secondary lines', () { + final pipeline = searchRowView(pipelineHit(), 'release'); + expect(pipeline.title, 'release'); + expect(pipeline.secondary, 'pipeline 7 · v3 · 4 stages'); + expect(pipeline.kindLabel, 'Pipeline'); + expect(pipeline.target, 'pipeline:7'); + + final blankName = searchRowView(pipelineHit({'name': ' '}), 'x'); + expect(blankName.title, 'pipeline 7'); + + final version = searchRowView(versionHit(), 'release'); + expect(version.title, 'pipeline 9 · v2'); + expect(version.secondary, startsWith('content abc · ')); + expect(version.recency, isNotNull); + + final run = searchRowView(runHit(), 'release'); + expect(run.title, 'run #11 · release'); + expect(run.secondary, startsWith('succeeded · ')); + expect(run.secondary.split(' · '), hasLength(2)); + + final unnamed = searchRowView(runHit({'pipeline_name': ''}), ''); + expect(unnamed.title, 'run #11'); + + final step = searchRowView(stepHit({'target': '#success'}), ''); + expect(step.title, 'run #11 · builder visit 2'); + expect(step.secondary, 'success · → #success'); + + final artifact = searchRowView(artifactHit(), 'notes'); + expect(artifact.title, 'notes.md'); + expect(artifact.secondary, 'run #11 · step 4 · text/markdown · 2.0 KiB'); + }); + + test('a field snippet marks the first case-insensitive query occurrence', () { + final row = searchRowView(fieldHit(), 'RELEASE'); + expect(row.snippet, 'the release is ready'); + expect(row.snippetSpans.map((span) => (span.text, span.matched)), [ + ('the ', false), + ('release', true), + (' is ready', false), + ]); + expect(row.snippetSpans.where((span) => span.matched), hasLength(1)); + + final absent = searchRowView(fieldHit({'snippet': 'no match'}), 'absent'); + expect(absent.snippetSpans.single.matched, isFalse); + expect(absent.snippetSpans.single.text, 'no match'); + + final blank = searchRowView(fieldHit({'snippet': ''}), 'release'); + expect(blank.snippetSpans, isEmpty); + }); + + test('unknown or targetless hits are read-only and never open a guess', () { + final unknown = searchRowView({ + 'kind': 'future_kind', + 'target': 'widget:7', + }, 'x'); + expect(unknown.title, 'widget:7'); + expect(unknown.secondary, 'kind "future_kind" · read-only'); + expect(unknown.openable, isFalse); + expect(unknown.target, isNull); + expect(unknown.kindLabel, 'Unrecognised result'); + + final targetless = searchRowView({ + 'kind': 'run', + 'run': {'id': 11}, + }, 'x'); + expect(targetless.openable, isFalse); + expect(targetless.target, isNull); + + expect(searchRowView(pipelineHit(), '').openable, isTrue); + expect(searchRowView(versionHit(), '').openable, isTrue); + expect(searchRowView(artifactHit(), '').openable, isTrue); + }); + + test('byte sizes use the shared binary rendering', () { + expect(humanBytes(0), '0 B'); + expect(humanBytes(1023), '1023 B'); + expect(humanBytes(1024), '1.0 KiB'); + expect(humanBytes(2048), '2.0 KiB'); + expect(humanBytes(1048576), '1.0 MiB'); + }); +} diff --git a/app/test/features/search/search_screen_states_test.dart b/app/test/features/search/search_screen_states_test.dart new file mode 100644 index 00000000..71292861 --- /dev/null +++ b/app/test/features/search/search_screen_states_test.dart @@ -0,0 +1,146 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/search/search_screen.dart'; + +class RecordingGateway implements ApiGateway { + RecordingGateway(this.reply); + + final JsonMap Function(String query, String kind) reply; + final calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add(Map.of(fields)); + final search = Map.from(fields['search'] as Map); + return reply(search['query'] as String, search['kind'] as String); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap response( + List results, { + bool truncated = false, + int scannedSteps = 2, + int scannedBytes = 128, +}) => { + 'search_results': { + 'results': results, + 'truncated': truncated, + 'scanned_steps': scannedSteps, + 'scanned_bytes': scannedBytes, + 'cap': 50, + 'scan_bound_bytes': 1 << 20, + }, +}; + +final pipeline = { + 'kind': 'pipeline', + 'target': 'pipeline:7', + 'pipeline': {'id': 7, 'name': 'Release planner', 'version': 3, 'stages': 4}, +}; + +Widget material(Widget child) => MaterialApp(home: child); + +void main() { + testWidgets( + 'a fresh screen sends no request and idle is not an empty result', + (tester) async { + final gateway = RecordingGateway((_, _) => response([pipeline])); + await tester.pumpWidget( + material(SearchScreen(gateway: gateway, onOpen: (_) {})), + ); + + expect(gateway.calls, isEmpty); + expect( + find.text('Search pipelines, runs and artifacts.'), + findsOneWidget, + ); + expect(find.textContaining('No matches'), findsNothing); + }, + ); + + testWidgets('an empty server result shows the query-specific empty copy', ( + tester, + ) async { + final gateway = RecordingGateway((_, _) => response(const [])); + await tester.pumpWidget( + material(SearchScreen(gateway: gateway, onOpen: (_) {})), + ); + + await tester.enterText(find.byKey(const ValueKey('search.field')), 'zzz'); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpAndSettle(); + + expect(gateway.calls, hasLength(1)); + expect(find.text('No matches for "zzz".'), findsOneWidget); + expect(find.text('Searching…'), findsNothing); + }); + + testWidgets( + 'a truncated empty reply keeps the server scan warning on screen', + (tester) async { + final gateway = RecordingGateway( + (_, _) => response( + const [], + truncated: true, + scannedSteps: 2000, + scannedBytes: 1048576, + ), + ); + await tester.pumpWidget( + material(SearchScreen(gateway: gateway, onOpen: (_) {})), + ); + + await tester.enterText( + find.byKey(const ValueKey('search.field')), + 'needle', + ); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpAndSettle(); + + expect( + find.text('No matches for "needle" within the server\'s scan limit.'), + findsOneWidget, + ); + expect(find.textContaining('Results truncated'), findsOneWidget); + expect(find.textContaining('scanned 2000 steps'), findsOneWidget); + expect(find.textContaining('scan limit 1.0 MiB'), findsOneWidget); + }, + ); + + testWidgets('changing Kind clears a typed token and requests the new kind', ( + tester, + ) async { + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final gateway = RecordingGateway((_, _) => response([pipeline])); + await tester.pumpWidget( + material(SearchScreen(gateway: gateway, onOpen: (_) {})), + ); + + await tester.enterText( + find.byKey(const ValueKey('search.field')), + 'plan t:run', + ); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpAndSettle(); + expect((gateway.calls.single['search'] as Map)['kind'], 'run'); + + await tester.tap(find.byKey(const ValueKey('search.kind'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Pipelines').last); + await tester.pumpAndSettle(); + + final field = tester.widget( + find.byKey(const ValueKey('search.field')), + ); + expect(field.controller!.text.trim(), 'plan'); + expect(field.controller!.text, isNot(contains('t:run'))); + expect((gateway.calls.last['search'] as Map)['kind'], 'pipeline'); + }); +} diff --git a/app/test/features/search/search_screen_test.dart b/app/test/features/search/search_screen_test.dart new file mode 100644 index 00000000..7c1b7eeb --- /dev/null +++ b/app/test/features/search/search_screen_test.dart @@ -0,0 +1,223 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/search/domain/search_models.dart'; +import 'package:pipelines_app/features/search/search_screen.dart'; + +class ImmediateGateway implements ApiGateway { + ImmediateGateway(this.reply); + + final JsonMap Function(String query, String kind) reply; + final calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add(Map.of(fields)); + final search = Map.from(fields['search'] as Map); + return reply(search['query'] as String, search['kind'] as String); + } + + @override + Stream get frames => const Stream.empty(); +} + +class FailingThenSucceedingGateway implements ApiGateway { + FailingThenSucceedingGateway(this.success); + + final JsonMap success; + var calls = 0; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls++; + if (calls == 1) throw StateError('unknown command: search'); + return success; + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap hit({ + required String kind, + required String target, + required Map payload, +}) => {'kind': kind, 'target': target, ...payload}; + +JsonMap response(List results) => { + 'search_results': { + 'results': results, + 'truncated': false, + 'scanned_steps': 4, + 'scanned_bytes': 512, + 'cap': 50, + 'scan_bound_bytes': 1 << 20, + }, +}; + +final pipeline = hit( + kind: 'pipeline', + target: 'pipeline:7', + payload: { + 'pipeline': {'id': 7, 'name': 'Release planner', 'version': 3, 'stages': 4}, + }, +); +final field = hit( + kind: 'field', + target: 'run:11:4:output', + payload: { + 'matched_field': 'output', + 'field': { + 'run_id': 11, + 'sequence': 4, + 'field': 'output', + 'snippet': 'the release is ready', + }, + }, +); + +void useNarrowSurface(WidgetTester tester) { + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); +} + +Widget largeText(Widget child) => MediaQuery( + data: const MediaQueryData(textScaler: TextScaler.linear(2)), + child: child, +); + +Future search(WidgetTester tester, String query) async { + await tester.enterText(find.byKey(const ValueKey('search.field')), query); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpAndSettle(); +} + +void main() { + for (final width in [390.0, 1000.0]) { + testWidgets( + 'Material search is native and usable at width $width and 2x text', + (tester) async { + useNarrowSurface(tester); + tester.view.physicalSize = Size(width, 844); + final gateway = ImmediateGateway((_, _) => response([pipeline, field])); + JsonMap? opened; + await tester.pumpWidget( + MaterialApp( + home: largeText( + SearchScreen( + gateway: gateway, + onOpen: (value) => opened = value, + cupertino: false, + ), + ), + ), + ); + + expect(find.byType(SearchBar), findsOneWidget); + expect(find.byType(DropdownButton), findsOneWidget); + expect(find.text('All kinds'), findsOneWidget); + expect(gateway.calls, isEmpty); + + await search(tester, 'release'); + + expect(gateway.calls.single, { + 'search': {'query': 'release', 'kind': '', 'limit': 0}, + }); + expect(find.text('Release planner'), findsOneWidget); + expect(find.textContaining('the release is ready'), findsOneWidget); + expect(find.textContaining('4 results'), findsNothing); + expect(tester.takeException(), isNull); + + await tester.tap( + find.byKey(const ValueKey('search.result.pipeline:7')), + ); + expect(opened?['target'], 'pipeline:7'); + expect(opened?['kind'], 'pipeline'); + }, + ); + } + + testWidgets( + 'Cupertino search uses native controls and opens the real target', + (tester) async { + useNarrowSurface(tester); + final gateway = ImmediateGateway((_, _) => response([pipeline])); + JsonMap? opened; + await tester.pumpWidget( + CupertinoApp( + home: largeText( + SearchScreen( + gateway: gateway, + onOpen: (value) => opened = value, + cupertino: true, + ), + ), + ), + ); + + expect(find.byType(CupertinoSearchTextField), findsOneWidget); + await search(tester, 'release'); + + expect(find.text('Release planner'), findsOneWidget); + expect(tester.takeException(), isNull); + await tester.tap(find.byKey(const ValueKey('search.result.pipeline:7'))); + expect(opened?['target'], 'pipeline:7'); + }, + ); + + testWidgets('a read-only hit cannot be opened', (tester) async { + useNarrowSurface(tester); + final unknown = hit( + kind: 'future_kind', + target: 'widget:7', + payload: const {}, + ); + final gateway = ImmediateGateway((_, _) => response([unknown])); + JsonMap? opened; + await tester.pumpWidget( + MaterialApp( + home: SearchScreen( + gateway: gateway, + onOpen: (value) => opened = value, + cupertino: false, + ), + ), + ); + await search(tester, 'widget'); + + expect(find.textContaining('read-only'), findsOneWidget); + await tester.tap(find.byKey(const ValueKey('search.result.widget:7'))); + expect(opened, isNull); + }); + + testWidgets('an unsupported server shows its sentence and retry recovers', ( + tester, + ) async { + useNarrowSurface(tester); + final gateway = FailingThenSucceedingGateway(response([pipeline])); + await tester.pumpWidget( + MaterialApp( + home: SearchScreen(gateway: gateway, onOpen: (_) {}, cupertino: false), + ), + ); + await search(tester, 'release'); + + expect( + find.text( + 'This server does not support search. Update the Pipelines server, then try again.', + ), + findsOneWidget, + ); + expect(find.byKey(const ValueKey('search.retry')), findsOneWidget); + + await tester.tap(find.byKey(const ValueKey('search.retry'))); + await tester.pumpAndSettle(); + + expect(gateway.calls, 2); + expect(find.text('Release planner'), findsOneWidget); + expect(find.byKey(const ValueKey('search.retry')), findsNothing); + }); +} diff --git a/app/test/features/search/search_test_support.dart b/app/test/features/search/search_test_support.dart new file mode 100644 index 00000000..fdad7425 --- /dev/null +++ b/app/test/features/search/search_test_support.dart @@ -0,0 +1,50 @@ +import 'dart:async'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/search/data/search_repository.dart'; +import 'package:pipelines_app/features/search/domain/search_controller.dart'; + +class QueuedGateway implements ApiGateway { + final calls = []; + final pending = >[]; + + @override + Future call(String type, [JsonMap fields = const {}]) { + calls.add(Map.of(fields)); + final completer = Completer(); + pending.add(completer); + return completer.future; + } + + @override + Stream get frames => const Stream.empty(); + + void succeed(int index, JsonMap reply) => pending[index].complete(reply); + void fail(int index, Object error) => pending[index].completeError(error); + + JsonMap get lastSearch => + Map.from((calls.last['search'] as Map)); +} + +JsonMap envelope( + List results, { + bool truncated = false, + int scannedSteps = 0, + int scannedBytes = 0, + int cap = 50, + int scanBoundBytes = 1 << 20, +}) => { + 'search_results': { + 'results': results, + 'truncated': truncated, + 'scanned_steps': scannedSteps, + 'scanned_bytes': scannedBytes, + 'cap': cap, + 'scan_bound_bytes': scanBoundBytes, + }, +}; + +OmniSearchController controllerFor(ApiGateway gateway) => OmniSearchController( + repository: SearchRepository(gateway), + debounce: Duration.zero, +); diff --git a/app/test/features/settings/fake_channel.dart b/app/test/features/settings/fake_channel.dart new file mode 100644 index 00000000..e7eabde4 --- /dev/null +++ b/app/test/features/settings/fake_channel.dart @@ -0,0 +1,115 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:web_socket_channel/web_socket_channel.dart'; + +/// A deterministic websocket channel for the Settings tests. It records every +/// outgoing request and lets the test complete readiness and deliver replies. +class FakeChannel implements WebSocketChannel { + FakeChannel(this.uri); + + final Uri uri; + final StreamController incoming = StreamController(); + final List outgoing = []; + final Completer readyCompleter = Completer(); + bool _closed = false; + + void markReady() { + if (!readyCompleter.isCompleted) readyCompleter.complete(); + } + + void reply(Map message) { + if (!incoming.isClosed) incoming.add(jsonEncode(message)); + } + + void fail(String message) { + if (!incoming.isClosed) incoming.addError(StateError(message)); + } + + void closeStream() { + if (!incoming.isClosed) { + _closed = true; + incoming.close(); + } + } + + List> get decodedOutgoing => outgoing + .map((item) => jsonDecode(item) as Map) + .toList(growable: false); + + @override + Stream get stream => incoming.stream; + + @override + WebSocketSink get sink => _FakeSink(this); + + @override + Future get ready => readyCompleter.future; + + @override + String? get protocol => null; + + @override + int? get closeCode => _closed ? 1000 : null; + + @override + String? get closeReason => null; + + @override + noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +class _FakeSink implements WebSocketSink { + _FakeSink(this.channel); + + final FakeChannel channel; + + @override + void add(dynamic event) { + if (event is String) channel.outgoing.add(event); + } + + @override + void addError(Object error, [StackTrace? stackTrace]) => throw error; + + @override + Future addStream(Stream stream) async { + await for (final item in stream) { + add(item); + } + } + + @override + Future close([int? closeCode, String? closeReason]) async { + channel.closeStream(); + } + + @override + Future get done async {} + + @override + noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +/// Records every channel the client asks for, so tests can prove that a rebuild +/// or an invalid URL opened no socket at all. +class FakeChannelFactory { + final List channels = []; + final List uris = []; + + FakeChannel get last => channels.last; + + WebSocketChannel call(Uri uri) { + uris.add(uri); + final channel = FakeChannel(uri); + channels.add(channel); + return channel; + } +} + +/// Let queued microtasks (state events, request sends, replies) run. +Future settle() async { + for (var i = 0; i < 4; i++) { + await Future.delayed(Duration.zero); + } +} diff --git a/app/test/features/settings/settings_controller_test.dart b/app/test/features/settings/settings_controller_test.dart new file mode 100644 index 00000000..bf03672e --- /dev/null +++ b/app/test/features/settings/settings_controller_test.dart @@ -0,0 +1,440 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart' + as transport; +import 'package:pipelines_app/features/settings/settings_controller.dart'; +import 'package:pipelines_app/features/settings/settings_copy.dart'; +import 'package:pipelines_app/features/settings/settings_store.dart'; + +import 'fake_channel.dart'; + +void main() { + test('initializes without opening a connection', () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + final controller = SettingsController( + client: client, + store: MemorySettingsStore( + serverUrl: 'ws://saved.test/connect', + workspace: '/srv/pipelines', + ), + ); + addTearDown(controller.dispose); + + await controller.initialize(); + await settle(); + + expect(controller.serverUrl, 'ws://saved.test/connect'); + expect(controller.workspaceDraft, '/srv/pipelines'); + expect(controller.savedWorkspace, '/srv/pipelines'); + expect(factory.channels, isEmpty); + expect(controller.connectionLines, ['Not connected']); + }); + + test( + 'an initial endpoint seeds the draft but is not persisted by itself', + () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + final store = MemorySettingsStore(serverUrl: 'ws://saved.test/connect'); + final controller = SettingsController( + client: client, + store: store, + initialEndpoint: Uri.parse('ws://initial.test:9000'), + ); + addTearDown(controller.dispose); + + await controller.initialize(); + + expect(controller.serverUrl, 'ws://initial.test:9000'); + expect(store.serverUrl, 'ws://saved.test/connect'); + }, + ); + + test('a native/default endpoint seeds an empty store', () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + final controller = SettingsController( + client: client, + store: MemorySettingsStore(), + defaultEndpoint: 'ws://page.test/connect', + ); + addTearDown(controller.dispose); + + await controller.initialize(); + + expect(controller.serverUrl, 'ws://page.test/connect'); + }); + + test('an invalid URL names the field error and opens no socket', () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + final store = MemorySettingsStore(); + final controller = SettingsController(client: client, store: store); + addTearDown(controller.dispose); + await controller.initialize(); + + controller.updateServerUrl('http://example.test'); + await controller.connect(); + await settle(); + + expect(controller.urlError, contains('Unsupported scheme')); + expect(factory.channels, isEmpty); + expect(store.serverUrl, ''); + }); + + test('a URL with credentials is rejected before it is persisted', () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + final store = MemorySettingsStore(); + final controller = SettingsController(client: client, store: store); + addTearDown(controller.dispose); + await controller.initialize(); + + controller.updateServerUrl('ws://operator:secret@example.test/connect'); + await controller.connect(); + await settle(); + + expect(controller.urlError, contains('Credentials are not supported')); + expect(factory.channels, isEmpty); + expect(store.serverUrl, ''); + }); + + test( + 'connect validates, normalizes, persists and pings exactly once', + () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + final store = MemorySettingsStore(); + final controller = SettingsController(client: client, store: store); + await controller.initialize(); + + controller.updateServerUrl(' ws://example.test:8123 '); + final connecting = controller.connect(); + await settle(); + expect(factory.uris.single.toString(), 'ws://example.test:8123/connect'); + expect(controller.serverUrl, 'ws://example.test:8123/connect'); + expect(store.serverUrl, 'ws://example.test:8123/connect'); + + factory.last.markReady(); + await connecting; + await settle(); + + final outgoing = factory.last.decodedOutgoing; + expect(outgoing, hasLength(1)); + expect(outgoing.single['type'], 'ping'); + expect(controller.connection.kind, transport.ConnectionKind.connected); + + factory.last.reply({ + 'id': outgoing.single['id'], + 'type': 'pong', + 'build': {'version': 'v9', 'commit': 'deadbee'}, + 'time': '2026-10-21T12:00:00Z', + }); + await settle(); + + expect(controller.buildVersion, 'v9'); + expect(controller.buildCommit, 'deadbee'); + expect(controller.serverTime, '2026-10-21T12:00:00Z'); + expect(controller.connectionLines, [ + 'Connected', + 'Server build v9 (deadbee)', + 'Server time 2026-10-21T12:00:00Z', + ]); + + // Rebuilding or notifying must not send another ping for this connection. + await settle(); + expect(factory.last.decodedOutgoing, hasLength(1)); + + controller.dispose(); + await client.dispose(); + }, + ); + + test( + 'the card is pending until the ping answers, then names missing values', + () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + final reply = Completer>(); + final controller = SettingsController( + client: client, + store: MemorySettingsStore(), + ping: () => reply.future, + ); + await controller.initialize(); + controller.updateServerUrl('ws://example.test:8123'); + final connecting = controller.connect(); + await settle(); + factory.last.markReady(); + await connecting; + await settle(); + + expect(controller.pingInFlight, isTrue); + expect(controller.connectionLines, [ + 'Connected', + serverDetailsPending, + ]); + + reply.complete({'type': 'pong'}); + await settle(); + + expect(controller.pingInFlight, isFalse); + expect(controller.connectionLines, [ + 'Connected', + 'Server build unavailable', + 'Server time unavailable', + ]); + + controller.dispose(); + await client.dispose(); + }, + ); + + test( + 'a ping failure is one explicit line, not two unavailable values', + () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + final controller = SettingsController( + client: client, + store: MemorySettingsStore(), + ping: () async => throw StateError('probe failed'), + ); + await controller.initialize(); + controller.updateServerUrl('ws://example.test:8123'); + final connecting = controller.connect(); + await settle(); + factory.last.markReady(); + await connecting; + await settle(); + + expect(controller.pingError, startsWith('Server details unavailable:')); + expect(controller.pingError, contains('probe failed')); + expect(controller.pingInFlight, isFalse); + expect(controller.connectionLines, [ + 'Connected', + startsWith('Server details unavailable:'), + ]); + expect(controller.connection.kind, transport.ConnectionKind.connected); + + controller.dispose(); + await client.dispose(); + }, + ); + + test( + 'disconnect clears server details and leaves the shared client alive', + () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + final controller = SettingsController( + client: client, + store: MemorySettingsStore(), + ); + await controller.initialize(); + controller.updateServerUrl('ws://example.test:8123'); + final connecting = controller.connect(); + await settle(); + factory.last.markReady(); + await connecting; + await settle(); + factory.last.reply({ + 'id': factory.last.decodedOutgoing.single['id'], + 'type': 'pong', + 'build': {'version': 'v9'}, + 'time': '2026-10-21T12:00:00Z', + }); + await settle(); + expect(controller.buildVersion, 'v9'); + + await controller.disconnect(); + await settle(); + + expect(controller.connection.kind, transport.ConnectionKind.idle); + expect(controller.buildVersion, ''); + expect(controller.serverTime, ''); + expect(controller.connectionLines, ['Not connected']); + + controller.dispose(); + await client.dispose(); + }, + ); + + test('reconnect opens one new connection after a disconnect', () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + final controller = SettingsController( + client: client, + store: MemorySettingsStore(), + ); + await controller.initialize(); + controller.updateServerUrl('ws://example.test:8123'); + final connecting = controller.connect(); + await settle(); + factory.last.markReady(); + await connecting; + + await controller.disconnect(); + await settle(); + final reconnecting = controller.reconnect(); + await settle(); + expect(factory.channels, hasLength(2)); + factory.last.markReady(); + await reconnecting; + await settle(); + expect(controller.connection.kind, transport.ConnectionKind.connected); + + controller.dispose(); + await client.dispose(); + }); + + test( + 'disposing the screen does not dispose or disconnect the shared client', + () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + final controller = SettingsController( + client: client, + store: MemorySettingsStore(), + ); + await controller.initialize(); + controller.updateServerUrl('ws://example.test:8123'); + final connecting = controller.connect(); + await settle(); + factory.last.markReady(); + await connecting; + await settle(); + + controller.dispose(); + await settle(); + + expect( + client.state.kind, + transport.ConnectionKind.connected, + reason: 'the feature must not disconnect a client it does not own', + ); + await client.dispose(); + }, + ); + + test('opening while already connected pings that connection once', () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + final connecting = client.connect(Uri.parse('ws://example.test:8123')); + await settle(); + factory.last.markReady(); + await connecting; + await settle(); + expect(factory.last.outgoing, isEmpty); + + final controller = SettingsController( + client: client, + store: MemorySettingsStore(), + ); + await controller.initialize(); + await settle(); + + expect(factory.last.decodedOutgoing, hasLength(1)); + expect(factory.last.decodedOutgoing.single['type'], 'ping'); + + controller.dispose(); + await client.dispose(); + }); + + test( + 'a failed endpoint write still connects but says it is session-only', + () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + final store = MemorySettingsStore()..failSaves = true; + final controller = SettingsController(client: client, store: store); + await controller.initialize(); + controller.updateServerUrl('ws://example.test:8123'); + final connecting = controller.connect(); + await settle(); + + expect(factory.channels, hasLength(1)); + expect(store.serverUrl, ''); + expect(controller.endpointSaveError, isNotEmpty); + + factory.last.markReady(); + await connecting; + await settle(); + expect(controller.connection.kind, transport.ConnectionKind.connected); + + controller.dispose(); + await client.dispose(); + }, + ); + + test('a dropped connection exposes the reason and retry backoff', () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + final controller = SettingsController( + client: client, + store: MemorySettingsStore(), + ); + await controller.initialize(); + controller.updateServerUrl('ws://example.test:8123'); + final connecting = controller.connect(); + await settle(); + factory.last.markReady(); + await connecting; + await settle(); + + factory.last.fail('socket gone'); + await settle(); + + expect(controller.connection.kind, transport.ConnectionKind.disconnected); + expect(controller.connection.reason, contains('socket gone')); + expect(controller.connection.retrying, isTrue); + expect( + controller.connectionLines, + containsAll(['Disconnected', 'Retrying with backoff\u2026']), + ); + + // Cancel the client's scheduled retry before the test ends. + await client.disconnect(); + controller.dispose(); + await client.dispose(); + }); + + test( + 'workspace save persists only an absolute path and reports failures', + () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + final store = MemorySettingsStore(); + final controller = SettingsController(client: client, store: store); + await controller.initialize(); + + controller.updateWorkspace('relative/path'); + expect(controller.workspaceError, workspacePathError); + await controller.saveWorkspace(); + expect(store.workspace, ''); + expect(controller.savedWorkspace, ''); + + controller.updateWorkspace(' /srv/pipelines '); + await controller.saveWorkspace(); + expect(store.workspace, '/srv/pipelines'); + expect(controller.savedWorkspace, '/srv/pipelines'); + expect(controller.workspaceDraft, '/srv/pipelines'); + + store.failSaves = true; + controller.updateWorkspace('/other/path'); + await controller.saveWorkspace(); + expect(controller.savedWorkspace, '/srv/pipelines'); + expect(controller.workspaceSaveError, isNotEmpty); + + controller.dispose(); + await client.dispose(); + }, + ); +} diff --git a/app/test/features/settings/settings_copy_test.dart b/app/test/features/settings/settings_copy_test.dart new file mode 100644 index 00000000..2fca897b --- /dev/null +++ b/app/test/features/settings/settings_copy_test.dart @@ -0,0 +1,160 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart' + as transport; +import 'package:pipelines_app/features/settings/default_endpoint.dart'; +import 'package:pipelines_app/features/settings/settings_copy.dart'; + +void main() { + group('workspace validation', () { + test('blank is untouched, relative is rejected, absolute is accepted', () { + expect(validateWorkspacePath(''), isNull); + expect(validateWorkspacePath(' '), isNull); + expect(validateWorkspacePath('repos/pipelines'), workspacePathError); + expect(validateWorkspacePath('/Users/you/repos/pipelines'), isNull); + expect( + validateWorkspacePath(' /srv/pipelines '), + isNull, + reason: 'trimmed before validating', + ); + }); + + test('Save needs a trimmed absolute path, never a blank field', () { + expect(canSaveWorkspace(''), isFalse); + expect(canSaveWorkspace(' '), isFalse); + expect(canSaveWorkspace('relative/path'), isFalse); + expect(canSaveWorkspace('/srv/pipelines'), isTrue); + expect(canSaveWorkspace(' /srv/pipelines '), isTrue); + }); + + test('the saved line names an empty value instead of showing nothing', () { + expect(savedWorkspaceLine(''), 'Saved workspace: (none)'); + expect( + savedWorkspaceLine(' /srv/pipelines '), + 'Saved workspace: /srv/pipelines', + ); + }); + }); + + group('server build and connection card', () { + test('build label includes only the reported parts', () { + expect(serverBuildLabel(), ''); + expect(serverBuildLabel(version: 'v1.2.3'), 'Server build v1.2.3'); + expect( + serverBuildLabel(version: 'v1.2.3', commit: 'abc1234'), + 'Server build v1.2.3 (abc1234)', + ); + expect(serverBuildLabel(commit: 'abc1234'), 'Server build (abc1234)'); + }); + + test('idle, connecting and disconnected states keep the app words', () { + expect( + connectionCardLines( + const transport.ConnectionState(transport.ConnectionKind.idle), + ), + ['Not connected'], + ); + expect( + connectionCardLines( + const transport.ConnectionState( + transport.ConnectionKind.connecting, + attempt: 3, + ), + ), + ['Connecting (attempt 3)\u2026'], + ); + expect( + connectionCardLines( + const transport.ConnectionState( + transport.ConnectionKind.disconnected, + reason: 'Connection closed', + retrying: true, + ), + ), + [ + 'Disconnected', + 'Connection closed', + 'Retrying with backoff\u2026', + ], + ); + expect( + connectionCardLines( + const transport.ConnectionState( + transport.ConnectionKind.disconnected, + ), + ), + ['Disconnected'], + ); + }); + + test('connected names unavailable build/time instead of zero', () { + final lines = connectionCardLines( + const transport.ConnectionState(transport.ConnectionKind.connected), + ); + expect(lines, [ + 'Connected', + 'Server build unavailable', + 'Server time unavailable', + ]); + }); + + test('connected reports the ping fields and an explicit ping error', () { + final lines = connectionCardLines( + const transport.ConnectionState(transport.ConnectionKind.connected), + buildVersion: 'v9', + buildCommit: 'deadbee', + serverTime: '2026-10-21T12:00:00Z', + pingError: 'Server details unavailable: timed out', + ); + expect(lines, [ + 'Connected', + 'Server build v9 (deadbee)', + 'Server time 2026-10-21T12:00:00Z', + 'Server details unavailable: timed out', + ]); + }); + + test( + 'connected while the ping is pending says loading, not unavailable', + () { + final lines = connectionCardLines( + const transport.ConnectionState(transport.ConnectionKind.connected), + pingInFlight: true, + ); + expect(lines, ['Connected', serverDetailsPending]); + expect(lines.any((line) => line.contains('unavailable')), isFalse); + }, + ); + + test('a failed ping is one explicit line, not two unavailable values', () { + final lines = connectionCardLines( + const transport.ConnectionState(transport.ConnectionKind.connected), + pingError: 'Server details unavailable: timed out', + ); + expect(lines, [ + 'Connected', + 'Server details unavailable: timed out', + ]); + }); + }); + + group('same-origin default endpoint', () { + test('native builds bake no endpoint', () { + expect(defaultServerUrl(web: false), ''); + }); + + test('web uses the page origin, upgraded to ws/wss', () { + expect( + defaultServerUrl(web: true, base: Uri.parse('http://127.0.0.1:8123/')), + 'ws://127.0.0.1:8123/connect', + ); + expect( + defaultServerUrl( + web: true, + base: Uri.parse('https://pipelines.example.test/pipelines'), + ), + 'wss://pipelines.example.test/connect', + ); + expect(defaultServerUrl(web: true, base: Uri.parse('about:blank')), ''); + }); + }); +} diff --git a/app/test/features/settings/settings_initial_connection_test.dart b/app/test/features/settings/settings_initial_connection_test.dart new file mode 100644 index 00000000..5b9ceff8 --- /dev/null +++ b/app/test/features/settings/settings_initial_connection_test.dart @@ -0,0 +1,63 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:pipelines_app/features/settings/settings_controller.dart'; +import 'package:pipelines_app/features/settings/settings_store.dart'; + +import 'fake_channel.dart'; + +class _DelayedStore extends MemorySettingsStore { + final loaded = Completer(); + + @override + Future load() => loaded.future; +} + +void main() { + test( + 'connected first frame loads details before preferences finish', + () async { + final factory = FakeChannelFactory(); + final client = PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + final connected = client.connect(Uri.parse('ws://fixture.test/connect')); + await settle(); + factory.last.markReady(); + await connected; + final store = _DelayedStore(); + final pong = Completer>(); + var pings = 0; + final controller = SettingsController( + client: client, + store: store, + ping: () { + pings++; + return pong.future; + }, + ); + addTearDown(controller.dispose); + + expect(controller.connectionLines, [ + 'Connected', + 'Loading server details…', + ]); + final initializing = controller.initialize(); + expect(controller.pingInFlight, isTrue); + expect(pings, 1); + store.loaded.complete(const SettingsValues()); + await initializing; + expect(pings, 1); + + await client.disconnect(); + await settle(); + pong.complete({ + 'type': 'pong', + 'build': {'version': 'stale'}, + }); + await settle(); + expect(controller.connectionLines, ['Not connected']); + expect(controller.buildVersion, isEmpty); + }, + ); +} diff --git a/app/test/features/settings/settings_screen_test.dart b/app/test/features/settings/settings_screen_test.dart new file mode 100644 index 00000000..66d4d2d1 --- /dev/null +++ b/app/test/features/settings/settings_screen_test.dart @@ -0,0 +1,314 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart' + as transport; +import 'package:pipelines_app/features/settings/settings_copy.dart'; +import 'package:pipelines_app/features/settings/settings_keys.dart'; +import 'package:pipelines_app/features/settings/settings_screen.dart'; +import 'package:pipelines_app/features/settings/settings_store.dart'; + +import 'fake_channel.dart'; + +void main() { + testWidgets('renders idle settings without opening a connection', ( + tester, + ) async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + + await _pump( + tester, + client, + store: MemorySettingsStore( + serverUrl: 'ws://saved.test/connect', + workspace: '/srv/pipelines', + ), + ); + + expect(find.text('Settings'), findsOneWidget); + expect(find.text('Connection'), findsOneWidget); + expect(find.text('Workspace'), findsOneWidget); + expect(find.text('Not connected'), findsOneWidget); + expect(find.text('Saved workspace: /srv/pipelines'), findsOneWidget); + expect( + tester.widget(find.byType(TextField).first).controller?.text, + 'ws://saved.test/connect', + ); + expect(find.byKey(SettingsKeys.connect), findsOneWidget); + expect(find.byKey(SettingsKeys.reconnect), findsOneWidget); + + await tester.pump(); + expect(factory.channels, isEmpty); + }); + + testWidgets('an invalid URL shows the field error and opens no socket', ( + tester, + ) async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + + await _pump(tester, client); + await tester.enterText(find.byType(TextField).first, 'http://example.test'); + await tester.pump(); + await tester.tap(find.byKey(SettingsKeys.connect)); + await tester.pump(); + await tester.pump(); + + expect(find.textContaining('Unsupported scheme'), findsOneWidget); + expect(factory.channels, isEmpty); + }); + + testWidgets('connect pings once and shows the reported build and time', ( + tester, + ) async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + + await _pump(tester, client); + await tester.enterText( + find.byType(TextField).first, + 'ws://example.test:8123', + ); + await tester.pump(); + await tester.tap(find.byKey(SettingsKeys.connect)); + await tester.pump(); + await tester.pump(); + + expect(factory.channels, hasLength(1)); + expect(factory.uris.single.toString(), 'ws://example.test:8123/connect'); + expect(find.text('Connecting (attempt 1)\u2026'), findsOneWidget); + + factory.last.markReady(); + await tester.pump(); + await tester.pump(); + final outgoing = factory.last.decodedOutgoing; + expect(outgoing, hasLength(1)); + expect(outgoing.single['type'], 'ping'); + + factory.last.reply({ + 'id': outgoing.single['id'], + 'type': 'pong', + 'build': {'version': 'v9', 'commit': 'deadbee'}, + 'time': '2026-10-21T12:00:00Z', + }); + await tester.pump(); + await tester.pump(); + + expect(find.text('Connected'), findsOneWidget); + expect(find.text('Server build v9 (deadbee)'), findsOneWidget); + expect(find.text('Server time 2026-10-21T12:00:00Z'), findsOneWidget); + expect(find.byKey(SettingsKeys.disconnect), findsOneWidget); + expect(find.byKey(SettingsKeys.connect), findsOneWidget); + expect(factory.last.decodedOutgoing, hasLength(1)); + }); + + testWidgets('connected without a ping reply names unavailable values', ( + tester, + ) async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + + await _pump(tester, client); + await tester.enterText( + find.byType(TextField).first, + 'ws://example.test:8123', + ); + await tester.pump(); + await tester.tap(find.byKey(SettingsKeys.connect)); + await tester.pump(); + await tester.pump(); + factory.last.markReady(); + await tester.pump(); + await tester.pump(); + expect(factory.last.decodedOutgoing.single['type'], 'ping'); + + expect(find.text('Connected'), findsOneWidget); + expect(find.text(serverDetailsPending), findsOneWidget); + expect(find.text('Server build unavailable'), findsNothing); + + factory.last.reply({ + 'id': factory.last.decodedOutgoing.single['id'], + 'type': 'pong', + }); + await tester.pump(); + await tester.pump(); + + expect(find.text(serverDetailsPending), findsNothing); + expect(find.text('Server build unavailable'), findsOneWidget); + expect(find.text('Server time unavailable'), findsOneWidget); + }); + + testWidgets( + 'workspace validation gates Save and only a save updates the line', + (tester) async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + final store = MemorySettingsStore(); + + await _pump(tester, client, store: store); + final workspace = find.byType(TextField).at(1); + await tester.enterText(workspace, 'relative/path'); + await tester.pump(); + + expect(find.textContaining('must be an absolute path'), findsOneWidget); + expect( + tester + .widget(find.byKey(SettingsKeys.saveWorkspace)) + .onPressed, + isNull, + ); + expect(find.text('Saved workspace: (none)'), findsOneWidget); + + await tester.enterText(workspace, ' /srv/pipelines '); + await tester.pump(); + await tester.tap(find.byKey(SettingsKeys.saveWorkspace)); + await tester.pump(); + await tester.pump(); + + expect(find.text('Saved workspace: /srv/pipelines'), findsOneWidget); + expect(store.workspace, '/srv/pipelines'); + }, + ); + + testWidgets('iOS uses Cupertino fields, buttons and navigation', ( + tester, + ) async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + + await _pump(tester, client, platform: TargetPlatform.iOS); + + expect(find.byType(CupertinoNavigationBar), findsOneWidget); + expect(find.byType(CupertinoTextField), findsNWidgets(2)); + expect(find.byType(TextField), findsNothing); + expect(find.byType(FilledButton), findsNothing); + expect(find.byKey(SettingsKeys.connect), findsOneWidget); + expect(find.text('Trusted LAN/VPN only'), findsOneWidget); + }); + + testWidgets('narrow window with large text scrolls without overflow', ( + tester, + ) async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + + await _pump(tester, client, textScale: 2, size: const Size(320, 640)); + + expect(tester.takeException(), isNull); + await tester.scrollUntilVisible( + find.byKey(SettingsKeys.saveWorkspace), + 200, + scrollable: find.byType(Scrollable).first, + ); + expect(find.byKey(SettingsKeys.saveWorkspace), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('large text keeps the full labels and supporting copy', ( + tester, + ) async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + + await _pump(tester, client, textScale: 2, size: const Size(320, 640)); + + expect(find.text('Workspace path (on the server)'), findsOneWidget); + expect(find.text('Server URL'), findsOneWidget); + for (final copy in [ + 'Workspace path (on the server)', + serverUrlHelper, + workspaceHelper, + ]) { + final text = tester.widget(find.text(copy)); + expect(text.maxLines, isNull, reason: 'no line cap on $copy'); + final paragraph = tester.renderObject(find.text(copy)); + expect( + paragraph.didExceedMaxLines, + isFalse, + reason: 'the whole copy is laid out for $copy', + ); + } + expect(tester.takeException(), isNull); + }); + + testWidgets('the text fields expose their labels to accessibility', ( + tester, + ) async { + final handle = tester.ensureSemantics(); + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + + await _pump(tester, client); + + final labels = [ + tester + .getSemantics(find.byType(TextField).at(0)) + .getSemanticsData() + .label, + tester + .getSemantics(find.byType(TextField).at(1)) + .getSemanticsData() + .label, + ]; + expect(labels[0], contains('Server URL')); + expect(labels[1], contains('Workspace path (on the server)')); + handle.dispose(); + }); + + testWidgets('unmounting leaves the shared client usable', (tester) async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + + await _pump(tester, client); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + + final connecting = client.connect(Uri.parse('ws://example.test:8123')); + await tester.pump(); + expect(factory.channels, hasLength(1)); + factory.last.markReady(); + await tester.pump(); + await connecting; + }); +} + +Future _pump( + WidgetTester tester, + transport.PipelinesClient client, { + SettingsStore? store, + TargetPlatform platform = TargetPlatform.android, + double textScale = 1, + Size size = const Size(800, 1200), +}) async { + await tester.binding.setSurfaceSize(size); + addTearDown(() => tester.binding.setSurfaceSize(null)); + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: platform), + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: child ?? const SizedBox.shrink(), + ), + home: SettingsScreen( + client: client, + store: store ?? MemorySettingsStore(), + ), + ), + ); + await tester.pump(); + await tester.pump(); +} diff --git a/app/test/features/settings/settings_store_test.dart b/app/test/features/settings/settings_store_test.dart new file mode 100644 index 00000000..216967a4 --- /dev/null +++ b/app/test/features/settings/settings_store_test.dart @@ -0,0 +1,68 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/settings/settings_store.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() { + SharedPreferences.setMockInitialValues({}); + }); + + test('starts blank when nothing is stored', () async { + const store = SharedPreferencesSettingsStore(); + final values = await store.load(); + expect(values.serverUrl, ''); + expect(values.workspace, ''); + }); + + test('writes only the feature-owned pipelines.next keys', () async { + const store = SharedPreferencesSettingsStore(); + expect(await store.saveServerUrl(' ws://127.0.0.1:8081/connect '), isTrue); + expect(await store.saveWorkspace(' /srv/pipelines '), isTrue); + + final preferences = await SharedPreferences.getInstance(); + expect( + preferences.getString(settingsServerUrlKey), + 'ws://127.0.0.1:8081/connect', + ); + expect(preferences.getString(settingsWorkspaceKey), '/srv/pipelines'); + expect(preferences.getKeys(), { + settingsServerUrlKey, + settingsWorkspaceKey, + }); + expect(settingsServerUrlKey, startsWith('pipelines.next.')); + expect(settingsWorkspaceKey, startsWith('pipelines.next.')); + + final reloaded = await store.load(); + expect(reloaded.serverUrl, 'ws://127.0.0.1:8081/connect'); + expect(reloaded.workspace, '/srv/pipelines'); + }); + + test('never reads or writes legacy web/Android preference keys', () async { + SharedPreferences.setMockInitialValues({ + 'pipelines.web.serverUrl.v2': 'ws://legacy.test/connect', + 'pipelines.web.workspace.v1': '/legacy/workspace', + 'server_url': 'ws://android.test/connect', + 'workspace': '/android/workspace', + }); + const store = SharedPreferencesSettingsStore(); + final values = await store.load(); + expect(values.serverUrl, ''); + expect(values.workspace, ''); + + await store.saveServerUrl('ws://new.test/connect'); + await store.saveWorkspace('/new/workspace'); + final preferences = await SharedPreferences.getInstance(); + expect( + preferences.getString('pipelines.web.serverUrl.v2'), + 'ws://legacy.test/connect', + ); + expect( + preferences.getString('pipelines.web.workspace.v1'), + '/legacy/workspace', + ); + expect(preferences.getString('server_url'), 'ws://android.test/connect'); + expect(preferences.getString('workspace'), '/android/workspace'); + }); +} diff --git a/app/test/features/templates/data/template_create_test.dart b/app/test/features/templates/data/template_create_test.dart new file mode 100644 index 00000000..68b82c4b --- /dev/null +++ b/app/test/features/templates/data/template_create_test.dart @@ -0,0 +1,147 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/templates/data/template_repository.dart'; + +import 'template_test_support.dart'; + +void main() { + test( + 'validate sends the exact source and returns the server graph', + () async { + final graph = { + 'stages': [ + {'key': 'build', 'type': 'model'}, + ], + 'unknown_graph_field': true, + }; + final gateway = RecordingGateway([ + {'type': 'validated', 'graph': graph}, + ]); + + final result = await TemplateRepository(gateway).validate(source); + + expect(gateway.calls.single.type, 'validate'); + expect(gateway.calls.single.fields, {'source': source}); + expect(gateway.calls.single.fields['source'], source); + expect(result, graph); + }, + ); + + test( + 'validate rejects a reply without a graph instead of faking success', + () async { + for (final reply in [ + {'type': 'validated'}, + {'type': 'validated', 'graph': null}, + ]) { + final gateway = RecordingGateway([reply]); + + await expectLater( + TemplateRepository(gateway).validate(source), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned no graph.', + ), + ), + ); + } + }, + ); + + test('validate propagates a server refusal verbatim', () async { + const refusal = ServerRefusal('invalid stage "añadir": unknown key'); + final gateway = RefusingGateway(refusal); + + await expectLater( + TemplateRepository(gateway).validate(source), + throwsA(same(refusal)), + ); + expect(gateway.calls, ['validate']); + }); + + test('submit refuses a blank name without sending anything', () async { + for (final name in ['', ' ', '\t\n']) { + final gateway = RecordingGateway([ + { + 'detail': {'id': 1}, + }, + ]); + + await expectLater( + TemplateRepository(gateway).submit(name, source), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'Enter a pipeline name.', + ), + ), + ); + expect(gateway.calls, isEmpty); + } + }); + + test( + 'submit trims the name, preserves the source and is always create-only', + () async { + final detail = { + 'id': 9, + 'name': 'Release 2', + 'version': 1, + }; + final gateway = RecordingGateway([ + {'type': 'submitted', 'detail': detail}, + ]); + + final result = await TemplateRepository( + gateway, + ).submit(' Release 2 ', source); + + expect(gateway.calls.single.type, 'submit'); + expect(gateway.calls.single.fields, { + 'name': 'Release 2', + 'source': source, + 'create_only': true, + }); + expect(gateway.calls.single.fields.keys, [ + 'name', + 'source', + 'create_only', + ]); + expect(result, detail); + }, + ); + + test( + 'submit rejects a reply without a detail instead of faking success', + () async { + final gateway = RecordingGateway([ + {'type': 'submitted'}, + ]); + + await expectLater( + TemplateRepository(gateway).submit('Release', source), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned no pipeline detail.', + ), + ), + ); + }, + ); + + test('submit propagates a server refusal verbatim', () async { + const refusal = ServerRefusal('a pipeline named "Release" already exists'); + final gateway = RefusingGateway(refusal); + + await expectLater( + TemplateRepository(gateway).submit(' Release ', source), + throwsA(same(refusal)), + ); + expect(gateway.calls, ['submit']); + }); +} diff --git a/app/test/features/templates/data/template_list_test.dart b/app/test/features/templates/data/template_list_test.dart new file mode 100644 index 00000000..63cd2e93 --- /dev/null +++ b/app/test/features/templates/data/template_list_test.dart @@ -0,0 +1,165 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/templates/data/template_repository.dart'; + +import 'template_test_support.dart'; + +void main() { + test( + 'list_templates sends only the type and preserves every field', + () async { + final catalogue = [ + { + 'key': 'release', + 'name': 'Release', + 'description': 'Ship a version', + 'source': source, + 'scheduled': true, + 'future_field': { + 'nested': [1, 2, 3], + }, + }, + { + 'key': 'blank', + 'name': '', + 'description': '', + 'source': 'name: empty', + 'scheduled': false, + }, + ]; + final gateway = RecordingGateway([ + {'templates': catalogue}, + ]); + + final entries = await TemplateRepository(gateway).listTemplates(); + + expect(gateway.calls, hasLength(1)); + expect(gateway.calls.single.type, 'list_templates'); + expect(gateway.calls.single.fields, isEmpty); + expect(entries, hasLength(2)); + expect(entries.first.key, 'release'); + expect(entries.first.name, 'Release'); + expect(entries.first.description, 'Ship a version'); + expect(entries.first.source, source); + expect(entries.first.scheduled, isTrue); + expect(entries.first.raw['future_field'], { + 'nested': [1, 2, 3], + }); + expect(entries.last.key, 'blank'); + expect(entries.last.scheduled, isFalse); + expect(entries.last.raw, isNot(contains('missing'))); + }, + ); + + test('list_templates leaves the server reply untouched', () async { + final first = { + 'key': 'one', + 'name': 'One', + 'source': source, + 'scheduled': true, + 'unknown': ['keep', 'me'], + }; + final reply = { + 'templates': [first], + 'usage': {'templates': 1}, + }; + final gateway = RecordingGateway([reply]); + + final entries = await TemplateRepository(gateway).listTemplates(); + + expect(reply['templates'], hasLength(1)); + expect(first, { + 'key': 'one', + 'name': 'One', + 'source': source, + 'scheduled': true, + 'unknown': ['keep', 'me'], + }); + expect(entries.single.raw['unknown'], ['keep', 'me']); + expect( + () => entries.single.raw['name'] = 'changed', + throwsUnsupportedError, + ); + expect(first['name'], 'One'); + }); + + test('list_templates freezes nested unknown data in raw', () async { + final nested = { + 'nested': [1, 2, 3], + }; + final gateway = RecordingGateway([ + { + 'templates': [ + { + 'key': 'one', + 'name': 'One', + 'source': source, + 'scheduled': true, + 'future_field': nested, + }, + ], + }, + ]); + + final entries = await TemplateRepository(gateway).listTemplates(); + final raw = entries.single.raw; + final future = raw['future_field'] as Map; + + expect(() => future['added'] = true, throwsUnsupportedError); + expect(() => (future['nested'] as List).add(4), throwsUnsupportedError); + expect(future['nested'], [1, 2, 3]); + // The unmodifiable copies do not alias the server reply either. + nested['added'] = true; + expect(raw['future_field'], isNot(contains('added'))); + }); + + test('list_templates rejects a catalogue that is not a list', () async { + final gateway = RecordingGateway([ + { + 'templates': {'key': 'not-a-list'}, + }, + ]); + + await expectLater( + TemplateRepository(gateway).listTemplates(), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned no template catalogue.', + ), + ), + ); + }); + + test( + 'list_templates rejects a catalogue entry that is not an object', + () async { + final gateway = RecordingGateway([ + { + 'templates': ['not-an-entry'], + }, + ]); + + await expectLater( + TemplateRepository(gateway).listTemplates(), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned a template that is not an object.', + ), + ), + ); + }, + ); + + test('list_templates treats a reply with no catalogue as empty', () async { + final gateway = RecordingGateway([{}]); + + final entries = await TemplateRepository(gateway).listTemplates(); + + expect(entries, isEmpty); + expect(gateway.calls.single.type, 'list_templates'); + }); +} diff --git a/app/test/features/templates/data/template_test_support.dart b/app/test/features/templates/data/template_test_support.dart new file mode 100644 index 00000000..f4f36500 --- /dev/null +++ b/app/test/features/templates/data/template_test_support.dart @@ -0,0 +1,47 @@ +import 'package:pipelines_app/core/api_gateway.dart'; + +/// A recording gateway: it captures every request and answers from [replies]. +class RecordingGateway implements ApiGateway { + RecordingGateway([List replies = const []]) + : _replies = [...replies]; + + final List _replies; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add((type: type, fields: Map.from(fields))); + return _replies.removeAt(0); + } + + @override + Stream get frames => const Stream.empty(); +} + +/// A gateway that refuses every request with the same server error object. +class RefusingGateway implements ApiGateway { + RefusingGateway(this.refusal); + + final Object refusal; + final List calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add(type); + throw refusal; + } + + @override + Stream get frames => const Stream.empty(); +} + +class ServerRefusal implements Exception { + const ServerRefusal(this.message); + final String message; + @override + String toString() => message; +} + +/// A source with Unicode, tabs, newlines and significant leading/trailing +/// whitespace: every request must carry it unchanged. +const source = ' name: "café"\n\tstages:\n - key: "añadir" 😀 \n'; diff --git a/app/test/tool/preview.test.mjs b/app/test/tool/preview.test.mjs new file mode 100644 index 00000000..3c6d6630 --- /dev/null +++ b/app/test/tool/preview.test.mjs @@ -0,0 +1,160 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, writeFile, symlink, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { createServer } from 'node:http'; +import { request as httpRequest } from 'node:http'; +import { gzipSync } from 'node:zlib'; +import net from 'node:net'; +import { start } from '../../tool/preview/server.mjs'; + +async function fixture(t, { auth = true, hanging = false } = {}) { + const root = await mkdtemp(join(tmpdir(), 'preview-')); + await writeFile(join(root, 'index.html'), 'shell'); + await writeFile(join(root, 'bundle.js'), 'bundle'); + const seen = []; + const upstream = createServer((req, res) => { + seen.push({ url: req.url, headers: req.headers, method: req.method }); + if (req.url === '/' && auth && req.headers.cookie !== 'sid=yes') { + res.writeHead(302, { location: '/login' }).end(); + } else if (req.url === '/' && hanging) { + // Deliberately hold the auth check open to exercise its timeout. + } else if (req.url === '/login' || req.url === '/logout' || req.url.startsWith('/artifacts/')) { + res.writeHead(200, { 'content-type': 'application/octet-stream' }).end('proxied'); + } else res.writeHead(200).end('authenticated'); + }); + upstream.on('upgrade', (req, socket, head) => { + seen.push({ url: req.url, headers: req.headers, upgraded: true }); + socket.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n'); + if (head.length) socket.write(head); + socket.pipe(socket); + }); + await new Promise((resolve) => upstream.listen(0, '127.0.0.1', resolve)); + const preview = await start({ root, upstream: `http://127.0.0.1:${upstream.address().port}`, port: 0 }); + t.after(async () => { + await preview.close(); + await new Promise((resolve) => upstream.close(resolve)); + await rm(root, { recursive: true, force: true }); + }); + return { root, upstream, preview, seen, base: `http://127.0.0.1:${preview.port}` }; +} + +function rawRequest(port, path, method, headers = {}) { + return new Promise((resolve, reject) => { + const request = httpRequest({ host: '127.0.0.1', port, path, method, headers }, (response) => { + const chunks = []; + response.on('data', (chunk) => chunks.push(chunk)); + response.on('end', () => resolve({ status: response.statusCode, headers: response.headers, body: Buffer.concat(chunks) })); + }); + request.on('error', reject); + request.end(); + }); +} + +test('guards assets and redirects unauthenticated document requests to proxy login', async (t) => { + const { base, seen } = await fixture(t); + const redirect = await fetch(`${base}/runs/4?tab=active`, { redirect: 'manual', headers: { accept: 'text/html' } }); + assert.equal(redirect.status, 302); + assert.equal(redirect.headers.get('location'), '/login?next=%2Fruns%2F4%3Ftab%3Dactive'); + assert.equal((await fetch(`${base}/bundle.js`)).status, 401); + const auth = { cookie: 'sid=yes' }; + assert.equal(await (await fetch(`${base}/bundle.js`, { headers: auth })).text(), 'bundle'); + assert.equal((await fetch(`${base}/login`)).status, 200); + assert.equal(seen.filter((item) => item.url === '/login').length, 1); + assert.equal((await fetch(`${base}/%2f%2fevil`, { headers: auth })).status, 400); +}); + +test('streams exact compressed range bytes for GET and HEAD with mapped proxy requests', async (t) => { + const bytes = gzipSync(Buffer.from('preserve these exact compressed bytes')); + const { base, upstream, seen } = await fixture(t); + upstream.removeAllListeners('request'); + upstream.on('request', (req, res) => { + if (req.url === '/') return res.end('authenticated'); + seen.push({ url: req.url, headers: req.headers, method: req.method }); + res.writeHead(206, { 'content-type': 'application/octet-stream', 'content-encoding': 'gzip', 'content-range': 'bytes 1-3/6', 'content-length': '3' }); + res.end(bytes.subarray(1, 4)); + }); + const auth = { cookie: 'sid=yes', range: 'bytes=1-3' }; + const response = await rawRequest(new URL(base).port, '/artifacts/x', 'GET', auth); + assert.equal(response.status, 206); + assert.equal(response.headers['content-encoding'], 'gzip'); + assert.deepEqual(response.body, bytes.subarray(1, 4)); + const head = await rawRequest(new URL(base).port, '/artifacts/x', 'HEAD', auth); + assert.equal(head.status, 206); + assert.equal(head.headers['content-length'], '3'); + assert.equal(head.body.byteLength, 0); + assert.equal(seen.at(-1).headers.range, 'bytes=1-3'); +}); + +test('rejects cross-origin and unauthenticated WebSocket upgrades before proxying', async (t) => { + const { preview, seen } = await fixture(t); + async function upgrade(headers) { + return new Promise((resolve) => { + const socket = net.connect(preview.port, '127.0.0.1', () => socket.write(`GET /connect HTTP/1.1\r\nHost: 127.0.0.1:${preview.port}\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n${headers}\r\n`)); + let response = ''; + socket.on('data', (chunk) => { response += chunk.toString(); if (response.includes('\r\n\r\n')) { socket.destroy(); resolve(response); } }); + socket.on('error', () => resolve(response)); + }); + } + assert.match(await upgrade(`Origin: http://evil.test\r\nCookie: sid=yes\r\n`), /^HTTP\/1\.1 403/); + assert.match(await upgrade(`Origin: http://127.0.0.1:${preview.port}\r\n`), /^HTTP\/1\.1 401/); + assert.equal(seen.filter((item) => item.upgraded).length, 0); +}); + +test('authenticates and maps same-origin WebSocket Origin; bytes flow both directions and close completes', async (t) => { + const { preview, seen } = await fixture(t); + const socket = net.connect(preview.port, '127.0.0.1'); + const chunks = []; + socket.on('data', (chunk) => chunks.push(chunk)); + socket.write(`GET /connect HTTP/1.1\r\nHost: 127.0.0.1:${preview.port}\r\nOrigin: http://127.0.0.1:${preview.port}\r\nCookie: sid=yes\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n`); + await new Promise((resolve, reject) => { + const deadline = setTimeout(() => reject(new Error('upgrade timeout')), 1500); + const poll = setInterval(() => { + if (chunks.some((chunk) => chunk.toString().includes('101 Switching Protocols'))) { clearInterval(poll); clearTimeout(deadline); resolve(); } + }, 10); + }); + const upgraded = seen.find((item) => item.upgraded); + assert.equal(upgraded.headers.origin, new URL(`http://${seen[0].headers.host}`).origin); + assert.equal(upgraded.headers.cookie, 'sid=yes'); + await new Promise((resolve) => setTimeout(resolve, 5200)); + assert.equal(socket.destroyed, false, 'healthy idle websocket must not time out'); + const payload = Buffer.from([0x81, 0x02, 0x6f, 0x6b]); + socket.write(payload); + await new Promise((resolve, reject) => { + const deadline = setTimeout(() => reject(new Error('echo timeout')), 1500); + const poll = setInterval(() => { + if (Buffer.concat(chunks).includes(payload)) { clearInterval(poll); clearTimeout(deadline); resolve(); } + }, 10); + }); + socket.destroy(); + await preview.close(); +}); + +test('fails closed on authentication timeout and closes idle upgraded sockets', async (t) => { + const { base } = await fixture(t, { auth: false, hanging: true }); + const started = Date.now(); + const response = await fetch(`${base}/bundle.js`); + assert.equal(response.status, 502); + assert.ok(Date.now() - started < 7000); +}); + +test('rejects encoded traversal and symlinked SPA fallback outside the root', async (t) => { + const root = await mkdtemp(join(tmpdir(), 'preview-')); + const outside = await mkdtemp(join(tmpdir(), 'preview-out-')); + await writeFile(join(outside, 'index.html'), 'private'); + await symlink(join(outside, 'index.html'), join(root, 'index.html')); + const upstream = createServer((req, res) => res.end('authenticated')); + await new Promise((resolve) => upstream.listen(0, '127.0.0.1', resolve)); + const preview = await start({ root, upstream: `http://127.0.0.1:${upstream.address().port}`, port: 0 }); + t.after(async () => { + await preview.close(); + await new Promise((resolve) => upstream.close(resolve)); + await rm(root, { recursive: true, force: true }); + await rm(outside, { recursive: true, force: true }); + }); + const response = await fetch(`http://127.0.0.1:${preview.port}/missing/route`, { headers: { cookie: 'sid=yes' } }); + assert.equal(response.status, 403); + assert.notEqual(await response.text(), 'private'); + assert.equal((await fetch(`http://127.0.0.1:${preview.port}/%2e%2e%2fsecret`, { headers: { cookie: 'sid=yes' } })).status, 403); +}); diff --git a/app/test/widget_test.dart b/app/test/widget_test.dart index 41dc58b8..774496bc 100644 --- a/app/test/widget_test.dart +++ b/app/test/widget_test.dart @@ -1,30 +1,101 @@ -// This is a basic Flutter widget test. -// -// To perform an interaction with a widget in your test, use the WidgetTester -// utility in the flutter_test package. For example, you can send tap and scroll -// gestures. You can also use WidgetTester to find child widgets in the widget -// tree, read text, and verify that the values of widget properties are correct. - +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/main.dart'; void main() { - testWidgets('Counter increments smoke test', (WidgetTester tester) async { - // Build our app and trigger a frame. - await tester.pumpWidget(const MyApp()); + for (final width in [390.0, 1000.0]) { + testWidgets( + 'Material shell adapts at width $width and supports large text', + (tester) async { + tester.view.physicalSize = Size(width, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + const MaterialApp( + home: MediaQuery( + data: MediaQueryData(textScaler: TextScaler.linear(2)), + child: AdaptiveShell(), + ), + ), + ); + expect(find.text('Pipelines'), findsWidgets); + expect(find.text('Pipelines — Not implemented'), findsOneWidget); + expect( + find.byType(NavigationBar), + width < 600 ? findsOneWidget : findsNothing, + ); + expect( + find.byType(NavigationRail), + width >= 600 ? findsOneWidget : findsNothing, + ); + await tester.tap(find.text('Runs').last); + await tester.pumpAndSettle(); + expect(find.text('Runs — Not implemented'), findsOneWidget); + }, + ); + } - // Verify that our counter starts at 0. - expect(find.text('0'), findsOneWidget); - expect(find.text('1'), findsNothing); + testWidgets('Cupertino shell uses native navigation controls', ( + tester, + ) async { + await tester.pumpWidget(const MyApp(cupertino: true)); + expect(find.byType(CupertinoNavigationBar), findsOneWidget); + expect(find.byType(CupertinoTabBar), findsOneWidget); + expect(find.text('Pipelines — Not implemented'), findsOneWidget); + }); - // Tap the '+' icon and trigger a frame. - await tester.tap(find.byIcon(Icons.add)); + testWidgets('Cupertino content stays inside safe area', (tester) async { + tester.view.padding = const FakeViewPadding(top: 36, bottom: 28); + addTearDown(tester.view.resetPadding); + await tester.pumpWidget(const MyApp(cupertino: true)); + final tabBar = tester.getRect(find.byType(CupertinoTabBar)); + expect(tabBar.bottom, lessThanOrEqualTo(900 - 28)); + expect(tester.takeException(), isNull); + }); + + testWidgets('destination state survives switching tabs', (tester) async { + var builds = 0; + await tester.pumpWidget( + MaterialApp( + home: AdaptiveShell( + destinationBodies: { + AppDestination.pipelines: (_) => StatefulBuilder( + builder: (context, setState) => TextButton( + onPressed: () => setState(() => builds++), + child: Text('Builds: $builds'), + ), + ), + AppDestination.runs: (_) => const Text('Runs screen'), + }, + ), + ), + ); + await tester.tap(find.text('Builds: 0')); await tester.pump(); + await tester.tap(find.text('Runs').last); + await tester.pumpAndSettle(); + await tester.tap(find.text('Pipelines').last); + await tester.pumpAndSettle(); + expect(find.text('Builds: 1'), findsOneWidget); + }); - // Verify that our counter has incremented. - expect(find.text('0'), findsNothing); - expect(find.text('1'), findsOneWidget); + testWidgets('destination content can be supplied by integration', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: AdaptiveShell( + destinationBodies: { + AppDestination.pipelines: (_) => + const Text('Injected pipelines screen'), + }, + ), + ), + ); + expect(find.text('Injected pipelines screen'), findsOneWidget); + expect(find.text('Pipelines — Not implemented'), findsNothing); }); } diff --git a/app/tool/artifact_list_probe.dart b/app/tool/artifact_list_probe.dart new file mode 100644 index 00000000..aecd9775 --- /dev/null +++ b/app/tool/artifact_list_probe.dart @@ -0,0 +1,194 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_visit_list.dart'; + +/// A fixture entry point for browser captures of [ArtifactVisitList]. It never +/// contacts a server: the groups below are recorded shapes, and the selection +/// line only echoes the widget's callback. +/// +/// Query parameters: +/// platform=ios render the Cupertino host instead of Material +/// scale=1.5 large-text check +/// state=empty no recorded groups +/// state=disabled rows rendered without a selection callback +/// state=unrecorded a record with no name, url or content type +void main() { + final params = Uri.base.queryParameters; + runApp( + _ProbeApp(cupertino: params['platform'] == 'ios', state: params['state']), + ); +} + +ArtifactRecord _record( + String name, { + required String url, + required String contentType, + required int sizeBytes, +}) { + return ArtifactRecord.fromJson({ + 'name': name, + 'url': url, + 'content_type': contentType, + 'size_bytes': sizeBytes, + }); +} + +const longName = + 'a-very-long-recorded-artifact-file-name-that-must-wrap-across-' + 'several-lines-at-large-text-sizes.xlsx'; + +final List _groups = [ + ArtifactGroup( + stageKey: 'build', + visit: 1, + artifacts: [ + _record( + longName, + url: '/artifacts/7/3/$longName', + contentType: + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + sizeBytes: 123456, + ), + ], + ), + ArtifactGroup( + stageKey: 'review', + visit: 1, + artifacts: [ + _record( + 'result.csv', + url: '/artifacts/7/1/result.csv', + contentType: 'text/csv', + sizeBytes: 2048, + ), + _record( + 'notes.md', + url: '/artifacts/7/1/notes.md', + contentType: 'text/markdown', + sizeBytes: 812, + ), + ], + ), + ArtifactGroup( + stageKey: 'review', + visit: 2, + artifacts: [ + _record( + 'result.csv', + url: '/artifacts/7/2/result.csv', + contentType: 'text/csv', + sizeBytes: 4096, + ), + ], + ), +]; + +/// Records the server sent without a name, url or content type. The list must +/// show the honest fallbacks rather than infer any of them. +final List _unrecordedGroups = [ + ArtifactGroup( + stageKey: 'review', + visit: 1, + artifacts: [ + ArtifactRecord.fromJson(const { + 'name': '', + 'url': '', + 'content_type': '', + 'size_bytes': 0, + }), + ArtifactRecord.fromJson(const { + 'name': 'notes.md', + 'url': '/artifacts/7/1/notes.md', + 'content_type': '', + 'size_bytes': 812, + }), + ], + ), +]; + +List _groupsFor(String? state) => switch (state) { + 'empty' => const [], + 'unrecorded' => _unrecordedGroups, + _ => _groups, +}; + +class _ProbeApp extends StatefulWidget { + const _ProbeApp({required this.cupertino, this.state}); + + final bool cupertino; + final String? state; + + @override + State<_ProbeApp> createState() => _ProbeAppState(); +} + +class _ProbeAppState extends State<_ProbeApp> { + ArtifactGroup? _selectedGroup; + ArtifactRecord? _selectedArtifact; + + String? get _selectedIdentity => _selectedGroup == null + ? null + : artifactVisitIdentity(_selectedGroup!, _selectedArtifact!); + + @override + Widget build(BuildContext context) { + final scale = + double.tryParse(Uri.base.queryParameters['scale'] ?? '') ?? 1.0; + final selected = _selectedGroup == null + ? 'Selected: none' + : 'Selected: ${_selectedGroup!.stageKey} · visit ' + '${_selectedGroup!.visit} · ${_selectedArtifact!.name}'; + final groups = _groupsFor(widget.state); + final selectable = widget.state != 'disabled'; + final body = Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 16, 16, 0), + child: Text('Artifact visit list probe'), + ), + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 16, 0), + child: Text(selected), + ), + Expanded( + child: ArtifactVisitList( + groups: groups, + selectedIdentity: _selectedIdentity, + onSelected: selectable + ? (group, artifact) => setState(() { + _selectedGroup = group; + _selectedArtifact = artifact; + }) + : null, + ), + ), + ], + ); + Widget scaled(BuildContext context, Widget? child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(scale)), + child: child ?? const SizedBox.shrink(), + ); + if (widget.cupertino) { + return CupertinoApp( + debugShowCheckedModeBanner: false, + builder: scaled, + home: CupertinoPageScaffold( + // Sections paint the grouped background; the page must match it or a + // white seam shows below the last section in light mode. + backgroundColor: CupertinoColors.systemGroupedBackground, + child: body, + ), + ); + } + return MaterialApp( + debugShowCheckedModeBanner: false, + builder: scaled, + home: Scaffold(body: body), + ); + } +} diff --git a/app/tool/changes_probe.mjs b/app/tool/changes_probe.mjs new file mode 100644 index 00000000..7c2f51c7 --- /dev/null +++ b/app/tool/changes_probe.mjs @@ -0,0 +1,419 @@ +// Real-browser evidence for the Changes viewer fixture. +// +// Usage (from app/): +// flutter build web --target tool/changes_probe_entry.dart --output build/probe-web +// node tool/changes_probe.mjs --root build/probe-web --out DIR +// +// Serves the fixture over loopback with an explicit text/html index, drives +// headless Chrome through the Chrome DevTools Protocol, enables Flutter +// semantics, clicks exact labels, verifies the body/labels change, copies the +// raw patch and writes real PNG captures at phone and desktop widths. +import { createServer } from 'node:http'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { setTimeout as delay } from 'node:timers/promises'; +import { extname, join, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; + +const args = new Map(); +for (let i = 2; i < process.argv.length; i++) { + const value = process.argv[i]; + if (value.startsWith('--')) args.set(value.slice(2), process.argv[++i]); +} +const root = resolve(args.get('root') ?? 'build/probe-web'); +const out = resolve(args.get('out') ?? 'build/changes-probe'); +const chromePath = + process.env.CHROME_PATH ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +await mkdir(out, { recursive: true }); + +const mime = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.svg': 'image/svg+xml', + '.ico': 'image/x-icon', + '.ttf': 'font/ttf', + '.otf': 'font/otf', + '.woff': 'font/woff', + '.woff2': 'font/woff2', + '.bin': 'application/octet-stream', + '.frag': 'application/octet-stream', +}; + +const server = createServer(async (req, res) => { + try { + const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname); + let filePath = resolve(root, '.' + pathname); + if (filePath !== root && !filePath.startsWith(root + sep)) { + res.writeHead(403).end(); + return; + } + if (pathname === '/' || pathname.endsWith('/')) { + filePath = join(filePath, 'index.html'); + } + const file = await readFile(filePath); + const type = mime[extname(filePath)] ?? 'application/octet-stream'; + res.writeHead(200, { 'content-type': type }).end(file); + } catch { + res.writeHead(404).end('not found'); + } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const port = server.address().port; +const origin = `http://127.0.0.1:${port}`; + +const profile = await mkdtemp(join(tmpdir(), 'd1-changes-chrome-')); +const chrome = spawn( + chromePath, + [ + '--headless=new', + '--no-first-run', + '--no-default-browser-check', + '--disable-gpu', + '--remote-debugging-port=0', + `--user-data-dir=${profile}`, + 'about:blank', + ], + { stdio: ['ignore', 'ignore', 'pipe'] }, +); +let stderr = ''; +chrome.stderr.on('data', (data) => { + stderr += data; +}); + +const waitFor = async (fn, what) => { + for (let i = 0; i < 120; i++) { + const value = await fn(); + if (value) return value; + await delay(100); + } + throw new Error(`Timed out waiting for ${what}: ${stderr.slice(-1500)}`); +}; + +let ws; +const evidence = { origin, captures: [], checks: [] }; +try { + const endpoint = await waitFor( + () => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1], + 'Chrome DevTools', + ); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', (event) => { + const message = JSON.parse(event.data); + if (message.id && pending.has(message.id)) { + pending.get(message.id)(message); + pending.delete(message.id); + } + }); + const send = (method, params = {}, sessionId) => + new Promise((resolveCall) => { + const callId = ++id; + pending.set(callId, resolveCall); + ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + + const created = await send('Target.createTarget', { url: 'about:blank' }); + if (!created.result) throw new Error(`Target creation failed: ${JSON.stringify(created)}`); + const target = created.result.targetId; + const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result + .sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + await send('Emulation.setDeviceMetricsOverride', { + width: 390, + height: 844, + deviceScaleFactor: 1, + mobile: true, + }, session); + + const evaluate = async (expression) => { + const response = await send( + 'Runtime.evaluate', + { expression, returnByValue: true, awaitPromise: true }, + session, + ); + if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); + return response.result?.result?.value; + }; + const labels = () => + evaluate( + "[...document.querySelectorAll('flt-semantics')].map(x => x.getAttribute('aria-label') || (x.innerText || '').trim()).filter(Boolean)", + ); + const bodyText = () => evaluate('document.body.innerText'); + const hasLabel = async (label) => (await labels()).includes(label); + const clickExact = async (label) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(label)}; + const nodes = [...document.querySelectorAll('flt-semantics')]; + const node = nodes.find(x => x.getAttribute('aria-label') === wanted) + || nodes.find(x => (x.innerText || '').trim() === wanted); + if (!node) return false; + node.click(); + return true; + })()`); + if (!clicked) throw new Error(`No exact semantics label ${JSON.stringify(label)}: ${JSON.stringify(await labels())}`); + await delay(450); + }; + // File rows announce their visible kind and meta after the path, so click by + // the stable action+path prefix rather than a fully spelled label. + const clickPrefix = async (prefix) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(prefix)}; + const nodes = [...document.querySelectorAll('flt-semantics')]; + // A container's innerText also starts with its first row, so click the + // most specific (shortest-text) node that starts with the row prefix. + const candidates = nodes.filter((x) => + (x.getAttribute('aria-label') || '').startsWith(wanted) + || (x.innerText || '').trim().startsWith(wanted)); + if (candidates.length === 0) return false; + candidates.sort((a, b) => (a.innerText || '').length - (b.innerText || '').length); + candidates[0].click(); + return true; + })()`); + if (!clicked) throw new Error(`No semantics label starting ${JSON.stringify(prefix)}: ${JSON.stringify(await labels())}`); + await delay(450); + }; + const activate = async () => { + await delay(3500); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(1000); + const current = await labels(); + if (!current.some((label) => label.includes('Changes probe'))) { + throw new Error(`Flutter semantics unavailable: ${JSON.stringify(current)}`); + } + }; + const navigate = async (url) => { + const navigation = await send('Page.navigate', { url }, session); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + await activate(); + }; + const capture = async (name, width, height, scale = 1) => { + await send('Emulation.setDeviceMetricsOverride', { + width, + height, + deviceScaleFactor: scale, + mobile: width < 600, + }, session); + await delay(350); + const data = (await send('Page.captureScreenshot', { format: 'png' }, session)).result.data; + const file = join(out, `${name}.png`); + await writeFile(file, Buffer.from(data, 'base64')); + evidence.captures.push(file); + return file; + }; + + await navigate(`${origin}/`); + const contentType = await evaluate( + "fetch('/').then(r => r.headers.get('content-type'))", + ); + evidence.checks.push({ check: 'index content-type is text/html', value: contentType }); + if (!String(contentType).toLowerCase().startsWith('text/html')) { + throw new Error(`Root index is not text/html: ${contentType}`); + } + + // Diff text inherits native host typography; it must not add a custom face. + const manifest = await evaluate("fetch('/assets/FontManifest.json').then(r => r.json())"); + const codeEntry = (Array.isArray(manifest) ? manifest : []).find( + (entry) => entry.family === 'RobotoMono', + ); + if (codeEntry) throw new Error('Diff build still overrides native typography'); + evidence.checks.push({ + check: 'the web build does not register a custom diff font', + }); + + const firstLabels = await labels(); + const firstBody = await bodyText(); + const firstRow = 'Open diff for lib/features/changes/domain/unified_patch.dart'; + const firstRowPresent = firstLabels.some((label) => label.startsWith(firstRow)); + const firstStates = ['Changes probe', 'Capture unavailable'].filter((label) => + firstBody.includes(label), + ); + evidence.checks.push({ + check: 'run summary and capture states are present', + value: firstStates, + fileRow: firstRowPresent, + }); + if (firstStates.length !== 2 || !firstRowPresent) { + throw new Error(`Run summary or capture states missing: ${JSON.stringify(firstBody)}`); + } + await capture('d1-changes-phone-list', 390, 844); + + const before = await bodyText(); + await clickPrefix('Open diff for lib/features/changes/domain/unified_patch.dart'); + const after = await bodyText(); + if (after === before) throw new Error('Opening the diff did not change the document body'); + for (const label of ['Rendered', 'Raw patch', 'Copy patch', 'Close diff']) { + if (!(await hasLabel(label))) throw new Error(`Open diff is missing ${label}: ${JSON.stringify(await labels())}`); + } + evidence.checks.push({ check: 'body changed and diff controls appeared', bodyChanged: true }); + const renderedFile = await capture('d1-changes-phone-diff', 390, 844); + + const renderedBody = await bodyText(); + await clickExact('Raw patch'); + const rawSemantics = (await labels()).some((label) => + label.startsWith('Raw patch for lib/features/changes/domain/unified_patch.dart'), + ); + if (!rawSemantics) { + throw new Error(`Raw patch view semantics missing: ${JSON.stringify(await labels())}`); + } + const rawBody = await bodyText(); + const rawFile = await capture('d1-changes-phone-raw', 390, 844); + const [renderedBytes, rawBytes] = await Promise.all([ + readFile(renderedFile), + readFile(rawFile), + ]); + if (renderedBytes.equals(rawBytes)) { + throw new Error('Raw patch capture is identical to the rendered capture'); + } + evidence.checks.push({ + check: 'Raw patch switched the body and the rendered pixels', + bodyChanged: rawBody !== renderedBody, + pixelsChanged: true, + rawSemantics, + }); + + await send('Browser.grantPermissions', { + origin, + permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'], + }); + await clickExact('Copy patch'); + let clipboard = null; + try { + clipboard = await evaluate('navigator.clipboard.readText()'); + } catch (error) { + evidence.checks.push({ check: 'clipboard readback unavailable', value: String(error) }); + } + if (clipboard != null) { + const startsWithHeader = String(clipboard).startsWith( + '--- "a/lib/features/changes/domain/unified_patch.dart"', + ); + if (!startsWithHeader) throw new Error('Clipboard did not contain the recorded raw patch'); + evidence.checks.push({ + check: 'Copy patch copied the raw patch', + startsWithHeader, + length: String(clipboard).length, + }); + } + await capture('d1-changes-phone-copied', 390, 844); + + await clickExact('Close diff'); + if (await hasLabel('Raw patch')) throw new Error('Close diff left the viewer open'); + evidence.checks.push({ check: 'Close diff returned to the list', bodyChanged: (await bodyText()) !== after }); + + // Filter changed filenames through the real text field when Flutter exposes + // it as a semantics input; record honestly when it does not. + const focused = await evaluate(`(() => { + const nodes = [...document.querySelectorAll('input, textarea')]; + const node = nodes.find(x => ((x.getAttribute('aria-label') || '') + ' ' + (x.placeholder || '')).toLowerCase().includes('filter changed files')); + if (!node) return false; + node.focus(); + node.click(); + return true; + })()`); + if (focused) { + await send('Input.insertText', { text: 'unified' }, session); + await delay(500); + const filtered = await labels(); + // A row is one single-line semantics node; a list container repeats its + // rows with newlines and must not be counted as an extra match. + const rows = (prefix) => + filtered.filter((label) => label.startsWith(prefix) && !label.includes('\n')); + const unifiedRows = rows('Open diff for lib/features/changes/domain/unified_patch.dart'); + const binaryRows = rows('Open diff for assets/pipelines-mark.png'); + evidence.checks.push({ + check: 'filtering by changed filename', + unifiedRows: unifiedRows.length, + binaryRows: binaryRows.length, + }); + if (unifiedRows.length === 0) { + throw new Error('Filtering removed the matching file'); + } + if (binaryRows.length !== 0) { + throw new Error('Filtering left a non-matching file visible'); + } + await capture('d1-changes-phone-filtered', 390, 844); + } else { + evidence.checks.push({ check: 'filter field not exposed as a semantics input', value: false }); + } + + // Visit numbering: two stages appear twice in this compact fixture. The + // implementer's visits are position-derived (1, 2); the resumed reviewer + // visit records control.visit 6, which must win over its position. + await navigate(`${origin}/?visits=1`); + const visitText = await bodyText(); + const visitsFor = (stage) => [ + ...visitText.matchAll(new RegExp(`${stage}\\s+Visit (\\d+)`, 'g')), + ].map((match) => match[1]); + const implementerVisits = visitsFor('implementer'); + const reviewerVisits = visitsFor('reviewer'); + evidence.checks.push({ + check: 'repeated stages show their own visit numbers', + implementerVisits, + reviewerVisits, + }); + if (implementerVisits.join(',') !== '1,2') { + throw new Error(`implementer visits are not 1,2: ${JSON.stringify(visitText)}`); + } + if (reviewerVisits.join(',') !== '1,6') { + throw new Error(`reviewer visits are not 1,6 (control.visit): ${JSON.stringify(visitText)}`); + } + const visitFile = await capture('d1-changes-phone-visits', 390, 844); + + await navigate(`${origin}/`); + await clickPrefix('Open diff for lib/features/changes/widgets/file_diff_viewer.dart'); + await capture('d1-changes-desktop-diff', 1280, 800); + await clickExact('Close diff'); + await capture('d1-changes-desktop-list', 1280, 800); + + // Presentation revision: the light theme and a narrow Cupertino surface, at + // 2x so glyph advance, line tints and the popup inset are inspectable. + await navigate(`${origin}/?theme=light`); + await capture('d1-changes-phone-light-list', 390, 844); + await clickPrefix('Open diff for lib/features/changes/domain/unified_patch.dart'); + await capture('d1-changes-phone-light-diff', 390, 844); + await clickExact('Raw patch'); + await capture('d1-changes-phone-light-raw', 390, 844); + await clickExact('Rendered'); + // The 2x capture is last in its state: Chrome only re-lays out Flutter when + // the CSS size changes, so scaling back down on the same page would capture a + // half-size frame. + await capture('d1-changes-phone-light-diff-2x', 390, 844, 2); + + await navigate(`${origin}/?theme=light`); + await capture('d1-changes-desktop-light-list', 1280, 800); + await clickPrefix('Open diff for lib/features/changes/widgets/file_diff_viewer.dart'); + await capture('d1-changes-desktop-light-diff', 1280, 800); + await clickExact('Close diff'); + + await navigate(`${origin}/?platform=cupertino&theme=light`); + await capture('d1-changes-cupertino-light-list', 390, 844); + await clickPrefix('Open diff for lib/features/changes/domain/unified_patch.dart'); + await capture('d1-changes-cupertino-light-diff', 390, 844); + await capture('d1-changes-cupertino-light-diff-2x', 390, 844, 2); + + await navigate(`${origin}/?platform=cupertino`); + const cupertinoLabels = await labels(); + if (!cupertinoLabels.some((label) => label.includes('Changes probe'))) { + throw new Error('Cupertino fixture did not load'); + } + await clickPrefix('Open diff for lib/features/changes/domain/unified_patch.dart'); + await capture('d1-changes-cupertino-diff', 1280, 800); + + evidence.checks.push({ check: 'Cupertino viewer opened', value: true }); + evidence.checks.push({ check: 'visit capture written', value: visitFile }); + console.log(JSON.stringify(evidence, null, 2)); +} finally { + ws?.close(); + chrome.kill('SIGTERM'); + await Promise.race([once(chrome, 'exit'), delay(3000)]); + server.close(); + await rm(profile, { recursive: true, force: true }); +} diff --git a/app/tool/changes_probe_entry.dart b/app/tool/changes_probe_entry.dart new file mode 100644 index 00000000..1e10890c --- /dev/null +++ b/app/tool/changes_probe_entry.dart @@ -0,0 +1,264 @@ +// Standalone fixture entry for real-browser Changes evidence. +// +// Build and probe (from app/): +// flutter build web --target tool/changes_probe_entry.dart --output build/probe-web +// node tool/changes_probe.mjs --root build/probe-web --out DIR +// +// These are server-shaped fixtures for rendering only. They are not a live run +// and never mutate a server. +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/changes/changes.dart'; + +const _multiHunkPatch = + '--- "a/lib/features/changes/domain/unified_patch.dart"\n' + '+++ "b/lib/features/changes/domain/unified_patch.dart"\n' + '@@ -12,6 +12,7 @@\n' + ' class ParsedPatch {\n' + ' const ParsedPatch({\n' + ' required this.raw,\n' + '+ required this.headerLines,\n' + ' required this.hunks,\n' + ' });\n' + ' \n' + '@@ -48,5 +49,5 @@\n' + '-PatchHunk? _parseHunkHeader(String line) {\n' + '+_HunkStart? _parseHunkHeader(String line) {\n' + " if (!line.startsWith('@@')) return null;\n" + " final end = line.indexOf('@@', 2);\n" + ' if (end < 0) return null;\n' + ' final ranges = _tokenizeRanges(line.substring(2, end));\n'; + +const _addedPatch = + '--- "/dev/null"\n' + '+++ "b/lib/features/changes/widgets/file_diff_viewer.dart"\n' + '@@ -0,0 +1,5 @@\n' + '+class FileDiffViewer extends StatefulWidget {\n' + '+ const FileDiffViewer({super.key, required this.file});\n' + '+\n' + '+ final FileChange file;\n' + '+}\n'; + +const _deletedPatch = + '--- "a/docs/legacy-notes.md"\n' + '+++ "/dev/null"\n' + '@@ -1,2 +0,0 @@\n' + '-# Legacy notes\n' + '-Removed with the viewer.\n'; + +const _truncatedPatch = + '--- "a/logs/capture.log"\n' + '+++ "b/logs/capture.log"\n' + '@@ -1,2 +1,3 @@\n' + '-capture started\n' + '+capture started\n' + '+and truncated mid-line'; + +List probeSteps() => [ + { + 'sequence': 1, + 'stage': 'implementer', + 'status': 'completed', + 'file_changes': { + 'status': 'partial', + 'scope': 'Git tracked and nonignored files in the run directory', + 'skipped': 2, + 'omitted': 0, + 'diagnostic': + 'Excluded protected, symlinked, oversized or unreadable files; this ' + 'is not a complete workspace diff.', + 'files': [ + { + 'path': 'lib/features/changes/domain/unified_patch.dart', + 'kind': 'modified', + 'patch': _multiHunkPatch, + 'before_mode': '0644', + 'after_mode': '0644', + }, + { + 'path': 'assets/pipelines-mark.png', + 'kind': 'modified', + 'binary': true, + }, + { + 'path': 'scripts/capture.sh', + 'kind': 'modified', + 'before_mode': '0644', + 'after_mode': '0755', + }, + { + 'path': 'docs/legacy-notes.md', + 'kind': 'deleted', + 'patch': _deletedPatch, + 'before_mode': '0644', + }, + { + 'path': 'logs/capture.log', + 'kind': 'modified', + 'patch': _truncatedPatch, + 'truncated': true, + }, + ], + }, + }, + { + 'sequence': 2, + 'stage': 'reviewer', + 'status': 'completed', + 'file_changes': { + 'status': 'complete', + 'scope': 'Git tracked and nonignored files in the run directory', + 'skipped': 0, + 'omitted': 0, + 'diagnostic': '', + 'files': [ + { + 'path': 'lib/features/changes/widgets/file_diff_viewer.dart', + 'kind': 'added', + 'patch': _addedPatch, + 'after_mode': '0644', + }, + { + 'path': 'lib/features/changes/domain/unified_patch.dart', + 'kind': 'modified', + 'patch': _multiHunkPatch, + }, + ], + }, + }, + { + 'sequence': 3, + 'stage': 'ui_reviewer', + 'status': 'completed', + 'file_changes': null, + }, + { + 'sequence': 4, + 'stage': 'committer', + 'status': 'completed', + 'file_changes': { + 'status': 'unavailable', + 'skipped': 0, + 'omitted': 0, + 'diagnostic': + 'Workspace snapshot unavailable; changes could not be compared.', + 'files': [], + }, + }, + { + 'sequence': 5, + 'stage': 'verifier', + 'status': 'completed', + 'file_changes': { + 'status': 'complete', + 'scope': 'Git tracked and nonignored files in the run directory', + 'skipped': 0, + 'omitted': 0, + 'diagnostic': '', + 'files': [], + }, + }, +]; + +/// A compact fixture whose only purpose is visit numbering: the same stages +/// appear more than once, one visit records an explicit `control.visit`, and +/// every capture is empty so the sections stay on one phone screen. +List probeVisitSteps() => [ + { + 'sequence': 1, + 'stage': 'implementer', + 'status': 'completed', + 'file_changes': { + 'status': 'complete', + 'scope': 'Git tracked and nonignored files in the run directory', + 'files': [], + }, + }, + { + 'sequence': 2, + 'stage': 'reviewer', + 'status': 'completed', + 'file_changes': { + 'status': 'complete', + 'scope': 'Git tracked and nonignored files in the run directory', + 'files': [], + }, + }, + { + 'sequence': 3, + 'stage': 'implementer', + 'status': 'completed', + 'file_changes': { + 'status': 'complete', + 'scope': 'Git tracked and nonignored files in the run directory', + 'files': [], + }, + }, + { + 'sequence': 4, + 'stage': 'reviewer', + 'status': 'completed', + 'control': {'visit': 6}, + 'file_changes': { + 'status': 'complete', + 'scope': 'Git tracked and nonignored files in the run directory', + 'files': [], + }, + }, +]; + +void main() { + final params = Uri.base.queryParameters; + final cupertino = params['platform'] == 'cupertino'; + final brightness = params['theme'] == 'light' + ? Brightness.light + : Brightness.dark; + final steps = params['visits'] == '1' ? probeVisitSteps() : probeSteps(); + if (cupertino) { + runApp( + CupertinoApp( + title: 'Changes probe', + theme: CupertinoThemeData(brightness: brightness), + home: _ProbeHome(cupertino: true, steps: steps), + ), + ); + } else { + runApp( + MaterialApp( + title: 'Changes probe', + theme: ThemeData( + brightness: brightness, + // Chrome on macOS reports a macOS default platform; the fixture + // states Material explicitly so both control sets are capturable. + platform: TargetPlatform.android, + ), + home: _ProbeHome(cupertino: false, steps: steps), + ), + ); + } +} + +class _ProbeHome extends StatelessWidget { + const _ProbeHome({required this.cupertino, required this.steps}); + + final bool cupertino; + final List steps; + + @override + Widget build(BuildContext context) { + final viewer = ChangesViewer(steps: steps); + if (cupertino) { + return CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar( + middle: Text('Changes probe'), + ), + child: SafeArea(child: viewer), + ); + } + return Scaffold( + appBar: AppBar(title: const Text('Changes probe')), + body: viewer, + ); + } +} diff --git a/app/tool/chat_sessions_probe.mjs b/app/tool/chat_sessions_probe.mjs new file mode 100644 index 00000000..42935d24 --- /dev/null +++ b/app/tool/chat_sessions_probe.mjs @@ -0,0 +1,112 @@ +import { createServer } from 'node:http'; +import { readFile } from 'node:fs/promises'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { setTimeout as delay } from 'node:timers/promises'; +import { join, extname, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; +import { mkdir, mkdtemp, rm } from 'node:fs/promises'; + +const root = resolve(process.env.PROBE_WEB_ROOT ?? join(process.cwd(), 'build/web')); +const variant = process.env.PROBE_VARIANT ?? 'material'; +const artifactDir = process.env.OPENCODE_ARTIFACT_DIR ?? join(tmpdir(), 'chat-sessions-capture'); +await mkdir(artifactDir, { recursive: true }); +const mime = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png', '.ico': 'image/x-icon' }; +const server = createServer(async (req, res) => { + try { + const path = resolve(root, '.' + decodeURIComponent(new URL(req.url, 'http://localhost').pathname)); + if (path !== root && !path.startsWith(root + sep)) return res.writeHead(403).end(); + const filePath = path === root || path.endsWith('/') ? join(path, 'index.html') : path; + const file = await readFile(filePath); + res.writeHead(200, { 'content-type': mime[extname(filePath)] ?? 'application/octet-stream' }).end(file); + } catch { res.writeHead(404).end('not found'); } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const port = server.address().port; + const profile = await mkdtemp(join(tmpdir(), 'chat-sessions-chrome-')); +const chrome = spawn('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', [ + '--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu', + '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank', +], { stdio: ['ignore', 'ignore', 'pipe'] }); +let stderr = ''; +chrome.stderr.on('data', data => { stderr += data; }); +const waitFor = async fn => { + for (let i = 0; i < 100; i++) { const value = await fn(); if (value) return value; await delay(100); } + throw new Error('Timed out waiting for Chrome DevTools'); +}; +let ws; +try { + const endpoint = await waitFor(() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1]); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', event => { + const msg = JSON.parse(event.data); + if (msg.method?.includes('detached') || msg.method?.includes('crashed')) console.error('CDP event', JSON.stringify(msg)); + if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); } + }); + const send = (method, params = {}, sessionId) => new Promise(resolve => { + const callId = ++id; pending.set(callId, resolve); + ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + const created = await send('Target.createTarget', { url: 'about:blank' }); + if (!created.result) throw new Error(`Target creation failed: ${JSON.stringify(created)}`); + const target = created.result.targetId; + const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + const navigation = await send('Page.navigate', { url: `http://127.0.0.1:${port}/` }, session); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + const evaluate = async expression => { + const response = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, session); + if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); + return response.result?.result?.value; + }; + await delay(3500); + const loaded = await evaluate("({url:location.href, ready:document.readyState, body:document.body.innerText, html:document.body.innerHTML.slice(0,500)})"); + if (!loaded?.url.includes(`127.0.0.1:${port}`)) throw new Error(`Fixture did not load: ${JSON.stringify(loaded)}`); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(2500); + const clickLabel = async label => { + const point = await evaluate(`(() => { const needle = ${JSON.stringify(label)}; const e=[...document.querySelectorAll('flt-semantics')].find(x => (x.getAttribute('aria-label') || x.innerText || '') === needle); if (!e) return null; const r=e.getBoundingClientRect(); return {x:r.x+r.width/2,y:r.y+r.height/2}; })()`); + if (!point) return false; + await send('Input.dispatchMouseEvent', { type: 'mousePressed', x: point.x, y: point.y, button: 'left', clickCount: 1 }, session); + await send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: point.x, y: point.y, button: 'left', clickCount: 1 }, session); + return true; + }; + const labels = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||x.innerText).filter(Boolean)"); + if (!labels?.some(x => x.includes('New chat'))) throw new Error(`Chat fixture semantics unavailable: ${JSON.stringify(labels)}`); + if (process.env.PROBE_DEBUG) console.log(JSON.stringify(labels)); + const capture = async (name, width, height) => { + await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 }, session); + await delay(350); + const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data; + await (await import('node:fs/promises')).writeFile(`${artifactDir}/${variant}-${name}.png`, Buffer.from(data, 'base64')); + }; + await capture('chat-sessions-desktop', 1280, 800); + await capture('chat-sessions-phone', 390, 844); + if (!await clickLabel('New chat')) throw new Error('Could not open create dialog'); + await delay(600); + await send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: 195, y: 680, deltaY: 598 }, session); + await delay(350); + const changedBody = await evaluate('document.body.innerText'); + await capture('chat-sessions-create-dialog', 390, 844); + if (!changedBody.includes('Server directory') || !changedBody.includes('Backend') || !changedBody.includes('New chats use the server default model.')) throw new Error(`Create dialog did not change rendered body to catalog controls: ${changedBody}`); + if (!await clickLabel('Cancel')) throw new Error('Could not close create dialog'); + await delay(600); + if (!await clickLabel('Chat actions for Open fixture')) throw new Error('Could not open row actions'); + await delay(600); + const actionsBody = await evaluate('document.body.innerText'); + const actionLabels = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x => x.getAttribute('aria-label') || x.innerText || '').filter(Boolean)"); + await capture('chat-sessions-actions', 390, 844); + if (!actionLabels.some(label => label.includes('Rename…'))) throw new Error(`Row actions unavailable: ${actionsBody} / ${actionLabels}`); + console.log(JSON.stringify({ variant, labels, captures: [`${variant}-chat-sessions-desktop.png`, `${variant}-chat-sessions-phone.png`, `${variant}-chat-sessions-create-dialog.png`, `${variant}-chat-sessions-actions.png`], bodyChanged: true }, null, 2)); +} finally { + ws?.close(); + chrome.kill('SIGTERM'); + await Promise.race([once(chrome, 'exit'), delay(3000)]); + server.close(); + await rm(profile, { recursive: true, force: true }); +} diff --git a/app/tool/chat_sessions_probe_entry.dart b/app/tool/chat_sessions_probe_entry.dart new file mode 100644 index 00000000..a0be1e08 --- /dev/null +++ b/app/tool/chat_sessions_probe_entry.dart @@ -0,0 +1,76 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/session_screen.dart'; + +class _FixtureGateway implements ApiGateway { + @override + Stream get frames => const Stream.empty(); + @override + Future call(String type, [JsonMap fields = const {}]) async { + if (type == 'chat_sessions') { + return { + 'chat_sessions': [ + { + 'id': 'probe-open', + 'title': 'Open fixture', + 'directory': '/workspace/demo', + 'starred': true, + }, + { + 'id': 'probe-closed', + 'title': 'Closed fixture', + 'directory': '/workspace/archive', + 'closed_at': '2026-01-01', + }, + { + 'id': 'probe-stream', + 'title': 'Streaming fixture', + 'directory': '/workspace/demo', + 'running': true, + }, + ], + }; + } + if (type == 'chat_directories') { + return { + 'chat_directories': ['/workspace/demo', '/workspace/archive'], + }; + } + if (type == 'chat_backends') { + return { + 'chat_backends': ['opencode', 'codex'], + }; + } + if (type == 'chat_create') { + return { + 'chat_session': { + 'id': 'probe-new', + 'title': 'New fixture', + 'directory': '/workspace/demo', + }, + }; + } + return {'chat_session': {}}; + } +} + +const _probeStyle = String.fromEnvironment( + 'CHAT_PROBE_STYLE', + defaultValue: 'material', +); + +void main() { + final home = ChatSessionsScreen(gateway: _FixtureGateway(), onOpen: (_) {}); + if (_probeStyle == 'cupertino') { + runApp(CupertinoApp(home: home)); + return; + } + runApp( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + home: home, + ), + ); +} diff --git a/app/tool/graph_edge_probe.dart b/app/tool/graph_edge_probe.dart new file mode 100644 index 00000000..42687e2d --- /dev/null +++ b/app/tool/graph_edge_probe.dart @@ -0,0 +1,182 @@ +import 'package:flutter/material.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/layout/graph_node_layout.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; +import 'package:pipelines_app/features/graph/painting/graph_edge_layer.dart'; +import 'package:pipelines_app/features/graph/routing/graph_edge_routing.dart'; +import 'package:pipelines_app/features/graph/routing/route_models.dart'; + +/// Browser-capture fixture for `GraphEdgeLayer` only. +/// +/// It composes caller-measured cards, the landed node layout, the landed +/// orthogonal router and the edge layer. It is not wired into `main.dart`; the +/// app shell, a real pipeline and any server stay untouched. Query parameter +/// `theme=dark` selects the dark native theme and `case=same-rank` swaps in a +/// two-node cycle that exercises same-rank edges between distinct nodes. +void main() => runApp(const GraphEdgeProbeApp()); + +const Map _definition = { + 'stages': [ + { + 'key': 'ingest', + 'edges': {'success': 'build', 'error': '#failure'}, + }, + { + 'key': 'build', + 'edges': {'success': 'verify', 'retry': 'build'}, + }, + { + 'key': 'verify', + 'edges': {'success': '#success', 'rework': 'ingest'}, + }, + ], +}; + +/// A two-node cycle: both nodes share one rank and both edges are same-rank +/// without being self loops. +const Map _sameRankDefinition = { + 'stages': [ + { + 'key': 'review', + 'edges': {'success': 'approve'}, + }, + { + 'key': 'approve', + 'edges': {'success': 'review'}, + }, + ], +}; + +class GraphEdgeProbeApp extends StatelessWidget { + const GraphEdgeProbeApp({super.key}); + + @override + Widget build(BuildContext context) { + final dark = Uri.base.queryParameters['theme'] == 'dark'; + return MaterialApp( + title: 'Graph edge layer probe', + theme: ThemeData( + brightness: dark ? Brightness.dark : Brightness.light, + colorScheme: ColorScheme.fromSeed( + seedColor: Colors.indigo, + brightness: dark ? Brightness.dark : Brightness.light, + ), + ), + home: const _ProbePage(), + ); + } +} + +class _ProbePage extends StatelessWidget { + const _ProbePage(); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scaler = MediaQuery.textScalerOf(context); + final sameRankCase = Uri.base.queryParameters['case'] == 'same-rank'; + final definition = sameRankCase ? _sameRankDefinition : _definition; + final nodes = graphNodes(definition); + final edges = graphEdges(definition); + final layout = layoutGraphNodes( + nodes: nodes, + edges: edges, + extents: { + for (final node in nodes) + node.key: _nodeExtent(theme.textTheme.bodyMedium, node.label, scaler), + }, + config: GraphLayoutConfig(columnGap: 120, rowGap: 24, padding: 16), + ); + final routing = routeGraphEdges( + layout: layout, + edges: edges, + labelExtents: { + for (final edge in edges) + edge.id: _labelExtent(theme.textTheme.labelSmall, edge.label, scaler), + }, + config: RoutingConfig( + nodeClearance: 8, + laneSpacing: 28, + corridorSpacing: 20, + portSpacing: 12, + labelGap: 4, + boundsPadding: 8, + ), + ); + final size = Size(routing.width, routing.height); + + return Scaffold( + appBar: AppBar(title: const Text('Graph edge layer')), + body: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + sameRankCase + ? 'A two-node cycle in one rank: both arrows are same-rank ' + 'and neither is a self loop.' + : 'Measured cards and routed edges: same-rank cycle edges, ' + 'forward edges to the terminals and a self loop, in the ' + 'native outline color and stroke.', + style: theme.textTheme.bodySmall, + ), + const SizedBox(height: 16), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: SizedBox.fromSize( + size: size, + child: Stack( + clipBehavior: Clip.none, + children: [ + GraphEdgeLayer( + routes: routing.routes, + canvasSize: size, + color: theme.colorScheme.outline, + strokeWidth: theme.dividerTheme.thickness ?? 1, + ), + for (final node in layout.nodes) + Positioned( + left: node.x, + top: node.y, + width: node.width, + height: node.height, + child: Card( + margin: EdgeInsets.zero, + child: Center( + child: Text( + nodeDisplayLabel(node.key), + style: theme.textTheme.bodyMedium, + ), + ), + ), + ), + ], + ), + ), + ), + ], + ), + ), + ); + } +} + +NodeExtent _nodeExtent(TextStyle? style, String text, TextScaler scaler) { + final painter = TextPainter( + text: TextSpan(text: text, style: style), + textDirection: TextDirection.ltr, + textScaler: scaler, + )..layout(); + return NodeExtent(width: painter.width + 32, height: painter.height + 20); +} + +LabelExtent _labelExtent(TextStyle? style, String text, TextScaler scaler) { + final painter = TextPainter( + text: TextSpan(text: text, style: style), + textDirection: TextDirection.ltr, + textScaler: scaler, + )..layout(); + return LabelExtent(width: painter.width + 8, height: painter.height + 4); +} diff --git a/app/tool/graph_node_probe.dart b/app/tool/graph_node_probe.dart new file mode 100644 index 00000000..46c07f9f --- /dev/null +++ b/app/tool/graph_node_probe.dart @@ -0,0 +1,90 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart'; + +const _longKey = 'implementer-with-an-unshortened-stage-label'; +const _oneXKey = 'narrow-one-x-stage-key-that-wraps'; + +/// Keys rendered in a 150 logical px box, with the text scale applied to them. +const _scaled = {_longKey: 2.0, _oneXKey: 1.0}; + +const _nodes = [ + GraphNode(key: 'plan', terminal: false, stageIndex: 0), + GraphNode(key: 'build', terminal: false, stageIndex: 1), + GraphNode(key: _longKey, terminal: false, stageIndex: 2), + GraphNode(key: _oneXKey, terminal: false, stageIndex: 3), + GraphNode(key: '#success', terminal: true), + GraphNode(key: '#failure', terminal: true), +]; + +/// A fixture-only page: one measured node per definition identity, with the +/// selected key reported so a browser click can prove the exact callback. +class _Probe extends StatefulWidget { + const _Probe({required this.cupertino}); + + final bool cupertino; + + @override + State<_Probe> createState() => _ProbeState(); +} + +class _ProbeState extends State<_Probe> { + String? _selected = 'build'; + + Widget _node(GraphNode node) { + final child = GraphStageNode( + node: node, + recordedStatus: node.key == 'build' ? 'running' : null, + selected: node.key == _selected, + onSelected: (key) => setState(() => _selected = key), + ); + final scale = _scaled[node.key]; + if (scale == null) return child; + return MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(scale)), + child: SizedBox(width: 150, child: child), + ); + } + + @override + Widget build(BuildContext context) { + final page = ListView( + padding: const EdgeInsets.all(16), + children: [ + Text('Selected: ${_selected ?? 'none'}'), + const SizedBox(height: 12), + Wrap( + spacing: 12, + runSpacing: 12, + children: [for (final node in _nodes) _node(node)], + ), + ], + ); + return widget.cupertino + ? CupertinoPageScaffold(child: SafeArea(child: page)) + : Scaffold(body: SafeArea(child: page)); + } +} + +void main() { + final cupertino = Uri.base.queryParameters['style'] == 'cupertino'; + runApp( + cupertino + ? CupertinoApp(home: const _Probe(cupertino: true)) + : MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + // Stock dark theme so the forced `prefers-color-scheme` capture is + // a real dark render rather than a duplicate light one. + darkTheme: ThemeData( + platform: TargetPlatform.android, + brightness: Brightness.dark, + ), + themeMode: ThemeMode.system, + home: const _Probe(cupertino: false), + ), + ); +} diff --git a/app/tool/graph_node_probe.mjs b/app/tool/graph_node_probe.mjs new file mode 100644 index 00000000..f5145df8 --- /dev/null +++ b/app/tool/graph_node_probe.mjs @@ -0,0 +1,151 @@ +// Browser acceptance for the isolated GraphStageNode fixture. +// +// Serves the probe build (`flutter build web -t tool/graph_node_probe.dart`) on +// an OS-assigned loopback port, drives a real headless Chrome, asserts labels, +// selection identity and the selected ARIA state, and writes captures. +// +// PROBE_VARIANT=material|cupertino PROBE_SCHEME=dark|light \ +// OPENCODE_ARTIFACT_DIR= node tool/graph_node_probe.mjs +import { createServer } from 'node:http'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { setTimeout as delay } from 'node:timers/promises'; +import { join, extname, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; + +const root = resolve(process.env.PROBE_WEB_ROOT ?? join(process.cwd(), 'build/web')); +const variant = process.env.PROBE_VARIANT ?? 'material'; +const scheme = process.env.PROBE_SCHEME ?? 'dark'; +const artifactDir = process.env.OPENCODE_ARTIFACT_DIR ?? join(tmpdir(), 'graph-node-capture'); +const prefix = scheme === 'light' ? 'light-' : ''; +const longKey = 'implementer-with-an-unshortened-stage-label'; +const oneXKey = 'narrow-one-x-stage-key-that-wraps'; +await mkdir(artifactDir, { recursive: true }); +const mime = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png', '.ico': 'image/x-icon' }; +const server = createServer(async (req, res) => { + try { + const path = resolve(root, '.' + decodeURIComponent(new URL(req.url, 'http://localhost').pathname)); + if (path !== root && !path.startsWith(root + sep)) return res.writeHead(403).end(); + const filePath = path === root || path.endsWith('/') ? join(path, 'index.html') : path; + const file = await readFile(filePath); + res.writeHead(200, { 'content-type': mime[extname(filePath)] ?? 'application/octet-stream' }).end(file); + } catch { res.writeHead(404).end('not found'); } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const port = server.address().port; +const profile = await mkdtemp(join(tmpdir(), 'graph-node-chrome-')); +const chrome = spawn('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', [ + '--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu', + '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank', +], { stdio: ['ignore', 'ignore', 'pipe'] }); +let stderr = ''; +chrome.stderr.on('data', data => { stderr += data; }); +const waitFor = async fn => { + for (let i = 0; i < 100; i++) { const value = await fn(); if (value) return value; await delay(100); } + throw new Error('Timed out waiting for Chrome DevTools'); +}; +let ws; +try { + const endpoint = await waitFor(() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1]); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', event => { + const msg = JSON.parse(event.data); + if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); } + }); + const send = (method, params = {}, sessionId) => new Promise(resolve => { + const callId = ++id; pending.set(callId, resolve); + ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + const created = await send('Target.createTarget', { url: 'about:blank' }); + const target = created.result.targetId; + const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + await send('Emulation.setEmulatedMedia', { + features: [{ name: 'prefers-color-scheme', value: scheme }], + }, session); + const navigation = await send('Page.navigate', { url: `http://127.0.0.1:${port}/?style=${variant}` }, session); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + const evaluate = async expression => { + const response = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, session); + if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); + return response.result?.result?.value; + }; + await delay(3500); + const loaded = await evaluate('({url:location.href, ready:document.readyState})'); + if (!loaded?.url.includes(`127.0.0.1:${port}/?style=${variant}`)) throw new Error(`Fixture did not load: ${JSON.stringify(loaded)}`); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(2500); + const semantics = () => evaluate("[...document.querySelectorAll('flt-semantics')].map(x=>({label:(x.getAttribute('aria-label')||x.innerText||'').trim(), selected:x.getAttribute('aria-current'), role:x.getAttribute('role')}))"); + const nodeAt = label => `[...document.querySelectorAll('flt-semantics')].find(x => (x.getAttribute('aria-label')||x.innerText||'').trim() === ${JSON.stringify(label)})`; + const initial = await semantics(); + const labels = initial.map(x => x.label); + for (const needle of ['Selected: build', 'plan', 'build', 'running', 'Success', 'Failure']) { + if (!labels.some(x => x.includes(needle))) throw new Error(`Missing semantics ${needle}: ${JSON.stringify(labels)}`); + } + // Flutter web maps Semantics(selected:) to aria-current, not aria-selected. + const current = initial.find(x => x.selected === 'true'); + // The fixture's selected node carries its recorded status, so its accessible + // label is 'build\nrunning'. + if (!current?.label.startsWith('build')) throw new Error(`Selected node is not announced: ${JSON.stringify(initial)}`); + if (process.env.PROBE_DEBUG) console.log(JSON.stringify(initial, null, 2)); + const clickLabel = async label => { + const point = await evaluate(`(() => { const e=${nodeAt(label)}; if (!e) return null; const r=e.getBoundingClientRect(); return {x:r.x+r.width/2,y:r.y+r.height/2}; })()`); + if (!point) return false; + await send('Input.dispatchMouseEvent', { type: 'mousePressed', x: point.x, y: point.y, button: 'left', clickCount: 1 }, session); + await send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: point.x, y: point.y, button: 'left', clickCount: 1 }, session); + return true; + }; + const nodeRect = async label => evaluate(`(() => { const e=${nodeAt(label)}; if (!e) return null; const r=e.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height}; })()`); + const capture = async (name, width, height, scale = 1) => { + await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 }, session); + await delay(2500); + const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data; + await writeFile(`${artifactDir}/${prefix}${variant}-${name}.png`, Buffer.from(data, 'base64')); + }; + await capture('nodes-phone', 390, 844); + await capture('nodes-desktop', 1280, 800); + // Enlarged crops of the wrapped cases: the reviewed Material defect was + // glyph ink crossing the painted boundary at 2x. + const crops = {}; + for (const [name, key] of [['long-2x', longKey], ['long-1x', oneXKey]]) { + const rect = await nodeRect(key); + if (!rect) throw new Error(`Missing node ${key}`); + crops[name] = rect; + const data = (await send('Page.captureScreenshot', { + format: 'png', + clip: { x: rect.x - 8, y: rect.y - 8, width: rect.width + 16, height: rect.height + 16, scale: 2 }, + captureBeyondViewport: false, + }, session)).result.data; + await writeFile(`${artifactDir}/${prefix}${variant}-${name}-crop.png`, Buffer.from(data, 'base64')); + } + if (!await clickLabel('plan')) throw new Error('Could not click plan node'); + await delay(600); + const afterPlan = await evaluate('document.body.innerText'); + if (!afterPlan.includes('Selected: plan')) throw new Error(`plan callback did not carry its key: ${afterPlan}`); + const planCurrent = (await semantics()).find(x => x.selected === 'true'); + if (planCurrent?.label !== 'plan') throw new Error(`plan is not announced selected: ${JSON.stringify(planCurrent)}`); + await capture('nodes-selected-plan', 390, 844); + if (!await clickLabel('Success')) throw new Error('Could not click Success terminal'); + await delay(600); + const afterTerminal = await evaluate('document.body.innerText'); + if (!afterTerminal.includes('Selected: #success')) throw new Error(`terminal callback did not carry its key: ${afterTerminal}`); + await capture('nodes-selected-terminal', 390, 844); + console.log(JSON.stringify({ + variant, scheme, labels, crops, + captures: [`${prefix}${variant}-nodes-phone.png`, `${prefix}${variant}-nodes-desktop.png`, + `${prefix}${variant}-nodes-selected-plan.png`, `${prefix}${variant}-nodes-selected-terminal.png`, + `${prefix}${variant}-long-2x-crop.png`, `${prefix}${variant}-long-1x-crop.png`], + }, null, 2)); +} finally { + ws?.close(); + chrome.kill('SIGTERM'); + await Promise.race([once(chrome, 'exit'), delay(3000)]); + server.close(); + await rm(profile, { recursive: true, force: true }); +} diff --git a/app/tool/preview/README.md b/app/tool/preview/README.md new file mode 100644 index 00000000..8dcfa751 --- /dev/null +++ b/app/tool/preview/README.md @@ -0,0 +1,24 @@ +# Flutter web preview + +Build and run from `app/`: + +```sh +/Users/alan/development/flutter/bin/flutter build web +UPSTREAM=http://127.0.0.1:8095 node tool/preview/server.mjs --port 8096 +``` + +The preview binds to loopback by default and authenticates static requests by +checking the upstream authenticated web proxy with the browser cookie. Unauthenticated +HTML navigation goes to the proxy's `/login?next=...`; unauthenticated assets and +WebSocket upgrades are refused. Login, logout and artifacts are streamed to the +proxy without decoding compressed response bodies. `/connect` accepts only a +same-origin browser Origin, checks the cookie, then maps Origin and Host to the +configured upstream origin before upgrading. HTTP and HTTPS upstreams are +supported using Node's normal TLS certificate verification. Set `UPSTREAM` to +the authenticated proxy, never the raw control server. The root path and files +must exist locally, and only GET, HEAD, and POST are supported. Tests use +isolated loopback fixtures and port 0. + +The persistent preview API is `start({ root, upstream, host, port })` from +`tool/preview/server.mjs`; it resolves to `{ server, port, close }`. Call +`close()` to stop accepting requests and close tracked upgraded sockets. diff --git a/app/tool/preview/server.mjs b/app/tool/preview/server.mjs new file mode 100644 index 00000000..abc8e55e --- /dev/null +++ b/app/tool/preview/server.mjs @@ -0,0 +1,202 @@ +import { createServer, request as httpRequest } from 'node:http'; +import { request as httpsRequest } from 'node:https'; +import { realpath, stat, readFile } from 'node:fs/promises'; +import { extname, resolve, sep } from 'node:path'; +import net from 'node:net'; +import tls from 'node:tls'; + +const mime = { + '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', '.wasm': 'application/wasm', + '.woff': 'font/woff', '.woff2': 'font/woff2', '.ttf': 'font/ttf', + '.json': 'application/json', '.css': 'text/css; charset=utf-8', + '.png': 'image/png', '.svg': 'image/svg+xml', +}; +const noCache = { 'Cache-Control': 'no-store' }; +const timeoutMs = 5000; + +function reply(res, status, body = '') { + if (res.destroyed) return; + if (!res.headersSent) res.writeHead(status, { ...noCache, 'Content-Type': 'text/plain; charset=utf-8' }); + res.end(body); +} + +function inside(base, path) { + return path === base || path.startsWith(base + sep); +} + +async function staticFile(base, pathname, req, res) { + let file = resolve(base, `.${pathname}`); + if (!inside(base, file)) return reply(res, 403); + try { + let real = await realpath(file); + if (!inside(base, real)) return reply(res, 403); + if ((await stat(real)).isDirectory()) { + real = await realpath(resolve(real, 'index.html')); + if (!inside(base, real)) return reply(res, 403); + } + file = real; + } catch (error) { + if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') return reply(res, 403); + if (extname(pathname)) return reply(res, 404, 'Not found'); + try { + file = await realpath(resolve(base, 'index.html')); + if (!inside(base, file)) return reply(res, 403); + } catch { return reply(res, 404, 'Not found'); } + } + try { + const body = await readFile(file); + res.writeHead(200, { ...noCache, 'Content-Type': mime[extname(file)] ?? 'application/octet-stream' }); + res.end(req.method === 'HEAD' ? undefined : body); + } catch { reply(res, 404, 'Not found'); } +} + +function upstreamRequest(target, options, callback) { + return (target.protocol === 'https:' ? httpsRequest : httpRequest)( + { protocol: target.protocol, hostname: target.hostname, port: target.port || undefined, + ...options, timeout: timeoutMs }, callback, + ); +} + +function proxy(req, res, target) { + const url = new URL(req.url, target); + const headers = { ...req.headers, host: target.host }; + delete headers.connection; + const upstream = upstreamRequest(target, { method: req.method, path: `${url.pathname}${url.search}`, headers }, (replyFromUpstream) => { + const forwarded = { ...replyFromUpstream.headers, ...noCache }; + res.writeHead(replyFromUpstream.statusCode ?? 502, forwarded); + replyFromUpstream.on('error', () => res.destroy()); + replyFromUpstream.pipe(res); + }); + upstream.setTimeout(timeoutMs, () => upstream.destroy(new Error('upstream timeout'))); + upstream.on('error', () => reply(res, 502, 'Upstream unavailable')); + req.on('aborted', () => upstream.destroy()); + res.on('close', () => { if (!res.writableEnded) upstream.destroy(); }); + if (req.method === 'GET' || req.method === 'HEAD') { req.resume(); upstream.end(); } + else req.pipe(upstream); +} + +function authCheck(req, target, callback) { + let completed = false; + const finish = (result) => { + if (completed) return; + completed = true; + req.removeListener('aborted', abort); + req.socket.removeListener('close', abort); + callback(result); + }; + const abort = () => check.destroy(); + const check = upstreamRequest(target, { method: 'GET', path: '/', headers: { + cookie: req.headers.cookie ?? '', accept: 'text/html', 'accept-encoding': 'identity', + } }, (response) => { + response.resume(); + finish(response.statusCode === 200); + }); + check.setTimeout(timeoutMs, () => check.destroy(new Error('authentication check timeout'))); + check.on('error', () => finish(null)); + req.once('aborted', abort); + req.socket.once('close', abort); + check.end(); +} + +function reject(socket, status, phrase = 'Forbidden') { + if (!socket.destroyed) socket.end(`HTTP/1.1 ${status} ${phrase}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`); +} + +export async function start({ root = resolve('build/web'), upstream = 'http://127.0.0.1:8095', host = '127.0.0.1', port = 8096 } = {}) { + const base = await realpath(root); + const target = new URL(upstream); + if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password) throw new Error('UPSTREAM must be credential-free HTTP(S)'); + const sockets = new Set(); + const upgrades = new Set(); + let closing = false; + let closePromise; + const server = createServer((req, res) => { + let url; + try { + url = new URL(req.url, 'http://preview'); + if (!req.url.startsWith('/') || req.url.startsWith('//')) throw new Error('invalid path'); + decodeURIComponent(url.pathname); + } catch { return reply(res, 400, 'Bad request'); } + const pathname = decodeURIComponent(url.pathname); + if (pathname.startsWith('//')) return reply(res, 400, 'Bad request'); + if (!['GET', 'HEAD', 'POST'].includes(req.method)) { + res.setHeader('Allow', 'GET, HEAD, POST'); return reply(res, 405); + } + if (pathname === '/login' || pathname === '/logout' || pathname.startsWith('/artifacts/')) return proxy(req, res, target); + if (req.method !== 'GET' && req.method !== 'HEAD') return reply(res, 405); + authCheck(req, target, (authenticated) => { + if (res.destroyed) return; + if (authenticated === null) return reply(res, 502, 'Authentication upstream unavailable'); + if (!authenticated) { + if (req.method === 'GET' && String(req.headers.accept ?? '').includes('text/html') && !pathname.startsWith('/assets/')) { + res.writeHead(302, { ...noCache, Location: `/login?next=${encodeURIComponent(`${url.pathname}${url.search}`)}` }); + return res.end(); + } + return reply(res, 401, 'Authentication required'); + } + staticFile(base, pathname, req, res); + }); + }); + server.on('connection', (socket) => { + sockets.add(socket); + socket.on('close', () => sockets.delete(socket)); + }); + server.on('upgrade', (req, socket, head) => { + upgrades.add(socket); + socket.on('close', () => upgrades.delete(socket)); + let origin; + try { + if (req.url.split('?')[0] !== '/connect' || !req.headers.host || !req.headers.origin || !req.url.startsWith('/')) throw new Error(); + origin = new URL(req.headers.origin); + if (!['http:', 'https:'].includes(origin.protocol) || origin.host.toLowerCase() !== req.headers.host.toLowerCase()) throw new Error(); + } catch { return reject(socket, 403); } + authCheck(req, target, (authenticated) => { + if (closing || socket.destroyed) return; + if (authenticated === null) return reject(socket, 502, 'Bad Gateway'); + if (!authenticated) return reject(socket, 401, 'Unauthorized'); + const connect = target.protocol === 'https:' ? tls.connect : net.connect; + const upstreamSocket = connect({ host: target.hostname, port: Number(target.port || (target.protocol === 'https:' ? 443 : 80)), ...(target.protocol === 'https:' ? { servername: target.hostname } : {}) }); + upgrades.add(upstreamSocket); + upstreamSocket.on('close', () => upgrades.delete(upstreamSocket)); + upstreamSocket.setTimeout(timeoutMs, () => upstreamSocket.destroy(new Error('upgrade timeout'))); + // Bound establishment only. A healthy, idle chat socket stays connected. + upstreamSocket.once('data', () => upstreamSocket.setTimeout(0)); + upstreamSocket.once(target.protocol === 'https:' ? 'secureConnect' : 'connect', () => { + const headers = { ...req.headers, host: target.host, origin: target.origin }; + const lines = Object.entries(headers).filter(([, value]) => value != null) + .map(([key, value]) => `${key}: ${Array.isArray(value) ? value.join(', ') : value}`).join('\r\n'); + upstreamSocket.write(`GET ${req.url} HTTP/1.1\r\n${lines}\r\n\r\n`); + if (head.length) upstreamSocket.write(head); + upstreamSocket.pipe(socket); + socket.pipe(upstreamSocket); + }); + upstreamSocket.on('error', () => socket.destroy()); + socket.on('error', () => upstreamSocket.destroy()); + socket.on('close', () => upstreamSocket.destroy()); + }); + }); + await new Promise((resolveListen, rejectListen) => { + server.once('error', rejectListen); + server.listen(port, host, resolveListen); + }); + return { + server, port: server.address().port, + close: () => closePromise ??= new Promise((resolveClose, rejectClose) => { + closing = true; + for (const socket of upgrades) socket.destroy(); + server.close((error) => error ? rejectClose(error) : resolveClose()); + for (const socket of sockets) socket.destroy(); + }), + }; +} + +if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) { + const args = Object.fromEntries(process.argv.slice(2).reduce((result, value, index, all) => { + if (value.startsWith('--')) result.push([value.slice(2), all[index + 1]]); + return result; + }, [])); + start({ root: args.root ?? 'build/web', upstream: process.env.UPSTREAM ?? args.upstream ?? 'http://127.0.0.1:8095', host: args.host ?? '127.0.0.1', port: Number(args.port ?? 8096) }) + .then((preview) => console.log(`preview http://${args.host ?? '127.0.0.1'}:${preview.port}`)) + .catch((error) => { console.error(error); process.exitCode = 1; }); +} diff --git a/app/tool/runs_probe.mjs b/app/tool/runs_probe.mjs new file mode 100644 index 00000000..4d816d2e --- /dev/null +++ b/app/tool/runs_probe.mjs @@ -0,0 +1,441 @@ +import { spawn, execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'; +import { once } from 'node:events'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; + +import { startFixture } from './runs_probe_server.mjs'; + +// Browser acceptance for the Runs destination. +// +// Build one of the bundles first, then run from app/: +// flutter build web +// flutter build web --target=tool/runs_probe_entry.dart -o build/probe_web +// OPENCODE_ARTIFACT_DIR= node tool/runs_probe.mjs build/web +// +// Requires Google Chrome and Tesseract (OCR assertions cover canvas-rendered +// selectable text that Flutter web does not expose through semantics). +const output = process.env.OPENCODE_ARTIFACT_DIR; +if (!output) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures'); +await mkdir(output, { recursive: true }); + +const root = resolve(process.argv[2] ?? 'build/probe_web'); +const fixture = await startFixture({ root }); + +const html = await fetch(`${fixture.url}/`); +const mime = html.headers.get('content-type') ?? ''; +if (html.status !== 200 || !mime.startsWith('text/html')) { + throw new Error(`Fixture index must be HTML: ${html.status} ${mime}`); +} +await html.text(); + +const profile = await mkdtemp(join(tmpdir(), 'i1-runs-chrome-')); +const chrome = spawn('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', [ + '--headless=new', + '--no-first-run', + '--no-default-browser-check', + '--disable-gpu', + '--remote-debugging-port=0', + `--user-data-dir=${profile}`, + 'about:blank', +], { stdio: ['ignore', 'ignore', 'pipe'] }); +let stderr = ''; +chrome.stderr.on('data', (data) => { stderr += data; }); + +let ws; +try { + const endpoint = await waitFor(() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1], 'Chrome DevTools'); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', (event) => { + const message = JSON.parse(event.data); + if (message.method?.includes('detached') || message.method?.includes('crashed')) { + console.error('CDP event', JSON.stringify(message)); + } + if (message.method === 'Runtime.exceptionThrown') { + console.error('PAGE EXCEPTION', JSON.stringify(message.params?.exceptionDetails)); + } + if (message.method === 'Log.entryAdded') { + console.error('PAGE LOG', JSON.stringify(message.params?.entry)); + } + if (message.method === 'Runtime.consoleAPICalled') { + console.error('PAGE CONSOLE', JSON.stringify(message.params)); + } + if (message.id && pending.has(message.id)) { + pending.get(message.id)(message); + pending.delete(message.id); + } + }); + const send = (method, params = {}, sessionId) => new Promise((resolveCall) => { + const callId = ++id; + pending.set(callId, resolveCall); + ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + + const target = (await send('Target.createTarget', { url: 'about:blank' })).result.targetId; + const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + await send('Log.enable', {}, session); + + const evaluate = async (expression) => { + const response = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, session); + if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); + if (response.result?.exceptionDetails) { + throw new Error(`Page exception: ${JSON.stringify(response.result.exceptionDetails)}`); + } + return response.result?.result?.value; + }; + + const enableSemantics = async () => { + await waitFor( + () => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"), + 'Flutter semantics placeholder', + ); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(600); + }; + + const navigation = await send('Page.navigate', { url: `${fixture.url}/` }, session); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + await enableSemantics(); + await waitFor( + async () => (await evaluate('location.pathname')) === '/pipelines', + 'boot route correction to /pipelines', + ); + + const semanticText = () => evaluate(`(() => { + const chunks = []; + for (const el of document.querySelectorAll('flt-semantics')) { + const label = el.getAttribute('aria-label'); + if (label) chunks.push(label); + const value = el.getAttribute('aria-valuetext'); + if (value) chunks.push(value); + if (el.value) chunks.push(String(el.value)); + if (!el.children.length && el.innerText) chunks.push(el.innerText); + } + for (const el of document.querySelectorAll('input, textarea')) { + const label = el.getAttribute('aria-label'); + if (label) chunks.push(label); + if (el.value) chunks.push(String(el.value)); + } + if (document.body?.innerText) chunks.push(document.body.innerText); + return [...new Set(chunks)].join('\\n'); + })()`); + + const assertBody = async (text) => { + try { + await waitFor( + async () => (await semanticText()).includes(text), + `body to contain ${JSON.stringify(text)}`, + ); + } catch (error) { + const textNow = await semanticText(); + let extra = ''; + if (process.env.PROBE_DEBUG) { + extra = `\nNodes: ${JSON.stringify(await evaluate(`[...document.querySelectorAll('flt-semantics, input, textarea')] + .map((el) => ({ tag: el.tagName, role: el.getAttribute('role'), label: el.getAttribute('aria-label'), value: el.getAttribute('aria-valuetext') ?? el.value, text: el.innerText })) + .filter((item) => item.label || item.value || item.text)`))}`; + } + throw new Error(`${error.message}\nBody now:\n${textNow.slice(0, 3000)}${extra}`); + } + }; + + const clickText = async (text, { contains = false } = {}) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(text)}; + const candidates = [...document.querySelectorAll('flt-semantics')].filter((el) => { + const label = (el.getAttribute('aria-label') || el.innerText || '').trim(); + return label === wanted || (${contains} && label.includes(wanted)); + }); + const interactive = candidates.find((el) => + ['button', 'tab', 'link', 'checkbox', 'menuitem'].includes(el.getAttribute('role')), + ); + const target = interactive ?? candidates[0]; + if (!target) return false; + target.click(); + return true; + })()`); + if (!clicked) { + const labels = await evaluate(`[...document.querySelectorAll('flt-semantics')] + .map((el) => (el.getAttribute('aria-label') || '').trim()).filter(Boolean)`); + throw new Error(`Could not click ${JSON.stringify(text)}. Labels: ${JSON.stringify(labels)}`); + } + await delay(300); + }; + + const capture = async (name) => { + const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data; + const path = join(output, `${name}.png`); + await writeFile(path, Buffer.from(data, 'base64')); + return path; + }; + + const ocr = async (path) => { + const { stdout } = await promisify(execFile)('tesseract', [path, 'stdout']); + return stdout; + }; + + const assertOcr = async (path, text) => { + const read = await ocr(path); + if (!read.toLowerCase().includes(text.toLowerCase())) { + throw new Error(`OCR of ${path} lacks ${JSON.stringify(text)}:\n${read.slice(0, 3000)}`); + } + }; + + const wheel = (deltaY) => send('Input.dispatchMouseEvent', { + type: 'mouseWheel', + x: 195, + y: 500, + deltaX: 0, + deltaY, + }, session); + + const scrollUntil = async (text) => { + for (let attempt = 0; attempt < 20; attempt++) { + if ((await semanticText()).includes(text)) return; + await wheel(400); + await delay(180); + } + throw new Error(`Could not scroll to ${JSON.stringify(text)}`); + }; + + const setSize = async (width, height) => { + await send('Emulation.setDeviceMetricsOverride', { + width, + height, + deviceScaleFactor: 1, + mobile: width < 600, + }, session); + await delay(500); + }; + + await setSize(390, 844); + await clickText('Runs'); + if ((await evaluate('location.pathname')) !== '/runs') { + throw new Error(`Runs tab did not update the URL: ${await evaluate('location.pathname')}`); + } + await assertBody('Fixture live run'); + await assertBody('Fixture pending run'); + await assertBody('Fixture failing run'); + const captures = [await capture('i1-runs-phone-list')]; + await assertOcr(captures[0], 'Fixture live run'); + + await setSize(1280, 800); + await assertBody('Fixture live run'); + captures.push(await capture('i1-runs-desktop-list')); + await assertOcr(captures[1], 'Fixture live run'); + await setSize(390, 844); + + const live = await fetch(`${fixture.url}/fixture/live`, { method: 'POST' }); + if (!live.ok) throw new Error(`Fixture live trigger failed: ${live.status}`); + await assertBody('succeeded'); + captures.push(await capture('i1-runs-phone-list-live')); + await assertOcr(captures[2], 'succeeded'); + + await clickText('Fixture pending run', { contains: true }); + await assertBody('Loading run details…'); + await assertBody('Back to list'); + captures.push(await capture('i1-runs-phone-pending')); + await assertOcr(captures[3], 'Loading run details'); + await clickText('Back to list', { contains: true }); + await assertBody('Fixture failing run'); + + await clickText('Fixture failing run', { contains: true }); + await assertBody('Fixture detail failure: run 3 is unavailable'); + await assertBody('Back to list'); + captures.push(await capture('i1-runs-phone-error')); + await assertOcr(captures[4], 'run 3 is unavailable'); + await clickText('Back to list', { contains: true }); + await assertBody('Fixture live run'); + + await clickText('Fixture live run', { contains: true }); + if ((await evaluate('location.pathname')) !== '/runs/1') { + throw new Error(`Run selection did not update the URL: ${await evaluate('location.pathname')}`); + } + await assertBody('Original prompt'); + await assertBody('Timeline'); + await assertBody('build · visit 3'); + captures.push(await capture('i1-runs-phone-detail')); + await assertOcr(captures[5], 'fixture prompt with spaces'); + + await setSize(1280, 800); + await assertBody('Original prompt'); + captures.push(await capture('i1-runs-desktop-detail')); + await assertOcr(captures[6], 'fixture prompt with spaces'); + await setSize(390, 844); + + await clickText('Input'); + await wheel(250); + await delay(300); + captures.push(await capture('i1-runs-phone-detail-input')); + await assertOcr(captures[7], 'input payload'); + + await scrollUntil('Output'); + await clickText('Output'); + await wheel(250); + await delay(300); + captures.push(await capture('i1-runs-phone-detail-output')); + await assertOcr(captures[8], 'answer'); + + await scrollUntil('Metrics'); + await clickText('Metrics'); + await wheel(300); + await delay(300); + captures.push(await capture('i1-runs-phone-detail-metrics')); + await assertOcr(captures[9], 'Total tokens'); + await assertOcr(captures[9], 'Reported cost'); + + // Browser Back/Forward move between the in-app routes, not out of the app. + const path = () => evaluate('location.pathname'); + await evaluate('history.back()'); + await waitFor( + async () => (await path()) === '/runs', + 'browser Back to /runs', + ); + await waitFor( + async () => (await semanticText()).includes('Fixture live run'), + 'browser Back to the runs list', + ); + await waitFor( + async () => (await semanticText()).includes('Fixture live run'), + 'browser Back to the runs list', + ); + captures.push(await capture('i1-runs-phone-browser-back-list')); + await assertOcr(captures[10], 'Fixture live run'); + + await evaluate('history.forward()'); + await waitFor( + async () => (await path()) === '/runs/1' && (await semanticText()).includes('Original prompt'), + 'browser Forward to /runs/1', + ); + captures.push(await capture('i1-runs-phone-browser-forward-detail')); + + // A direct /runs/1 load is a real deep link: the detail opens and the URL stays. + await send('Page.navigate', { url: `${fixture.url}/runs/1` }, session); + await enableSemantics(); + await assertBody('Original prompt'); + if ((await path()) !== '/runs/1') throw new Error(`Deep link moved to ${await path()}`); + captures.push(await capture('i1-deeplink-run-1-phone')); + + // A drop keeps the open detail, reports reconnecting rather than unavailable, + // and has no raw transport exception anywhere on the page. + const beforeDrop = await (await fetch(`${fixture.url}/fixture/state`)).json(); + const refused = await fetch(`${fixture.url}/fixture/refuse`, { method: 'POST' }); + if (!refused.ok) throw new Error(`Fixture refuse failed: ${refused.status}`); + await assertBody('Reconnecting to Pipelines…'); + const duringDrop = await semanticText(); + for (const raw of ['WebSocketException', 'WebSocketChannelException', 'Failed to connect']) { + if (duringDrop.includes(raw)) throw new Error(`Raw transport text shown: ${raw}`); + } + if ((await path()) !== '/runs/1') throw new Error(`Drop moved the URL to ${await path()}`); + captures.push(await capture('i1-reconnect-detail-retained-phone')); + await assertOcr(captures[13], 'Original prompt'); + + // Accepting again plus Retry restores the same detail without a remount. + const accepted = await fetch(`${fixture.url}/fixture/accept`, { method: 'POST' }); + if (!accepted.ok) throw new Error(`Fixture accept failed: ${accepted.status}`); + await clickText('Retry'); + await waitFor( + async () => + !(await semanticText()).includes('Reconnecting to Pipelines…') && + (await semanticText()).includes('Original prompt'), + 'detail restored after reconnect', + ); + if ((await path()) !== '/runs/1') throw new Error(`Reconnect moved the URL to ${await path()}`); + captures.push(await capture('i1-reconnect-detail-restored-phone')); + + // A first connection while the server refuses upgrades is friendly: the gate + // never prints the transport exception and does not flicker to "connecting". + await fetch(`${fixture.url}/fixture/refuse`, { method: 'POST' }); + await send('Page.navigate', { url: `${fixture.url}/runs` }, session); + await enableSemantics(); + await assertBody('Pipelines server unavailable'); + const gate = await semanticText(); + for (const raw of ['WebSocketException', 'WebSocketChannelException', 'Failed to connect']) { + if (gate.includes(raw)) throw new Error(`Gate printed raw transport text: ${raw}`); + } + captures.push(await capture('i1-gate-unavailable-friendly-phone')); + await delay(1500); + if (!(await semanticText()).includes('Pipelines server unavailable')) { + throw new Error('Gate left the unavailable state while retrying'); + } + await assertOcr(captures[15], 'Pipelines server unavailable'); + + await fetch(`${fixture.url}/fixture/accept`, { method: 'POST' }); + await clickText('Retry'); + await assertBody('Fixture live run'); + captures.push(await capture('i1-gate-recovered-list-phone')); + + await clickText('Settings'); + await assertBody('Server URL'); + await assertBody('Fixture settings build'); + if ((await path()) !== '/settings') throw new Error('Settings did not update route'); + captures.push(await capture('settings-cupertino-registered-phone')); + + // Material host: the same deep link and route must render standard Material + // controls (the Cupertino host was selected by the macOS browser above). + await send( + 'Emulation.setUserAgentOverride', + { + userAgent: + 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 ' + + '(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36', + platform: 'Linux x86_64', + }, + session, + ); + await send('Page.navigate', { url: `${fixture.url}/runs/1` }, session); + await enableSemantics(); + await assertBody('Original prompt'); + await assertBody('Back to list'); + if ((await path()) !== '/runs/1') { + throw new Error(`Material deep link moved to ${await path()}`); + } + captures.push(await capture('i1-material-deeplink-run-1-phone')); + + const beforeSettings = await (await fetch(`${fixture.url}/fixture/state`)).json(); + await clickText('Settings'); + await assertBody('Server URL'); + await assertBody('Fixture settings build'); + const afterSettings = await (await fetch(`${fixture.url}/fixture/state`)).json(); + if (beforeSettings.subscribed !== afterSettings.subscribed || afterSettings.connections !== 1) { + throw new Error('Settings opened another connection instead of sharing the app socket'); + } + captures.push(await capture('settings-material-registered-phone')); + + const fixtureState = await (await fetch(`${fixture.url}/fixture/state`)).json(); + if (fixtureState.subscribed < 2) throw new Error(`App never resubscribed: ${JSON.stringify(fixtureState)}`); + if (fixtureState.listRuns < 2) throw new Error(`App never reloaded: ${JSON.stringify(fixtureState)}`); + if (fixtureState.getRun < 2) throw new Error(`Detail was not rehydrated: ${JSON.stringify(fixtureState)}`); + if (fixtureState.dropped < 1) throw new Error(`Fixture never dropped: ${JSON.stringify(fixtureState)}`); + console.log(JSON.stringify({ + ok: true, + fixture: fixture.url, + subscribed: fixtureState.subscribed, + listRuns: fixtureState.listRuns, + getRun: fixtureState.getRun, + dropped: fixtureState.dropped, + live: fixtureState.live, + captures, + }, null, 2)); +} finally { + ws?.close(); + chrome.kill('SIGTERM'); + await Promise.race([once(chrome, 'exit'), delay(3000)]); + await fixture.close(); + await rm(profile, { recursive: true, force: true }); +} + +async function waitFor(check, label, attempts = 160) { + for (let attempt = 0; attempt < attempts; attempt++) { + const value = await check(); + if (value) return value; + await delay(100); + } + throw new Error(`Timed out waiting for ${label}`); +} diff --git a/app/tool/runs_probe_entry.dart b/app/tool/runs_probe_entry.dart new file mode 100644 index 00000000..332c62e9 --- /dev/null +++ b/app/tool/runs_probe_entry.dart @@ -0,0 +1,8 @@ +import 'package:pipelines_app/application/bootstrap.dart'; + +/// Browser acceptance entrypoint. +/// +/// This is intentionally the same composition as `lib/main.dart`; the +/// deterministic list/detail/error/live behavior comes from the isolated +/// websocket fixture that serves this bundle, not from app-side fake data. +void main() => runPipelinesApp(); diff --git a/app/tool/runs_probe_server.mjs b/app/tool/runs_probe_server.mjs new file mode 100644 index 00000000..79160044 --- /dev/null +++ b/app/tool/runs_probe_server.mjs @@ -0,0 +1,418 @@ +import { createHash } from 'node:crypto'; +import { createServer } from 'node:http'; +import { readFile, realpath, stat } from 'node:fs/promises'; +import { extname, join, resolve, sep } from 'node:path'; +import { once } from 'node:events'; + +const MIME = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.wasm': 'application/wasm', + '.css': 'text/css; charset=utf-8', + '.png': 'image/png', + '.svg': 'image/svg+xml', + '.ico': 'image/x-icon', + '.ttf': 'font/ttf', + '.otf': 'font/otf', + '.woff': 'font/woff', + '.woff2': 'font/woff2', +}; + +const RUNS = [ + { + id: 1, + title: 'Fixture live run', + name: 'fixture-live', + status: 'running', + created_at: '2026-10-21T12:00:00Z', + pipeline_id: 10, + }, + { + id: 2, + title: 'Fixture pending run', + name: 'fixture-pending', + status: 'running', + created_at: '2026-10-21T11:00:00Z', + pipeline_id: 10, + }, + { + id: 3, + title: 'Fixture failing run', + name: 'fixture-failing', + status: 'failed', + created_at: '2026-10-21T10:00:00Z', + pipeline_id: 10, + }, +]; + +const LIVE_EVENT = { + type: 'run_event', + run_id: 1, + status: 'succeeded', + outcome: 'success', + completed_steps: 2, + current_stage: 'test', + finished_at: '2026-10-21T12:05:00Z', +}; + +function detail(id, live) { + const status = id === 1 && live ? 'succeeded' : id === 3 ? 'failed' : 'running'; + return { + id, + title: RUNS.find((run) => run.id === id)?.title ?? `Run ${id}`, + name: 'fixture-pipeline', + status, + input: { + prompt: ' fixture prompt with spaces ', + note: 'input payload', + }, + output: { answer: 42, nested: { ok: true } }, + usage: { + stages: 2, + tokens_total: 120, + tokens_known_stages: 2, + tokens_in: 70, + tokens_out: 50, + split_known: true, + cost_known_stages: 2, + cost_usd: 0.25, + }, + steps: [ + { + stage: 'build', + sequence: 3, + status: 'completed', + outcome: 'success', + target: '#success', + }, + { + stage: 'test', + sequence: 4, + status: status === 'failed' ? 'failed' : 'completed', + outcome: status === 'failed' ? 'failure' : 'success', + target: status === 'failed' ? '#failure' : '#success', + }, + ], + }; +} + +function accept(key) { + return createHash('sha1') + .update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`) + .digest('base64'); +} + +function frame(opcode, payload) { + const length = payload.length; + let header; + if (length < 126) { + header = Buffer.from([0x80 | opcode, length]); + } else if (length < 65536) { + header = Buffer.alloc(4); + header[0] = 0x80 | opcode; + header[1] = 126; + header.writeUInt16BE(length, 2); + } else { + header = Buffer.alloc(10); + header[0] = 0x80 | opcode; + header[1] = 127; + header.writeBigUInt64BE(BigInt(length), 2); + } + return Buffer.concat([header, payload]); +} + +class Connection { + constructor(socket, owner) { + this.socket = socket; + this.owner = owner; + this.buffer = Buffer.alloc(0); + this.fragments = []; + this.fragmentOpcode = 0; + } + + push(chunk) { + if (chunk?.length) this.buffer = Buffer.concat([this.buffer, chunk]); + this.parse(); + } + + parse() { + while (this.buffer.length >= 2) { + const first = this.buffer[0]; + const second = this.buffer[1]; + const fin = (first & 0x80) !== 0; + const opcode = first & 0x0f; + const masked = (second & 0x80) !== 0; + let length = second & 0x7f; + let offset = 2; + if (length === 126) { + if (this.buffer.length < 4) return; + length = this.buffer.readUInt16BE(2); + offset = 4; + } else if (length === 127) { + if (this.buffer.length < 10) return; + const big = this.buffer.readBigUInt64BE(2); + if (big > BigInt(Number.MAX_SAFE_INTEGER)) return this.close(); + length = Number(big); + offset = 10; + } + const maskOffset = offset; + if (masked) { + if (this.buffer.length < offset + 4) return; + offset += 4; + } + if (this.buffer.length < offset + length) return; + let payload = Buffer.from(this.buffer.subarray(offset, offset + length)); + if (masked) { + const mask = this.buffer.subarray(maskOffset, maskOffset + 4); + for (let index = 0; index < payload.length; index++) { + payload[index] ^= mask[index % 4]; + } + } + this.buffer = this.buffer.subarray(offset + length); + this.handleFrame(fin, opcode, payload); + } + } + + handleFrame(fin, opcode, payload) { + if (opcode === 0x8) return this.close(); + if (opcode === 0x9) return void this.socket.write(frame(0x0a, payload)); + if (opcode === 0x0a) return; + if (opcode === 0x0) { + this.fragments.push(payload); + if (fin) { + const data = Buffer.concat(this.fragments); + this.fragments = []; + this.message(this.fragmentOpcode, data); + } + return; + } + if (opcode !== 0x1) return; + if (!fin) { + this.fragmentOpcode = opcode; + this.fragments = [payload]; + return; + } + this.message(opcode, payload); + } + + message(_opcode, payload) { + let request; + try { + request = JSON.parse(payload.toString('utf8')); + } catch { + return; + } + this.owner.onMessage(this, request); + } + + send(value) { + if (this.socket.destroyed) return; + this.socket.write(frame(0x1, Buffer.from(JSON.stringify(value)))); + } + + close() { + if (!this.socket.destroyed) this.socket.end(); + } +} + +async function staticFile(base, pathname, req, res) { + let file = resolve(base, `.${pathname}`); + if (file !== base && !file.startsWith(base + sep)) { + res.writeHead(403).end(); + return; + } + try { + if ((await stat(file)).isDirectory()) file = join(file, 'index.html'); + } catch { + if (extname(pathname)) { + res.writeHead(404).end('not found'); + return; + } + file = join(base, 'index.html'); + } + try { + const body = await readFile(file); + res + .writeHead(200, { + 'content-type': MIME[extname(file)] ?? 'application/octet-stream', + 'cache-control': 'no-store', + }) + .end(req.method === 'HEAD' ? undefined : body); + } catch { + res.writeHead(404).end('not found'); + } +} + +/** + * A deterministic, isolated Pipelines protocol fixture for the browser probe. + * It serves the built probe bundle and upgrades /connect on the same origin, so + * the normal web composition infers this server from Uri.base. + */ +export async function startFixture({ root }) { + const base = await realpath(root); + const connections = new Set(); + const sockets = new Set(); + let subscribed = 0; + let live = false; + let refuse = false; + let dropped = 0; + let listRuns = 0; + let getRun = 0; + + const dropConnections = () => { + for (const connection of connections) connection.close(); + connections.clear(); + dropped++; + }; + + const broadcast = (value) => { + for (const connection of connections) connection.send(value); + }; + + const server = createServer(async (req, res) => { + const pathname = new URL(req.url, 'http://fixture').pathname; + if (pathname === '/fixture/live' && req.method === 'POST') { + live = true; + broadcast(LIVE_EVENT); + res.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}'); + return; + } + if (pathname === '/fixture/drop' && req.method === 'POST') { + dropConnections(); + res.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}'); + return; + } + if (pathname === '/fixture/refuse' && req.method === 'POST') { + refuse = true; + dropConnections(); + res.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}'); + return; + } + if (pathname === '/fixture/accept' && req.method === 'POST') { + refuse = false; + res.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}'); + return; + } + if (pathname === '/fixture/state') { + res + .writeHead(200, { 'content-type': 'application/json' }) + .end(JSON.stringify({ + subscribed, + live, + connections: connections.size, + refuse, + dropped, + listRuns, + getRun, + })); + return; + } + if (req.method !== 'GET' && req.method !== 'HEAD') { + res.writeHead(405).end(); + return; + } + await staticFile(base, pathname, req, res); + }); + + server.on('upgrade', (req, socket, head) => { + if (refuse) { + socket.end('HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n'); + return; + } + const url = new URL(req.url, 'http://fixture'); + if ( + url.pathname !== '/connect' || + req.headers.upgrade?.toLowerCase() !== 'websocket' || + !req.headers['sec-websocket-key'] + ) { + socket.end('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n'); + return; + } + socket.write( + 'HTTP/1.1 101 Switching Protocols\r\n' + + 'Upgrade: websocket\r\n' + + 'Connection: Upgrade\r\n' + + `Sec-WebSocket-Accept: ${accept(req.headers['sec-websocket-key'])}\r\n\r\n`, + ); + const connection = new Connection(socket, { + onMessage: (client, request) => { + if (request.type === 'subscribe') { + // The real server may not acknowledge `subscribe`; keep it silent so + // the app's send-only path is exercised. + subscribed++; + return; + } + if (request.type === 'unsubscribe') return; + if (request.type === 'ping') { + client.send({ + id: request.id, type: 'pong', + build: { version: 'Fixture settings build' }, + time: '2026-10-21T12:00:00Z', + }); + return; + } + if (request.type === 'list_runs') { + listRuns++; + client.send({ id: request.id, type: 'runs', runs: RUNS, usage: null }); + return; + } + if (request.type === 'get_run') { + getRun++; + const id = request.run_id; + if (id === 2) { + // Deliberately slow so the browser sees the pending/Back state; + // it must still answer so the serialized request queue continues. + setTimeout(() => { + client.send({ id: request.id, type: 'run', run_detail: detail(2, live) }); + }, 2500); + return; + } + if (id === 3) { + client.send({ + id: request.id, + type: 'error', + error: 'Fixture detail failure: run 3 is unavailable', + }); + return; + } + client.send({ id: request.id, type: 'run', run_detail: detail(id, live) }); + return; + } + client.send({ + id: request.id, + type: 'error', + error: `Fixture does not implement ${request.type}`, + }); + }, + }); + connections.add(connection); + socket.on('data', (chunk) => connection.push(chunk)); + socket.on('close', () => connections.delete(connection)); + socket.on('error', () => connections.delete(connection)); + connection.push(head); + }); + + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + server.on('connection', (socket) => { + sockets.add(socket); + socket.on('close', () => sockets.delete(socket)); + }); + const port = server.address().port; + return { + server, + port, + url: `http://127.0.0.1:${port}`, + get subscribed() { + return subscribed; + }, + close: () => + new Promise((resolveClose) => { + for (const connection of connections) connection.close(); + server.close(() => resolveClose()); + for (const socket of sockets) socket.destroy(); + }), + }; +} diff --git a/app/tool/schedules_list_probe.mjs b/app/tool/schedules_list_probe.mjs new file mode 100644 index 00000000..19ab6481 --- /dev/null +++ b/app/tool/schedules_list_probe.mjs @@ -0,0 +1,252 @@ +import { createServer } from 'node:http'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { setTimeout as delay } from 'node:timers/promises'; +import { join, extname, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; + +// Serves the Flutter web build produced by: +// flutter build web -t tool/schedules_list_probe_app.dart +// The fixture is local-only: no Pipelines server, authentication or real +// schedule is touched. +const root = join(process.cwd(), 'build/web'); +const outputIndex = process.argv.indexOf('--out'); +const output = outputIndex >= 0 + ? resolve(process.argv[outputIndex + 1]) + : resolve(process.env.OPENCODE_ARTIFACT_DIR ?? join(process.cwd(), 'build/schedules-captures')); +const chromePath = process.env.CHROME_PATH + ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +const mime = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', + '.json': 'application/json', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.svg': 'image/svg+xml', + '.ico': 'image/x-icon', + '.css': 'text/css; charset=utf-8', + '.ttf': 'font/ttf', + '.otf': 'font/otf', + '.woff': 'font/woff', + '.woff2': 'font/woff2', + '.bin': 'application/octet-stream', +}; + +const server = createServer(async (req, res) => { + try { + const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname); + const path = resolve(root, '.' + pathname); + if (path !== root && !path.startsWith(root + sep)) { + return res.writeHead(403).end(); + } + const filePath = pathname.endsWith('/') ? join(path, 'index.html') : path; + const file = await readFile(filePath); + res + .writeHead(200, { + 'content-type': mime[extname(filePath)] ?? 'application/octet-stream', + 'cache-control': 'no-store', + }) + .end(file); + } catch { + res.writeHead(404).end('not found'); + } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const port = server.address().port; +const profile = await mkdtemp(join(tmpdir(), 's1b-schedules-chrome-')); +const chrome = spawn(chromePath, [ + '--headless=new', + '--no-first-run', + '--no-default-browser-check', + '--disable-gpu', + '--remote-debugging-port=0', + `--user-data-dir=${profile}`, + 'about:blank', +], { stdio: ['ignore', 'ignore', 'pipe'] }); +let stderr = ''; +chrome.stderr.on('data', data => { stderr += data; }); +const waitFor = async (fn, label, attempts = 160) => { + for (let i = 0; i < attempts; i++) { + const value = await fn(); + if (value) return value; + await delay(100); + } + throw new Error(`Timed out waiting for ${label}`); +}; +let ws; +try { + const endpoint = await waitFor( + () => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1], + 'Chrome DevTools', + ); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + const pageErrors = []; + ws.addEventListener('message', event => { + const msg = JSON.parse(event.data); + if (msg.method === 'Runtime.exceptionThrown') { + pageErrors.push(msg.params?.exceptionDetails?.text ?? 'page exception'); + } + if (msg.id && pending.has(msg.id)) { + pending.get(msg.id)(msg); + pending.delete(msg.id); + } + }); + const send = (method, params = {}, sessionId) => new Promise(resolveCall => { + const callId = ++id; + pending.set(callId, resolveCall); + ws.send(JSON.stringify({ + id: callId, + method, + params, + ...(sessionId ? { sessionId } : {}), + })); + }); + const created = await send('Target.createTarget', { url: 'about:blank' }); + if (!created.result) throw new Error(`Target creation failed: ${JSON.stringify(created)}`); + const target = created.result.targetId; + const session = ( + await send('Target.attachToTarget', { targetId: target, flatten: true }) + ).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + const evaluate = async expression => { + const response = await send( + 'Runtime.evaluate', + { expression, returnByValue: true, awaitPromise: true }, + session, + ); + if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); + if (response.result?.exceptionDetails) { + throw new Error(`Runtime exception: ${JSON.stringify(response.result.exceptionDetails)}`); + } + return response.result?.result?.value; + }; + await mkdir(output, { recursive: true }); + const cases = [ + { + name: 's1b-schedules-material-390', + theme: 'material', + scale: 1, + width: 390, + height: 844, + expect: ['4 schedules', 'Research batteries', 'Pipeline 4 · v2', 'Timer: Every 24h', 'Timezone: Europe/London', 'Next due:'], + }, + { + name: 's1b-schedules-material-390-2x', + theme: 'material', + scale: 2, + width: 390, + height: 844, + expect: ['Research batteries', 'Pipeline 4 · v2', 'Workspace: /srv/research', 'Timer: Every 24h'], + }, + { + name: 's1b-schedules-material-390-dark', + theme: 'material', + brightness: 'dark', + scale: 1, + width: 390, + height: 844, + expect: ['4 schedules', 'Research batteries', 'Pipeline 4 · v2', 'Timezone: Europe/London', 'Next due:'], + }, + { + name: 's1b-schedules-cupertino-390', + theme: 'cupertino', + scale: 1, + width: 390, + height: 844, + expect: ['Research batteries', 'Pipeline 4 · v2', 'Timezone: Europe/London'], + }, + { + name: 's1b-schedules-material-1100', + theme: 'material', + scale: 1, + width: 1100, + height: 800, + expect: ['Research batteries', 'Nightly report', 'Weekly digest', 'Sparse server record'], + }, + ]; + const results = []; + for (const item of cases) { + const query = new URLSearchParams({ theme: item.theme, scale: String(item.scale) }); + if (item.brightness) query.set('brightness', item.brightness); + const url = `http://127.0.0.1:${port}/?${query}`; + const navigation = await send('Page.navigate', { url }, session); + if (navigation.error || navigation.result?.errorText) { + throw new Error(`Navigation failed: ${JSON.stringify(navigation)}`); + } + await send( + 'Emulation.setDeviceMetricsOverride', + { + width: item.width, + height: item.height, + deviceScaleFactor: 1, + mobile: item.width < 600, + }, + session, + ); + await delay(2500); + const placeholder = await waitFor( + () => evaluate("!!document.querySelector('flt-semantics-placeholder')"), + `${item.name} semantics placeholder`, + ); + if (!placeholder) throw new Error(`${item.name}: no semantics placeholder`); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + const labels = await waitFor(async () => { + const current = await evaluate( + "[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||x.innerText).filter(Boolean)", + ); + return current?.some(label => label.includes('Research batteries')) ? current : null; + }, `${item.name} schedule content`); + const text = labels.join('\n'); + for (const expected of item.expect) { + if (!text.includes(expected)) { + throw new Error(`${item.name}: missing ${JSON.stringify(expected)} in ${JSON.stringify(labels)}`); + } + } + if (/does not support|No schedules yet|socket closed/.test(text)) { + throw new Error(`${item.name}: unexpected state text ${JSON.stringify(labels)}`); + } + await delay(400); + const screenshot = await send( + 'Page.captureScreenshot', + { format: 'png', captureBeyondViewport: false }, + session, + ); + const file = `${item.name}.png`; + await writeFile(join(output, file), Buffer.from(screenshot.result.data, 'base64')); + results.push({ + name: item.name, + file, + width: item.width, + height: item.height, + theme: item.theme, + brightness: item.brightness ?? 'platform', + checked: item.expect, + labelCount: labels.length, + }); + } + if (pageErrors.length) { + throw new Error(`Page exceptions: ${JSON.stringify(pageErrors)}`); + } + const manifest = { + url: `http://127.0.0.1:${port}/`, + fixture: 'tool/schedules_list_probe_app.dart', + output, + captures: results, + }; + await writeFile(join(output, 'manifest.json'), JSON.stringify(manifest, null, 2)); + console.log(JSON.stringify(manifest, null, 2)); +} finally { + ws?.close(); + chrome.kill('SIGTERM'); + await Promise.race([once(chrome, 'exit'), delay(3000)]); + server.close(); + await rm(profile, { recursive: true, force: true }); +} diff --git a/app/tool/schedules_list_probe_app.dart b/app/tool/schedules_list_probe_app.dart new file mode 100644 index 00000000..e272bb3b --- /dev/null +++ b/app/tool/schedules_list_probe_app.dart @@ -0,0 +1,110 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/schedules/screen.dart'; + +/// Isolated browser fixture for the read-only schedules list. +/// +/// Run with: +/// flutter build web -t tool/schedules_list_probe_app.dart +/// and open `/?theme=cupertino&scale=2`. +void main() { + final parameters = Uri.base.queryParameters; + final cupertino = parameters['theme'] == 'cupertino'; + final dark = parameters['brightness'] == 'dark'; + final scale = double.tryParse(parameters['scale'] ?? '') ?? 1.0; + final screen = SchedulesScreen(gateway: _FixtureGateway(), onOpen: (_) {}); + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of(context).copyWith(textScaler: TextScaler.linear(scale)), + child: app!, + ); + if (cupertino) { + runApp( + CupertinoApp( + debugShowCheckedModeBanner: false, + builder: media, + home: CupertinoPageScaffold(child: SafeArea(child: screen)), + ), + ); + return; + } + runApp( + MaterialApp( + debugShowCheckedModeBanner: false, + theme: dark ? ThemeData(brightness: Brightness.dark) : null, + builder: media, + home: Scaffold( + appBar: AppBar(title: const Text('Schedules')), + body: screen, + ), + ), + ); +} + +class _FixtureGateway implements ApiGateway { + @override + Future call(String type, [JsonMap fields = const {}]) async { + if (type != 'list_schedules') { + throw StateError('The schedules list fixture only lists schedules.'); + } + return { + 'type': 'schedules', + 'schedules': [ + { + 'id': 8, + 'revision': 3, + 'name': 'Research batteries', + 'pipeline_id': 4, + 'version': 2, + 'enabled': true, + 'input': {'prompt': 'Find battery chemistry sources'}, + 'workspace': '/srv/research', + 'rule': { + 'every': '24h', + 'days': ['mon', 'wed'], + 'timezone': 'Europe/London', + }, + 'next_due': '2026-10-22T09:00:00Z', + }, + { + 'id': 9, + 'revision': 1, + 'name': 'Nightly report', + 'pipeline_id': 7, + 'version': 5, + 'enabled': false, + 'input': {'prompt': 'Summarise the open issues'}, + 'workspace': '/srv/reports', + 'rule': { + 'times': ['10:00', '18:30'], + 'days': [], + 'timezone': 'Local', + }, + }, + { + 'id': 10, + 'revision': 2, + 'name': 'Weekly digest', + 'pipeline_id': 12, + 'version': 1, + 'enabled': true, + 'input': {'prompt': 'Collect the week’s changes'}, + 'workspace': '/srv/digest', + 'rule': {'every': '168h', 'days': []}, + 'next_due': '2026-10-26T08:30:00+01:00', + }, + { + 'id': 11, + 'revision': 1, + 'name': 'Sparse server record', + 'enabled': false, + 'input': {}, + 'rule': {}, + }, + ], + }; + } + + @override + Stream get frames => const Stream.empty(); +} diff --git a/app/tool/search_fixture/main.dart b/app/tool/search_fixture/main.dart new file mode 100644 index 00000000..1328cd07 --- /dev/null +++ b/app/tool/search_fixture/main.dart @@ -0,0 +1,190 @@ +// Web-only fixture entrypoint for rendered search evidence. It is not part of +// the application's `main.dart`; build it explicitly with: +// flutter build web -t tool/search_fixture/main.dart +// `?cupertino=1` renders the same screen inside a CupertinoApp. +import 'dart:convert'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/search/search_screen.dart'; + +void main() { + final cupertino = Uri.base.queryParameters['cupertino'] == '1'; + runApp( + cupertino + ? const CupertinoApp( + title: 'Search fixture', + home: _FixtureHost(cupertino: true), + ) + : const MaterialApp( + title: 'Search fixture', + home: _FixtureHost(cupertino: false), + ), + ); +} + +class _FixtureHost extends StatelessWidget { + const _FixtureHost({required this.cupertino}); + + final bool cupertino; + + @override + Widget build(BuildContext context) => SearchScreen( + gateway: const _FixtureGateway(), + cupertino: cupertino, + onOpen: (hit) { + final route = cupertino + ? CupertinoPageRoute( + builder: (_) => _Opened(hit: hit, cupertino: true), + ) + : MaterialPageRoute( + builder: (_) => _Opened(hit: hit, cupertino: false), + ); + Navigator.of(context).push(route); + }, + ); +} + +class _Opened extends StatelessWidget { + const _Opened({required this.hit, required this.cupertino}); + + final JsonMap hit; + final bool cupertino; + + @override + Widget build(BuildContext context) { + final body = Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text( + 'Opened ${hit['kind']} target: ${hit['target']}', + textAlign: TextAlign.center, + ), + ), + ); + if (cupertino) { + return CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar(middle: Text('Opened')), + child: body, + ); + } + return Scaffold( + appBar: AppBar(title: const Text('Opened')), + body: body, + ); + } +} + +class _FixtureGateway implements ApiGateway { + const _FixtureGateway(); + + @override + Future call(String type, [JsonMap fields = const {}]) async { + if (type != 'search') throw StateError('unexpected request: $type'); + final request = Map.from(fields['search'] as Map); + final query = '${request['query'] ?? ''}'.trim().toLowerCase(); + final kind = '${request['kind'] ?? ''}'; + await Future.delayed(const Duration(milliseconds: 180)); + var hits = _fixtureHits + .where((hit) { + if (kind.isNotEmpty && hit['kind'] != kind) return false; + if (query.isEmpty) return true; + return jsonEncode(hit).toLowerCase().contains(query); + }) + .toList(growable: false); + return { + 'search_results': { + 'query': request['query'], + 'kind': kind, + 'results': hits, + 'truncated': true, + 'scanned_steps': 2000, + 'scanned_bytes': 1048576, + 'cap': 50, + 'scan_bound_bytes': 1048576, + }, + }; + } + + @override + Stream get frames => const Stream.empty(); +} + +const _fixtureHits = [ + { + 'kind': 'pipeline', + 'target': 'pipeline:24', + 'score': 3, + 'recency': '2026-10-20T09:18:00Z', + 'pipeline': {'id': 24, 'name': 'Plan and land', 'version': 5, 'stages': 4}, + }, + { + 'kind': 'run', + 'target': 'run:457', + 'score': 2, + 'recency': '2026-10-20T08:42:00Z', + 'run': { + 'id': 457, + 'pipeline_name': 'Plan and land', + 'status': 'succeeded', + 'workspace': '/Users/alan/repos/pipelines', + 'created_at': '2026-10-20T08:12:00Z', + 'finished_at': '2026-10-20T08:42:00Z', + }, + }, + { + 'kind': 'field', + 'target': 'run:457:3:input', + 'score': 1, + 'matched_field': 'input', + 'recency': '2026-10-20T08:20:00Z', + 'field': { + 'run_id': 457, + 'sequence': 3, + 'field': 'input', + 'snippet': 'Plan the change before implementing it', + }, + }, + { + 'kind': 'artifact', + 'target': '/artifacts/457/2/plan.md', + 'score': 1, + 'recency': '2026-10-20T08:24:00Z', + 'artifact': { + 'run_id': 457, + 'sequence': 2, + 'name': 'plan.md', + 'content_type': 'text/markdown', + 'size_bytes': 2048, + 'url': '/artifacts/457/2/plan.md', + }, + }, + { + 'kind': 'version', + 'target': 'pipeline:22:v6', + 'score': 2, + 'recency': '2026-10-18T16:05:00Z', + 'version': { + 'pipeline_id': 22, + 'version': 6, + 'content_hash': '9f2c1ad', + 'created_at': '2026-10-18T16:05:00Z', + }, + }, + { + 'kind': 'step', + 'target': 'run:457:1', + 'score': 1, + 'recency': '2026-10-20T08:14:00Z', + 'step': { + 'run_id': 457, + 'sequence': 1, + 'stage': 'planner', + 'visit': 1, + 'outcome': 'success', + 'target': '#success', + 'diagnostic': 'plan accepted', + }, + }, +]; diff --git a/app/tool/search_probe.mjs b/app/tool/search_probe.mjs new file mode 100644 index 00000000..172efb1f --- /dev/null +++ b/app/tool/search_probe.mjs @@ -0,0 +1,246 @@ +// Real Chrome evidence for the Flutter search screen. Serves the fixture build +// from build/web on an OS-assigned loopback port and drives the page through +// Chrome DevTools Protocol, like tool/shell_probe.mjs. Usage: +// flutter build web -t tool/search_fixture/main.dart +// OPENCODE_ARTIFACT_DIR= node tool/search_probe.mjs +import { createServer } from 'node:http'; +import { readFile, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { setTimeout as delay } from 'node:timers/promises'; +import { join, extname, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; + +const root = join(process.cwd(), 'build/web'); +const artifactDir = process.env.OPENCODE_ARTIFACT_DIR; +if (!artifactDir) throw new Error('OPENCODE_ARTIFACT_DIR is required for captures'); +const mime = { + '.html': 'text/html', + '.js': 'text/javascript', + '.json': 'application/json', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.ico': 'image/x-icon', + '.ttf': 'font/ttf', + '.otf': 'font/otf', +}; +const server = createServer(async (req, res) => { + try { + const path = resolve( + root, + '.' + decodeURIComponent(new URL(req.url, 'http://localhost').pathname), + ); + if (path !== root && !path.startsWith(root + sep)) { + return res.writeHead(403).end(); + } + const filePath = + path === root || path.endsWith('/') ? join(path, 'index.html') : path; + const file = await readFile(filePath); + res + .writeHead(200, { + 'content-type': mime[extname(filePath)] ?? 'application/octet-stream', + }) + .end(file); + } catch { + res.writeHead(404).end('not found'); + } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const port = server.address().port; +const profile = await mkdtemp(join(tmpdir(), 'x1-search-chrome-')); +const chrome = spawn( + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + [ + '--headless=new', + '--no-first-run', + '--no-default-browser-check', + '--disable-gpu', + '--remote-debugging-port=0', + `--user-data-dir=${profile}`, + 'about:blank', + ], + { stdio: ['ignore', 'ignore', 'pipe'] }, +); +let stderr = ''; +chrome.stderr.on('data', (data) => { + stderr += data; +}); +const waitFor = async (fn) => { + for (let i = 0; i < 100; i++) { + const value = await fn(); + if (value) return value; + await delay(100); + } + throw new Error('Timed out waiting for Chrome DevTools'); +}; +const result = { captures: [], evidence: {} }; +let ws; +try { + const endpoint = await waitFor(() => + stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1], + ); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', (event) => { + const msg = JSON.parse(event.data); + if (msg.id && pending.has(msg.id)) { + pending.get(msg.id)(msg); + pending.delete(msg.id); + } + }); + const send = (method, params = {}, sessionId) => + new Promise((resolve) => { + const callId = ++id; + pending.set(callId, resolve); + ws.send( + JSON.stringify({ + id: callId, + method, + params, + ...(sessionId ? { sessionId } : {}), + }), + ); + }); + const created = await send('Target.createTarget', { url: 'about:blank' }); + if (!created.result) { + throw new Error(`Target creation failed: ${JSON.stringify(created)}`); + } + const target = created.result.targetId; + const session = ( + await send('Target.attachToTarget', { targetId: target, flatten: true }) + ).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + const evaluate = async (expression) => { + const response = await send( + 'Runtime.evaluate', + { expression, returnByValue: true, awaitPromise: true }, + session, + ); + if (response.error) { + throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); + } + return response.result?.result?.value; + }; + const clickMatching = (needle) => + evaluate(`(() => { + const needle = ${JSON.stringify(needle)}; + const nodes = [...document.querySelectorAll('flt-semantics')]; + const e = nodes.find(x => x.hasAttribute('flt-tappable') && + (x.getAttribute('aria-label') || x.innerText || '').includes(needle)); + if (!e) return false; + e.click(); + return true; + })()`); + const capture = async (name, width, height) => { + await send( + 'Emulation.setDeviceMetricsOverride', + { width, height, deviceScaleFactor: 1, mobile: width < 600 }, + session, + ); + await delay(350); + const data = ( + await send( + 'Page.captureScreenshot', + { format: 'png', captureBeyondViewport: false }, + session, + ) + ).result.data; + const path = join(artifactDir, `${name}.png`); + await writeFile(path, Buffer.from(data, 'base64')); + result.captures.push(path); + }; + const load = async (url, width, height) => { + await send( + 'Emulation.setDeviceMetricsOverride', + { width, height, deviceScaleFactor: 1, mobile: width < 600 }, + session, + ); + const navigation = await send('Page.navigate', { url }, session); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + await delay(3500); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(900); + }; + const typeText = async (query) => { + const focused = await evaluate(`(() => { + const input = document.querySelector('input[type="search"]') || document.querySelector('input.flt-text-editing'); + if (!input) return false; input.focus(); return true; })()`); + if (!focused) throw new Error('Search input not found'); + await delay(400); + const inserted = await send('Input.insertText', { text: query }, session); + if (inserted.error) throw new Error(JSON.stringify(inserted)); + await delay(1400); + return (await evaluate('document.body.innerText')).trim(); + }; + const typeQuery = async (query) => { + const trimmed = await typeText(query); + if (!trimmed.includes('Plan and land')) { + throw new Error(`Results missing after typing: ${JSON.stringify(trimmed)}`); + } + return { + typed: query, + resultTitles: ['Plan and land', 'run #457 · Plan and land', 'run #457 · step 3 · input', + 'plan.md', 'run #457 · planner visit 1'].filter((title) => trimmed.includes(title)), + showsServerSnippet: trimmed.includes('Plan the change before implementing it'), + showsRecency: /\d{1,2} [A-Z][a-z]{2} \d{2}:\d{2}/.test(trimmed), + showsBounds: + trimmed.includes('Results truncated') && + trimmed.includes('cap 50') && + trimmed.includes('scanned 2000 steps'), + }; + }; + const typeTruncatedEmpty = async (query) => { + const text = await typeText(query); + const emptyCopy = `No matches for "${query}" within the server's scan limit.`; + const missing = [ + emptyCopy, 'Results truncated', '0 results', + 'scanned 2000 steps', 'scan limit 1.0 MiB', + ].filter((needle) => !text.includes(needle)); + if (missing.length) throw new Error(`Truncated empty missing ${JSON.stringify(missing)}`); + return { typed: query, emptyCopy, showsTruncationWarning: true, showsBounds: true }; + }; + + const base = `http://127.0.0.1:${port}/`; + await load(base, 390, 844); + result.evidence.materialPhone = await typeQuery('plan'); + await capture('x1-search-material-phone', 390, 844); + if (!(await clickMatching('Plan and land'))) { + throw new Error('Could not open the pipeline row'); + } + await delay(700); + const opened = await evaluate('document.body.innerText'); + if (!opened.includes('pipeline:24')) { + throw new Error(`Opened target missing: ${JSON.stringify(opened)}`); + } + result.evidence.opened = 'pipeline:24'; + await capture('x1-search-open-target', 390, 844); + + await load(base, 1280, 800); + result.evidence.materialDesktop = await typeQuery('plan'); + await capture('x1-search-material-desktop', 1280, 800); + + await load(`${base}?cupertino=1`, 390, 844); + result.evidence.cupertinoPhone = await typeQuery('plan'); + await capture('x1-search-cupertino-phone', 390, 844); + + await load(base, 390, 844); + result.evidence.materialTruncatedEmpty = await typeTruncatedEmpty('needle'); + await capture('x1-search-truncated-empty', 390, 844); + + await load(`${base}?cupertino=1`, 390, 844); + result.evidence.cupertinoTruncatedEmpty = + await typeTruncatedEmpty('needle'); + await capture('x1-search-truncated-empty-cupertino', 390, 844); + + console.log(JSON.stringify(result, null, 2)); +} finally { + ws?.close(); + chrome.kill('SIGTERM'); + await Promise.race([once(chrome, 'exit'), delay(3000)]); + server.close(); + await rm(profile, { recursive: true, force: true }); +} diff --git a/app/tool/settings_probe.dart b/app/tool/settings_probe.dart new file mode 100644 index 00000000..4c954dbe --- /dev/null +++ b/app/tool/settings_probe.dart @@ -0,0 +1,71 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:pipelines_app/features/settings/settings.dart'; + +/// A fixture entry point for browser captures of the Settings screen. It does +/// not change `main.dart` or the shell, and it never uses the production +/// preferences store: all persisted values live in a [MemorySettingsStore]. +/// +/// Query parameters: +/// endpoint=ws://127.0.0.1:PORT/connect seed the URL field / connect target +/// workspace=/srv/pipelines seed the saved workspace +/// connect=1 explicitly connect after first frame +/// platform=ios render the Cupertino controls +/// theme=dark dark Material theme +/// scale=1.5 large-text check +void main() { + final params = Uri.base.queryParameters; + final endpoint = params['endpoint']?.trim(); + final client = PipelinesClient(); + final store = MemorySettingsStore( + workspace: params['workspace']?.trim() ?? '', + ); + final isIOS = params['platform'] == 'ios'; + final isDark = params['theme'] == 'dark'; + final scale = double.tryParse(params['scale'] ?? '') ?? 1; + + runApp( + MaterialApp( + title: 'Pipelines Settings probe', + theme: ThemeData( + platform: isIOS ? TargetPlatform.iOS : TargetPlatform.android, + brightness: isDark ? Brightness.dark : Brightness.light, + colorScheme: ColorScheme.fromSeed( + seedColor: Colors.blue, + brightness: isDark ? Brightness.dark : Brightness.light, + ), + ), + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(scale)), + child: child ?? const SizedBox.shrink(), + ), + home: SettingsScreen( + client: client, + initialEndpoint: (endpoint == null || endpoint.isEmpty) + ? null + : Uri.tryParse(endpoint), + store: store, + ), + ), + ); + + if (params['connect'] == '1') { + final target = (endpoint == null || endpoint.isEmpty) + ? defaultServerUrl() + : endpoint; + if (target.isNotEmpty) { + WidgetsBinding.instance.addPostFrameCallback((_) { + unawaited( + client.connect(Uri.parse(target)).catchError((Object _) { + // The screen renders the client's truthful state; an invalid + // fixture endpoint must not take the probe down. + }), + ); + }); + } + } +} diff --git a/app/tool/settings_probe_capture.dart b/app/tool/settings_probe_capture.dart new file mode 100644 index 00000000..f15d6803 --- /dev/null +++ b/app/tool/settings_probe_capture.dart @@ -0,0 +1,318 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +/// Drives the Settings probe in real headless Chrome through the DevTools +/// protocol and writes PNG captures. It only talks to the local probe origin +/// passed with `--url`; it never contacts the production server. +/// +/// Usage: +/// dart run tool/settings_probe_capture.dart \ +/// --url http://127.0.0.1:PORT/ --out /path/to/captures +/// +/// Set CHROME_PATH if Chrome is not at the default macOS location. +Future main(List arguments) async { + final url = _argument(arguments, '--url'); + final outPath = _argument(arguments, '--out'); + if (url == null || outPath == null) { + stderr.writeln('usage: ... --url URL --out DIRECTORY'); + exitCode = 64; + return; + } + final out = Directory(outPath)..createSync(recursive: true); + final chromePath = + Platform.environment['CHROME_PATH'] ?? + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; + final profile = await Directory.systemTemp.createTemp('settings-probe-'); + final chrome = await Process.start(chromePath, [ + '--headless=new', + '--disable-gpu', + '--hide-scrollbars', + '--no-first-run', + '--no-default-browser-check', + '--remote-debugging-port=0', + '--user-data-dir=${profile.path}', + 'about:blank', + ]); + final stderrLines = chrome.stderr + .transform(utf8.decoder) + .transform(const LineSplitter()) + .asBroadcastStream(); + try { + final browserWs = await stderrLines + .firstWhere((line) => line.contains('DevTools listening on ')) + .timeout(const Duration(seconds: 20)); + final browserUrl = browserWs.substring(browserWs.indexOf('ws://')); + final parsed = Uri.parse(browserUrl); + final pageWs = await _pageTarget(parsed); + final cdp = Cdp(await WebSocket.connect(pageWs)); + await cdp.send('Page.enable'); + await cdp.send('Runtime.enable'); + + final scenarios = [ + 'idle', + 'connected', + 'validation', + 'workspace', + 'dark', + 'ios', + 'narrow', + ]; + for (final scenario in scenarios) { + await _runScenario(cdp, url, out, scenario); + stdout.writeln('captured $scenario'); + } + await cdp.close(); + } finally { + chrome.kill(ProcessSignal.sigterm); + await profile.delete(recursive: true).catchError((_) => profile); + } +} + +Future _runScenario( + Cdp cdp, + String base, + Directory out, + String scenario, +) async { + var target = base; + var width = 1200; + var height = 900; + switch (scenario) { + case 'idle': + break; + case 'connected': + target = '$base?connect=1'; + break; + case 'validation': + target = '$base?endpoint=http%3A%2F%2Fexample.test'; + break; + case 'workspace': + target = '$base?connect=1'; + break; + case 'dark': + target = '$base?connect=1&theme=dark'; + break; + case 'ios': + target = '$base?connect=1&platform=ios'; + break; + case 'narrow': + width = 390; + height = 844; + target = '$base?connect=1&scale=1.6'; + } + await cdp.send('Emulation.setDeviceMetricsOverride', { + 'width': width, + 'height': height, + 'deviceScaleFactor': 1, + 'mobile': false, + }); + await cdp.send('Page.navigate', {'url': target}); + await Future.delayed(const Duration(seconds: 4)); + if (scenario == 'validation' || scenario == 'workspace') { + await _enableSemantics(cdp); + if (scenario == 'validation') { + await _click(cdp, 'Connect'); + await Future.delayed(const Duration(milliseconds: 800)); + } else { + await _typeWorkspace(cdp, '/srv/pipelines'); + await _click(cdp, 'Save workspace'); + await Future.delayed(const Duration(milliseconds: 800)); + } + } + final shot = await cdp.send('Page.captureScreenshot', { + 'format': 'png', + 'captureBeyondViewport': false, + }); + final data = (shot['result'] as Map)['data'] as String; + File( + '${out.path}/settings-$scenario.png', + ).writeAsBytesSync(base64Decode(data)); +} + +Future _enableSemantics(Cdp cdp) async { + await cdp.evaluate(''' + (() => { + const placeholder = document.querySelector('flt-semantics-placeholder'); + if (placeholder) { + placeholder.click(); + return 'semantics requested'; + } + return 'no placeholder'; + })() + '''); + await Future.delayed(const Duration(milliseconds: 900)); + if (Platform.environment['DUMP_DOM'] == '1') { + stdout.writeln( + await cdp.evaluate( + "document.querySelector('flt-semantics-host')?.innerHTML ?? 'none'", + ), + ); + } +} + +Future _click(Cdp cdp, String label) async { + final result = await cdp.evaluate(''' + (() => { + const byLabel = [...document.querySelectorAll('[aria-label]')] + .find((element) => element.getAttribute('aria-label') === ${jsonEncode(label)}); + const byRole = [...document.querySelectorAll('[role="button"]')] + .find((element) => (element.textContent || '').trim() === ${jsonEncode(label)}); + const target = byLabel || byRole; + if (!target) { + return 'missing; labels=' + [...document.querySelectorAll('[aria-label]')] + .map((element) => element.getAttribute('aria-label')).join('|') + + '; roles=' + [...document.querySelectorAll('[role="button"]')] + .map((element) => (element.textContent || '').trim()).join('|'); + } + target.click(); + return 'clicked ' + target.tagName + ' ' + (target.getAttribute('role') || ''); + })() + '''); + stdout.writeln('click "$label": $result'); +} + +Future _typeWorkspace(Cdp cdp, String value) async { + final found = await cdp.evaluate(''' + (() => { + const target = [...document.querySelectorAll('[aria-label]')] + .find((element) => (element.getAttribute('aria-label') || '') + .startsWith('Workspace path')); + if (!target) return 'missing'; + target.click(); + target.focus(); + return 'focused ' + target.tagName; + })() + '''); + stdout.writeln('workspace field: $found'); + await Future.delayed(const Duration(milliseconds: 400)); + final rect = await cdp.evaluate(''' + (() => { + const target = [...document.querySelectorAll('[aria-label]')] + .find((element) => (element.getAttribute('aria-label') || '') + .startsWith('Workspace path')); + if (!target) return null; + const r = target.getBoundingClientRect(); + return {x: r.left + r.width / 2, y: r.top + r.height / 2}; + })() + '''); + if (rect != 'null') { + final match = RegExp(r'x: ([0-9.]+), y: ([0-9.]+)').firstMatch(rect); + if (match != null) { + final x = double.parse(match.group(1)!); + final y = double.parse(match.group(2)!); + for (final type in ['mousePressed', 'mouseReleased']) { + await cdp.send('Input.dispatchMouseEvent', { + 'type': type, + 'x': x, + 'y': y, + 'button': 'left', + 'clickCount': 1, + }); + } + await Future.delayed(const Duration(milliseconds: 300)); + } + } + await cdp.send('Input.insertText', {'text': value}); + await Future.delayed(const Duration(milliseconds: 300)); + final typed = await cdp.evaluate(''' + (() => { + const el = document.activeElement; + if (!el) return 'no active element'; + if (el.value === ${jsonEncode(value)}) return 'insertText worked'; + el.value = ${jsonEncode(value)}; + el.dispatchEvent(new InputEvent('input', { + bubbles: true, + inputType: 'insertText', + data: ${jsonEncode(value)}, + })); + el.dispatchEvent(new Event('change', {bubbles: true})); + return 'dispatched input; value=' + el.value; + })() + '''); + stdout.writeln('workspace input: $typed'); + await Future.delayed(const Duration(milliseconds: 500)); +} + +Future _pageTarget(Uri browserWs) async { + final client = HttpClient(); + try { + final request = await client.getUrl( + Uri( + scheme: 'http', + host: browserWs.host, + port: browserWs.port, + path: '/json/list', + ), + ); + final response = await request.close(); + final body = await response.transform(utf8.decoder).join(); + final targets = jsonDecode(body) as List; + final page = targets.cast>().firstWhere( + (target) => target['type'] == 'page', + ); + return page['webSocketDebuggerUrl'] as String; + } finally { + client.close(force: true); + } +} + +String? _argument(List arguments, String name) { + final index = arguments.indexOf(name); + if (index < 0 || index + 1 >= arguments.length) return null; + return arguments[index + 1]; +} + +class Cdp { + Cdp(this._socket) { + _socket.listen(_onMessage); + } + + final WebSocket _socket; + final Map>> _pending = {}; + int _next = 0; + + Future> send( + String method, [ + Map params = const {}, + ]) { + final id = ++_next; + final completer = Completer>(); + _pending[id] = completer; + _socket.add( + jsonEncode({ + 'id': id, + 'method': method, + 'params': params, + }), + ); + return completer.future.timeout(const Duration(seconds: 30)); + } + + Future evaluate(String expression) async { + final reply = await send('Runtime.evaluate', { + 'expression': expression, + 'returnByValue': true, + 'awaitPromise': true, + }); + final result = reply['result'] as Map; + return '${result['result']?['value']}'; + } + + void _onMessage(dynamic data) { + if (data is! String) return; + final message = jsonDecode(data) as Map; + final id = message['id']; + if (id is! int) return; + final completer = _pending.remove(id); + if (completer == null) return; + final error = message['error']; + if (error != null) { + completer.completeError(StateError('$error')); + } else { + completer.complete(message); + } + } + + Future close() => _socket.close(); +} diff --git a/app/tool/settings_probe_server.dart b/app/tool/settings_probe_server.dart new file mode 100644 index 00000000..af2a564f --- /dev/null +++ b/app/tool/settings_probe_server.dart @@ -0,0 +1,103 @@ +import 'dart:convert'; +import 'dart:io'; + +/// An isolated loopback fixture for the Settings browser probe. +/// +/// It serves the probe's `build/web` output and upgrades `/connect` to a +/// websocket that answers `ping` with a deterministic pong (build + time), so +/// the screen can be exercised in a real browser without the production server, +/// authentication changes or any deployment. It binds loopback on an OS-assigned +/// port unless `--port` is given. +/// +/// Usage: +/// dart run tool/settings_probe_server.dart --root build/probe_web +Future main(List arguments) async { + var rootPath = 'build/probe_web'; + var port = 0; + for (var i = 0; i < arguments.length; i++) { + if (arguments[i] == '--root' && i + 1 < arguments.length) { + rootPath = arguments[++i]; + } else if (arguments[i] == '--port' && i + 1 < arguments.length) { + port = int.parse(arguments[++i]); + } + } + final root = Directory(rootPath).absolute; + if (!root.existsSync()) { + stderr.writeln('Probe build not found at ${root.path}'); + exitCode = 2; + return; + } + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, port); + stdout.writeln('http://127.0.0.1:${server.port}/'); + await for (final request in server) { + unawaited(_handle(request, root)); + } +} + +Future _handle(HttpRequest request, Directory root) async { + if (request.uri.path == '/connect' && + WebSocketTransformer.isUpgradeRequest(request)) { + final socket = await WebSocketTransformer.upgrade(request); + stdout.writeln('connect'); + socket.listen((data) { + if (data is! String) return; + final Object? decoded; + try { + decoded = jsonDecode(data); + } on FormatException { + return; + } + if (decoded is! Map) return; + if (decoded['type'] != 'ping') return; + stdout.writeln('ping'); + socket.add( + jsonEncode({ + 'id': decoded['id'], + 'type': 'pong', + 'protocol': 1, + 'build': { + 'version': 'probe-1.2.3', + 'commit': 'abc1234', + }, + 'time': '2026-10-21T12:00:00Z', + }), + ); + }); + return; + } + + var relative = request.uri.path; + if (relative.isEmpty || relative == '/') relative = '/index.html'; + final file = File('${root.path}${relative.replaceAll('..', '')}'); + if (!file.existsSync()) { + request.response.statusCode = HttpStatus.notFound; + await request.response.close(); + return; + } + request.response.headers.contentType = _contentType(relative); + request.response.headers.set('Cache-Control', 'no-store'); + await request.response.addStream(file.openRead()); + await request.response.close(); +} + +ContentType _contentType(String path) { + final extension = path.split('.').last.toLowerCase(); + return switch (extension) { + 'html' => ContentType.html, + 'js' || 'mjs' => ContentType('text', 'javascript', charset: 'utf-8'), + 'css' => ContentType('text', 'css', charset: 'utf-8'), + 'json' || 'map' => ContentType.json, + 'png' => ContentType('image', 'png'), + 'svg' => ContentType('image', 'svg+xml'), + 'ico' => ContentType('image', 'x-icon'), + 'wasm' => ContentType('application', 'wasm'), + 'ttf' || 'otf' => ContentType('font', 'ttf'), + _ => ContentType.binary, + }; +} + +void unawaited(Future future) { + future.catchError((Object error, StackTrace stack) { + stderr.writeln('probe server: $error'); + }); +} diff --git a/app/tool/shell_probe.mjs b/app/tool/shell_probe.mjs new file mode 100644 index 00000000..c0e02bc2 --- /dev/null +++ b/app/tool/shell_probe.mjs @@ -0,0 +1,94 @@ +import { createServer } from 'node:http'; +import { readFile } from 'node:fs/promises'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { setTimeout as delay } from 'node:timers/promises'; +import { join, extname, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; +import { mkdtemp, rm } from 'node:fs/promises'; + +const root = join(process.cwd(), 'build/web'); +const mime = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png', '.ico': 'image/x-icon' }; +const server = createServer(async (req, res) => { + try { + const path = resolve(root, '.' + decodeURIComponent(new URL(req.url, 'http://localhost').pathname)); + if (path !== root && !path.startsWith(root + sep)) return res.writeHead(403).end(); + const filePath = path.endsWith('/') ? join(path, 'index.html') : path; + const file = await readFile(filePath); + res.writeHead(200, { 'content-type': mime[extname(filePath)] ?? 'application/octet-stream' }).end(file); + } catch { res.writeHead(404).end('not found'); } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const port = server.address().port; +const profile = await mkdtemp(join(tmpdir(), 'f2-shell-chrome-')); +const chrome = spawn('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', [ + '--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu', + '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank', +], { stdio: ['ignore', 'ignore', 'pipe'] }); +let stderr = ''; +chrome.stderr.on('data', data => { stderr += data; }); +const waitFor = async fn => { + for (let i = 0; i < 100; i++) { const value = await fn(); if (value) return value; await delay(100); } + throw new Error('Timed out waiting for Chrome DevTools'); +}; +let ws; +try { + const endpoint = await waitFor(() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1]); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', event => { + const msg = JSON.parse(event.data); + if (msg.method?.includes('detached') || msg.method?.includes('crashed')) console.error('CDP event', JSON.stringify(msg)); + if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); } + }); + const send = (method, params = {}, sessionId) => new Promise(resolve => { + const callId = ++id; pending.set(callId, resolve); + ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + const created = await send('Target.createTarget', { url: 'about:blank' }); + if (!created.result) throw new Error(`Target creation failed: ${JSON.stringify(created)}`); + const target = created.result.targetId; + const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + const navigation = await send('Page.navigate', { url: `http://127.0.0.1:${port}/` }, session); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + const evaluate = async expression => { + const response = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, session); + if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); + return response.result?.result?.value; + }; + await delay(3500); + const loaded = await evaluate("({url:location.href, ready:document.readyState, body:document.body.innerText, html:document.body.innerHTML.slice(0,500)})"); + if (!loaded?.url.includes(`127.0.0.1:${port}`)) throw new Error(`Fixture did not load: ${JSON.stringify(loaded)}`); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(900); + const clickLabel = async label => evaluate(`(() => { const e=[...document.querySelectorAll('flt-semantics')].find(x => (x.getAttribute('aria-label') || x.innerText || '') === ${JSON.stringify(label)}); if (!e) return false; e.click(); return true; })()`); + const labels = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||x.innerText).filter(Boolean)"); + if (!labels?.some(x => x.includes('Pipelines'))) throw new Error(`Flutter semantics unavailable: ${JSON.stringify(labels)}`); + const capture = async (name, width, height) => { + await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 }, session); + await delay(350); + const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data; + await (await import('node:fs/promises')).writeFile(`${process.env.OPENCODE_ARTIFACT_DIR}/${name}.png`, Buffer.from(data, 'base64')); + }; + await capture('f2-shell-phone', 390, 844); + for (const label of ['Runs', 'Chat', 'Settings', 'Pipelines']) { + if (!await clickLabel(label)) throw new Error(`Could not interact with ${label} navigation`); + await delay(250); + const current = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||x.innerText).filter(Boolean)"); + if (!current?.some(x => x.includes(label + ' — Not implemented'))) throw new Error(`${label} body missing after navigation: ${JSON.stringify(current)}`); + if (label === 'Runs' || label === 'Settings') await capture(`f2-shell-phone-${label.toLowerCase()}`, 390, 844); + } + await capture('f2-shell-desktop', 1280, 800); + console.log(JSON.stringify({ labels, captures: ['f2-shell-phone.png', 'f2-shell-phone-runs.png', 'f2-shell-phone-settings.png', 'f2-shell-desktop.png'], navigated: ['Runs', 'Chat', 'Settings', 'Pipelines'] }, null, 2)); +} finally { + ws?.close(); + chrome.kill('SIGTERM'); + await Promise.race([once(chrome, 'exit'), delay(3000)]); + server.close(); + await rm(profile, { recursive: true, force: true }); +} diff --git a/docs/notes/session-export-handoff-gate.md b/docs/notes/session-export-handoff-gate.md index 6f09e72c..086d550a 100644 --- a/docs/notes/session-export-handoff-gate.md +++ b/docs/notes/session-export-handoff-gate.md @@ -73,7 +73,7 @@ retry and refresh of an already-open Session tab. Large (>256 KiB) API fixtures, wrong identity, partial/empty exports, restart, cancellation, workspace reservation, and exactly-once successor admission have focused regressions. A full ordinary artifact inventory no longer blocks versioned audit repair. -Repairs have a separate bounded allowance (twenty attempts, each at most 2 MiB), +Repairs have a separate bounded allowance (twenty attempts, each at most 8 MiB), so neither the ordinary inventory's file count nor its byte budget consumes the mandatory audit-recovery capacity. The ordinary scan limits remain unchanged. diff --git a/docs/notes/session-export-inline-attachments.md b/docs/notes/session-export-inline-attachments.md new file mode 100644 index 00000000..4c03d10e --- /dev/null +++ b/docs/notes/session-export-inline-attachments.md @@ -0,0 +1,26 @@ +# Complete visual audit exports without duplicate inline payloads + +Run34 visit3 retained a complete, untruncated native session (71 messages, +4,196,297 decoded native bytes), but the HTML audit exceeded the8MiB render cap. +The readable tool projection printed47 inline `data:` attachment URIs as text, +duplicating3,752,634 bytes already stored in complete native message records. + +The renderer now summarizes an inline attachment in the readable projection +ONLY when its exact URI bytes also occur in that message's retained native +record. The complete native JSON remains unchanged and HTML-escaped. If the +native record is absent or does not contain the payload, the original full +projection is kept; there is no evidence loss or fabricated completeness. + +No source/render/artifact bound is raised. All remain at their existing limits, +and genuinely oversized exports still report partial/truncated. No HTML is +executed from the attachment; MIME labels and native data stay escaped. + +Read-only scratch export of the exact original visual-review session now +produces4,676,544 bytes,71 messages, `truncated:false`. Production originals and +checkpoints were not overwritten by this proof. + +Regressions cover a4MiB inline payload retained exactly once, fallback when no +native copy exists, and escaped/unescaped hostile native JSON/MIME values. The +full Go suite passes with the unrelated notification-test URL env isolated. +Installation remains deferred until a quiescent service window; no active run +may be interrupted just to activate this correction. diff --git a/docs/notes/session-export-render-cap.md b/docs/notes/session-export-render-cap.md new file mode 100644 index 00000000..3ffd0b34 --- /dev/null +++ b/docs/notes/session-export-render-cap.md @@ -0,0 +1,44 @@ +# Session export: rendered-file cap aligned with the artifact bound + +## Problem + +Six computed Flutter runs (34, 37, 39, 42, 49, 50) reached Code visit 1 with a +successful, quiescent agent session but stopped at the export handoff gate. Each +recorded `session_export.status: partial`, `html_bytes: 2097152`, +`truncated: true`; the manual versioned repair of run 34 hit the same exact size. +The sessions had completed their computation, so a stage rerun was not the right +recovery. + +A read-only inspection of the recorded session rows showed the original native +data for those six sessions was between 1,083,391 and 2,111,470 bytes (the +complete HTTP export envelope for one of them was 2,126,449 bytes). All were +well inside the existing 8 MiB source read cap. The binding limit was the 2 MiB +rendered-file cap: html escaping and the readable projection keep native text +more than once, so an ordinary session can render larger than its source. +Re-exporting the six exact sessions read-only into scratch directories with the +new cap produced complete, untruncated files of 2,252,874 to 4,276,358 bytes. + +## Change + +`internal/stage/session_export.go` raises `SessionExportFileLimit` from 2 MiB to +8 MiB. That value is the same as the server's ordinary per-artifact file bound +(`maxArtifactFileBytes` in `internal/server/artifacts.go`), so a complete export +remains listed and served instead of being cut below the bound that the artifact +inventory already enforces. + +The source read remains capped by `SessionExportSourceLimit` (the single +`opencode.MaxSessionExport` value, 8 MiB). Normal export verification, versioned +export repair and the handoff gate all use `SessionExportFileLimit`, so they now +share one larger bound. The export still refuses to overwrite an existing file, +still marks any cut with a visible leading and trailing banner, and still reports +`truncated: true` and `status: partial`; nothing treats a partial export as +complete. + +## Checks + +Focused stage and server regressions cover a complete export above the old 2 MiB +cap but inside the new cap, a file above the new cap rejected as partial with the +verification diagnostic, repair accepting the larger complete file while the +original evidence stays unchanged, and the constant staying within the ordinary +artifact file bound. Focused stage/server suites and `go build ./...` plus +`go vet ./...` are run before landing; see the delivery report for exact results. diff --git a/docs/stage-artifacts.md b/docs/stage-artifacts.md index b29260d0..b2da6462 100644 --- a/docs/stage-artifacts.md +++ b/docs/stage-artifacts.md @@ -97,10 +97,13 @@ no special casing. `opencode session export `. Both reuse the same invocation helper and session-ID/messages validation as the transcript readback. The file is the harness's real session, never a reconstruction. -- Bounds: the source read is capped at 8 MiB and the rendered file at 2 MiB. When - either is cut, the file carries a visible truncation banner near the start and - the end and the step records `truncated: true`; a truncated export is never - described as whole. +- Bounds: the source read is capped at 8 MiB and the rendered file at 8 MiB, + matching the ordinary per-artifact file bound. The rendered file can exceed + its source because html escaping and the readable projection keep native text + more than once, so the previous 2 MiB render cap cut complete sessions that + were well inside the source bound. When either bound is exceeded, the file + carries a visible truncation banner near the start and the end and the step + records `truncated: true`; a truncated export is never described as whole. - Evidence: the step records `session_export` (`session_id`, `backend`, `source`, `html`, `html_bytes`, `messages`, `truncated`, `diagnostic`), so `pipelines inspect RUN_ID --json` shows what was written without reading the diff --git a/internal/author/skill/references/operations.md b/internal/author/skill/references/operations.md index 06a6013a..c67de23b 100644 --- a/internal/author/skill/references/operations.md +++ b/internal/author/skill/references/operations.md @@ -249,9 +249,10 @@ landed. presented. A run recorded before the HTML-only change still lists `session.md` among its stored artifacts (dated evidence kept on disk, not deleted); every listing — app, TUI, web spike — hides it rather than showing it beside the html. -- The source read is capped at 8 MiB and the rendered file at 2 MiB; a cut source or - a cut rendered file carries a visible truncation banner at both ends and - `session_export.truncated: true`, and a truncated export is never called whole. +- The source read is capped at 8 MiB and the rendered file at 8 MiB, matching the + ordinary per-artifact file bound; a cut source or a cut rendered file carries a + visible truncation banner at both ends and `session_export.truncated: true`, and + a truncated export is never called whole. - The step records `session_export` (`session_id`, `backend`, `source`, the html file name, `html_bytes`, `messages`, `truncated`, `diagnostic`) in `inspect RUN_ID --json`. A record written before the change still carried diff --git a/internal/server/session_export_gate_test.go b/internal/server/session_export_gate_test.go index a32a0943..3c9519c4 100644 --- a/internal/server/session_export_gate_test.go +++ b/internal/server/session_export_gate_test.go @@ -136,6 +136,56 @@ func TestSessionExportGateRetryOnlyAndExactlyOnce(t *testing.T) { } } +// TestSessionExportGateAcceptsRepairAboveOldRenderCap keeps the handoff gate's +// versioned-repair verification on the same larger bound as normal export. +func TestSessionExportGateAcceptsRepairAboveOldRenderCap(t *testing.T) { + h, s, id, first, second := gateRunner(t, func(context.Context, stage.SessionExportRequest) (stage.SessionExportResult, error) { + return stage.SessionExportResult{}, errors.New("export offline") + }, false) + h.runner.wg.Wait() + ctx := context.Background() + if err := s.ConfirmRecoveredSession(ctx, pipeline.SessionOwner{RunID: id, ID: "ses_exact"}); err != nil { + t.Fatal(err) + } + size := int64(2<<20) + 4096 + h.runner.exportSession = func(_ context.Context, req stage.SessionExportRequest) (stage.SessionExportResult, error) { + if err := os.MkdirAll(req.ArtifactsDir, 0700); err != nil { + return stage.SessionExportResult{}, err + } + f, err := os.Create(filepath.Join(req.ArtifactsDir, req.FileName)) + if err != nil { + return stage.SessionExportResult{}, err + } + if err := f.Truncate(size); err != nil { + f.Close() + return stage.SessionExportResult{}, err + } + if err := f.Close(); err != nil { + return stage.SessionExportResult{}, err + } + return stage.SessionExportResult{Source: "native_export", HTML: req.FileName, HTMLBytes: size, Messages: 2}, nil + } + if _, err := h.runner.repairSessionExport(ctx, id, 1); err != nil { + t.Fatal(err) + } + // The worker promotes a persisted complete repair before claiming a lease. + job, err := s.ClaimSessionExportJob(ctx, time.Now().Add(time.Second), time.Minute) + if err != nil { + t.Fatal(err) + } + if job != nil { + t.Fatalf("complete repair still claimed as a recovery job: %+v", job) + } + if err := h.runner.resumeExportGates(ctx); err != nil { + t.Fatal(err) + } + h.runner.wg.Wait() + d, _ := s.GetRun(ctx, id) + if first.Load() != 1 || second.Load() != 1 || d.Status != "succeeded" || len(d.Steps) != 2 { + t.Fatalf("large repair did not advance the gate: %+v (%d/%d)", d, first.Load(), second.Load()) + } +} + func TestSessionExportGateCleanupUnconfirmedDoesNotExportOrAdvance(t *testing.T) { var exports atomic.Int32 h, s, id, _, second := gateRunner(t, func(ctx context.Context, req stage.SessionExportRequest) (stage.SessionExportResult, error) { diff --git a/internal/server/session_export_repair_test.go b/internal/server/session_export_repair_test.go index 4c0d8252..c2aabf3a 100644 --- a/internal/server/session_export_repair_test.go +++ b/internal/server/session_export_repair_test.go @@ -111,6 +111,57 @@ func TestRuntimeSessionExportRepairPreservesOriginalAndUsesRecordedOwner(t *test } } +// TestRuntimeSessionExportRepairAcceptsAboveTheOldRenderCap proves a versioned +// repair uses the same larger bound as a normal export while leaving the +// original recorded evidence untouched. +func TestRuntimeSessionExportRepairAcceptsAboveTheOldRenderCap(t *testing.T) { + h, s, id := sessionExportRunner(t, "v2", func(stage.SessionExportRequest) (stage.SessionExportResult, error) { + return stage.SessionExportResult{}, errors.New("initial export unavailable") + }) + if err := s.ConfirmRecoveredSession(context.Background(), pipeline.SessionOwner{RunID: id, ID: "ses_run"}); err != nil { + t.Fatal(err) + } + original, err := s.GetRun(context.Background(), id) + if err != nil { + t.Fatal(err) + } + before, _ := json.Marshal(original.Steps[0].SessionExport) + size := int64(2<<20) + 4096 + h.runner.exportSession = func(_ context.Context, req stage.SessionExportRequest) (stage.SessionExportResult, error) { + if err := os.MkdirAll(req.ArtifactsDir, 0700); err != nil { + return stage.SessionExportResult{}, err + } + f, err := os.Create(filepath.Join(req.ArtifactsDir, req.FileName)) + if err != nil { + return stage.SessionExportResult{}, err + } + if err := f.Truncate(size); err != nil { + f.Close() + return stage.SessionExportResult{}, err + } + if err := f.Close(); err != nil { + return stage.SessionExportResult{}, err + } + return stage.SessionExportResult{Source: "native_export", HTML: req.FileName, HTMLBytes: size, Messages: 2}, nil + } + repaired, err := h.runner.repairSessionExport(context.Background(), id, 1) + if err != nil { + t.Fatal(err) + } + latest := repaired.Steps[0].SessionExportRepairs[0] + if latest.Status != "complete" || latest.HTMLBytes != size || latest.HTML == "" { + t.Fatalf("repair above the old cap was not complete: %+v", latest) + } + after, _ := json.Marshal(repaired.Steps[0].SessionExport) + if string(before) != string(after) { + t.Fatal("repair above the old cap overwrote original evidence") + } + info, err := os.Stat(filepath.Join(h.runner.artifactsRoot, "1", "stages", "01-"+repaired.Steps[0].Stage, latest.HTML)) + if err != nil || info.Size() != size { + t.Fatalf("repair file missing or resized: %v %+v", err, info) + } +} + func TestRuntimeRepairRejectsUnrecordedAndActiveVisits(t *testing.T) { h, _, id := sessionExportRunner(t, "v2", func(stage.SessionExportRequest) (stage.SessionExportResult, error) { return stage.SessionExportResult{}, errors.New("unavailable") diff --git a/internal/server/session_export_status_test.go b/internal/server/session_export_status_test.go index a1bae02a..10daae33 100644 --- a/internal/server/session_export_status_test.go +++ b/internal/server/session_export_status_test.go @@ -1,10 +1,13 @@ package server import ( - "git.a-wan.net/alan/pipelines/internal/protocol" "os" "path/filepath" + "strings" "testing" + + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/stage" ) func TestSessionExportCompleteness(t *testing.T) { @@ -56,3 +59,61 @@ func TestRuntimeSessionExportFileVerificationDoesNotClaimMissingEvidence(t *test }) } } + +func sizedSessionFile(t *testing.T, size int64) string { + t.Helper() + dir := t.TempDir() + path := filepath.Join(dir, "session.html") + f, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + if err := f.Truncate(size); err != nil { + f.Close() + t.Fatal(err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + return dir +} + +// TestRuntimeSessionExportVerificationAcceptsAboveTheOldRenderCap pins the +// ordinary-session case the previous 2 MiB rendered bound cut. The file is +// larger than that old cap and inside the artifact-aligned bound, so normal +// export verification must keep it and classify the evidence complete. +func TestRuntimeSessionExportVerificationAcceptsAboveTheOldRenderCap(t *testing.T) { + size := int64(2<<20) + 4096 + dir := sizedSessionFile(t, size) + evidence := &protocol.SessionExport{Source: "native_export", Messages: 2, HTML: "session.html", HTMLBytes: size} + verifySessionExportFile(evidence, dir) + classifySessionExport(evidence) + if evidence.Status != "complete" || evidence.HTML != "session.html" || evidence.HTMLBytes != size || evidence.Diagnostic != "" { + t.Fatalf("complete export above the old cap was rejected: %+v", evidence) + } +} + +// TestRuntimeSessionExportVerificationRejectsAboveTheNewCap confirms the larger +// bound is still a hard bound: an oversized file is not presented as evidence. +func TestRuntimeSessionExportVerificationRejectsAboveTheNewCap(t *testing.T) { + size := int64(stage.SessionExportFileLimit) + 1 + dir := sizedSessionFile(t, size) + evidence := &protocol.SessionExport{Source: "native_export", Messages: 2, HTML: "session.html", HTMLBytes: size} + verifySessionExportFile(evidence, dir) + classifySessionExport(evidence) + if evidence.Status != "partial" || evidence.HTML != "" || evidence.HTMLBytes != 0 || !strings.Contains(evidence.Diagnostic, "bounded verification") { + t.Fatalf("oversized export was not rejected as partial: %+v", evidence) + } +} + +// TestSessionExportFileLimitStaysInsideArtifactBounds keeps the render cap +// principled: larger than the cap that cut ordinary sessions, and no larger +// than the ordinary per-artifact file bound that serves the file. +func TestSessionExportFileLimitStaysInsideArtifactBounds(t *testing.T) { + if stage.SessionExportFileLimit <= 2<<20 { + t.Fatalf("render cap %d did not grow beyond the old 2 MiB cutoff", stage.SessionExportFileLimit) + } + if stage.SessionExportFileLimit > maxArtifactFileBytes { + t.Fatalf("render cap %d exceeds the artifact file bound %d", stage.SessionExportFileLimit, maxArtifactFileBytes) + } +} diff --git a/internal/stage/session_export.go b/internal/stage/session_export.go index 583602dd..f7562b2d 100644 --- a/internal/stage/session_export.go +++ b/internal/stage/session_export.go @@ -20,7 +20,7 @@ import ( // artifacts directory as one html file so the existing artifact listing and // serving paths find it with no special casing. The source read is capped at // SessionExportSourceLimit and the rendered file at SessionExportFileLimit, so -// the export adds at most ~2 MiB per step, inside the artifact scan limits. +// the export stays inside the server's per-artifact file bound. const ( // SessionHTMLFile is the one session export a stage writes. SessionHTMLFile = "session.html" @@ -32,8 +32,15 @@ const ( // SessionExportSourceLimit is the native session read cap; it is the one // opencode.MaxSessionExport value, not a second copy. SessionExportSourceLimit = opencode.MaxSessionExport - SessionExportFileLimit = 2 << 20 - SessionExportTimeout = 10 * time.Second + // SessionExportFileLimit is the rendered file cap. Ordinary native sessions + // commonly render a little larger than their raw source because html escaping + // and the readable projection duplicate native text; the previous 2 MiB cap + // cut complete sessions that were well inside the source bound. This cap + // matches the server's per-artifact file bound (maxArtifactFileBytes in + // internal/server/artifacts.go), so a complete export remains listed and + // served while a genuinely oversized one is still visibly truncated. + SessionExportFileLimit = 8 << 20 + SessionExportTimeout = 10 * time.Second ) // SessionExportRequest names the stage session to export and the evidence the @@ -255,7 +262,11 @@ func renderHTMLMessage(out *bytes.Buffer, index int, message opencode.ExportedMe fmt.Fprintf(out, "

id: %s | model: %s | agent: %s | created_at: %d

\n", html.EscapeString(message.ID), html.EscapeString(message.Model), html.EscapeString(message.Agent), message.CreatedAt) for _, part := range message.Parts { - renderHTMLPart(out, part) + if part.Type == protocol.ChatPartTool { + renderHTMLToolWithNativeRecord(out, part, message.Raw) + } else { + renderHTMLPart(out, part) + } } // The readable projection is not the complete native record: tools can // carry inline images and provider-specific metadata absent from ChatPart. @@ -290,6 +301,10 @@ func renderHTMLPart(out *bytes.Buffer, part opencode.ExportedPart) { // renderHTMLTool renders a tool call with its name, status, input, result and // error, escaping every value. func renderHTMLTool(out *bytes.Buffer, part opencode.ExportedPart) { + renderHTMLToolWithNativeRecord(out, part, nil) +} + +func renderHTMLToolWithNativeRecord(out *bytes.Buffer, part opencode.ExportedPart, native []byte) { name := part.Name if name == "" { name = part.ID @@ -309,7 +324,16 @@ func renderHTMLTool(out *bytes.Buffer, part opencode.ExportedPart) { if content.Text != "" { fmt.Fprintf(out, "
%s
\n", html.EscapeString(content.Text)) } else if content.URI != "" { - fmt.Fprintf(out, "

%s (%s)

\n", html.EscapeString(content.URI), html.EscapeString(content.Mime)) + // Inline screenshot/file data is already retained verbatim in the + // complete native record. Printing megabytes of base64 again as a + // paragraph adds no readable evidence and can truncate the whole + // audit. Summarize only when that exact payload is demonstrably in + // this message's native bytes; otherwise preserve the old full output. + if len(content.URI) >= 5 && strings.EqualFold(content.URI[:5], "data:") && bytes.Contains(native, []byte(content.URI)) { + fmt.Fprintf(out, "

Inline attachment (%s): complete payload retained in the native message below.

\n", html.EscapeString(content.Mime)) + } else { + fmt.Fprintf(out, "

%s (%s)

\n", html.EscapeString(content.URI), html.EscapeString(content.Mime)) + } } } if part.State.Error != nil { diff --git a/internal/stage/session_export_inline_test.go b/internal/stage/session_export_inline_test.go new file mode 100644 index 00000000..87249d51 --- /dev/null +++ b/internal/stage/session_export_inline_test.go @@ -0,0 +1,68 @@ +package stage + +import ( + "encoding/json" + "html" + "strconv" + "strings" + "testing" + + "git.a-wan.net/alan/pipelines/internal/opencode" + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +func inlineSession(uri string, native json.RawMessage) opencode.ExportedSession { + return opencode.ExportedSession{ID: "ses_inline", Backend: "v2", Messages: []opencode.ExportedMessage{{ + ID: "message_inline", Role: "assistant", Raw: native, + Parts: []opencode.ExportedPart{{Type: protocol.ChatPartTool, Name: "screenshot", State: &protocol.ChatToolState{ + Content: []protocol.ChatToolContent{{URI: uri, Mime: "image/png"}}, + }}}, + }}} +} + +func TestSessionExportRetainsLargeInlinePayloadOnceWithoutRaisingBounds(t *testing.T) { + uri := "data:image/png;base64," + strings.Repeat("A", 4<<20) + native, err := json.Marshal(map[string]any{"id": "message_inline", "image": uri, "future_field": "retained"}) + if err != nil { + t.Fatal(err) + } + doc, truncated := renderSessionHTML(inlineSession(uri, native), SessionExportRequest{}) + if truncated || len(doc) > SessionExportFileLimit { + t.Fatalf("complete native screenshot was truncated by duplicate projection: bytes=%d", len(doc)) + } + if strings.Count(doc, uri) != 1 || !strings.Contains(html.UnescapeString(doc), string(native)) { + t.Fatal("exact native payload was lost or duplicated") + } + if !strings.Contains(doc, "complete payload retained in the native message below") || strings.Contains(doc, "TRUNCATED") { + t.Fatal("inline projection did not accurately describe retained complete evidence") + } +} + +func TestSessionExportNeverSummarizesInlinePayloadAbsentFromNativeRecord(t *testing.T) { + uri := "data:image/png;base64,AAAA" + for _, native := range []json.RawMessage{nil, json.RawMessage(`{"unrelated":"record"}`)} { + doc, truncated := renderSessionHTML(inlineSession(uri, native), SessionExportRequest{}) + if truncated || !strings.Contains(doc, uri) || strings.Contains(doc, "class=\"inline-attachment\"") { + t.Fatal("inline payload without a complete native copy was omitted") + } + } +} + +func TestSessionExportInlineProjectionDoesNotCreateExecutableMarkup(t *testing.T) { + uri := `data:text/html,` + native, err := json.Marshal(map[string]string{"attachment": uri}) + if err != nil { + t.Fatal(err) + } + // Cover both escaped and unescaped native JSON encodings: only the latter + // contains the literal URI and therefore takes the new summary path. + plain := json.RawMessage(`{"attachment":` + strconv.Quote(uri) + `}`) + for _, raw := range []json.RawMessage{native, plain} { + session := inlineSession(uri, raw) + session.Messages[0].Parts[0].State.Content[0].Mime = `image/png">` + doc, _ := renderSessionHTML(session, SessionExportRequest{}) + if strings.Contains(doc, "