Merge branch 'main' into flutter/p1-pipelines
This commit is contained in:
+5
-1
@@ -45,6 +45,10 @@ app.*.map.json
|
||||
/android/app/release
|
||||
|
||||
# The repository ignores runtime data/ directories. Feature repository source
|
||||
# is code, not runtime data, and must be included in fresh checkouts.
|
||||
# and its mirroring tests are code, not runtime data, and must be included in
|
||||
# fresh checkouts. The test negation is required too: without it every
|
||||
# `test/**/data/` directory is silently dropped from the candidate.
|
||||
!/lib/**/data/
|
||||
!/lib/**/data/**
|
||||
!/test/**/data/
|
||||
!/test/**/data/**
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
- Standard Material and Cupertino controls, including buttons/menus in custom graphs/diffs/chat. System typography, theme colors, light/dark, content-driven layout and text scaling. No fixed row/bubble/button dimensions, bespoke palette or CSS token port. Platform differences are intentional. Centralize necessary layout constraints; do not ban legitimate native default spacing or graph coordinates.
|
||||
- Develop and test ONLY web now. No ADB, emulators, device changes, Android/iOS builds or installs. Keep source portable to all three targets. Explicitly report mobile as unverified.
|
||||
- Small cohesive files (aim below 250 lines; split by responsibility, not arbitrary fragments). Each task owns a directory and its tests. Do not edit another lane or root pubspec/main unless assigned.
|
||||
- Code quality is a delivery requirement. No minified implementations, silent capability fallbacks, fake data masking missing features, or workarounds that bypass the real defect. A pipeline success does not waive missing behavior, native controls, regression coverage or rendered evidence. Label incomplete work honestly and complete it before claiming parity.
|
||||
- The manager drives authorized routine integration and recovery without repeatedly stopping for permission. Feature implementation stays in pipelines where appropriate; infrastructure blockers can be resolved directly within the user's authorized scope. Verify quiescence, preserve data and rollback, act, and report actual results. Ask only for genuinely new scope or unresolved destructive choices.
|
||||
|
||||
## Shared contract
|
||||
- `lib/core/api_gateway.dart`: `JsonMap` alias; `ApiGateway.call(type, [fields])` yields the entire decoded reply envelope; `frames` yields unsolicited server envelopes. Gateway owns request IDs. Do not put domain interpretation in transport.
|
||||
|
||||
+245
-5
@@ -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
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../shell/adaptive_shell.dart';
|
||||
import '../shell/destination.dart';
|
||||
|
||||
/// The injectable application shell. Composition supplies the live feature
|
||||
/// bodies and, when it owns a route, the selected destination; widget tests
|
||||
/// can continue to pass a small map or no bodies at all.
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({
|
||||
super.key,
|
||||
this.destinationBodies = const {},
|
||||
this.cupertino,
|
||||
this.destination,
|
||||
this.onDestinationSelected,
|
||||
}) : routerConfig = null;
|
||||
|
||||
/// A host for a [Router]-owned location, so browser Back/Forward and deep
|
||||
/// links use Flutter's multi-entry web history instead of a second, competing
|
||||
/// history implementation.
|
||||
const MyApp.router({
|
||||
super.key,
|
||||
required RouterConfig<Object> this.routerConfig,
|
||||
this.cupertino,
|
||||
}) : destinationBodies = const {},
|
||||
destination = null,
|
||||
onDestinationSelected = null;
|
||||
|
||||
final Map<AppDestination, WidgetBuilder> destinationBodies;
|
||||
final bool? cupertino;
|
||||
final AppDestination? destination;
|
||||
final ValueChanged<AppDestination>? onDestinationSelected;
|
||||
final RouterConfig<Object>? routerConfig;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final router = routerConfig;
|
||||
if (cupertino ?? _platformIsCupertino) {
|
||||
if (router != null) {
|
||||
return CupertinoApp.router(title: 'Pipelines', routerConfig: router);
|
||||
}
|
||||
return CupertinoApp(
|
||||
title: 'Pipelines',
|
||||
home: AdaptiveShell(
|
||||
destinationBodies: destinationBodies,
|
||||
cupertino: true,
|
||||
destination: destination,
|
||||
onDestinationSelected: onDestinationSelected,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (router != null) {
|
||||
return MaterialApp.router(
|
||||
title: 'Pipelines',
|
||||
theme: ThemeData(),
|
||||
darkTheme: ThemeData(brightness: Brightness.dark),
|
||||
themeMode: ThemeMode.system,
|
||||
routerConfig: router,
|
||||
);
|
||||
}
|
||||
return MaterialApp(
|
||||
title: 'Pipelines',
|
||||
theme: ThemeData(),
|
||||
darkTheme: ThemeData(brightness: Brightness.dark),
|
||||
themeMode: ThemeMode.system,
|
||||
home: AdaptiveShell(
|
||||
destinationBodies: destinationBodies,
|
||||
destination: destination,
|
||||
onDestinationSelected: onDestinationSelected,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
bool get _platformIsCupertino =>
|
||||
defaultTargetPlatform == TargetPlatform.iOS ||
|
||||
defaultTargetPlatform == TargetPlatform.macOS;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/// The destinations the app has a URL for.
|
||||
///
|
||||
/// The set mirrors [AppDestination] but stays free of widget imports so the
|
||||
/// parser and serialiser can be exercised without a Flutter host.
|
||||
enum AppRouteKind { pipelines, runs, chat, settings }
|
||||
|
||||
/// One page route: a destination plus the run it opens, if any.
|
||||
///
|
||||
/// Parsing is total, like the web client's route model: an unknown or
|
||||
/// malformed path resolves to the default Pipelines list instead of throwing.
|
||||
/// The serialiser is its inverse for every route the app can produce.
|
||||
class AppRoute {
|
||||
const AppRoute(this.kind, {this.runId});
|
||||
|
||||
static const pipelines = AppRoute(AppRouteKind.pipelines);
|
||||
static const runs = AppRoute(AppRouteKind.runs);
|
||||
static const chat = AppRoute(AppRouteKind.chat);
|
||||
static const settings = AppRoute(AppRouteKind.settings);
|
||||
|
||||
static const run = _RunRouteFactory();
|
||||
|
||||
final AppRouteKind kind;
|
||||
|
||||
/// The run shown by the Runs destination, or null for the list.
|
||||
final int? runId;
|
||||
|
||||
/// The path the app writes into history for this route.
|
||||
String get path => switch (kind) {
|
||||
AppRouteKind.pipelines => '/pipelines',
|
||||
AppRouteKind.runs => runId == null ? '/runs' : '/runs/$runId',
|
||||
AppRouteKind.chat => '/chat',
|
||||
AppRouteKind.settings => '/settings',
|
||||
};
|
||||
|
||||
/// Parses a browser pathname (or a full URL) into a route.
|
||||
///
|
||||
/// `/runs/abc` and other malformed details are the default route, matching
|
||||
/// the web parser; `/pipelines/` and other trailing slashes are normalised.
|
||||
static AppRoute parse(String location) {
|
||||
var path = location.trim();
|
||||
if (path.isEmpty) return pipelines;
|
||||
if (path.contains('://')) {
|
||||
final uri = Uri.tryParse(path);
|
||||
if (uri == null) return pipelines;
|
||||
path = uri.path;
|
||||
}
|
||||
final hash = path.indexOf('#');
|
||||
if (hash != -1) path = path.substring(0, hash);
|
||||
final query = path.indexOf('?');
|
||||
if (query != -1) path = path.substring(0, query);
|
||||
|
||||
final segments = <String>[];
|
||||
for (final raw in path.split('/')) {
|
||||
if (raw.isEmpty) continue;
|
||||
try {
|
||||
segments.add(Uri.decodeComponent(raw));
|
||||
} on ArgumentError {
|
||||
return pipelines;
|
||||
}
|
||||
}
|
||||
if (segments.isEmpty) return pipelines;
|
||||
|
||||
return switch (segments.first) {
|
||||
'pipelines' when segments.length == 1 => pipelines,
|
||||
'runs' when segments.length == 1 => runs,
|
||||
'runs' when segments.length == 2 => _runRoute(segments[1]),
|
||||
'chat' when segments.length == 1 => chat,
|
||||
'settings' when segments.length == 1 => settings,
|
||||
_ => pipelines,
|
||||
};
|
||||
}
|
||||
|
||||
static AppRoute _runRoute(String value) {
|
||||
if (!RegExp(r'^[0-9]+$').hasMatch(value)) return pipelines;
|
||||
final id = int.tryParse(value);
|
||||
if (id == null || id <= 0) return pipelines;
|
||||
return AppRoute(AppRouteKind.runs, runId: id);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is AppRoute && other.kind == kind && other.runId == runId;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(kind, runId);
|
||||
|
||||
@override
|
||||
String toString() => path;
|
||||
}
|
||||
|
||||
/// `AppRoute.run(3)` reads better than a constructor named after a field.
|
||||
class _RunRouteFactory {
|
||||
const _RunRouteFactory();
|
||||
|
||||
AppRoute call(int id) => AppRoute(AppRouteKind.runs, runId: id);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'app_route.dart';
|
||||
|
||||
/// Parses the browser (or platform) location into the app's routes.
|
||||
class AppRouteParser extends RouteInformationParser<AppRoute> {
|
||||
const AppRouteParser();
|
||||
|
||||
@override
|
||||
Future<AppRoute> parseRouteInformation(
|
||||
RouteInformation routeInformation,
|
||||
) async => AppRoute.parse(routeInformation.uri.path);
|
||||
|
||||
@override
|
||||
RouteInformation restoreRouteInformation(AppRoute configuration) =>
|
||||
RouteInformation(uri: Uri(path: configuration.path));
|
||||
}
|
||||
|
||||
/// Owns the app's current route and builds the shell for it.
|
||||
///
|
||||
/// Route changes made by the operator go through [goTo]; the Router reports
|
||||
/// them as browser history entries. Browser Back/Forward and deep links arrive
|
||||
/// through [setNewRoutePath] and update the same route.
|
||||
class AppRouterDelegate extends RouterDelegate<AppRoute> with ChangeNotifier {
|
||||
AppRouterDelegate({
|
||||
required this.builder,
|
||||
required this.onPopToRuns,
|
||||
required this.cupertino,
|
||||
AppRoute initial = AppRoute.pipelines,
|
||||
}) : _route = initial;
|
||||
|
||||
final Widget Function(BuildContext context, AppRoute route) builder;
|
||||
|
||||
/// Called when a system Back belongs to the Runs detail, not the app stack.
|
||||
final VoidCallback onPopToRuns;
|
||||
|
||||
final bool cupertino;
|
||||
|
||||
final _navigatorKey = GlobalKey<NavigatorState>();
|
||||
static const _pageKey = ValueKey<String>('pipelines-shell');
|
||||
|
||||
AppRoute _route;
|
||||
|
||||
AppRoute get route => _route;
|
||||
|
||||
@override
|
||||
AppRoute get currentConfiguration => _route;
|
||||
|
||||
/// A single-page Navigator supplies the Overlay, overlay portals and route
|
||||
/// context that native controls (action sheets, tooltips) require. The page
|
||||
/// key is stable, so changing the route updates the shell in place instead of
|
||||
/// remounting it and losing the open run.
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final child = builder(context, _route);
|
||||
return Navigator(
|
||||
key: _navigatorKey,
|
||||
pages: [
|
||||
if (cupertino)
|
||||
CupertinoPage<void>(key: _pageKey, child: child)
|
||||
else
|
||||
MaterialPage<void>(key: _pageKey, child: child),
|
||||
],
|
||||
onDidRemovePage: (_) {},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setInitialRoutePath(AppRoute configuration) async {
|
||||
_route = configuration;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setNewRoutePath(AppRoute configuration) async {
|
||||
if (configuration == _route) return;
|
||||
_route = configuration;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> popRoute() async {
|
||||
if (_route.runId == null) return false;
|
||||
onPopToRuns();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Records a user move; the Router turns the new configuration into a
|
||||
/// history entry (or a replacement when it already matches the location).
|
||||
void goTo(AppRoute route) {
|
||||
if (route == _route) return;
|
||||
_route = route;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
/// The location a web launch starts at, or the Pipelines list elsewhere.
|
||||
///
|
||||
/// Only the path is meaningful to [AppRouteParser]; the origin stays out of
|
||||
/// route configuration so a serialised route is always app-relative.
|
||||
RouteInformation initialRouteInformation() {
|
||||
if (!kIsWeb) return RouteInformation(uri: Uri(path: '/pipelines'));
|
||||
final path = Uri.base.path;
|
||||
return RouteInformation(uri: Uri(path: path.isEmpty ? '/' : path));
|
||||
}
|
||||
@@ -0,0 +1,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<ConnectionState> _states;
|
||||
late final StreamSubscription<JsonMap> _frames;
|
||||
ConnectionState _connection = const ConnectionState(ConnectionKind.idle);
|
||||
bool _subscribed = false, _disposed = false, _everConnected = false;
|
||||
int _connectionEpoch = 0;
|
||||
RunSubscriptionState _subscription = RunSubscriptionState.pending;
|
||||
String _subscriptionError = '';
|
||||
String? _subscribeRequest;
|
||||
|
||||
ApiGateway get gateway => _client;
|
||||
|
||||
/// 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<void> start() async {
|
||||
if (_disposed || endpoint == null) return;
|
||||
await _client.connect(endpoint!);
|
||||
}
|
||||
|
||||
/// Retries now: reopens a disconnected socket, or repeats a refused watch on
|
||||
/// a healthy one.
|
||||
Future<void> retry() async {
|
||||
if (_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<void> stop() async {
|
||||
if (_disposed) return;
|
||||
_sendUnsubscribe();
|
||||
await _client.disconnect();
|
||||
}
|
||||
|
||||
void _onState(ConnectionState state) {
|
||||
if (_disposed) return;
|
||||
final wasConnected = connected;
|
||||
_connection = state;
|
||||
if (state.kind == ConnectionKind.connected) {
|
||||
_everConnected = true;
|
||||
_connectionEpoch++;
|
||||
_subscription = RunSubscriptionState.pending;
|
||||
_subscriptionError = '';
|
||||
_subscribe();
|
||||
} else if (wasConnected) {
|
||||
_subscribed = false;
|
||||
_subscribeRequest = null;
|
||||
_subscription = RunSubscriptionState.pending;
|
||||
_subscriptionError = '';
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _onFrame(JsonMap frame) {
|
||||
if (_disposed) return;
|
||||
final id = frame['id'];
|
||||
if (id is! String || id != _subscribeRequest) return;
|
||||
switch (frame['type']) {
|
||||
case 'subscribe':
|
||||
_subscription = RunSubscriptionState.live;
|
||||
_subscriptionError = '';
|
||||
break;
|
||||
case 'error':
|
||||
_subscription = RunSubscriptionState.refused;
|
||||
final reason = '${frame['error'] ?? ''}'.trim();
|
||||
_subscriptionError = reason.isEmpty
|
||||
? 'Live run updates are unavailable.'
|
||||
: reason;
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _subscribe() {
|
||||
if (_subscribed || !connected) return;
|
||||
try {
|
||||
_subscribeRequest = _client.sendOnly('subscribe', const {
|
||||
'workspace': '',
|
||||
});
|
||||
_subscribed = true;
|
||||
} on NotConnectedError {
|
||||
// A close raced the connected state; the next connected transition
|
||||
// subscribes instead of leaving a half-registered watch.
|
||||
}
|
||||
}
|
||||
|
||||
void _sendUnsubscribe() {
|
||||
if (!_subscribed) return;
|
||||
_subscribed = false;
|
||||
_subscribeRequest = null;
|
||||
if (!connected) return;
|
||||
try {
|
||||
_client.sendOnly('unsubscribe');
|
||||
} on NotConnectedError {
|
||||
// The socket already closed, which drops the watch server-side.
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_sendUnsubscribe();
|
||||
unawaited(_states.cancel());
|
||||
unawaited(_frames.cancel());
|
||||
unawaited(_client.dispose());
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import 'app_url_strategy_stub.dart'
|
||||
if (dart.library.js_interop) 'app_url_strategy_web.dart'
|
||||
as platform;
|
||||
|
||||
/// Chooses the URL form the app's routes use.
|
||||
///
|
||||
/// Web serves real paths (`/runs/1`) so a route can be bookmarked, opened
|
||||
/// directly and handled by browser Back/Forward; other platforms keep their
|
||||
/// in-memory route state.
|
||||
void useAppUrlStrategy() => platform.useAppUrlStrategy();
|
||||
@@ -0,0 +1 @@
|
||||
void useAppUrlStrategy() {}
|
||||
@@ -0,0 +1,3 @@
|
||||
import 'package:flutter_web_plugins/url_strategy.dart';
|
||||
|
||||
void useAppUrlStrategy() => usePathUrlStrategy();
|
||||
@@ -0,0 +1,20 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import 'app_url_strategy.dart';
|
||||
import 'pipelines_app.dart';
|
||||
import 'server_endpoint.dart';
|
||||
|
||||
/// Native builds must supply their server explicitly; there is no baked host.
|
||||
const configuredServerUrl = String.fromEnvironment('PIPELINES_SERVER_URL');
|
||||
|
||||
/// Resolves the endpoint for this launch and starts the normal composition.
|
||||
void runPipelinesApp({Uri? base, String configured = configuredServerUrl}) {
|
||||
useAppUrlStrategy();
|
||||
final server = ServerEndpoint.resolve(
|
||||
base: base ?? Uri.base,
|
||||
web: kIsWeb,
|
||||
configured: configured,
|
||||
);
|
||||
runApp(PipelinesApp(server: server));
|
||||
}
|
||||
@@ -0,0 +1,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<PipelinesApp> createState() => _PipelinesAppState();
|
||||
}
|
||||
|
||||
class _PipelinesAppState extends State<PipelinesApp> {
|
||||
late final AppSession _session;
|
||||
late final AppRouterDelegate _delegate;
|
||||
late final RouteInformationProvider _provider;
|
||||
late final bool _ownsProvider;
|
||||
late final RouterConfig<AppRoute> _config;
|
||||
late final bool _cupertino;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_session = AppSession(endpoint: widget.server.uri, client: widget.client);
|
||||
_ownsProvider = widget.routeInformationProvider == null;
|
||||
_provider =
|
||||
widget.routeInformationProvider ??
|
||||
PlatformRouteInformationProvider(
|
||||
initialRouteInformation: initialRouteInformation(),
|
||||
);
|
||||
// A malformed or unknown boot path renders Pipelines, so make the address
|
||||
// bar agree with the rendered destination instead of showing a dead link.
|
||||
final initial = AppRoute.parse(_provider.value.uri.path);
|
||||
if (_provider.value.uri.path != initial.path) {
|
||||
_provider.routerReportsNewRouteInformation(
|
||||
RouteInformation(uri: Uri(path: initial.path)),
|
||||
type: RouteInformationReportingType.neglect,
|
||||
);
|
||||
}
|
||||
_cupertino = widget.cupertino ?? _platformIsCupertino;
|
||||
_delegate = AppRouterDelegate(
|
||||
initial: initial,
|
||||
cupertino: _cupertino,
|
||||
onPopToRuns: () => _delegate.goTo(AppRoute.runs),
|
||||
builder: _buildShell,
|
||||
);
|
||||
_config = RouterConfig<AppRoute>(
|
||||
routeInformationParser: const AppRouteParser(),
|
||||
routerDelegate: _delegate,
|
||||
routeInformationProvider: _provider,
|
||||
);
|
||||
unawaited(_session.start());
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_delegate.dispose();
|
||||
if (_ownsProvider) {
|
||||
(_provider as PlatformRouteInformationProvider).dispose();
|
||||
}
|
||||
_session.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) =>
|
||||
MyApp.router(cupertino: _cupertino, routerConfig: _config);
|
||||
|
||||
Widget _buildShell(BuildContext context, AppRoute route) => AdaptiveShell(
|
||||
cupertino: _cupertino,
|
||||
destination: _destinationOf(route.kind),
|
||||
onDestinationSelected: (destination) =>
|
||||
_delegate.goTo(_routeOf(destination)),
|
||||
destinationBodies: {
|
||||
AppDestination.runs: (_) => RunsDestination(
|
||||
session: _session,
|
||||
server: widget.server,
|
||||
initialRunId: route.runId,
|
||||
onRunSelected: (id) => _delegate.goTo(AppRoute.run(id)),
|
||||
onBack: () => _delegate.goTo(AppRoute.runs),
|
||||
),
|
||||
AppDestination.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;
|
||||
}
|
||||
@@ -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<int>? onRunSelected;
|
||||
final VoidCallback? onBack;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => AnimatedBuilder(
|
||||
animation: session,
|
||||
builder: (context, _) {
|
||||
final cupertino = usesCupertinoHost(context);
|
||||
if ((server.requiresConfiguration || server.error != null) &&
|
||||
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')),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import '../core/transport/server_url.dart';
|
||||
|
||||
/// The single endpoints decision for an app launch.
|
||||
///
|
||||
/// A web build is served by the Pipelines proxy itself, so its own page origin
|
||||
/// is the only endpoint it may use: the browser reaches the same host over
|
||||
/// ws(s) at `/connect`. A native build has no trustworthy origin and must be
|
||||
/// given an explicit endpoint at build time; there is no default host.
|
||||
class ServerEndpoint {
|
||||
const ServerEndpoint._({
|
||||
this.uri,
|
||||
this.error,
|
||||
this.requiresConfiguration = false,
|
||||
});
|
||||
|
||||
/// Validated websocket endpoint, or null when configuration is missing or
|
||||
/// invalid. Never a guessed fallback.
|
||||
final Uri? uri;
|
||||
|
||||
/// Why no endpoint could be resolved, shown verbatim by the connection gate.
|
||||
final String? error;
|
||||
|
||||
/// Native builds without an explicit endpoint. This is a configuration
|
||||
/// state, not a server error, so the gate can explain the required setting.
|
||||
final bool requiresConfiguration;
|
||||
|
||||
static ServerEndpoint resolve({
|
||||
required Uri base,
|
||||
required bool web,
|
||||
String configured = '',
|
||||
}) {
|
||||
if (web) {
|
||||
if ((base.scheme != 'http' && base.scheme != 'https') ||
|
||||
base.host.isEmpty) {
|
||||
return const ServerEndpoint._(
|
||||
error:
|
||||
'The Pipelines endpoint is inferred from the page URL, '
|
||||
'which is not HTTP(S).',
|
||||
);
|
||||
}
|
||||
final secure = base.scheme == 'https';
|
||||
final sameOrigin = Uri(
|
||||
scheme: secure ? 'wss' : 'ws',
|
||||
host: base.host,
|
||||
port: base.hasPort ? base.port : null,
|
||||
path: '/connect',
|
||||
);
|
||||
return _validated(sameOrigin);
|
||||
}
|
||||
final value = configured.trim();
|
||||
if (value.isEmpty) {
|
||||
return const ServerEndpoint._(requiresConfiguration: true);
|
||||
}
|
||||
return _validated(Uri.tryParse(value) ?? Uri());
|
||||
}
|
||||
|
||||
static ServerEndpoint _validated(Uri value) {
|
||||
try {
|
||||
final endpoint = ServerUrl.validate(value.toString());
|
||||
return ServerEndpoint._(uri: Uri.parse(endpoint.wsUrl));
|
||||
} on FormatException catch (error) {
|
||||
return ServerEndpoint._(error: error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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';
|
||||
}
|
||||
@@ -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<JsonMap>.broadcast();
|
||||
final _states = StreamController<ConnectionState>.broadcast();
|
||||
final Map<String, Completer<JsonMap>> _pending = {};
|
||||
WebSocketChannel? _channel;
|
||||
StreamSubscription<dynamic>? _subscription;
|
||||
Uri? _endpoint;
|
||||
Timer? _reconnect;
|
||||
int _generation = 0, _sequence = 0, _attempt = 0;
|
||||
bool _manual = true, _disposed = false;
|
||||
ConnectionState _state = const ConnectionState(ConnectionKind.idle);
|
||||
Future<void> _queue = Future.value();
|
||||
|
||||
@override
|
||||
Stream<JsonMap> get frames => _frames.stream;
|
||||
Stream<ConnectionState> get states => _states.stream;
|
||||
ConnectionState get state => _state;
|
||||
|
||||
/// Last validated endpoint, including changes made through native Settings.
|
||||
Uri? get endpoint => _endpoint;
|
||||
|
||||
Future<void> 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<void> _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<JsonMap> call(String type, [JsonMap fields = const {}]) {
|
||||
final completer = Completer<JsonMap>();
|
||||
final generation = _generation;
|
||||
final snapshot = Map<String, dynamic>.of(fields);
|
||||
final run = _queue.then(
|
||||
(_) => _sendCall(type, snapshot, completer, generation),
|
||||
);
|
||||
_queue = run.catchError((_) {});
|
||||
return completer.future;
|
||||
}
|
||||
|
||||
Future<void> _sendCall(
|
||||
String type,
|
||||
JsonMap fields,
|
||||
Completer<JsonMap> 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<void>(
|
||||
(_) => 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<String, dynamic>) 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<void> 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<void> dispose() async {
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
await disconnect();
|
||||
await _frames.close();
|
||||
await _states.close();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'artifact_record.dart';
|
||||
|
||||
/// Whether a step actually carried an artifact list.
|
||||
///
|
||||
/// An absent (or null) field means the capture is unavailable: an older step, a
|
||||
/// running visit, or a reply that did not include the field. It must never be
|
||||
/// reported as an empty capture. An explicitly recorded empty list is a known,
|
||||
/// empty capture.
|
||||
enum ArtifactCaptureAvailability { unavailable, recorded }
|
||||
|
||||
/// The recorded capture facts of one step: availability, files, and how many
|
||||
/// files the bounded scan excluded or omitted. Pure: it reads the step and adds
|
||||
/// no server call.
|
||||
class ArtifactCapture {
|
||||
const ArtifactCapture._({
|
||||
required this.availability,
|
||||
required this.artifacts,
|
||||
required this.skipped,
|
||||
required this.truncated,
|
||||
});
|
||||
|
||||
factory ArtifactCapture.fromStep(JsonMap step) {
|
||||
final value = step['artifacts'];
|
||||
final available = step.containsKey('artifacts') && value is List;
|
||||
final artifacts = available
|
||||
? <ArtifactRecord>[
|
||||
for (final item in value)
|
||||
if (item is Map)
|
||||
ArtifactRecord.fromJson(Map<String, dynamic>.from(item)),
|
||||
]
|
||||
: const <ArtifactRecord>[];
|
||||
return ArtifactCapture._(
|
||||
availability: available
|
||||
? ArtifactCaptureAvailability.recorded
|
||||
: ArtifactCaptureAvailability.unavailable,
|
||||
artifacts: List<ArtifactRecord>.unmodifiable(artifacts),
|
||||
skipped: _countOf(step['artifacts_skipped']),
|
||||
truncated: _countOf(step['artifacts_truncated']),
|
||||
);
|
||||
}
|
||||
|
||||
final ArtifactCaptureAvailability availability;
|
||||
|
||||
/// Every recorded file, including utility and retired files.
|
||||
final List<ArtifactRecord> artifacts;
|
||||
|
||||
/// Files excluded from the bounded per-step scan.
|
||||
final int skipped;
|
||||
|
||||
/// Files omitted by the capture's total budget.
|
||||
final int truncated;
|
||||
|
||||
bool get isAvailable => availability == ArtifactCaptureAvailability.recorded;
|
||||
|
||||
bool get isPartial => skipped > 0 || truncated > 0;
|
||||
|
||||
static int _countOf(dynamic value) {
|
||||
if (value is num) return value.toInt();
|
||||
if (value is String) return int.tryParse(value.trim()) ?? 0;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../graph/domain/stage_visits.dart';
|
||||
import 'artifact_record.dart';
|
||||
import 'artifact_selection.dart';
|
||||
|
||||
/// One gallery group: the stage-produced artifacts of a recorded stage visit.
|
||||
class ArtifactGroup {
|
||||
const ArtifactGroup({
|
||||
required this.stageKey,
|
||||
required this.visit,
|
||||
required this.artifacts,
|
||||
});
|
||||
|
||||
final String stageKey;
|
||||
|
||||
/// The display visit number: `control.visit` when positive, else the position
|
||||
/// within the stage's ordered visits. Never a synthetic visit.
|
||||
final int visit;
|
||||
|
||||
final List<ArtifactRecord> artifacts;
|
||||
}
|
||||
|
||||
int _sequenceOf(JsonMap step) {
|
||||
final sequence = step['sequence'];
|
||||
return sequence is num ? sequence.toInt() : 0;
|
||||
}
|
||||
|
||||
/// Sequence order with recorded order as the tie-break, matching the web
|
||||
/// client's stable sort.
|
||||
List<JsonMap> _orderedBySequence(List<JsonMap> steps) {
|
||||
final indexed = <({int position, JsonMap step})>[
|
||||
for (var index = 0; index < steps.length; index += 1)
|
||||
(position: index, step: steps[index]),
|
||||
];
|
||||
indexed.sort((a, b) {
|
||||
final bySequence = _sequenceOf(a.step).compareTo(_sequenceOf(b.step));
|
||||
return bySequence != 0 ? bySequence : a.position.compareTo(b.position);
|
||||
});
|
||||
return <JsonMap>[for (final entry in indexed) entry.step];
|
||||
}
|
||||
|
||||
/// Groups a run's stage artifacts by stage and recorded visit.
|
||||
///
|
||||
/// Stages keep first-appearance order and each stage's visits are ordered by
|
||||
/// sequence. A shared `public/` file is attributed to the visit that first
|
||||
/// recorded it, because the server records the whole public directory on every
|
||||
/// model visit. Only visits with at least one presented stage artifact produce a
|
||||
/// group, so an unavailable or empty capture never yields an empty group. An
|
||||
/// artifact-less run yields an empty list rather than a fabricated stage.
|
||||
List<ArtifactGroup> artifactGroups(List<JsonMap> steps) {
|
||||
if (steps.isEmpty) return const <ArtifactGroup>[];
|
||||
|
||||
final attributed = <JsonMap, List<ArtifactRecord>>{};
|
||||
final seenPublic = <String>{};
|
||||
for (final recordedStep in _orderedBySequence(steps)) {
|
||||
final repairs = repairArtifactNames(recordedStep);
|
||||
final kept = <ArtifactRecord>[];
|
||||
for (final artifact in stageArtifactsFrom(
|
||||
artifactsOf(recordedStep),
|
||||
repairs: repairs,
|
||||
)) {
|
||||
if (artifact.isPublicName) {
|
||||
if (seenPublic.contains(artifact.name)) continue;
|
||||
seenPublic.add(artifact.name);
|
||||
}
|
||||
kept.add(artifact);
|
||||
}
|
||||
attributed[recordedStep] = List<ArtifactRecord>.unmodifiable(kept);
|
||||
}
|
||||
|
||||
final groups = <ArtifactGroup>[];
|
||||
for (final entry in visitsByStage(steps).entries) {
|
||||
final visits = entry.value;
|
||||
for (var index = 0; index < visits.length; index += 1) {
|
||||
final artifacts = attributed[visits[index]];
|
||||
if (artifacts == null || artifacts.isEmpty) continue;
|
||||
groups.add(
|
||||
ArtifactGroup(
|
||||
stageKey: entry.key,
|
||||
visit: displayVisit(visits[index], index),
|
||||
artifacts: artifacts,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
return List<ArtifactGroup>.unmodifiable(groups);
|
||||
}
|
||||
|
||||
/// One visit's stage artifacts, excluding shared public files that an earlier
|
||||
/// visit already recorded. A repeated non-public name in a later visit stays
|
||||
/// because it is a different recorded artifact, not the same shared file.
|
||||
List<ArtifactRecord> visitArtifacts(JsonMap step, List<JsonMap> runSteps) {
|
||||
final all = stageArtifacts(step);
|
||||
if (runSteps.isEmpty) return all;
|
||||
final seen = <String>{};
|
||||
for (final candidate in _orderedBySequence(runSteps)) {
|
||||
if (identical(candidate, step) ||
|
||||
_sequenceOf(candidate) == _sequenceOf(step)) {
|
||||
break;
|
||||
}
|
||||
for (final artifact in stageArtifacts(candidate)) {
|
||||
if (artifact.isPublicName) seen.add(artifact.name);
|
||||
}
|
||||
}
|
||||
return <ArtifactRecord>[
|
||||
for (final artifact in all)
|
||||
if (!artifact.isPublicName || !seen.contains(artifact.name)) artifact,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
/// What an artifact is from the gallery's point of view: the two media kinds it
|
||||
/// previews and the file kinds it labels with a type word. Mirrors the web
|
||||
/// client's `ArtifactKind` vocabulary.
|
||||
enum ArtifactKind {
|
||||
image,
|
||||
video,
|
||||
audio,
|
||||
pdf,
|
||||
json,
|
||||
archive,
|
||||
spreadsheet,
|
||||
log,
|
||||
code,
|
||||
document,
|
||||
other,
|
||||
}
|
||||
|
||||
const Set<String> _archiveExtensions = <String>{
|
||||
'zip',
|
||||
'tar',
|
||||
'gz',
|
||||
'tgz',
|
||||
'bz2',
|
||||
'xz',
|
||||
'rar',
|
||||
'7z',
|
||||
'jar',
|
||||
'war',
|
||||
};
|
||||
|
||||
const Set<String> _archiveMimes = <String>{
|
||||
'application/zip',
|
||||
'application/gzip',
|
||||
'application/x-tar',
|
||||
'application/x-7z-compressed',
|
||||
'application/x-rar-compressed',
|
||||
'application/java-archive',
|
||||
};
|
||||
|
||||
const Set<String> _spreadsheetExtensions = <String>{
|
||||
'csv',
|
||||
'tsv',
|
||||
'xls',
|
||||
'xlsx',
|
||||
'ods',
|
||||
};
|
||||
|
||||
const Set<String> _spreadsheetMimes = <String>{
|
||||
'text/csv',
|
||||
'text/tab-separated-values',
|
||||
'application/vnd.ms-excel',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
};
|
||||
|
||||
const Set<String> _codeExtensions = <String>{
|
||||
'kt',
|
||||
'kts',
|
||||
'java',
|
||||
'go',
|
||||
'py',
|
||||
'rb',
|
||||
'php',
|
||||
'rs',
|
||||
'c',
|
||||
'h',
|
||||
'cc',
|
||||
'cpp',
|
||||
'hpp',
|
||||
'cs',
|
||||
'js',
|
||||
'jsx',
|
||||
'ts',
|
||||
'tsx',
|
||||
'mjs',
|
||||
'cjs',
|
||||
'swift',
|
||||
'scala',
|
||||
'sh',
|
||||
'bash',
|
||||
'zsh',
|
||||
'fish',
|
||||
'ps1',
|
||||
'sql',
|
||||
'yaml',
|
||||
'yml',
|
||||
'toml',
|
||||
'ini',
|
||||
'xml',
|
||||
'gradle',
|
||||
'properties',
|
||||
'proto',
|
||||
};
|
||||
|
||||
const Set<String> _codeMimes = <String>{
|
||||
'application/xml',
|
||||
'application/x-yaml',
|
||||
'application/javascript',
|
||||
'text/javascript',
|
||||
'text/x-python',
|
||||
'text/x-java-source',
|
||||
'text/x-kotlin',
|
||||
'application/x-sh',
|
||||
'application/x-httpd-php',
|
||||
'application/sql',
|
||||
};
|
||||
|
||||
const Set<String> _documentExtensions = <String>{
|
||||
'txt',
|
||||
'md',
|
||||
'markdown',
|
||||
'rst',
|
||||
'doc',
|
||||
'docx',
|
||||
'odt',
|
||||
'rtf',
|
||||
'html',
|
||||
'htm',
|
||||
};
|
||||
|
||||
const Set<String> _markdownExtensions = <String>{'md', 'markdown', 'txt'};
|
||||
|
||||
const Set<String> _documentMimes = <String>{
|
||||
'application/msword',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'application/rtf',
|
||||
};
|
||||
|
||||
const Map<ArtifactKind, String> _kindLabels = <ArtifactKind, String>{
|
||||
ArtifactKind.image: 'Image',
|
||||
ArtifactKind.video: 'Video',
|
||||
ArtifactKind.audio: 'Audio',
|
||||
ArtifactKind.pdf: 'PDF',
|
||||
ArtifactKind.json: 'JSON',
|
||||
ArtifactKind.archive: 'Archive',
|
||||
ArtifactKind.spreadsheet: 'Spreadsheet',
|
||||
ArtifactKind.log: 'Log',
|
||||
ArtifactKind.code: 'Code',
|
||||
ArtifactKind.document: 'Document',
|
||||
ArtifactKind.other: 'File',
|
||||
};
|
||||
|
||||
/// Whether a recorded content type is an image the gallery previews.
|
||||
bool isImageContentType(String contentType) => contentType.startsWith('image/');
|
||||
|
||||
/// Whether a recorded content type is a video; videos get a poster tile and are
|
||||
/// never decoded inline or autoplayed.
|
||||
bool isVideoContentType(String contentType) => contentType.startsWith('video/');
|
||||
|
||||
/// The lowercased extension of [name], or '' when it carries none.
|
||||
String _extensionOf(String name) {
|
||||
final dot = name.lastIndexOf('.');
|
||||
return dot == -1 ? '' : name.substring(dot + 1).toLowerCase();
|
||||
}
|
||||
|
||||
/// The gallery kind for a recorded content type and name.
|
||||
///
|
||||
/// Image and video come straight from the content type; the other kinds match
|
||||
/// the normalised MIME first, then the name's extension. Pure and total: an
|
||||
/// unknown type is [ArtifactKind.other], never a guess that changes an action.
|
||||
ArtifactKind artifactKind(String contentType, String name) {
|
||||
if (isImageContentType(contentType)) return ArtifactKind.image;
|
||||
if (isVideoContentType(contentType)) return ArtifactKind.video;
|
||||
final mime = contentType.split(';').first.trim().toLowerCase();
|
||||
final ext = _extensionOf(name);
|
||||
if (mime.startsWith('audio/')) return ArtifactKind.audio;
|
||||
if (mime == 'application/pdf' || ext == 'pdf') return ArtifactKind.pdf;
|
||||
if (mime.contains('json') || ext == 'json') return ArtifactKind.json;
|
||||
if (_archiveMimes.contains(mime) || _archiveExtensions.contains(ext)) {
|
||||
return ArtifactKind.archive;
|
||||
}
|
||||
if (_spreadsheetMimes.contains(mime) ||
|
||||
_spreadsheetExtensions.contains(ext)) {
|
||||
return ArtifactKind.spreadsheet;
|
||||
}
|
||||
if (ext == 'log') return ArtifactKind.log;
|
||||
if (mime == 'text/html') return ArtifactKind.document;
|
||||
if (_codeMimes.contains(mime) || _codeExtensions.contains(ext)) {
|
||||
return ArtifactKind.code;
|
||||
}
|
||||
if (mime.startsWith('text/') ||
|
||||
_documentMimes.contains(mime) ||
|
||||
_documentExtensions.contains(ext)) {
|
||||
return ArtifactKind.document;
|
||||
}
|
||||
return ArtifactKind.other;
|
||||
}
|
||||
|
||||
/// The prose word naming [kind], so a type glyph never has to be read alone.
|
||||
String artifactKindLabel(ArtifactKind kind) => _kindLabels[kind] ?? 'File';
|
||||
|
||||
/// Whether an artifact is text the viewer can render as markdown: `text/markdown`
|
||||
/// or `text/plain` (parameters ignored), or an md/markdown/txt name.
|
||||
bool isMarkdownArtifact(String contentType, String name) {
|
||||
final mime = contentType.split(';').first.trim().toLowerCase();
|
||||
if (mime == 'text/markdown' || mime == 'text/plain') return true;
|
||||
return _markdownExtensions.contains(_extensionOf(name));
|
||||
}
|
||||
|
||||
/// Whether an artifact opens inside the full-screen viewer: images, videos, and
|
||||
/// markdown/text documents. A `text/plain` log, source file or spreadsheet stays
|
||||
/// an external file because those are evidence, not prose.
|
||||
bool isViewerArtifact(String contentType, String name) {
|
||||
if (isImageContentType(contentType) || isVideoContentType(contentType)) {
|
||||
return true;
|
||||
}
|
||||
return artifactKind(contentType, name) == ArtifactKind.document &&
|
||||
isMarkdownArtifact(contentType, name);
|
||||
}
|
||||
|
||||
/// Human-readable byte size, matching the web client: whole bytes under 1 KiB,
|
||||
/// otherwise one decimal with a binary unit (KiB/MiB/GiB/TiB/PiB/EiB).
|
||||
String humanBytes(num size) {
|
||||
final value = size.truncate();
|
||||
const unit = 1024;
|
||||
if (value < unit) return '$value B';
|
||||
var div = unit;
|
||||
var exp = 0;
|
||||
var scaled = value ~/ unit;
|
||||
while (scaled >= unit) {
|
||||
div *= unit;
|
||||
exp++;
|
||||
scaled ~/= unit;
|
||||
}
|
||||
return '${(value / div).toStringAsFixed(1)} ${'KMGTPE'[exp]}iB';
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
/// The retired markdown session export file name. Nothing writes it any more,
|
||||
/// but a run recorded before the HTML-only change still lists `session.md`: it
|
||||
/// is dated evidence that is never presented beside `session.html`.
|
||||
const String legacySessionMarkdownArtifact = 'session.md';
|
||||
|
||||
/// The files the turn protocol itself writes for every visit. They are audit
|
||||
/// evidence, not stage output, so the artifact gallery lists stage files first
|
||||
/// and keeps these for an audit/debug surface.
|
||||
const List<String> systemArtifactNames = <String>[
|
||||
'input.md',
|
||||
'memory.md',
|
||||
'output.md',
|
||||
'session.html',
|
||||
];
|
||||
|
||||
/// One recorded artifact of a stage visit.
|
||||
///
|
||||
/// The server is the authority: [name], [url], [contentType] and [sizeBytes]
|
||||
/// are read verbatim and every other field is kept in [raw]. A record is never
|
||||
/// inferred or completed locally; a missing url stays empty rather than being
|
||||
/// fabricated from the name. Two records with the same name stay distinct
|
||||
/// because only the recorded url identifies an artifact.
|
||||
class ArtifactRecord {
|
||||
const ArtifactRecord({
|
||||
required this.name,
|
||||
required this.url,
|
||||
required this.contentType,
|
||||
required this.sizeBytes,
|
||||
required this.raw,
|
||||
});
|
||||
|
||||
factory ArtifactRecord.fromJson(JsonMap json) {
|
||||
final raw = _frozenMap(json);
|
||||
return ArtifactRecord(
|
||||
name: _text(raw['name']),
|
||||
url: _text(raw['url']),
|
||||
contentType: _text(raw['content_type']),
|
||||
sizeBytes: _intOf(raw['size_bytes']),
|
||||
raw: raw,
|
||||
);
|
||||
}
|
||||
|
||||
/// The recorded file name, including any `public/` prefix.
|
||||
final String name;
|
||||
|
||||
/// The recorded artifact url exactly as the server sent it.
|
||||
final String url;
|
||||
|
||||
/// The server-sniffed content type, possibly with parameters.
|
||||
final String contentType;
|
||||
|
||||
/// The recorded byte size; 0 when the server recorded none.
|
||||
final int sizeBytes;
|
||||
|
||||
/// Every field the server sent, including fields this slice does not model.
|
||||
/// Deeply unmodifiable, so a view cannot mutate the server reply.
|
||||
final JsonMap raw;
|
||||
|
||||
bool get hasUrl => url.trim().isNotEmpty;
|
||||
bool get isLegacySessionMarkdown => name == legacySessionMarkdownArtifact;
|
||||
bool get isSystem => isSystemArtifactName(name);
|
||||
bool get isPublicName => name.startsWith('public/');
|
||||
|
||||
static String _text(dynamic value) => value == null ? '' : '$value';
|
||||
|
||||
static int _intOf(dynamic value) {
|
||||
if (value is num) return value.toInt();
|
||||
if (value is String) return int.tryParse(value.trim()) ?? 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static JsonMap _frozenMap(JsonMap json) => Map<String, dynamic>.unmodifiable(
|
||||
json.map((key, value) => MapEntry(key, _frozen(value))),
|
||||
);
|
||||
|
||||
static dynamic _frozen(dynamic value) {
|
||||
if (value is Map) return _frozenMap(Map<String, dynamic>.from(value));
|
||||
if (value is List) return List<dynamic>.unmodifiable(value.map(_frozen));
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
bool isSystemArtifactName(String name) => systemArtifactNames.contains(name);
|
||||
@@ -0,0 +1,67 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'artifact_record.dart';
|
||||
|
||||
/// Parses one step's recorded artifact list. An absent, null or malformed list
|
||||
/// yields no records; the capture state (and its unavailable wording) is
|
||||
/// reported by `artifact_capture.dart`, never treated as an empty capture here.
|
||||
List<ArtifactRecord> artifactsOf(JsonMap step) {
|
||||
final value = step['artifacts'];
|
||||
if (value is! List) return const <ArtifactRecord>[];
|
||||
return <ArtifactRecord>[
|
||||
for (final item in value)
|
||||
if (item is Map) ArtifactRecord.fromJson(Map<String, dynamic>.from(item)),
|
||||
];
|
||||
}
|
||||
|
||||
/// The html names a visit's session-export repairs produced.
|
||||
Set<String> repairArtifactNames(JsonMap step) {
|
||||
final value = step['session_export_repairs'];
|
||||
if (value is! List) return const <String>{};
|
||||
return <String>{
|
||||
for (final entry in value)
|
||||
if (entry is Map &&
|
||||
entry['html'] is String &&
|
||||
'${entry['html']}'.trim().isNotEmpty)
|
||||
'${entry['html']}',
|
||||
};
|
||||
}
|
||||
|
||||
/// The artifacts of one visit as presented: the recorded files with the retired
|
||||
/// markdown session export filtered out. Duplicate names are kept because an
|
||||
/// artifact's identity is its recorded url, not its name.
|
||||
List<ArtifactRecord> presentedArtifacts(Iterable<ArtifactRecord> artifacts) {
|
||||
return <ArtifactRecord>[
|
||||
for (final artifact in artifacts)
|
||||
if (!artifact.isLegacySessionMarkdown) artifact,
|
||||
];
|
||||
}
|
||||
|
||||
/// A visit's stage-produced artifacts: everything except the turn-owned files
|
||||
/// and repaired session exports. Order is preserved.
|
||||
List<ArtifactRecord> stageArtifactsFrom(
|
||||
Iterable<ArtifactRecord> artifacts, {
|
||||
Set<String> repairs = const <String>{},
|
||||
}) {
|
||||
return <ArtifactRecord>[
|
||||
for (final artifact in presentedArtifacts(artifacts))
|
||||
if (!artifact.isSystem && !repairs.contains(artifact.name)) artifact,
|
||||
];
|
||||
}
|
||||
|
||||
/// A visit's system files and repaired exports, in recorded order.
|
||||
List<ArtifactRecord> systemArtifactsFrom(
|
||||
Iterable<ArtifactRecord> artifacts, {
|
||||
Set<String> repairs = const <String>{},
|
||||
}) {
|
||||
return <ArtifactRecord>[
|
||||
for (final artifact in presentedArtifacts(artifacts))
|
||||
if (artifact.isSystem || repairs.contains(artifact.name)) artifact,
|
||||
];
|
||||
}
|
||||
|
||||
/// Convenience for callers holding a raw step rather than parsed records.
|
||||
List<ArtifactRecord> stageArtifacts(JsonMap step) =>
|
||||
stageArtifactsFrom(artifactsOf(step), repairs: repairArtifactNames(step));
|
||||
|
||||
List<ArtifactRecord> systemArtifacts(JsonMap step) =>
|
||||
systemArtifactsFrom(artifactsOf(step), repairs: repairArtifactNames(step));
|
||||
@@ -0,0 +1,78 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'artifact_capture.dart';
|
||||
import 'artifact_groups.dart';
|
||||
import 'artifact_selection.dart';
|
||||
|
||||
/// The "capture pending" wording shared by a running visit's summary and the
|
||||
/// run-level empty state, so the two never spell it differently.
|
||||
const String artifactCapturePending = 'capture pending';
|
||||
|
||||
/// The explicit message shown where the run's gallery would be when there are
|
||||
/// no recorded artifacts. A running run says capture pending; a finished run
|
||||
/// with available captures says plainly that nothing was recorded.
|
||||
String artifactsEmptyMessage(bool executing) => executing
|
||||
? 'Artifacts · $artifactCapturePending'
|
||||
: 'No artifacts recorded for this run.';
|
||||
|
||||
/// The run summary's Artifacts section header.
|
||||
///
|
||||
/// The recorded count is exactly the number of tiles [artifactGroups] yields;
|
||||
/// the title takes its singular form for one. A run whose capture is unavailable
|
||||
/// says so instead of claiming that nothing was recorded. Partial capture is
|
||||
/// flagged when any visit excluded or omitted files.
|
||||
String artifactsHeader(List<JsonMap> steps, {required bool executing}) {
|
||||
final recorded = artifactGroups(
|
||||
steps,
|
||||
).fold<int>(0, (sum, group) => sum + group.artifacts.length);
|
||||
if (recorded == 0) {
|
||||
if (executing) return artifactsEmptyMessage(true);
|
||||
final unavailable = steps.any(
|
||||
(step) => !ArtifactCapture.fromStep(step).isAvailable,
|
||||
);
|
||||
return unavailable
|
||||
? 'Artifacts · capture unavailable'
|
||||
: artifactsEmptyMessage(false);
|
||||
}
|
||||
final partial = steps.any((step) => ArtifactCapture.fromStep(step).isPartial);
|
||||
var label =
|
||||
'${recorded == 1 ? 'Artifact' : 'Artifacts'} · $recorded recorded';
|
||||
if (partial) label += ' · partial capture';
|
||||
return label;
|
||||
}
|
||||
|
||||
/// The per-visit artifacts label.
|
||||
///
|
||||
/// A running visit says capture pending. A finished visit whose capture field was
|
||||
/// absent says capture unavailable rather than "not recorded"; only an explicitly
|
||||
/// empty capture says "not recorded for this visit". Recorded counts exclude the
|
||||
/// turn-owned files and the retired session markdown, so the words match tiles.
|
||||
String artifactsSummary(JsonMap step, {int? count}) {
|
||||
final capture = ArtifactCapture.fromStep(step);
|
||||
final recorded = count ?? stageArtifacts(step).length;
|
||||
if (recorded == 0) {
|
||||
if (step['status'] == 'running') {
|
||||
return 'Artifacts · $artifactCapturePending';
|
||||
}
|
||||
if (!capture.isAvailable) return 'Artifacts · capture unavailable';
|
||||
return 'Artifacts · not recorded for this visit';
|
||||
}
|
||||
var label = 'Artifacts · $recorded recorded';
|
||||
if (capture.isPartial) label += ' · partial capture';
|
||||
return label;
|
||||
}
|
||||
|
||||
/// The partial-capture notes, one line per non-zero count and nothing when the
|
||||
/// capture was complete or had no presented files. An unavailable capture yields
|
||||
/// no notes because there is no evidence to quantify.
|
||||
List<String> artifactCaptureNotes(JsonMap step) {
|
||||
final notes = <String>[];
|
||||
if (presentedArtifacts(artifactsOf(step)).isEmpty) return notes;
|
||||
final capture = ArtifactCapture.fromStep(step);
|
||||
if (capture.skipped > 0) {
|
||||
notes.add('${capture.skipped} files excluded from artifact capture.');
|
||||
}
|
||||
if (capture.truncated > 0) {
|
||||
notes.add('${capture.truncated} files omitted by artifact capture limits.');
|
||||
}
|
||||
return notes;
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import '../../../core/transport/server_url.dart';
|
||||
|
||||
/// A validated artifact url plus whether it points outside the configured
|
||||
/// server origin.
|
||||
class ResolvedArtifactUrl {
|
||||
const ResolvedArtifactUrl({required this.uri, required this.external});
|
||||
|
||||
final Uri uri;
|
||||
|
||||
/// True when the url's origin differs from the configured server origin (or
|
||||
/// the configured origin is unusable). A future authenticated fetch must send
|
||||
/// no cookies, authorization header or other server credentials for an
|
||||
/// external url.
|
||||
final bool external;
|
||||
|
||||
String get url => uri.toString();
|
||||
}
|
||||
|
||||
const List<String> _unsafePrefixes = <String>['//', r'\\', r'\/', '/\\'];
|
||||
|
||||
/// Resolves a recorded artifact url for display and opening.
|
||||
///
|
||||
/// A server-relative path (`/artifacts/...`, or a path without the leading
|
||||
/// slash) resolves against the configured websocket endpoint's http(s) origin,
|
||||
/// dropping the endpoint path and query. An absolute http(s) url is preserved,
|
||||
/// including its encoded path and query. Output is always http(s): protocol-
|
||||
/// relative (`//host`), hostless, credentialed, malformed and non-http(s) urls
|
||||
/// are rejected with null. A blank or invalid configured endpoint resolves no
|
||||
/// relative path; it never invents a host.
|
||||
ResolvedArtifactUrl? resolveArtifactUrl(
|
||||
String configuredEndpoint,
|
||||
String artifactUrl,
|
||||
) {
|
||||
final raw = artifactUrl.trim();
|
||||
if (raw.isEmpty) return null;
|
||||
for (final prefix in _unsafePrefixes) {
|
||||
if (raw.startsWith(prefix)) return null;
|
||||
}
|
||||
final parsed = Uri.tryParse(raw);
|
||||
if (parsed == null) return null;
|
||||
|
||||
final configured = _httpOrigin(configuredEndpoint);
|
||||
if (parsed.hasScheme) {
|
||||
final scheme = parsed.scheme.toLowerCase();
|
||||
if (scheme != 'http' && scheme != 'https') return null;
|
||||
if (!parsed.hasAuthority || parsed.host.isEmpty) return null;
|
||||
if (parsed.userInfo.isNotEmpty) return null;
|
||||
return ResolvedArtifactUrl(
|
||||
uri: parsed,
|
||||
external: configured == null || parsed.origin != configured.origin,
|
||||
);
|
||||
}
|
||||
|
||||
if (configured == null) return null;
|
||||
final relative = raw.startsWith('/') ? raw : '/$raw';
|
||||
final resolved = Uri.tryParse('${configured.origin}$relative');
|
||||
if (resolved == null) return null;
|
||||
final scheme = resolved.scheme.toLowerCase();
|
||||
if (scheme != 'http' && scheme != 'https') return null;
|
||||
if (!resolved.hasAuthority || resolved.host.isEmpty) return null;
|
||||
if (resolved.userInfo.isNotEmpty) return null;
|
||||
return ResolvedArtifactUrl(uri: resolved, external: false);
|
||||
}
|
||||
|
||||
/// The http(s) origin of a configured websocket endpoint, or null when the
|
||||
/// endpoint is blank, malformed, or not a ws/wss url.
|
||||
Uri? _httpOrigin(String configuredEndpoint) {
|
||||
try {
|
||||
final endpoint = ServerUrl.validate(configuredEndpoint);
|
||||
final http = Uri.parse(endpoint.httpUrl);
|
||||
final scheme = http.scheme.toLowerCase();
|
||||
if (scheme != 'http' && scheme != 'https') return null;
|
||||
if (http.host.isEmpty) return null;
|
||||
return Uri.parse(http.origin);
|
||||
} on FormatException {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import 'artifact_groups.dart';
|
||||
import 'artifact_kind.dart';
|
||||
import 'artifact_record.dart';
|
||||
|
||||
/// One artifact in the viewer's filtered page list, with the stage visit it
|
||||
/// belongs to. [identity] is the recorded url when there is one; otherwise it is
|
||||
/// a visit-scoped key so two url-less records never collapse into one page.
|
||||
class PagedArtifact {
|
||||
const PagedArtifact({
|
||||
required this.stageKey,
|
||||
required this.visit,
|
||||
required this.artifact,
|
||||
required this.pageIndex,
|
||||
});
|
||||
|
||||
final String stageKey;
|
||||
final int visit;
|
||||
final ArtifactRecord artifact;
|
||||
|
||||
/// Position in the filtered page list.
|
||||
final int pageIndex;
|
||||
|
||||
String get identity => artifact.hasUrl
|
||||
? artifact.url
|
||||
: '$stageKey\u0000$visit\u0000$pageIndex\u0000${artifact.name}';
|
||||
}
|
||||
|
||||
/// The artifacts the viewer can page through, in gallery order: group by group,
|
||||
/// each group's images, videos and markdown/text documents in recorded order.
|
||||
/// Other artifacts open externally and are not part of this list. Pure: it only
|
||||
/// filters and orders records the gallery already holds.
|
||||
List<PagedArtifact> pagedArtifacts(List<ArtifactGroup> groups) {
|
||||
final pages = <PagedArtifact>[];
|
||||
for (final group in groups) {
|
||||
for (final artifact in group.artifacts) {
|
||||
if (!isViewerArtifact(artifact.contentType, artifact.name)) continue;
|
||||
pages.add(
|
||||
PagedArtifact(
|
||||
stageKey: group.stageKey,
|
||||
visit: group.visit,
|
||||
artifact: artifact,
|
||||
pageIndex: pages.length,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
return List<PagedArtifact>.unmodifiable(pages);
|
||||
}
|
||||
|
||||
/// Each page's recorded url mapped to its page index, so a tile and the viewer
|
||||
/// derive from the same ordered list. The first occurrence of a url wins. A
|
||||
/// record with no recorded url has no fetchable identity and is omitted.
|
||||
Map<String, int> viewerIndexByUrl(List<ArtifactGroup> groups) {
|
||||
final indices = <String, int>{};
|
||||
for (final page in pagedArtifacts(groups)) {
|
||||
if (!page.artifact.hasUrl) continue;
|
||||
indices.putIfAbsent(page.artifact.url, () => page.pageIndex);
|
||||
}
|
||||
return indices;
|
||||
}
|
||||
|
||||
/// Paging from [current] by [delta] within `count` pages, clamped at both ends
|
||||
/// so a page never wraps and an empty list is index 0.
|
||||
int pagedIndex(int current, int delta, int count) {
|
||||
if (count <= 0) return 0;
|
||||
final wanted = current + delta;
|
||||
if (wanted < 0) return 0;
|
||||
if (wanted >= count) return count - 1;
|
||||
return wanted;
|
||||
}
|
||||
|
||||
/// The viewer's position label, e.g. `2 of 5 · image/png`.
|
||||
String artifactViewerPositionLabel(int index, int count, String contentType) {
|
||||
final type = contentType.split(';').first.trim();
|
||||
return '${index + 1} of $count · ${type.isEmpty ? 'artifact' : type}';
|
||||
}
|
||||
@@ -0,0 +1,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<ArtifactGroup> 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) ...<Widget>[
|
||||
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<String>('${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.'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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';
|
||||
@@ -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<FileChange> 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 = <FileChange>[];
|
||||
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<String, dynamic>.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<StageCapture> stageCaptures(List<JsonMap> 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 = <String, int>{};
|
||||
final captures = <StageCapture>[];
|
||||
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;
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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 = <String>[];
|
||||
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<String> 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 = <String>[];
|
||||
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<FileChange> filterFileChanges(Iterable<FileChange> 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';
|
||||
@@ -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<String> 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<String> get tags => [
|
||||
if (binary) 'binary',
|
||||
if (truncated) 'truncated',
|
||||
if (otherModeChange) 'mode change',
|
||||
];
|
||||
|
||||
FileChange withSteps(List<String> 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<String, dynamic>.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;
|
||||
}
|
||||
@@ -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<PatchLine> 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<String> headerLines;
|
||||
final List<PatchHunk> hunks;
|
||||
final int added;
|
||||
final int removed;
|
||||
|
||||
bool get isEmpty => hunks.isEmpty;
|
||||
}
|
||||
@@ -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<FileChange> 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<JsonMap> 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<StageCapture> visits) {
|
||||
final entries = <String, FileChange>{};
|
||||
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 = <String>{};
|
||||
|
||||
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 ? <String>[] : [...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(' '),
|
||||
);
|
||||
}
|
||||
@@ -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 = <String>[];
|
||||
final hunks = <PatchHunk>[];
|
||||
_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<PatchLine> 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<int>? _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<int>? _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;
|
||||
}
|
||||
@@ -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<FileChange> onOpen;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final capture = stage.capture;
|
||||
final filtered = capture == null
|
||||
? const <FileChange>[]
|
||||
: 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<FileChange> 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,
|
||||
};
|
||||
}
|
||||
@@ -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<DiffForm> onChanged,
|
||||
}) {
|
||||
if (usesCupertino(context)) {
|
||||
return CupertinoSlidingSegmentedControl<DiffForm>(
|
||||
groupValue: form,
|
||||
onValueChanged: (value) {
|
||||
if (value != null) onChanged(value);
|
||||
},
|
||||
children: const {
|
||||
DiffForm.rendered: _SegmentLabel('Rendered'),
|
||||
DiffForm.raw: _SegmentLabel('Raw patch'),
|
||||
},
|
||||
);
|
||||
}
|
||||
return SegmentedButton<DiffForm>(
|
||||
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),
|
||||
);
|
||||
}
|
||||
@@ -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<JsonMap> steps;
|
||||
|
||||
@override
|
||||
State<ChangesViewer> createState() => _ChangesViewerState();
|
||||
}
|
||||
|
||||
class _ChangesViewerState extends State<ChangesViewer> {
|
||||
final _filter = TextEditingController();
|
||||
late List<StageCapture> _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),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<FileDiffViewer> createState() => _FileDiffViewerState();
|
||||
}
|
||||
|
||||
class _FileDiffViewerState extends State<FileDiffViewer> {
|
||||
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<void> _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<void> 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<void>(context: context, builder: buildDialog);
|
||||
}
|
||||
return showDialog<void>(context: context, builder: buildDialog);
|
||||
}
|
||||
@@ -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,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<List<JsonMap>> sessions() async =>
|
||||
_maps((await gateway.call('chat_sessions'))['chat_sessions']);
|
||||
Future<JsonMap> 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<String, dynamic>.from(catalog) : {};
|
||||
}
|
||||
|
||||
Future<JsonMap> selectModel(
|
||||
String sessionId,
|
||||
String provider,
|
||||
String model,
|
||||
) => gateway.call('chat_model', {
|
||||
'chat_model': {
|
||||
'session_id': sessionId,
|
||||
'provider': provider,
|
||||
'model': model,
|
||||
},
|
||||
});
|
||||
Future<List<JsonMap>> shells(String sessionId) async => _maps(
|
||||
(await gateway.call('chat_shells', {
|
||||
'chat_query': {'session_id': sessionId},
|
||||
}))['chat_shells'],
|
||||
);
|
||||
Future<List<String>> 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<String>()
|
||||
.where((entry) => entry.trim().isNotEmpty)
|
||||
.toList();
|
||||
}
|
||||
|
||||
Future<List<String>> 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<String>()
|
||||
.where((entry) => entry.trim().isNotEmpty)
|
||||
.toList();
|
||||
if (result.isEmpty) throw StateError('Server returned no chat backends.');
|
||||
return result;
|
||||
}
|
||||
|
||||
Future<JsonMap> 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<JsonMap> 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<JsonMap> subscribe(String sessionId) =>
|
||||
gateway.call('chat_subscribe', {
|
||||
'chat_subscribe': {'session_id': sessionId},
|
||||
});
|
||||
Future<JsonMap> 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<JsonMap> rename(String sessionId, String title) =>
|
||||
gateway.call('chat_rename', {
|
||||
'chat_rename': {'session_id': sessionId, 'title': title.trim()},
|
||||
});
|
||||
Future<JsonMap> star(String sessionId, bool starred) =>
|
||||
gateway.call('chat_star', {
|
||||
'chat_query': {'session_id': sessionId, 'starred': starred},
|
||||
});
|
||||
Future<JsonMap> close(String sessionId) => gateway.call('chat_close', {
|
||||
'chat_query': {'session_id': sessionId},
|
||||
});
|
||||
Future<JsonMap> reopen(String sessionId) => gateway.call('chat_reopen', {
|
||||
'chat_query': {'session_id': sessionId},
|
||||
});
|
||||
|
||||
Future<JsonMap> prompt(
|
||||
String sessionId,
|
||||
String text, {
|
||||
required String operationId,
|
||||
List<String> files = const [],
|
||||
List<JsonMap> 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 = <String, dynamic>{
|
||||
'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<JsonMap> interrupt(String sessionId) =>
|
||||
gateway.call('chat_interrupt', {
|
||||
'chat_query': {'session_id': sessionId},
|
||||
});
|
||||
Future<JsonMap> 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<JsonMap> 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<JsonMap> _maps(Object? value) => (value as List? ?? const [])
|
||||
.whereType<Map>()
|
||||
.map((item) => Map<String, dynamic>.from(item))
|
||||
.toList();
|
||||
}
|
||||
@@ -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<JsonMap> filterChatSessions(List<JsonMap> 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<JsonMap> sessions})> groupChatSessions(
|
||||
List<JsonMap> sessions,
|
||||
) {
|
||||
final groups = <String, List<JsonMap>>{};
|
||||
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<String, dynamic>.from(value);
|
||||
final result = <String, dynamic>{};
|
||||
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;
|
||||
}
|
||||
@@ -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>()
|
||||
.map((m) => Map<String, dynamic>.from(m))
|
||||
.toList();
|
||||
final incoming = (page['messages'] as List? ?? const [])
|
||||
.whereType<Map>()
|
||||
.map((m) => Map<String, dynamic>.from(m))
|
||||
.toList();
|
||||
final latest = <Object, JsonMap>{};
|
||||
for (final message in incoming) {
|
||||
if (message['id'] != null) latest[message['id']] = message;
|
||||
}
|
||||
final combined = older ? [...incoming, ...held] : [...held, ...incoming];
|
||||
final seen = <Object>{};
|
||||
final messages = <JsonMap>[];
|
||||
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<JsonMap> transcriptRows(List<JsonMap> messages) {
|
||||
final rows = <JsonMap>[];
|
||||
String? key;
|
||||
final parts = <JsonMap>[];
|
||||
void flush() {
|
||||
if (key != null && parts.isNotEmpty) {
|
||||
rows.add({
|
||||
'kind': 'assistant',
|
||||
'key': key,
|
||||
'parts': List<JsonMap>.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<String, dynamic>.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<JsonMap> reconcileChatUser(List<JsonMap> 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<JsonMap>.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>()
|
||||
.map((m) => Map<String, dynamic>.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': <JsonMap>[],
|
||||
});
|
||||
index = messages.length - 1;
|
||||
}
|
||||
final message = messages[index];
|
||||
final parts = (message['parts'] as List? ?? const [])
|
||||
.whereType<Map>()
|
||||
.map((p) => Map<String, dynamic>.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<String, dynamic>.from(incoming));
|
||||
} else {
|
||||
final merged = {
|
||||
...parts[partIndex],
|
||||
...Map<String, dynamic>.from(incoming),
|
||||
};
|
||||
if (parts[partIndex]['state'] is Map && incoming['state'] is Map) {
|
||||
merged['state'] = {
|
||||
...Map<String, dynamic>.from(parts[partIndex]['state'] as Map),
|
||||
...Map<String, dynamic>.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<String> 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<String, List<QueuedChatSend>> _sessions = {};
|
||||
List<QueuedChatSend> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export 'ui/sessions/chat_sessions_screen.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<MaterialApp>() == 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<String> 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(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<String> directories;
|
||||
final List<String> backends;
|
||||
final String? directory;
|
||||
final String? backend;
|
||||
final ValueChanged<String> onDirectory;
|
||||
final ValueChanged<String> 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<String> values;
|
||||
final ValueChanged<String> onSelected;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return DropdownButtonFormField<String>(
|
||||
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<String> values;
|
||||
final ValueChanged<String> onSelected;
|
||||
|
||||
Future<void> _choose(BuildContext context) async {
|
||||
final choice = await showCupertinoModalPopup<String>(
|
||||
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),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<JsonMap> 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<JsonMap> sessions;
|
||||
final String query;
|
||||
final bool loading;
|
||||
final String? error;
|
||||
final ValueChanged<JsonMap> onOpen;
|
||||
final ValueChanged<JsonMap> onRename;
|
||||
final ValueChanged<JsonMap> onClose;
|
||||
final ValueChanged<JsonMap> onReopen;
|
||||
final ValueChanged<JsonMap> onStar;
|
||||
final VoidCallback onClearSearch;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final visible = filterChatSessions(sessions, query);
|
||||
final sections = <ChatSessionSection>[
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<JsonMap> _sessions = const [];
|
||||
String? _error;
|
||||
bool _loading = true;
|
||||
bool _disposed = false;
|
||||
int _generation = 0;
|
||||
|
||||
List<JsonMap> 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<void> 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<void> star(String sessionId, bool starred) =>
|
||||
_mutate(() => repository.star(sessionId, starred));
|
||||
|
||||
Future<void> close(String sessionId) =>
|
||||
_mutate(() => repository.close(sessionId));
|
||||
|
||||
Future<void> reopen(String sessionId) =>
|
||||
_mutate(() => repository.reopen(sessionId));
|
||||
|
||||
Future<void> rename(String sessionId, String title) =>
|
||||
_mutate(() => repository.rename(sessionId, title));
|
||||
|
||||
Future<JsonMap?> 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<String, dynamic>.from(session) : null;
|
||||
} catch (error) {
|
||||
_error = '$error';
|
||||
_notify();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _mutate(Future<JsonMap> 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();
|
||||
}
|
||||
}
|
||||
@@ -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<ChatSessionsScreen> createState() => _ChatSessionsScreenState();
|
||||
}
|
||||
|
||||
class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
|
||||
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<void> _rename(JsonMap session) async {
|
||||
final title = await showRenameChatDialog(context, session);
|
||||
if (title == null || !mounted) return;
|
||||
await _controller.rename(_sessionId(session), title);
|
||||
}
|
||||
|
||||
Future<void> _close(JsonMap session) async {
|
||||
if (!await confirmCloseChat(context, session)) return;
|
||||
if (!mounted) return;
|
||||
await _controller.close(_sessionId(session));
|
||||
}
|
||||
|
||||
Future<void> _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'),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<ChatDraft?> showChatCreateDialog(
|
||||
BuildContext context, {
|
||||
required ChatRepository repository,
|
||||
}) {
|
||||
final dialog = CreateChatDialog(repository: repository);
|
||||
return chatControlsStyleOf(context) == ChatControlsStyle.cupertino
|
||||
? showCupertinoDialog<ChatDraft>(context: context, builder: (_) => dialog)
|
||||
: showDialog<ChatDraft>(context: context, builder: (_) => dialog);
|
||||
}
|
||||
|
||||
class CreateChatDialog extends StatefulWidget {
|
||||
const CreateChatDialog({super.key, required this.repository});
|
||||
|
||||
final ChatRepository repository;
|
||||
|
||||
@override
|
||||
State<CreateChatDialog> createState() => _CreateChatDialogState();
|
||||
}
|
||||
|
||||
class _CreateChatDialogState extends State<CreateChatDialog> {
|
||||
final _name = TextEditingController(text: 'New chat');
|
||||
final _instructions = TextEditingController();
|
||||
List<String> _directories = const [];
|
||||
List<String> _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<void> _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'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<String?> showRenameChatDialog(BuildContext context, JsonMap session) {
|
||||
final dialog = _RenameChatDialog(initialTitle: chatSessionTitle(session));
|
||||
return chatControlsStyleOf(context) == ChatControlsStyle.cupertino
|
||||
? showCupertinoDialog<String>(context: context, builder: (_) => dialog)
|
||||
: showDialog<String>(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<TextEditingValue>(
|
||||
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'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<SessionAction> onSelected;
|
||||
final Set<String> 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<SessionAction>(
|
||||
tooltip: label,
|
||||
onSelected: onSelected,
|
||||
itemBuilder: (context) => _menuItems(session),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _showSheet(BuildContext context) async {
|
||||
final action = await showCupertinoModalPopup<SessionAction>(
|
||||
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<PopupMenuEntry<SessionAction>> _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<bool> confirmCloseChat(BuildContext context, JsonMap session) async {
|
||||
final title = chatSessionTitle(session);
|
||||
final body = closeChatConfirmation(title);
|
||||
final confirmed = chatControlsStyleOf(context) == ChatControlsStyle.cupertino
|
||||
? await showCupertinoDialog<bool>(
|
||||
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<bool>(
|
||||
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;
|
||||
}
|
||||
@@ -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<ChatSessionSection> sections;
|
||||
final String? emptyMessage;
|
||||
final Set<String> duplicateTitles;
|
||||
final ValueChanged<JsonMap> onOpen;
|
||||
final ValueChanged<JsonMap> onRename;
|
||||
final ValueChanged<JsonMap> onClose;
|
||||
final ValueChanged<JsonMap> onReopen;
|
||||
final ValueChanged<JsonMap> 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<CupertinoListSection> _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<String> duplicateTitles;
|
||||
final ValueChanged<JsonMap> onOpen;
|
||||
final ValueChanged<JsonMap> onRename;
|
||||
final ValueChanged<JsonMap> onClose;
|
||||
final ValueChanged<JsonMap> onReopen;
|
||||
final ValueChanged<JsonMap> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<ChatSessionSection> sections;
|
||||
final String? emptyMessage;
|
||||
final Set<String> duplicateTitles;
|
||||
final ValueChanged<JsonMap> onOpen;
|
||||
final ValueChanged<JsonMap> onRename;
|
||||
final ValueChanged<JsonMap> onClose;
|
||||
final ValueChanged<JsonMap> onReopen;
|
||||
final ValueChanged<JsonMap> 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<String> duplicateTitles;
|
||||
final ValueChanged<JsonMap> onOpen;
|
||||
final ValueChanged<JsonMap> onRename;
|
||||
final ValueChanged<JsonMap> onClose;
|
||||
final ValueChanged<JsonMap> onReopen;
|
||||
final ValueChanged<JsonMap> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String> duplicateChatTitles(Iterable<JsonMap> sessions) {
|
||||
final seen = <String>{};
|
||||
final duplicates = <String>{};
|
||||
for (final session in sessions) {
|
||||
final title = chatSessionTitle(session);
|
||||
if (!seen.add(title)) duplicates.add(title);
|
||||
}
|
||||
return duplicates;
|
||||
}
|
||||
|
||||
String sessionActionsLabel(JsonMap session, Set<String> 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;
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import 'graph_protocol.dart';
|
||||
|
||||
/// The graph definition: nodes and edges declared by a pipeline, never the
|
||||
/// evidence that a run executed them. Run evidence lives in
|
||||
/// `run_graph_state.dart`; keeping the two shapes separate means a definition
|
||||
/// can be drawn without claiming a visit happened.
|
||||
///
|
||||
/// Mirrors `stageOutcomes`, `edgeLabel`, `graphEdges` and `nodeDisplayLabel`
|
||||
/// from `web/src/graph.js` (and `web/src/runDetail.js`). Pure data only.
|
||||
|
||||
/// Ordering priority: success first, error last, every other outcome
|
||||
/// alphabetical in between (the web client's `outcomePriority`).
|
||||
int _outcomePriority(String outcome) {
|
||||
if (outcome == 'success') return 0;
|
||||
if (outcome == 'error') return 2;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/// A stage's edge outcomes in the app's one stable order.
|
||||
List<String> stageOutcomes(dynamic stage) {
|
||||
final edges = stage is Map ? stage['edges'] : null;
|
||||
if (edges is! Map) return const <String>[];
|
||||
final outcomes = edges.keys.map((key) => '$key').toList();
|
||||
outcomes.sort((a, b) {
|
||||
final priority = _outcomePriority(a) - _outcomePriority(b);
|
||||
return priority != 0 ? priority : a.compareTo(b);
|
||||
});
|
||||
return outcomes;
|
||||
}
|
||||
|
||||
/// The outcome label on an edge: `error*` for an implicit fallback error route.
|
||||
String edgeLabel(dynamic stage, String outcome) {
|
||||
final implicitFallback = stage is Map && stage['fallback_error'] == true;
|
||||
return outcome == 'error' && implicitFallback ? 'error*' : outcome;
|
||||
}
|
||||
|
||||
/// One declared edge, in stable definition order.
|
||||
class GraphEdge {
|
||||
const GraphEdge({
|
||||
required this.id,
|
||||
required this.source,
|
||||
required this.outcome,
|
||||
required this.target,
|
||||
required this.label,
|
||||
required this.fallback,
|
||||
required this.knownTarget,
|
||||
});
|
||||
|
||||
/// The 1-based id assigned in stable definition order (`Graph.edges()`).
|
||||
final int id;
|
||||
final String source;
|
||||
final String outcome;
|
||||
|
||||
/// The resolved target: `#` has already become `#success`/`#failure`.
|
||||
final String target;
|
||||
final String label;
|
||||
|
||||
/// True only for the parser's implicit `error -> #failure` route.
|
||||
final bool fallback;
|
||||
|
||||
/// True when [target] is a terminal or a stage declared in this graph.
|
||||
///
|
||||
/// An empty or unknown target is kept exactly as recorded, with this flag
|
||||
/// false, so callers can show it honestly instead of inventing a node.
|
||||
final bool knownTarget;
|
||||
|
||||
bool get isTerminal => isTerminalTarget(target);
|
||||
}
|
||||
|
||||
/// One graph definition node: a declared stage, or a terminal the definition
|
||||
/// routes to.
|
||||
class GraphNode {
|
||||
const GraphNode({required this.key, required this.terminal, this.stageIndex});
|
||||
|
||||
final String key;
|
||||
final bool terminal;
|
||||
|
||||
/// The node's stage declaration index, or null for a terminal.
|
||||
final int? stageIndex;
|
||||
|
||||
String get label => nodeDisplayLabel(key);
|
||||
String get shortLabel => nodeLabel(key);
|
||||
}
|
||||
|
||||
List<Map<String, dynamic>> _stages(dynamic graph) {
|
||||
if (graph is! Map) return const <Map<String, dynamic>>[];
|
||||
final stages = graph['stages'];
|
||||
if (stages is! List) return const <Map<String, dynamic>>[];
|
||||
return stages.whereType<Map>().map(Map<String, dynamic>.from).toList();
|
||||
}
|
||||
|
||||
String _stageKey(Map<String, dynamic> stage) => '${stage['key'] ?? ''}';
|
||||
|
||||
/// Every definition edge in stable id order.
|
||||
///
|
||||
/// Stages keep declaration order and each stage's outcomes use
|
||||
/// [stageOutcomes]; ids are contiguous in that order. An absent (null) edge
|
||||
/// value declares no edge and is skipped, while an empty or unknown target is
|
||||
/// preserved with [GraphEdge.knownTarget] false.
|
||||
List<GraphEdge> graphEdges(dynamic graph) {
|
||||
final stages = _stages(graph);
|
||||
final stageKeys = <String>{
|
||||
for (final stage in stages)
|
||||
if (_stageKey(stage).isNotEmpty) _stageKey(stage),
|
||||
};
|
||||
final result = <GraphEdge>[];
|
||||
for (final stage in stages) {
|
||||
final edges = stage['edges'];
|
||||
if (edges is! Map) continue;
|
||||
final source = _stageKey(stage);
|
||||
for (final outcome in stageOutcomes(stage)) {
|
||||
final raw = edges[outcome];
|
||||
if (raw == null) continue;
|
||||
final target = resolveTarget(outcome, '$raw') ?? '';
|
||||
result.add(
|
||||
GraphEdge(
|
||||
id: result.length + 1,
|
||||
source: source,
|
||||
outcome: outcome,
|
||||
target: target,
|
||||
label: edgeLabel(stage, outcome),
|
||||
fallback: outcome == 'error' && stage['fallback_error'] == true,
|
||||
knownTarget: isTerminalTarget(target) || stageKeys.contains(target),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// The definition's nodes in declaration order.
|
||||
///
|
||||
/// A stage key identifies one node even when it is declared twice; self edges
|
||||
/// and loops therefore never duplicate identity. Terminal nodes are appended
|
||||
/// failure first, then success, once any declared edge resolves to a terminal
|
||||
/// (the same `hasTerminal` rule the web layout uses). They are still
|
||||
/// definition nodes, not evidence that a run reached them.
|
||||
List<GraphNode> graphNodes(dynamic graph) {
|
||||
final stages = _stages(graph);
|
||||
final seen = <String>{};
|
||||
final nodes = <GraphNode>[];
|
||||
for (var index = 0; index < stages.length; index += 1) {
|
||||
final key = _stageKey(stages[index]);
|
||||
if (key.isEmpty || !seen.add(key)) continue;
|
||||
nodes.add(GraphNode(key: key, terminal: false, stageIndex: index));
|
||||
}
|
||||
if (graphEdges(graph).any((edge) => edge.isTerminal)) {
|
||||
nodes.add(const GraphNode(key: failureEnd, terminal: true));
|
||||
nodes.add(const GraphNode(key: successEnd, terminal: true));
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/// Protocol terminal targets and the labels the graph uses for them.
|
||||
///
|
||||
/// Mirrors `web/src/protocol.js` (`SUCCESS_END`, `FAILURE_END`,
|
||||
/// `isTerminal`, `resolveTarget`) and the label helpers in `web/src/graph.js`.
|
||||
/// Pure Dart: no Flutter imports and no layout or rendering decisions.
|
||||
library;
|
||||
|
||||
/// The explicit success terminal (`Protocol.SUCCESS_END`).
|
||||
const String successEnd = '#success';
|
||||
|
||||
/// The explicit failure terminal (`Protocol.FAILURE_END`).
|
||||
const String failureEnd = '#failure';
|
||||
|
||||
/// True only for the two explicit terminal targets.
|
||||
///
|
||||
/// A bare `#` is not itself terminal; [resolveTarget] turns it into one using
|
||||
/// the outcome, exactly as the server and the web client do.
|
||||
bool isTerminalTarget(String? target) =>
|
||||
target == successEnd || target == failureEnd;
|
||||
|
||||
/// Mirrors `Protocol.resolveTarget`: a bare `#` is the outcome's terminal.
|
||||
///
|
||||
/// Every other value is preserved verbatim, including an empty or unknown
|
||||
/// stage key. A missing target stays null rather than becoming a terminal, so
|
||||
/// a blank edge cannot fabricate a visit or a terminal node.
|
||||
String? resolveTarget(String? outcome, String? target) {
|
||||
if (target != '#') return target;
|
||||
return outcome == 'error' ? failureEnd : successEnd;
|
||||
}
|
||||
|
||||
/// A graph node title: a stage keeps its key, a terminal reads Success/Failure.
|
||||
String nodeDisplayLabel(String? key) {
|
||||
if (key == successEnd) return 'Success';
|
||||
if (key == failureEnd) return 'Failure';
|
||||
return key ?? '';
|
||||
}
|
||||
|
||||
/// The TUI-mirroring label: terminal targets are all caps.
|
||||
String nodeLabel(String? key) {
|
||||
if (key == successEnd) return 'SUCCESS';
|
||||
if (key == failureEnd) return 'FAILURE';
|
||||
return key ?? '';
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import 'graph_protocol.dart';
|
||||
|
||||
/// Which stages and routes a run actually recorded.
|
||||
///
|
||||
/// This is executed-route evidence, deliberately distinct from the graph
|
||||
/// definition's nodes and edges. It mirrors `runGraphState` from
|
||||
/// `web/src/runDetail.js` (Android `RunGraphState.from`): every recorded step's
|
||||
/// stage is visited once in first-appearance order, a step with a non-blank
|
||||
/// outcome and target contributes one deduplicated `source\0outcome\0target`
|
||||
/// route, and only a resolved terminal is added by its target. A non-terminal
|
||||
/// target is not visited until a step lands on it.
|
||||
///
|
||||
/// The run map is the same detail produced by the runs feature; this helper
|
||||
/// reads recorded steps and never folds live events a second time.
|
||||
class RunGraphState {
|
||||
RunGraphState({
|
||||
required List<String> visitedStages,
|
||||
required List<String> takenRoutes,
|
||||
required this.currentStage,
|
||||
required this.executing,
|
||||
required this.currentStageStartedAt,
|
||||
}) : visitedStages = List.unmodifiable(visitedStages),
|
||||
takenRoutes = List.unmodifiable(takenRoutes);
|
||||
|
||||
/// Visited stage keys in first-appearance order, without duplicates.
|
||||
final List<String> visitedStages;
|
||||
|
||||
/// Taken routes as `source\0outcome\0resolvedTarget`, in recorded order.
|
||||
final List<String> takenRoutes;
|
||||
|
||||
/// The run's current stage, else the last recorded visit's stage, else null.
|
||||
final String? currentStage;
|
||||
final bool executing;
|
||||
|
||||
/// The running visit's start for [currentStage], only while executing.
|
||||
final String? currentStageStartedAt;
|
||||
|
||||
bool isStageVisited(String key) => visitedStages.contains(key);
|
||||
|
||||
/// True when a recorded visit took this definition route. The target is
|
||||
/// resolved with the same `#` rule the definition edges use.
|
||||
bool isRouteTaken(String source, String outcome, String target) {
|
||||
final resolved = resolveTarget(outcome, target);
|
||||
if (resolved == null || resolved.isEmpty) return false;
|
||||
return takenRoutes.contains('$source\u0000$outcome\u0000$resolved');
|
||||
}
|
||||
|
||||
/// The active stage for a live run, else null. A finished run has none.
|
||||
String? get activeStage {
|
||||
if (!executing || currentStage == null || currentStage!.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
return currentStage;
|
||||
}
|
||||
}
|
||||
|
||||
List<Map<String, dynamic>> _steps(dynamic run) {
|
||||
if (run is! Map) return const <Map<String, dynamic>>[];
|
||||
final steps = run['steps'];
|
||||
if (steps is! List) return const <Map<String, dynamic>>[];
|
||||
return steps.whereType<Map>().map(Map<String, dynamic>.from).toList();
|
||||
}
|
||||
|
||||
String _text(dynamic value) => '${value ?? ''}';
|
||||
|
||||
/// Derives [RunGraphState] from one run detail map.
|
||||
///
|
||||
/// Missing or malformed steps yield no visits and no routes; nothing is
|
||||
/// fabricated from a missing capture. Repeated visits stay one identity per
|
||||
/// stage, and self edges or loops never recurse.
|
||||
RunGraphState runGraphState(dynamic run) {
|
||||
final steps = _steps(run);
|
||||
final visitedStages = <String>[];
|
||||
final seenStages = <String>{};
|
||||
final takenRoutes = <String>[];
|
||||
final seenRoutes = <String>{};
|
||||
|
||||
void visit(String? key) {
|
||||
if (key == null || key.isEmpty || !seenStages.add(key)) return;
|
||||
visitedStages.add(key);
|
||||
}
|
||||
|
||||
for (final step in steps) {
|
||||
final stage = _text(step['stage']);
|
||||
if (stage.isNotEmpty) visit(stage);
|
||||
|
||||
final outcome = _text(step['outcome']);
|
||||
final target = _text(step['target']);
|
||||
if (outcome.trim().isEmpty || target.trim().isEmpty) continue;
|
||||
|
||||
final resolved = resolveTarget(outcome, target);
|
||||
if (resolved == null || resolved.isEmpty) continue;
|
||||
final route = '$stage\u0000$outcome\u0000$resolved';
|
||||
if (seenRoutes.add(route)) takenRoutes.add(route);
|
||||
if (isTerminalTarget(resolved)) visit(resolved);
|
||||
}
|
||||
|
||||
final lastStage = steps.isEmpty ? '' : _text(steps.last['stage']);
|
||||
final rawCurrent = _text(run is Map ? run['current_stage'] : null);
|
||||
final currentStage = rawCurrent.trim().isNotEmpty
|
||||
? rawCurrent
|
||||
: (lastStage.trim().isNotEmpty ? lastStage : null);
|
||||
final executing = run is Map && run['executing'] == true;
|
||||
|
||||
String? currentStageStartedAt;
|
||||
if (executing && currentStage != null) {
|
||||
for (var index = steps.length - 1; index >= 0; index -= 1) {
|
||||
final step = steps[index];
|
||||
if (_text(step['stage']) != currentStage) continue;
|
||||
if (_text(step['status']) != 'running') continue;
|
||||
final started = _text(step['started_at']);
|
||||
if (started.trim().isNotEmpty) currentStageStartedAt = started;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return RunGraphState(
|
||||
visitedStages: visitedStages,
|
||||
takenRoutes: takenRoutes,
|
||||
currentStage: currentStage,
|
||||
executing: executing,
|
||||
currentStageStartedAt: currentStageStartedAt,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
/// Recorded stage-visit selection, matching the web client's timeline and
|
||||
/// stage pane. Visits are ordered by their recorded sequence, never by the
|
||||
/// order a caller happens to pass them in; repeated visits to one stage stay
|
||||
/// separate entries. Pure data: no widgets, layout or coordinates.
|
||||
|
||||
int _sequenceOf(JsonMap step) {
|
||||
final sequence = step['sequence'];
|
||||
return sequence is num ? sequence.toInt() : 0;
|
||||
}
|
||||
|
||||
int _positiveVisit(dynamic control) {
|
||||
if (control is! Map) return 0;
|
||||
final visit = control['visit'];
|
||||
if (visit is num) return visit > 0 ? visit.toInt() : 0;
|
||||
return int.tryParse('${visit ?? ''}') ?? 0;
|
||||
}
|
||||
|
||||
/// The visit number a timeline row shows: the recorded `control.visit` when it
|
||||
/// is positive, else the position within the stage's ordered visits.
|
||||
int displayVisit(JsonMap step, int index) {
|
||||
final recorded = _positiveVisit(step['control']);
|
||||
return recorded > 0 ? recorded : index + 1;
|
||||
}
|
||||
|
||||
/// Clamps a visit index into `[0, count)`; an empty list yields 0.
|
||||
int clampVisitIndex(int index, int count) {
|
||||
if (count <= 0) return 0;
|
||||
if (index < 0) return 0;
|
||||
return index >= count ? count - 1 : index;
|
||||
}
|
||||
|
||||
List<JsonMap> _ordered(List<JsonMap> visits) {
|
||||
final indexed = <({int position, JsonMap step})>[
|
||||
for (var index = 0; index < visits.length; index += 1)
|
||||
(position: index, step: visits[index]),
|
||||
];
|
||||
indexed.sort((a, b) {
|
||||
final bySequence = _sequenceOf(a.step).compareTo(_sequenceOf(b.step));
|
||||
return bySequence != 0 ? bySequence : a.position.compareTo(b.position);
|
||||
});
|
||||
return [for (final entry in indexed) entry.step];
|
||||
}
|
||||
|
||||
/// Every stage's recorded visits, ordered by sequence.
|
||||
///
|
||||
/// The map keeps stage first-appearance order. Equal sequences keep their
|
||||
/// recorded order (the web client's stable sort), and a stage with no recorded
|
||||
/// visit is simply absent rather than present with a synthetic visit.
|
||||
Map<String, List<JsonMap>> visitsByStage(List<JsonMap> steps) {
|
||||
final grouped = <String, List<JsonMap>>{};
|
||||
for (final step in steps) {
|
||||
final stage = '${step['stage'] ?? ''}';
|
||||
grouped.putIfAbsent(stage, () => <JsonMap>[]).add(step);
|
||||
}
|
||||
return <String, List<JsonMap>>{
|
||||
for (final entry in grouped.entries) entry.key: _ordered(entry.value),
|
||||
};
|
||||
}
|
||||
|
||||
/// One selected stage visit. [step] is null when the stage has no recorded
|
||||
/// visit, so callers cannot mistake an absent capture for an execution.
|
||||
class StageVisitSelection {
|
||||
const StageVisitSelection({
|
||||
required this.stageKey,
|
||||
required this.visits,
|
||||
required this.index,
|
||||
});
|
||||
|
||||
final String stageKey;
|
||||
|
||||
/// The stage's visits ordered by sequence.
|
||||
final List<JsonMap> visits;
|
||||
|
||||
/// The clamped index into [visits]; 0 when there are none.
|
||||
final int index;
|
||||
|
||||
bool get hasVisit => visits.isNotEmpty;
|
||||
JsonMap? get step => hasVisit ? visits[index] : null;
|
||||
int get visitNumber => step == null ? 0 : displayVisit(step!, index);
|
||||
|
||||
/// True when an explicit requested index was clamped, so a caller can
|
||||
/// correct its route exactly as the web stage route does.
|
||||
bool correctedRequest(int? requested) =>
|
||||
requested != null && requested != index;
|
||||
}
|
||||
|
||||
/// Selects a stage's visit exactly as the web stage pane does.
|
||||
///
|
||||
/// A null [visitIndex] means the stage's most recent recorded visit; an
|
||||
/// out-of-range index is clamped to the last visit (negative values to the
|
||||
/// first). A stage with no recorded visits returns [StageVisitSelection.step]
|
||||
/// null instead of a fabricated visit.
|
||||
StageVisitSelection selectStageVisit(
|
||||
List<JsonMap> steps,
|
||||
String stageKey, {
|
||||
int? visitIndex,
|
||||
}) {
|
||||
final visits = visitsByStage(steps)[stageKey] ?? const <JsonMap>[];
|
||||
final wanted = visitIndex ?? (visits.isEmpty ? 0 : visits.length - 1);
|
||||
return StageVisitSelection(
|
||||
stageKey: stageKey,
|
||||
visits: visits,
|
||||
index: clampVisitIndex(wanted, visits.length),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import '../domain/graph_definition.dart';
|
||||
import 'graph_ranks.dart';
|
||||
import 'layout_models.dart';
|
||||
|
||||
/// Places definition nodes in topological columns.
|
||||
///
|
||||
/// Nodes keep definition order inside a rank, each column is as wide as its
|
||||
/// widest measured node, and columns are top-aligned. A node is centred in its
|
||||
/// column, so heterogeneous widths and text-expanded heights stay separated by
|
||||
/// [GraphLayoutConfig.rowGap] inside a rank and [GraphLayoutConfig.columnGap]
|
||||
/// between ranks. Nothing is clipped to a fixed box: the supplied measured
|
||||
/// width and height are used verbatim and the returned bounds include them.
|
||||
///
|
||||
/// [nodes] and [edges] normally come from `graphNodes`/`graphEdges`. Edges whose
|
||||
/// source or target is not one of [nodes] are ignored, so an unknown target can
|
||||
/// never invent a node. A measurement is required for every node; a missing one
|
||||
/// is an error rather than a made-up size. Extra measurement entries are
|
||||
/// ignored because they cannot become nodes.
|
||||
GraphLayout layoutGraphNodes({
|
||||
required List<GraphNode> nodes,
|
||||
required List<GraphEdge> edges,
|
||||
required Map<String, NodeExtent> extents,
|
||||
required GraphLayoutConfig config,
|
||||
}) {
|
||||
_validateNodeKeys(nodes);
|
||||
final ranks = assignGraphRanks(nodes, edges);
|
||||
final measured = <String, NodeExtent>{};
|
||||
final missing = <String>[];
|
||||
for (final node in nodes) {
|
||||
final extent = extents[node.key];
|
||||
if (extent == null) {
|
||||
missing.add(node.key);
|
||||
} else {
|
||||
measured[node.key] = extent;
|
||||
}
|
||||
}
|
||||
if (missing.isNotEmpty) {
|
||||
throw ArgumentError.value(
|
||||
missing,
|
||||
'extents',
|
||||
'missing measured extents for graph nodes',
|
||||
);
|
||||
}
|
||||
|
||||
final columns = List<List<GraphNode>>.generate(
|
||||
ranks.rankCount,
|
||||
(_) => <GraphNode>[],
|
||||
);
|
||||
for (final node in nodes) {
|
||||
columns[ranks.rankOf[node.key]!].add(node);
|
||||
}
|
||||
|
||||
final columnWidths = <double>[
|
||||
for (final column in columns)
|
||||
column.fold<double>(
|
||||
0,
|
||||
(width, node) => math.max(width, measured[node.key]!.width),
|
||||
),
|
||||
];
|
||||
final columnHeights = <double>[
|
||||
for (final column in columns)
|
||||
_columnHeight(column, measured, config.rowGap),
|
||||
];
|
||||
final columnX = <double>[];
|
||||
var nextX = config.padding;
|
||||
for (var rank = 0; rank < columns.length; rank += 1) {
|
||||
columnX.add(nextX);
|
||||
nextX += columnWidths[rank];
|
||||
if (rank + 1 < columns.length) nextX += config.columnGap;
|
||||
}
|
||||
|
||||
final boxes = <GraphNodeBox>[];
|
||||
for (var rank = 0; rank < columns.length; rank += 1) {
|
||||
var nextY = config.padding;
|
||||
for (final node in columns[rank]) {
|
||||
final extent = measured[node.key]!;
|
||||
boxes.add(
|
||||
GraphNodeBox(
|
||||
key: node.key,
|
||||
terminal: node.terminal,
|
||||
stageIndex: node.stageIndex,
|
||||
rank: rank,
|
||||
x: columnX[rank] + (columnWidths[rank] - extent.width) / 2,
|
||||
y: nextY,
|
||||
width: extent.width,
|
||||
height: extent.height,
|
||||
),
|
||||
);
|
||||
nextY += extent.height + config.rowGap;
|
||||
}
|
||||
}
|
||||
|
||||
final width =
|
||||
config.padding * 2 +
|
||||
columnWidths.fold<double>(0, (sum, column) => sum + column) +
|
||||
config.columnGap * math.max(0, columns.length - 1);
|
||||
final height =
|
||||
config.padding * 2 +
|
||||
columnHeights.fold<double>(
|
||||
0,
|
||||
(tallest, column) => math.max(tallest, column),
|
||||
);
|
||||
|
||||
return GraphLayout(
|
||||
nodes: boxes,
|
||||
width: width,
|
||||
height: height,
|
||||
rankCount: ranks.rankCount,
|
||||
ranks: ranks.rankOf,
|
||||
);
|
||||
}
|
||||
|
||||
void _validateNodeKeys(List<GraphNode> nodes) {
|
||||
final seen = <String>{};
|
||||
for (final node in nodes) {
|
||||
if (node.key.isEmpty) {
|
||||
throw ArgumentError.value(
|
||||
node.key,
|
||||
'nodes',
|
||||
'node key must not be empty',
|
||||
);
|
||||
}
|
||||
if (!seen.add(node.key)) {
|
||||
throw ArgumentError.value(node.key, 'nodes', 'duplicate graph node key');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
double _columnHeight(
|
||||
List<GraphNode> column,
|
||||
Map<String, NodeExtent> measured,
|
||||
double rowGap,
|
||||
) {
|
||||
if (column.isEmpty) return 0;
|
||||
var height = 0.0;
|
||||
for (final node in column) {
|
||||
height += measured[node.key]!.height;
|
||||
}
|
||||
return height + rowGap * (column.length - 1);
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
import 'dart:collection';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import '../domain/graph_definition.dart';
|
||||
|
||||
/// Deterministic 0-based ranks for a graph definition's nodes.
|
||||
///
|
||||
/// Ranks come from the condensation DAG: every strongly connected component
|
||||
/// shares one rank, and a component sits one past its deepest predecessor
|
||||
/// (longest path). Self loops and cycles therefore stay finite, a cycle's
|
||||
/// members do not drift apart, and disconnected nodes stay at rank 0. Edges
|
||||
/// whose endpoints are not definition nodes are ignored: an unknown target
|
||||
/// never invents a node.
|
||||
class GraphRanks {
|
||||
GraphRanks({
|
||||
required Map<String, int> rankOf,
|
||||
required this.rankCount,
|
||||
required List<List<String>> components,
|
||||
}) : rankOf = Map.unmodifiable(rankOf),
|
||||
components = List.unmodifiable(<List<String>>[
|
||||
for (final component in components) List.unmodifiable(component),
|
||||
]);
|
||||
|
||||
/// Every definition key's rank, in definition order.
|
||||
final Map<String, int> rankOf;
|
||||
|
||||
/// Number of distinct ranks, 0 for an empty node set.
|
||||
final int rankCount;
|
||||
|
||||
/// Strongly connected components as keys, each sorted by definition order and
|
||||
/// the list sorted by its first member.
|
||||
final List<List<String>> components;
|
||||
}
|
||||
|
||||
/// One DFS frame for the iterative Tarjan walk.
|
||||
class _Frame {
|
||||
_Frame(this.node);
|
||||
|
||||
final int node;
|
||||
int nextChild = 0;
|
||||
}
|
||||
|
||||
/// Assigns ranks to exactly the supplied [nodes].
|
||||
///
|
||||
/// [edges] is read for ordering only; it never adds nodes. Duplicate edges are
|
||||
/// harmless. The walk is iterative, so a deep chain cannot overflow the call
|
||||
/// stack, and the work is linear in nodes plus edges.
|
||||
GraphRanks assignGraphRanks(List<GraphNode> nodes, List<GraphEdge> edges) {
|
||||
final indexOf = <String, int>{};
|
||||
for (var index = 0; index < nodes.length; index += 1) {
|
||||
indexOf[nodes[index].key] = index;
|
||||
}
|
||||
|
||||
final adjacency = List<List<int>>.generate(nodes.length, (_) => <int>[]);
|
||||
final seenPairs = <int>{};
|
||||
for (final edge in edges) {
|
||||
final source = indexOf[edge.source];
|
||||
final target = indexOf[edge.target];
|
||||
if (source == null || target == null) continue;
|
||||
if (!seenPairs.add(source * nodes.length + target)) continue;
|
||||
adjacency[source].add(target);
|
||||
}
|
||||
|
||||
final components = _components(adjacency);
|
||||
final componentOf = List<int>.filled(nodes.length, -1);
|
||||
for (var component = 0; component < components.length; component += 1) {
|
||||
for (final node in components[component]) {
|
||||
componentOf[node] = component;
|
||||
}
|
||||
}
|
||||
|
||||
// Condensation edges and their indegrees.
|
||||
final successors = List<Set<int>>.generate(components.length, (_) => <int>{});
|
||||
final indegree = List<int>.filled(components.length, 0);
|
||||
for (var source = 0; source < adjacency.length; source += 1) {
|
||||
final from = componentOf[source];
|
||||
for (final target in adjacency[source]) {
|
||||
final to = componentOf[target];
|
||||
if (from == to) continue;
|
||||
if (successors[from].add(to)) indegree[to] += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Longest-path ranks over the condensation. Queue order only has to be a
|
||||
// topological order; the resulting rank per component is unique.
|
||||
final ranks = List<int>.filled(components.length, 0);
|
||||
final ready = ListQueue<int>();
|
||||
for (var component = 0; component < components.length; component += 1) {
|
||||
if (indegree[component] == 0) ready.add(component);
|
||||
}
|
||||
var settled = 0;
|
||||
while (ready.isNotEmpty) {
|
||||
final component = ready.removeFirst();
|
||||
settled += 1;
|
||||
for (final next in successors[component]) {
|
||||
ranks[next] = math.max(ranks[next], ranks[component] + 1);
|
||||
indegree[next] -= 1;
|
||||
if (indegree[next] == 0) ready.add(next);
|
||||
}
|
||||
}
|
||||
if (settled != components.length) {
|
||||
// The condensation cannot contain a cycle by construction; stop rather than
|
||||
// return a silently truncated layout.
|
||||
throw StateError('graph condensation was not acyclic');
|
||||
}
|
||||
|
||||
final componentKeys = <List<String>>[
|
||||
for (final component in components)
|
||||
<String>[for (final node in component) nodes[node].key],
|
||||
];
|
||||
final componentOrder = <int>[
|
||||
for (var component = 0; component < components.length; component += 1)
|
||||
component,
|
||||
]..sort((a, b) => components[a].first.compareTo(components[b].first));
|
||||
|
||||
final rankOf = <String, int>{};
|
||||
var rankCount = 0;
|
||||
for (var index = 0; index < nodes.length; index += 1) {
|
||||
final rank = ranks[componentOf[index]];
|
||||
rankOf[nodes[index].key] = rank;
|
||||
if (rank + 1 > rankCount) rankCount = rank + 1;
|
||||
}
|
||||
|
||||
return GraphRanks(
|
||||
rankOf: rankOf,
|
||||
rankCount: rankCount,
|
||||
components: <List<String>>[
|
||||
for (final component in componentOrder) componentKeys[component],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// Tarjan's strongly connected components, emitted sinks first.
|
||||
///
|
||||
/// Iterative rather than recursive so a long chain cannot exhaust the stack.
|
||||
/// Members are sorted by definition index, which keeps every output stable.
|
||||
List<List<int>> _components(List<List<int>> adjacency) {
|
||||
final discovery = List<int>.filled(adjacency.length, -1);
|
||||
final low = List<int>.filled(adjacency.length, 0);
|
||||
final onStack = List<bool>.filled(adjacency.length, false);
|
||||
final stack = <int>[];
|
||||
final components = <List<int>>[];
|
||||
var nextDiscovery = 0;
|
||||
|
||||
for (var root = 0; root < adjacency.length; root += 1) {
|
||||
if (discovery[root] != -1) continue;
|
||||
discovery[root] = low[root] = nextDiscovery;
|
||||
nextDiscovery += 1;
|
||||
stack.add(root);
|
||||
onStack[root] = true;
|
||||
final callStack = <_Frame>[_Frame(root)];
|
||||
|
||||
while (callStack.isNotEmpty) {
|
||||
final frame = callStack.last;
|
||||
final node = frame.node;
|
||||
if (frame.nextChild < adjacency[node].length) {
|
||||
final child = adjacency[node][frame.nextChild];
|
||||
frame.nextChild += 1;
|
||||
if (discovery[child] == -1) {
|
||||
discovery[child] = low[child] = nextDiscovery;
|
||||
nextDiscovery += 1;
|
||||
stack.add(child);
|
||||
onStack[child] = true;
|
||||
callStack.add(_Frame(child));
|
||||
} else if (onStack[child]) {
|
||||
low[node] = math.min(low[node], discovery[child]);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
callStack.removeLast();
|
||||
if (callStack.isNotEmpty) {
|
||||
final parent = callStack.last.node;
|
||||
low[parent] = math.min(low[parent], low[node]);
|
||||
}
|
||||
if (low[node] == discovery[node]) {
|
||||
final component = <int>[];
|
||||
while (stack.isNotEmpty) {
|
||||
final member = stack.removeLast();
|
||||
onStack[member] = false;
|
||||
component.add(member);
|
||||
if (member == node) break;
|
||||
}
|
||||
component.sort();
|
||||
components.add(component);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return components;
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
/// Pure geometry for a workflow graph's node layout.
|
||||
///
|
||||
/// Every size and gap is supplied by the caller. The native renderer measures
|
||||
/// each node after text layout (including the platform's text scaling), so this
|
||||
/// library never assumes a node width, font, palette or device class.
|
||||
///
|
||||
/// No Flutter imports: rectangles are plain numbers so the same result can be
|
||||
/// built into widgets, a canvas or a test fixture.
|
||||
library;
|
||||
|
||||
void _requireFiniteNonNegative(String name, double value) {
|
||||
if (!value.isFinite || value < 0) {
|
||||
throw ArgumentError.value(value, name, 'must be finite and non-negative');
|
||||
}
|
||||
}
|
||||
|
||||
/// One caller-measured node extent, in logical pixels.
|
||||
///
|
||||
/// A width or height may be zero for an empty label; the layout still keeps the
|
||||
/// node separate from its neighbours through the configured gaps.
|
||||
class NodeExtent {
|
||||
NodeExtent({required this.width, required this.height}) {
|
||||
_requireFiniteNonNegative('width', width);
|
||||
_requireFiniteNonNegative('height', height);
|
||||
}
|
||||
|
||||
final double width;
|
||||
final double height;
|
||||
}
|
||||
|
||||
/// The gaps a caller reserves around measured nodes.
|
||||
///
|
||||
/// [columnGap] separates adjacent ranks, [rowGap] separates nodes sharing a
|
||||
/// rank, and [padding] is the outer margin included in [GraphLayout] bounds.
|
||||
class GraphLayoutConfig {
|
||||
GraphLayoutConfig({
|
||||
required this.columnGap,
|
||||
required this.rowGap,
|
||||
this.padding = 0,
|
||||
}) {
|
||||
_requireFiniteNonNegative('columnGap', columnGap);
|
||||
_requireFiniteNonNegative('rowGap', rowGap);
|
||||
_requireFiniteNonNegative('padding', padding);
|
||||
}
|
||||
|
||||
final double columnGap;
|
||||
final double rowGap;
|
||||
final double padding;
|
||||
}
|
||||
|
||||
/// One placed node.
|
||||
///
|
||||
/// [key], [terminal] and [stageIndex] are the definition node's own identity,
|
||||
/// copied unchanged. [x]/[y] are the measured rectangle's top-left corner in
|
||||
/// graph space and [rank] is its 0-based topological column.
|
||||
class GraphNodeBox {
|
||||
const GraphNodeBox({
|
||||
required this.key,
|
||||
required this.terminal,
|
||||
required this.stageIndex,
|
||||
required this.rank,
|
||||
required this.x,
|
||||
required this.y,
|
||||
required this.width,
|
||||
required this.height,
|
||||
});
|
||||
|
||||
final String key;
|
||||
final bool terminal;
|
||||
final int? stageIndex;
|
||||
final int rank;
|
||||
final double x;
|
||||
final double y;
|
||||
final double width;
|
||||
final double height;
|
||||
|
||||
double get right => x + width;
|
||||
double get bottom => y + height;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is GraphNodeBox &&
|
||||
other.key == key &&
|
||||
other.terminal == terminal &&
|
||||
other.stageIndex == stageIndex &&
|
||||
other.rank == rank &&
|
||||
other.x == x &&
|
||||
other.y == y &&
|
||||
other.width == width &&
|
||||
other.height == height;
|
||||
|
||||
@override
|
||||
int get hashCode =>
|
||||
Object.hash(key, terminal, stageIndex, rank, x, y, width, height);
|
||||
}
|
||||
|
||||
/// An immutable node layout: every placed box plus the total graph bounds.
|
||||
///
|
||||
/// [nodes] is ordered by rank first and definition order inside a rank; use
|
||||
/// [ranks] or [nodeFor] for keyed lookup. [width] and [height] include the
|
||||
/// caller's padding; every box's [right] and [bottom] stay inside them.
|
||||
/// [ranks] exposes each definition key's 0-based rank; [rankCount] is the
|
||||
/// number of columns (0 for an empty node set).
|
||||
class GraphLayout {
|
||||
GraphLayout({
|
||||
required List<GraphNodeBox> nodes,
|
||||
required this.width,
|
||||
required this.height,
|
||||
required this.rankCount,
|
||||
required Map<String, int> ranks,
|
||||
}) : nodes = List.unmodifiable(nodes),
|
||||
ranks = Map.unmodifiable(ranks);
|
||||
|
||||
final List<GraphNodeBox> nodes;
|
||||
final Map<String, int> ranks;
|
||||
final double width;
|
||||
final double height;
|
||||
final int rankCount;
|
||||
|
||||
bool get isEmpty => nodes.isEmpty;
|
||||
|
||||
/// The placed box for [key], or null when the definition has no such node.
|
||||
GraphNodeBox? nodeFor(String key) {
|
||||
for (final node in nodes) {
|
||||
if (node.key == key) return node;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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<EdgeRoute> 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<EdgeRoute> 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);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import '../layout/layout_models.dart';
|
||||
import 'route_geometry.dart';
|
||||
import 'route_models.dart';
|
||||
|
||||
/// One vertical-corridor request from a wrapping route.
|
||||
///
|
||||
/// A route needs a track right of its source and a track beside its target;
|
||||
/// both gaps are 0-based column gaps (`rankCount` is the right free gap).
|
||||
class CorridorRequest {
|
||||
const CorridorRequest({
|
||||
required this.edgeId,
|
||||
required this.sourceGap,
|
||||
required this.targetGap,
|
||||
});
|
||||
|
||||
final int edgeId;
|
||||
final int sourceGap;
|
||||
final int targetGap;
|
||||
}
|
||||
|
||||
/// Assigned x coordinates for every wrapping route's two vertical tracks.
|
||||
class CorridorPlan {
|
||||
CorridorPlan({
|
||||
required Map<int, double> sourceX,
|
||||
required Map<int, double> targetX,
|
||||
}) : sourceX = Map.unmodifiable(sourceX),
|
||||
targetX = Map.unmodifiable(targetX);
|
||||
|
||||
final Map<int, double> sourceX;
|
||||
final Map<int, double> targetX;
|
||||
}
|
||||
|
||||
/// Spreads corridor requests across the free band of each column gap.
|
||||
///
|
||||
/// Requests keep edge-id order, so equal input yields equal coordinates. Tracks
|
||||
/// are distinct inside a gap; a narrow gap compresses the spacing instead of
|
||||
/// pushing a corridor into a node column.
|
||||
CorridorPlan planCorridors({
|
||||
required GraphLayout layout,
|
||||
required List<CorridorRequest> requests,
|
||||
required RoutingConfig config,
|
||||
}) {
|
||||
final ordered = <CorridorRequest>[...requests]
|
||||
..sort((a, b) => a.edgeId.compareTo(b.edgeId));
|
||||
final slots = <int, List<_Slot>>{};
|
||||
for (final request in ordered) {
|
||||
slots
|
||||
.putIfAbsent(request.sourceGap, () => <_Slot>[])
|
||||
.add(_Slot(request.edgeId, source: true));
|
||||
slots
|
||||
.putIfAbsent(request.targetGap, () => <_Slot>[])
|
||||
.add(_Slot(request.edgeId, source: false));
|
||||
}
|
||||
|
||||
final gaps = ColumnGaps(
|
||||
nodes: layout.nodes,
|
||||
rankCount: layout.rankCount,
|
||||
layoutWidth: layout.width,
|
||||
);
|
||||
final sourceX = <int, double>{};
|
||||
final targetX = <int, double>{};
|
||||
final gapKeys = slots.keys.toList()..sort();
|
||||
for (final gapKey in gapKeys) {
|
||||
final gapSlots = slots[gapKey]!;
|
||||
final band = gaps.band(gapKey, config.nodeClearance);
|
||||
final positions = _trackPositions(
|
||||
band,
|
||||
gapSlots.length,
|
||||
config.corridorSpacing,
|
||||
);
|
||||
for (var index = 0; index < gapSlots.length; index += 1) {
|
||||
if (gapSlots[index].source) {
|
||||
sourceX[gapSlots[index].edgeId] = positions[index];
|
||||
} else {
|
||||
targetX[gapSlots[index].edgeId] = positions[index];
|
||||
}
|
||||
}
|
||||
}
|
||||
return CorridorPlan(sourceX: sourceX, targetX: targetX);
|
||||
}
|
||||
|
||||
List<double> _trackPositions(GapBand band, int count, double spacing) {
|
||||
if (count == 0) return const <double>[];
|
||||
if (band.open) {
|
||||
return <double>[
|
||||
for (var index = 0; index < count; index += 1) band.lo + spacing * index,
|
||||
];
|
||||
}
|
||||
final width = band.hi - band.lo;
|
||||
if (count == 1) return <double>[(band.lo + band.hi) / 2];
|
||||
if (width <= 0) return List<double>.filled(count, band.lo);
|
||||
final step = math.min(spacing, width / (count - 1));
|
||||
return <double>[
|
||||
for (var index = 0; index < count; index += 1) band.lo + step * index,
|
||||
];
|
||||
}
|
||||
|
||||
class _Slot {
|
||||
const _Slot(this.edgeId, {required this.source});
|
||||
|
||||
final int edgeId;
|
||||
final bool source;
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import '../layout/layout_models.dart';
|
||||
import 'route_geometry.dart';
|
||||
import 'route_models.dart';
|
||||
|
||||
/// Places one measured edge label without overlapping a node or another label.
|
||||
///
|
||||
/// Candidates are tried in a deterministic order: the midpoint of each
|
||||
/// horizontal run (above, then below), then each vertical run (right, then
|
||||
/// left), sliding along the run before giving up. A run too narrow for the
|
||||
/// box pushes the label to a free shelf below the drawing, which expands the
|
||||
/// routing bounds instead of covering a node.
|
||||
EdgeLabelBox placeEdgeLabel({
|
||||
required EdgeRoute route,
|
||||
required LabelExtent extent,
|
||||
required List<GraphNodeBox> nodes,
|
||||
required List<EdgeLabelBox> placed,
|
||||
required RoutingConfig config,
|
||||
required double floorY,
|
||||
}) {
|
||||
final width = extent.width;
|
||||
final height = extent.height;
|
||||
for (final candidate in _candidates(route, width, height, config.labelGap)) {
|
||||
final box = EdgeLabelBox(
|
||||
edgeId: route.id,
|
||||
x: candidate.x,
|
||||
y: candidate.y,
|
||||
width: width,
|
||||
height: height,
|
||||
);
|
||||
if (_fits(box, nodes, placed, config)) return box;
|
||||
}
|
||||
|
||||
// The fallback shelf is below every route and every existing label, so it
|
||||
// cannot cover a node. Growing it down expands the returned bounds.
|
||||
var top = math.max(
|
||||
floorY,
|
||||
placed.fold<double>(0, (bottom, box) => math.max(bottom, box.bottom)),
|
||||
);
|
||||
top += config.labelGap;
|
||||
final centre = _routeCentreX(route);
|
||||
final step = math.max(height + config.labelGap, 1.0);
|
||||
for (var attempt = 0; attempt < 100000; attempt += 1) {
|
||||
final x = math.max(0.0, centre - width / 2);
|
||||
final box = EdgeLabelBox(
|
||||
edgeId: route.id,
|
||||
x: x,
|
||||
y: top,
|
||||
width: width,
|
||||
height: height,
|
||||
);
|
||||
if (_fits(box, nodes, placed, config)) return box;
|
||||
top += step;
|
||||
}
|
||||
// A zero-sized label cannot collide; this is unreachable for real extents.
|
||||
return EdgeLabelBox(
|
||||
edgeId: route.id,
|
||||
x: math.max(0.0, centre - width / 2),
|
||||
y: top,
|
||||
width: width,
|
||||
height: height,
|
||||
);
|
||||
}
|
||||
|
||||
bool _fits(
|
||||
EdgeLabelBox box,
|
||||
List<GraphNodeBox> nodes,
|
||||
List<EdgeLabelBox> placed,
|
||||
RoutingConfig config,
|
||||
) {
|
||||
if (box.x < 0 || box.y < 0) return false;
|
||||
for (final node in nodes) {
|
||||
if (boxIntersectsNode(
|
||||
x: box.x,
|
||||
y: box.y,
|
||||
width: box.width,
|
||||
height: box.height,
|
||||
node: node,
|
||||
gap: config.labelGap,
|
||||
)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for (final other in placed) {
|
||||
if (boxesOverlap(
|
||||
ax: box.x,
|
||||
ay: box.y,
|
||||
aw: box.width,
|
||||
ah: box.height,
|
||||
bx: other.x,
|
||||
by: other.y,
|
||||
bw: other.width,
|
||||
bh: other.height,
|
||||
gap: config.labelGap,
|
||||
)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
List<_LabelCandidate> _candidates(
|
||||
EdgeRoute route,
|
||||
double width,
|
||||
double height,
|
||||
double gap,
|
||||
) {
|
||||
const fractions = <double>[0.5, 0.35, 0.65, 0.2, 0.8, 0.08, 0.92];
|
||||
final horizontals = <_Run>[];
|
||||
final verticals = <_Run>[];
|
||||
for (var index = 1; index < route.points.length; index += 1) {
|
||||
final a = route.points[index - 1];
|
||||
final b = route.points[index];
|
||||
if (a.y == b.y) {
|
||||
horizontals.add(_Run(a, b, (b.x - a.x).abs(), index));
|
||||
} else if (a.x == b.x) {
|
||||
verticals.add(_Run(a, b, (b.y - a.y).abs(), index));
|
||||
}
|
||||
}
|
||||
horizontals.sort((a, b) {
|
||||
final length = b.length.compareTo(a.length);
|
||||
return length != 0 ? length : a.order.compareTo(b.order);
|
||||
});
|
||||
verticals.sort((a, b) {
|
||||
final length = b.length.compareTo(a.length);
|
||||
return length != 0 ? length : a.order.compareTo(b.order);
|
||||
});
|
||||
|
||||
final candidates = <_LabelCandidate>[];
|
||||
for (final run in horizontals) {
|
||||
for (final fraction in fractions) {
|
||||
final x = run.a.x + (run.b.x - run.a.x) * fraction;
|
||||
final left = x - width / 2;
|
||||
candidates.add(_LabelCandidate(left, run.a.y - gap - height));
|
||||
candidates.add(_LabelCandidate(left, run.a.y + gap));
|
||||
}
|
||||
}
|
||||
for (final run in verticals) {
|
||||
for (final fraction in fractions) {
|
||||
final y = run.a.y + (run.b.y - run.a.y) * fraction;
|
||||
final top = y - height / 2;
|
||||
candidates.add(_LabelCandidate(run.a.x + gap, top));
|
||||
candidates.add(_LabelCandidate(run.a.x - gap - width, top));
|
||||
}
|
||||
}
|
||||
return candidates;
|
||||
}
|
||||
|
||||
double _routeCentreX(EdgeRoute route) {
|
||||
if (route.points.isEmpty) return 0;
|
||||
var lo = route.points.first.x;
|
||||
var hi = lo;
|
||||
for (final point in route.points) {
|
||||
lo = math.min(lo, point.x);
|
||||
hi = math.max(hi, point.x);
|
||||
}
|
||||
return (lo + hi) / 2;
|
||||
}
|
||||
|
||||
class _Run {
|
||||
const _Run(this.a, this.b, this.length, this.order);
|
||||
|
||||
final RoutePoint a;
|
||||
final RoutePoint b;
|
||||
final double length;
|
||||
final int order;
|
||||
}
|
||||
|
||||
class _LabelCandidate {
|
||||
const _LabelCandidate(this.x, this.y);
|
||||
|
||||
final double x;
|
||||
final double y;
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import '../domain/graph_definition.dart';
|
||||
import '../layout/layout_models.dart';
|
||||
import 'corridor_plan.dart';
|
||||
import 'route_geometry.dart';
|
||||
import 'route_models.dart';
|
||||
|
||||
/// One routed edge before labels and bounds are assembled.
|
||||
///
|
||||
/// Internal to the routing library: callers receive the immutable public
|
||||
/// [EdgeRoute] instead.
|
||||
class PlannedEdgeRoute {
|
||||
PlannedEdgeRoute({
|
||||
required this.edge,
|
||||
required this.kind,
|
||||
required this.straight,
|
||||
required this.sourcePort,
|
||||
required this.targetPort,
|
||||
required List<RoutePoint> points,
|
||||
}) : points = List.unmodifiable(points);
|
||||
|
||||
final GraphEdge edge;
|
||||
final RouteKind kind;
|
||||
final bool straight;
|
||||
final RoutePort sourcePort;
|
||||
final RoutePort targetPort;
|
||||
final List<RoutePoint> points;
|
||||
|
||||
EdgeRoute toRoute() => EdgeRoute(
|
||||
id: edge.id,
|
||||
source: edge.source,
|
||||
outcome: edge.outcome,
|
||||
target: edge.target,
|
||||
label: edge.label,
|
||||
fallback: edge.fallback,
|
||||
kind: kind,
|
||||
straight: straight,
|
||||
sourcePort: sourcePort,
|
||||
targetPort: targetPort,
|
||||
points: points,
|
||||
);
|
||||
}
|
||||
|
||||
/// Plans orthogonal polylines for every edge whose endpoints have placed boxes.
|
||||
///
|
||||
/// [edges] must already be filtered to known endpoints and sorted by id. The
|
||||
/// plan is deterministic: forward one-rank routes take a straight horizontal
|
||||
/// run when the measured boxes and labels leave room, and every other route
|
||||
/// gets a unique lane below the node grid plus vertical corridors inside the
|
||||
/// column gaps. Corridors and lanes never enter a node column.
|
||||
///
|
||||
/// All horizontal stubs share one [AxisTrackAllocator], so two different edges
|
||||
/// cannot occupy the same run in a column gap even when they touch different
|
||||
/// nodes on the same row.
|
||||
List<PlannedEdgeRoute> planEdgeRoutes({
|
||||
required GraphLayout layout,
|
||||
required List<GraphEdge> edges,
|
||||
required double maxLabelHeight,
|
||||
required RoutingConfig config,
|
||||
}) {
|
||||
if (edges.isEmpty) return const <PlannedEdgeRoute>[];
|
||||
final nodes = <String, GraphNodeBox>{
|
||||
for (final node in layout.nodes) node.key: node,
|
||||
};
|
||||
final kinds = <int, RouteKind>{};
|
||||
for (final edge in edges) {
|
||||
final source = nodes[edge.source]!;
|
||||
final target = nodes[edge.target]!;
|
||||
kinds[edge.id] = _kindFor(edge, source, target, layout);
|
||||
}
|
||||
|
||||
final trackSpacing = math.max(
|
||||
config.portSpacing,
|
||||
maxLabelHeight + config.labelGap,
|
||||
);
|
||||
final runs = AxisTrackAllocator(trackSpacing);
|
||||
final straightY = <int, double>{};
|
||||
for (final edge in edges) {
|
||||
if (kinds[edge.id] != RouteKind.forward) continue;
|
||||
final source = nodes[edge.source]!;
|
||||
final target = nodes[edge.target]!;
|
||||
if (target.rank != source.rank + 1) continue;
|
||||
if (target.x <= source.right) continue;
|
||||
final sourceInset = portInset(source, config.portSpacing);
|
||||
final targetInset = portInset(target, config.portSpacing);
|
||||
final lo = math.max(source.y + sourceInset, target.y + targetInset);
|
||||
final hi = math.min(
|
||||
source.bottom - sourceInset,
|
||||
target.bottom - targetInset,
|
||||
);
|
||||
if (hi <= lo) continue;
|
||||
final y = runs.allocate(
|
||||
desired: (lo + hi) / 2,
|
||||
min: lo,
|
||||
max: hi,
|
||||
spanLo: source.right,
|
||||
spanHi: target.x,
|
||||
);
|
||||
if (y != null) straightY[edge.id] = y;
|
||||
}
|
||||
|
||||
final laneStep = math.max(
|
||||
config.laneSpacing,
|
||||
maxLabelHeight + config.labelGap,
|
||||
);
|
||||
final contentBottom = layout.nodes.fold<double>(
|
||||
0,
|
||||
(bottom, node) => math.max(bottom, node.bottom),
|
||||
);
|
||||
final wrapPlans = <_WrapPlan>[];
|
||||
final corridorRequests = <CorridorRequest>[];
|
||||
var laneIndex = 0;
|
||||
for (final edge in edges) {
|
||||
if (straightY.containsKey(edge.id)) continue;
|
||||
final source = nodes[edge.source]!;
|
||||
final target = nodes[edge.target]!;
|
||||
final kind = kinds[edge.id]!;
|
||||
final laneY =
|
||||
contentBottom + config.nodeClearance + laneStep * (laneIndex + 1);
|
||||
laneIndex += 1;
|
||||
final sourceGap = (source.rank + 1).clamp(0, layout.rankCount);
|
||||
final targetGap = kind == RouteKind.forward
|
||||
? target.rank.clamp(0, layout.rankCount)
|
||||
: (target.rank + 1).clamp(0, layout.rankCount);
|
||||
corridorRequests.add(
|
||||
CorridorRequest(
|
||||
edgeId: edge.id,
|
||||
sourceGap: sourceGap,
|
||||
targetGap: targetGap,
|
||||
),
|
||||
);
|
||||
wrapPlans.add(_WrapPlan(edge: edge, kind: kind, laneY: laneY));
|
||||
}
|
||||
|
||||
final corridors = planCorridors(
|
||||
layout: layout,
|
||||
requests: corridorRequests,
|
||||
config: config,
|
||||
);
|
||||
final sourceTrackX = corridors.sourceX;
|
||||
final targetTrackX = corridors.targetX;
|
||||
|
||||
final sourcePorts = <int, RoutePort>{};
|
||||
final targetPorts = <int, RoutePort>{};
|
||||
for (final edge in edges) {
|
||||
final y = straightY[edge.id];
|
||||
if (y == null) continue;
|
||||
final source = nodes[edge.source]!;
|
||||
final target = nodes[edge.target]!;
|
||||
sourcePorts[edge.id] = RoutePort(
|
||||
side: RoutePortSide.right,
|
||||
point: RoutePoint(source.right, y),
|
||||
);
|
||||
targetPorts[edge.id] = RoutePort(
|
||||
side: RoutePortSide.left,
|
||||
point: RoutePoint(target.x, y),
|
||||
);
|
||||
}
|
||||
for (final plan in wrapPlans) {
|
||||
final edge = plan.edge;
|
||||
final source = nodes[edge.source]!;
|
||||
final target = nodes[edge.target]!;
|
||||
final sourceTrack = sourceTrackX[edge.id]!;
|
||||
final targetTrack = targetTrackX[edge.id]!;
|
||||
final sourceInset = portInset(source, config.portSpacing);
|
||||
final targetInset = portInset(target, config.portSpacing);
|
||||
final sourceY = runs.allocate(
|
||||
desired: source.y + source.height / 2,
|
||||
min: source.y + sourceInset,
|
||||
max: source.bottom - sourceInset,
|
||||
spanLo: source.right,
|
||||
spanHi: sourceTrack,
|
||||
);
|
||||
final targetSide = plan.kind == RouteKind.forward
|
||||
? RoutePortSide.left
|
||||
: RoutePortSide.right;
|
||||
final targetBorder = targetSide == RoutePortSide.left
|
||||
? target.x
|
||||
: target.right;
|
||||
final targetY = runs.allocate(
|
||||
desired: target.y + target.height / 2,
|
||||
min: target.y + targetInset,
|
||||
max: target.bottom - targetInset,
|
||||
spanLo: math.min(targetBorder, targetTrack),
|
||||
spanHi: math.max(targetBorder, targetTrack),
|
||||
);
|
||||
sourcePorts[edge.id] = RoutePort(
|
||||
side: RoutePortSide.right,
|
||||
point: RoutePoint(source.right, sourceY ?? source.y + source.height / 2),
|
||||
);
|
||||
targetPorts[edge.id] = RoutePort(
|
||||
side: targetSide,
|
||||
point: RoutePoint(targetBorder, targetY ?? target.y + target.height / 2),
|
||||
);
|
||||
}
|
||||
|
||||
final planned = <int, PlannedEdgeRoute>{};
|
||||
for (final edge in edges) {
|
||||
final value = straightY[edge.id];
|
||||
if (value != null) {
|
||||
planned[edge.id] = PlannedEdgeRoute(
|
||||
edge: edge,
|
||||
kind: kinds[edge.id]!,
|
||||
straight: true,
|
||||
sourcePort: sourcePorts[edge.id]!,
|
||||
targetPort: targetPorts[edge.id]!,
|
||||
points: _collapse(<RoutePoint>[
|
||||
sourcePorts[edge.id]!.point,
|
||||
targetPorts[edge.id]!.point,
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
for (final plan in wrapPlans) {
|
||||
final sourceTrack = sourceTrackX[plan.edge.id]!;
|
||||
final targetTrack = targetTrackX[plan.edge.id]!;
|
||||
planned[plan.edge.id] = PlannedEdgeRoute(
|
||||
edge: plan.edge,
|
||||
kind: plan.kind,
|
||||
straight: false,
|
||||
sourcePort: sourcePorts[plan.edge.id]!,
|
||||
targetPort: targetPorts[plan.edge.id]!,
|
||||
points: _collapse(<RoutePoint>[
|
||||
sourcePorts[plan.edge.id]!.point,
|
||||
RoutePoint(sourceTrack, sourcePorts[plan.edge.id]!.point.y),
|
||||
RoutePoint(sourceTrack, plan.laneY),
|
||||
RoutePoint(targetTrack, plan.laneY),
|
||||
RoutePoint(targetTrack, targetPorts[plan.edge.id]!.point.y),
|
||||
targetPorts[plan.edge.id]!.point,
|
||||
]),
|
||||
);
|
||||
}
|
||||
return <PlannedEdgeRoute>[for (final edge in edges) planned[edge.id]!];
|
||||
}
|
||||
|
||||
RouteKind _kindFor(
|
||||
GraphEdge edge,
|
||||
GraphNodeBox source,
|
||||
GraphNodeBox target,
|
||||
GraphLayout layout,
|
||||
) {
|
||||
if (edge.source == edge.target) return RouteKind.selfLoop;
|
||||
final sourceRank = layout.ranks[edge.source] ?? source.rank;
|
||||
final targetRank = layout.ranks[edge.target] ?? target.rank;
|
||||
if (targetRank > sourceRank) return RouteKind.forward;
|
||||
if (targetRank < sourceRank) return RouteKind.back;
|
||||
return RouteKind.sameRank;
|
||||
}
|
||||
|
||||
List<RoutePoint> _collapse(List<RoutePoint> points) {
|
||||
final result = <RoutePoint>[];
|
||||
for (final point in points) {
|
||||
if (result.isEmpty || result.last != point) result.add(point);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
class _WrapPlan {
|
||||
_WrapPlan({required this.edge, required this.kind, required this.laneY});
|
||||
|
||||
final GraphEdge edge;
|
||||
final RouteKind kind;
|
||||
final double laneY;
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import '../domain/graph_definition.dart';
|
||||
import '../layout/layout_models.dart';
|
||||
import 'edge_label_placement.dart';
|
||||
import 'edge_route_planner.dart';
|
||||
import 'route_models.dart';
|
||||
|
||||
/// Routes every definition edge that has a placed source and target.
|
||||
///
|
||||
/// The node boxes and ranks come from the landed [GraphLayout]; this function
|
||||
/// never moves them, invents a node or assumes a node size. Callers supply one
|
||||
/// measured [LabelExtent] for every routed edge, plus the clearances and lane
|
||||
/// spacing in [RoutingConfig].
|
||||
///
|
||||
/// Edges with an unknown, empty or missing endpoint are returned in
|
||||
/// [GraphRouting.skipped] with their definition identity intact. A routed edge
|
||||
/// keeps its id, source, outcome, target, label and fallback flag. Results are
|
||||
/// ordered by definition edge id and are stable for repeated input.
|
||||
GraphRouting routeGraphEdges({
|
||||
required GraphLayout layout,
|
||||
required List<GraphEdge> edges,
|
||||
required Map<int, LabelExtent> labelExtents,
|
||||
required RoutingConfig config,
|
||||
}) {
|
||||
final ordered = <GraphEdge>[...edges]..sort((a, b) => a.id.compareTo(b.id));
|
||||
final seenIds = <int>{};
|
||||
for (final edge in ordered) {
|
||||
if (!seenIds.add(edge.id)) {
|
||||
throw ArgumentError.value(edge.id, 'edges', 'duplicate edge id');
|
||||
}
|
||||
}
|
||||
|
||||
final nodes = <String, GraphNodeBox>{
|
||||
for (final node in layout.nodes) node.key: node,
|
||||
};
|
||||
final routed = <GraphEdge>[];
|
||||
final skipped = <RouteDiagnostic>[];
|
||||
for (final edge in ordered) {
|
||||
if (!nodes.containsKey(edge.source)) {
|
||||
skipped.add(
|
||||
RouteDiagnostic(
|
||||
id: edge.id,
|
||||
source: edge.source,
|
||||
outcome: edge.outcome,
|
||||
target: edge.target,
|
||||
reason: RouteSkipReason.unknownSource,
|
||||
message: 'source "${edge.source}" has no placed node',
|
||||
),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (!edge.knownTarget || !nodes.containsKey(edge.target)) {
|
||||
skipped.add(
|
||||
RouteDiagnostic(
|
||||
id: edge.id,
|
||||
source: edge.source,
|
||||
outcome: edge.outcome,
|
||||
target: edge.target,
|
||||
reason: RouteSkipReason.unknownTarget,
|
||||
message: edge.target.isEmpty
|
||||
? 'edge target is empty'
|
||||
: 'target "${edge.target}" has no placed node',
|
||||
),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
routed.add(edge);
|
||||
}
|
||||
|
||||
final missing = <int>[
|
||||
for (final edge in routed)
|
||||
if (!labelExtents.containsKey(edge.id)) edge.id,
|
||||
];
|
||||
if (missing.isNotEmpty) {
|
||||
throw ArgumentError.value(
|
||||
missing,
|
||||
'labelExtents',
|
||||
'missing measured label extents for routed edges',
|
||||
);
|
||||
}
|
||||
|
||||
var maxLabelHeight = 0.0;
|
||||
for (final edge in routed) {
|
||||
maxLabelHeight = math.max(maxLabelHeight, labelExtents[edge.id]!.height);
|
||||
}
|
||||
final planned = planEdgeRoutes(
|
||||
layout: layout,
|
||||
edges: routed,
|
||||
maxLabelHeight: maxLabelHeight,
|
||||
config: config,
|
||||
);
|
||||
final routes = <EdgeRoute>[for (final plan in planned) plan.toRoute()];
|
||||
var floorY = layout.height;
|
||||
for (final route in routes) {
|
||||
for (final point in route.points) {
|
||||
floorY = math.max(floorY, point.y);
|
||||
}
|
||||
}
|
||||
|
||||
final labels = <EdgeLabelBox>[];
|
||||
for (var index = 0; index < routes.length; index += 1) {
|
||||
labels.add(
|
||||
placeEdgeLabel(
|
||||
route: routes[index],
|
||||
extent: labelExtents[routes[index].id]!,
|
||||
nodes: layout.nodes,
|
||||
placed: labels,
|
||||
config: config,
|
||||
floorY: floorY,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
var width = layout.width;
|
||||
var height = layout.height;
|
||||
for (final route in routes) {
|
||||
for (final point in route.points) {
|
||||
width = math.max(width, point.x);
|
||||
height = math.max(height, point.y);
|
||||
}
|
||||
}
|
||||
for (final label in labels) {
|
||||
width = math.max(width, label.right);
|
||||
height = math.max(height, label.bottom);
|
||||
}
|
||||
|
||||
return GraphRouting(
|
||||
routes: routes,
|
||||
labels: labels,
|
||||
skipped: skipped,
|
||||
width: width + config.boundsPadding,
|
||||
height: height + config.boundsPadding,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import '../layout/layout_models.dart';
|
||||
|
||||
/// Geometry helpers for deterministic orthogonal routing.
|
||||
///
|
||||
/// Everything here is plain numbers: no Flutter types, no drawing and no
|
||||
/// assumed metrics. The helpers are internal to the routing library.
|
||||
|
||||
/// Reserves horizontal or vertical tracks without collinear overlap.
|
||||
///
|
||||
/// A track is a position on [axis] plus the interval it spans on the other
|
||||
/// axis. Two tracks only conflict when both their positions and their spans
|
||||
/// overlap, so a long cross lane and a short stub may share a coordinate when
|
||||
/// their runs do not meet.
|
||||
class AxisTrackAllocator {
|
||||
AxisTrackAllocator(this.step);
|
||||
|
||||
final double step;
|
||||
final List<_Track> _placed = <_Track>[];
|
||||
|
||||
/// The nearest free position to [desired], or null when none is found.
|
||||
double? allocate({
|
||||
required double desired,
|
||||
required double min,
|
||||
required double max,
|
||||
required double spanLo,
|
||||
required double spanHi,
|
||||
}) {
|
||||
if (max < min) return null;
|
||||
final start = desired.clamp(min, max);
|
||||
var spacing = step;
|
||||
while (spacing > 0.0001) {
|
||||
for (var attempt = 0; attempt <= 512; attempt += 1) {
|
||||
final candidates = attempt == 0
|
||||
? <double>[start]
|
||||
: <double>[start + attempt * spacing, start - attempt * spacing];
|
||||
for (final candidate in candidates) {
|
||||
if (candidate < min || candidate > max) continue;
|
||||
if (_isFree(candidate, spanLo, spanHi, spacing)) {
|
||||
_placed.add(_Track(candidate, spanLo, spanHi));
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
spacing /= 2;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
bool _isFree(double position, double spanLo, double spanHi, double spacing) {
|
||||
for (final track in _placed) {
|
||||
if ((track.position - position).abs() >= spacing) continue;
|
||||
final overlaps = track.lo <= spanHi && spanLo <= track.hi;
|
||||
if (overlaps) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
class _Track {
|
||||
const _Track(this.position, this.lo, this.hi);
|
||||
|
||||
final double position;
|
||||
final double lo;
|
||||
final double hi;
|
||||
}
|
||||
|
||||
/// The x band available for vertical corridors in each column gap.
|
||||
///
|
||||
/// Gap `g` sits before rank `g`; gap `rankCount` is the free space right of the
|
||||
/// last column. Left/right bounds come from the placed boxes themselves, so a
|
||||
/// corridor never crosses a column, including heterogeneous node widths.
|
||||
class ColumnGaps {
|
||||
ColumnGaps({
|
||||
required List<GraphNodeBox> nodes,
|
||||
required this.rankCount,
|
||||
required this.layoutWidth,
|
||||
}) : _left = List<double>.filled(rankCount + 1, 0),
|
||||
_right = List<double>.filled(rankCount + 1, layoutWidth) {
|
||||
final rankRight = List<double>.filled(rankCount, 0);
|
||||
final rankLeft = List<double>.filled(rankCount, layoutWidth);
|
||||
for (final node in nodes) {
|
||||
if (node.rank < 0 || node.rank >= rankCount) continue;
|
||||
rankRight[node.rank] = math.max(rankRight[node.rank], node.right);
|
||||
rankLeft[node.rank] = math.min(rankLeft[node.rank], node.x);
|
||||
}
|
||||
var left = 0.0;
|
||||
for (var rank = 0; rank < rankCount; rank += 1) {
|
||||
_left[rank] = left;
|
||||
left = math.max(left, rankRight[rank]);
|
||||
}
|
||||
_left[rankCount] = left;
|
||||
var right = layoutWidth;
|
||||
_right[rankCount] = right;
|
||||
for (var rank = rankCount - 1; rank >= 0; rank -= 1) {
|
||||
right = math.min(right, rankLeft[rank]);
|
||||
_right[rank] = right;
|
||||
}
|
||||
}
|
||||
|
||||
final int rankCount;
|
||||
final double layoutWidth;
|
||||
final List<double> _left;
|
||||
final List<double> _right;
|
||||
|
||||
/// The usable band in gap [index], inset by at most [clearance].
|
||||
///
|
||||
/// The rightmost gap is open-ended because a loop may expand the canvas;
|
||||
/// every other gap is bounded by the neighbouring columns.
|
||||
GapBand band(int index, double clearance) {
|
||||
final gap = index.clamp(0, rankCount);
|
||||
final left = _left[gap];
|
||||
final right = _right[gap];
|
||||
if (gap == rankCount) {
|
||||
return GapBand(lo: left + clearance, hi: double.infinity, open: true);
|
||||
}
|
||||
if (gap == 0) {
|
||||
return GapBand(
|
||||
lo: double.negativeInfinity,
|
||||
hi: right - clearance,
|
||||
open: true,
|
||||
);
|
||||
}
|
||||
final width = math.max(0.0, right - left);
|
||||
final inset = math.min(clearance, width / 4);
|
||||
return GapBand(lo: left + inset, hi: right - inset, open: false);
|
||||
}
|
||||
}
|
||||
|
||||
/// One usable corridor band.
|
||||
class GapBand {
|
||||
const GapBand({required this.lo, required this.hi, required this.open});
|
||||
|
||||
final double lo;
|
||||
final double hi;
|
||||
final bool open;
|
||||
}
|
||||
|
||||
/// The inset a port keeps from a node corner.
|
||||
double portInset(GraphNodeBox node, double portSpacing) =>
|
||||
math.min(portSpacing / 2, node.height / 2);
|
||||
|
||||
/// True when an axis-aligned box overlaps [node], optionally inflated by [gap].
|
||||
bool boxIntersectsNode({
|
||||
required double x,
|
||||
required double y,
|
||||
required double width,
|
||||
required double height,
|
||||
required GraphNodeBox node,
|
||||
double gap = 0,
|
||||
}) {
|
||||
return x < node.right + gap &&
|
||||
x + width > node.x - gap &&
|
||||
y < node.bottom + gap &&
|
||||
y + height > node.y - gap;
|
||||
}
|
||||
|
||||
/// True when two label-sized boxes overlap, optionally inflated by [gap].
|
||||
bool boxesOverlap({
|
||||
required double ax,
|
||||
required double ay,
|
||||
required double aw,
|
||||
required double ah,
|
||||
required double bx,
|
||||
required double by,
|
||||
required double bw,
|
||||
required double bh,
|
||||
double gap = 0,
|
||||
}) {
|
||||
return ax < bx + bw + gap &&
|
||||
ax + aw + gap > bx &&
|
||||
ay < by + bh + gap &&
|
||||
ay + ah + gap > by;
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
/// Pure orthogonal geometry for a workflow graph's edges and labels.
|
||||
///
|
||||
/// The caller owns every measurement: node boxes come from the landed
|
||||
/// `GraphLayout`, label extents are measured after text layout, and clearances
|
||||
/// or spacings come from [RoutingConfig]. This library never assumes a font,
|
||||
/// widget style, device class or CSS value, and it has no Flutter imports.
|
||||
///
|
||||
/// The same result can be built into a painter, native widgets or a test
|
||||
/// fixture; no drawing decision lives here.
|
||||
library;
|
||||
|
||||
export 'routing_inputs.dart';
|
||||
|
||||
/// One point on an orthogonal route, in graph space.
|
||||
class RoutePoint {
|
||||
const RoutePoint(this.x, this.y);
|
||||
|
||||
final double x;
|
||||
final double y;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is RoutePoint && other.x == x && other.y == y;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(x, y);
|
||||
|
||||
@override
|
||||
String toString() => 'RoutePoint($x, $y)';
|
||||
}
|
||||
|
||||
/// The border an edge leaves or enters through.
|
||||
enum RoutePortSide { top, right, bottom, left }
|
||||
|
||||
/// A route endpoint on a node's border.
|
||||
///
|
||||
/// [side] is the edge's outward direction: a right port leaves to the right
|
||||
/// (or enters from the right), a left port leaves to the left, and so on.
|
||||
class RoutePort {
|
||||
const RoutePort({required this.side, required this.point});
|
||||
|
||||
final RoutePortSide side;
|
||||
final RoutePoint point;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is RoutePort && other.side == side && other.point == point;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(side, point);
|
||||
|
||||
@override
|
||||
String toString() => 'RoutePort($side, ${point.x}, ${point.y})';
|
||||
}
|
||||
|
||||
/// How an edge relates to the layer it comes from.
|
||||
enum RouteKind {
|
||||
/// The target is in a later rank.
|
||||
forward,
|
||||
|
||||
/// Both endpoints share a rank (a cycle or strongly connected component).
|
||||
sameRank,
|
||||
|
||||
/// The target is in an earlier rank. Ranks from `assignGraphRanks` only
|
||||
/// produce this for a caller-supplied layout; it is still routed honestly.
|
||||
back,
|
||||
|
||||
/// The source and target are the same node.
|
||||
selfLoop,
|
||||
}
|
||||
|
||||
/// Why an edge has no route.
|
||||
enum RouteSkipReason {
|
||||
/// The source key has no placed node.
|
||||
unknownSource,
|
||||
|
||||
/// The target key has no placed node, including an empty/unknown target.
|
||||
unknownTarget,
|
||||
}
|
||||
|
||||
/// One edge's deterministic orthogonal route.
|
||||
///
|
||||
/// [id], [source], [outcome], [target], [label] and [fallback] are copied from
|
||||
/// the definition edge unchanged. [points] starts at [sourcePort] and ends at
|
||||
/// [targetPort]; every consecutive pair shares one coordinate.
|
||||
class EdgeRoute {
|
||||
EdgeRoute({
|
||||
required this.id,
|
||||
required this.source,
|
||||
required this.outcome,
|
||||
required this.target,
|
||||
required this.label,
|
||||
required this.fallback,
|
||||
required this.kind,
|
||||
required this.straight,
|
||||
required this.sourcePort,
|
||||
required this.targetPort,
|
||||
required List<RoutePoint> points,
|
||||
}) : points = List.unmodifiable(points);
|
||||
|
||||
final int id;
|
||||
final String source;
|
||||
final String outcome;
|
||||
final String target;
|
||||
final String label;
|
||||
final bool fallback;
|
||||
final RouteKind kind;
|
||||
|
||||
/// True when the route is one straight horizontal segment.
|
||||
final bool straight;
|
||||
final RoutePort sourcePort;
|
||||
final RoutePort targetPort;
|
||||
final List<RoutePoint> points;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is EdgeRoute &&
|
||||
other.id == id &&
|
||||
other.source == source &&
|
||||
other.outcome == outcome &&
|
||||
other.target == target &&
|
||||
other.label == label &&
|
||||
other.fallback == fallback &&
|
||||
other.kind == kind &&
|
||||
other.straight == straight &&
|
||||
other.sourcePort == sourcePort &&
|
||||
other.targetPort == targetPort &&
|
||||
_samePoints(other.points, points);
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(
|
||||
id,
|
||||
source,
|
||||
outcome,
|
||||
target,
|
||||
label,
|
||||
fallback,
|
||||
kind,
|
||||
straight,
|
||||
sourcePort,
|
||||
targetPort,
|
||||
Object.hashAll(points),
|
||||
);
|
||||
}
|
||||
|
||||
/// One measured label box placed clear of node interiors.
|
||||
class EdgeLabelBox {
|
||||
const EdgeLabelBox({
|
||||
required this.edgeId,
|
||||
required this.x,
|
||||
required this.y,
|
||||
required this.width,
|
||||
required this.height,
|
||||
});
|
||||
|
||||
final int edgeId;
|
||||
final double x;
|
||||
final double y;
|
||||
final double width;
|
||||
final double height;
|
||||
|
||||
double get right => x + width;
|
||||
double get bottom => y + height;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is EdgeLabelBox &&
|
||||
other.edgeId == edgeId &&
|
||||
other.x == x &&
|
||||
other.y == y &&
|
||||
other.width == width &&
|
||||
other.height == height;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(edgeId, x, y, width, height);
|
||||
}
|
||||
|
||||
/// An edge the router deliberately did not draw.
|
||||
///
|
||||
/// The definition identity is preserved so a caller can present a diagnostic
|
||||
/// instead of inventing a node, route or visit.
|
||||
class RouteDiagnostic {
|
||||
const RouteDiagnostic({
|
||||
required this.id,
|
||||
required this.source,
|
||||
required this.outcome,
|
||||
required this.target,
|
||||
required this.reason,
|
||||
required this.message,
|
||||
});
|
||||
|
||||
final int id;
|
||||
final String source;
|
||||
final String outcome;
|
||||
final String target;
|
||||
final RouteSkipReason reason;
|
||||
final String message;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is RouteDiagnostic &&
|
||||
other.id == id &&
|
||||
other.source == source &&
|
||||
other.outcome == outcome &&
|
||||
other.target == target &&
|
||||
other.reason == reason &&
|
||||
other.message == message;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(id, source, outcome, target, reason, message);
|
||||
}
|
||||
|
||||
/// The complete immutable routing result.
|
||||
///
|
||||
/// [width] and [height] include every route point and label box as well as the
|
||||
/// landed layout bounds, so a loop that leaves the node grid expands the
|
||||
/// returned box instead of being clipped. [routes] and [skipped] are ordered by
|
||||
/// definition edge id; [labels] follows the same order.
|
||||
class GraphRouting {
|
||||
GraphRouting({
|
||||
required List<EdgeRoute> routes,
|
||||
required List<EdgeLabelBox> labels,
|
||||
required List<RouteDiagnostic> skipped,
|
||||
required this.width,
|
||||
required this.height,
|
||||
}) : routes = List.unmodifiable(routes),
|
||||
labels = List.unmodifiable(labels),
|
||||
skipped = List.unmodifiable(skipped);
|
||||
|
||||
final List<EdgeRoute> routes;
|
||||
final List<EdgeLabelBox> labels;
|
||||
final List<RouteDiagnostic> skipped;
|
||||
final double width;
|
||||
final double height;
|
||||
|
||||
bool get isEmpty => routes.isEmpty;
|
||||
|
||||
/// The route for [id], or null when that edge was skipped.
|
||||
EdgeRoute? routeFor(int id) {
|
||||
for (final route in routes) {
|
||||
if (route.id == id) return route;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// The label box for [id], or null when the edge was skipped.
|
||||
EdgeLabelBox? labelFor(int id) {
|
||||
for (final label in labels) {
|
||||
if (label.edgeId == id) return label;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
bool _samePoints(List<RoutePoint> a, List<RoutePoint> b) {
|
||||
if (a.length != b.length) return false;
|
||||
for (var index = 0; index < a.length; index += 1) {
|
||||
if (a[index] != b[index]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/// Caller-supplied measurements and clearances for graph-edge routing.
|
||||
///
|
||||
/// No font, widget style, device class or CSS value is assumed: every size is
|
||||
/// measured or chosen by the caller.
|
||||
library;
|
||||
|
||||
void _requireFiniteNonNegative(String name, double value) {
|
||||
if (!value.isFinite || value < 0) {
|
||||
throw ArgumentError.value(value, name, 'must be finite and non-negative');
|
||||
}
|
||||
}
|
||||
|
||||
void _requireFinitePositive(String name, double value) {
|
||||
if (!value.isFinite || value <= 0) {
|
||||
throw ArgumentError.value(value, name, 'must be finite and positive');
|
||||
}
|
||||
}
|
||||
|
||||
/// A caller-measured edge label extent, in logical pixels.
|
||||
class LabelExtent {
|
||||
LabelExtent({required this.width, required this.height}) {
|
||||
_requireFiniteNonNegative('width', width);
|
||||
_requireFiniteNonNegative('height', height);
|
||||
}
|
||||
|
||||
final double width;
|
||||
final double height;
|
||||
}
|
||||
|
||||
/// Clearances and spacings a caller reserves for edge geometry.
|
||||
///
|
||||
/// [nodeClearance] is the distance a lane or corridor keeps from every node
|
||||
/// edge. [laneSpacing] separates the horizontal tracks used by wrapping
|
||||
/// routes, [corridorSpacing] separates vertical tracks inside one column gap,
|
||||
/// and [portSpacing] separates ports on a node side. [labelGap] keeps a label
|
||||
/// box off its wire; [boundsPadding] is added to the returned bounds.
|
||||
///
|
||||
/// The router may widen a lane step beyond [laneSpacing] when the measured
|
||||
/// label heights need the room. Inside a narrow column gap it compresses
|
||||
/// corridor or port spacing rather than routing a track into a node column.
|
||||
class RoutingConfig {
|
||||
RoutingConfig({
|
||||
required this.nodeClearance,
|
||||
required this.laneSpacing,
|
||||
required this.corridorSpacing,
|
||||
required this.portSpacing,
|
||||
required this.labelGap,
|
||||
this.boundsPadding = 0,
|
||||
}) {
|
||||
_requireFiniteNonNegative('nodeClearance', nodeClearance);
|
||||
_requireFinitePositive('laneSpacing', laneSpacing);
|
||||
_requireFinitePositive('corridorSpacing', corridorSpacing);
|
||||
_requireFinitePositive('portSpacing', portSpacing);
|
||||
_requireFiniteNonNegative('labelGap', labelGap);
|
||||
_requireFiniteNonNegative('boundsPadding', boundsPadding);
|
||||
}
|
||||
|
||||
final double nodeClearance;
|
||||
final double laneSpacing;
|
||||
final double corridorSpacing;
|
||||
final double portSpacing;
|
||||
final double labelGap;
|
||||
final double boundsPadding;
|
||||
}
|
||||
@@ -0,0 +1,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<String> 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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/// A refused operator action and, when one was started, the bounded re-read of
|
||||
/// server truth that follows it.
|
||||
///
|
||||
/// The prompt shows [message] and allows dismissal immediately; it must never
|
||||
/// wait for [stillPossible]. That future is only observed so a retry can be
|
||||
/// ruled out once server truth arrives: `true` means the re-read found the run
|
||||
/// still allows the action, `false` means it plainly does not, and `null` means
|
||||
/// the re-read failed or was overtaken, leaving a deliberate retry possible.
|
||||
class ActionRefusal {
|
||||
const ActionRefusal(this.message, {this.stillPossible});
|
||||
|
||||
final String message;
|
||||
final Future<bool?>? stillPossible;
|
||||
}
|
||||
|
||||
/// Local guards, distinct from a server refusal; they never claim success.
|
||||
const actionOptionRequired = 'Choose an option before continuing.';
|
||||
const actionAlreadySending = 'That action is still being sent.';
|
||||
@@ -0,0 +1,165 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'action_refusal.dart';
|
||||
import 'cancel_wording.dart';
|
||||
|
||||
/// Sends the confirmed cancellation. Returns null once the server has accepted
|
||||
/// it, or an [ActionRefusal] carrying the server's words verbatim; the prompt
|
||||
/// then stays open with dismissal available immediately.
|
||||
typedef CancelSubmit = Future<ActionRefusal?> Function();
|
||||
|
||||
/// Opens the native cancel confirmation for [runId].
|
||||
///
|
||||
/// Nothing is sent until the operator presses the confirm action, and the
|
||||
/// dismiss action (`Keep`) only closes the prompt.
|
||||
Future<void> showCancelRunPrompt({
|
||||
required BuildContext context,
|
||||
required num runId,
|
||||
required bool cupertino,
|
||||
required CancelSubmit onSubmit,
|
||||
}) {
|
||||
final prompt = _CancelPrompt(
|
||||
runId: runId,
|
||||
cupertino: cupertino,
|
||||
onSubmit: onSubmit,
|
||||
);
|
||||
if (cupertino) {
|
||||
return showCupertinoDialog<void>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (_) => prompt,
|
||||
);
|
||||
}
|
||||
return showDialog<void>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (_) => prompt,
|
||||
);
|
||||
}
|
||||
|
||||
class _CancelPrompt extends StatefulWidget {
|
||||
const _CancelPrompt({
|
||||
required this.runId,
|
||||
required this.cupertino,
|
||||
required this.onSubmit,
|
||||
});
|
||||
|
||||
final num runId;
|
||||
final bool cupertino;
|
||||
final CancelSubmit onSubmit;
|
||||
|
||||
@override
|
||||
State<_CancelPrompt> createState() => _CancelPromptState();
|
||||
}
|
||||
|
||||
class _CancelPromptState extends State<_CancelPrompt> {
|
||||
bool _sending = false;
|
||||
bool _checking = false;
|
||||
bool _blocked = false;
|
||||
String? _error;
|
||||
|
||||
void _keep() {
|
||||
if (!_sending) Navigator.of(context).pop();
|
||||
}
|
||||
|
||||
Future<void> _confirm() async {
|
||||
if (_sending || _checking || _blocked) return;
|
||||
setState(() {
|
||||
_sending = true;
|
||||
_error = null;
|
||||
});
|
||||
final refusal = await widget.onSubmit();
|
||||
if (!mounted) return;
|
||||
if (refusal == null) {
|
||||
Navigator.of(context).pop();
|
||||
return;
|
||||
}
|
||||
final check = refusal.stillPossible;
|
||||
setState(() {
|
||||
_sending = false;
|
||||
_error = refusal.message;
|
||||
_checking = check != null;
|
||||
});
|
||||
if (check == null) return;
|
||||
bool? stillPossible;
|
||||
try {
|
||||
stillPossible = await check;
|
||||
} catch (_) {
|
||||
// The action reports re-read failures as null; never fabricate one here.
|
||||
}
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_checking = false;
|
||||
_blocked = stillPossible == false;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final dialog = widget.cupertino ? _cupertino(context) : _material(context);
|
||||
return PopScope(canPop: !_sending, child: dialog);
|
||||
}
|
||||
|
||||
bool get _confirmDisabled => _sending || _checking || _blocked;
|
||||
|
||||
Widget _material(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return AlertDialog(
|
||||
scrollable: true,
|
||||
title: Text(cancelDialogTitle(widget.runId)),
|
||||
content: _body(errorStyle: TextStyle(color: theme.colorScheme.error)),
|
||||
actions: [
|
||||
TextButton(
|
||||
key: cancelKeepKey,
|
||||
onPressed: _sending ? null : _keep,
|
||||
child: const Text(cancelKeepLabel),
|
||||
),
|
||||
FilledButton(
|
||||
key: cancelConfirmKey,
|
||||
onPressed: _confirmDisabled ? null : _confirm,
|
||||
child: const Text(cancelConfirmLabel),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _cupertino(BuildContext context) {
|
||||
return CupertinoAlertDialog(
|
||||
title: Text(cancelDialogTitle(widget.runId)),
|
||||
content: _body(
|
||||
errorStyle: TextStyle(
|
||||
color: CupertinoColors.systemRed.resolveFrom(context),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
CupertinoDialogAction(
|
||||
key: cancelKeepKey,
|
||||
onPressed: _sending ? null : _keep,
|
||||
child: const Text(cancelKeepLabel),
|
||||
),
|
||||
CupertinoDialogAction(
|
||||
key: cancelConfirmKey,
|
||||
isDestructiveAction: true,
|
||||
onPressed: _confirmDisabled ? null : _confirm,
|
||||
child: const Text(cancelConfirmLabel),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _body({required TextStyle errorStyle}) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const Text(cancelDialogMessage),
|
||||
if (_error case final error?)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Text(error, key: cancelErrorKey, style: errorStyle),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
/// Whether the operator may cancel [run], matching `canCancel` in
|
||||
/// `web/src/actions.js` exactly:
|
||||
///
|
||||
/// `(executing || (status == "waiting" && export_pending_sequence > 0)) &&
|
||||
/// !cancel_requested && !cleanup_unconfirmed`
|
||||
///
|
||||
/// The status word alone is not enough: a stale `running` status without
|
||||
/// `executing` is not cancellable, while a run waiting on a pending session
|
||||
/// export is.
|
||||
bool canCancelRun(JsonMap? run) {
|
||||
if (run == null) return false;
|
||||
final exportPending = _number(run['export_pending_sequence']);
|
||||
return (run['executing'] == true ||
|
||||
(run['status'] == 'waiting' && exportPending > 0)) &&
|
||||
run['cancel_requested'] != true &&
|
||||
run['cleanup_unconfirmed'] != true;
|
||||
}
|
||||
|
||||
/// The run id used by the cancel request, or null for a malformed run.
|
||||
num? cancelRunId(JsonMap run) {
|
||||
final id = run['id'];
|
||||
return id is num ? id : null;
|
||||
}
|
||||
|
||||
/// `Number(value) > 0`, tolerating numeric strings as the browser does.
|
||||
double _number(dynamic value) {
|
||||
if (value is num) return value.toDouble();
|
||||
return double.tryParse('${value ?? ''}'.trim()) ?? 0;
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../data/runs_repository.dart';
|
||||
import 'action_refusal.dart';
|
||||
import 'cancel_dialog.dart';
|
||||
import 'cancel_eligibility.dart';
|
||||
import 'cancel_wording.dart';
|
||||
|
||||
/// The run detail's deliberate cancel entry point.
|
||||
///
|
||||
/// Renders one native button only while [run] is cancellable under the browser
|
||||
/// client's rule. Opening the prompt or choosing [cancelKeepLabel] sends
|
||||
/// nothing; only the confirm action asks the server to stop the run. A refusal
|
||||
/// is returned to the kept-open prompt immediately and the run is re-read
|
||||
/// separately, so [onRunChanged] still receives server truth without locking
|
||||
/// the prompt while that read is pending.
|
||||
class CancelRunAction extends StatefulWidget {
|
||||
const CancelRunAction({
|
||||
super.key,
|
||||
required this.run,
|
||||
required this.gateway,
|
||||
required this.onRunChanged,
|
||||
});
|
||||
|
||||
final JsonMap run;
|
||||
final ApiGateway gateway;
|
||||
final ValueChanged<JsonMap> onRunChanged;
|
||||
|
||||
@override
|
||||
State<CancelRunAction> createState() => _CancelRunActionState();
|
||||
}
|
||||
|
||||
class _CancelRunActionState extends State<CancelRunAction> {
|
||||
bool _dialogOpen = false;
|
||||
Future<bool?>? _resync;
|
||||
|
||||
bool _usesCupertino(BuildContext context) {
|
||||
final material = Localizations.of<MaterialLocalizations>(
|
||||
context,
|
||||
MaterialLocalizations,
|
||||
);
|
||||
return material == null;
|
||||
}
|
||||
|
||||
Future<void> _open() async {
|
||||
final id = cancelRunId(widget.run);
|
||||
if (id == null || !canCancelRun(widget.run) || _dialogOpen) return;
|
||||
_dialogOpen = true;
|
||||
try {
|
||||
await showCancelRunPrompt(
|
||||
context: context,
|
||||
runId: id,
|
||||
cupertino: _usesCupertino(context),
|
||||
onSubmit: () => _submit(id),
|
||||
);
|
||||
} finally {
|
||||
_dialogOpen = false;
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
}
|
||||
|
||||
Future<ActionRefusal?> _submit(num id) async {
|
||||
final repository = RunsRepository(widget.gateway);
|
||||
try {
|
||||
final run = await repository.cancelRun(id);
|
||||
if (!mounted) return null;
|
||||
if (_owns(id)) widget.onRunChanged(run);
|
||||
return null;
|
||||
} catch (error) {
|
||||
return ActionRefusal(
|
||||
describeCancelError(error),
|
||||
stillPossible: _resyncRun(id),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
bool _owns(num id) => mounted && cancelRunId(widget.run) == id;
|
||||
|
||||
/// One bounded re-read per refusal. A refusal that arrives while a read is
|
||||
/// already in flight observes that same read instead of starting another.
|
||||
Future<bool?> _resyncRun(num id) {
|
||||
return _resync ??= _readRun(id);
|
||||
}
|
||||
|
||||
Future<bool?> _readRun(num id) async {
|
||||
try {
|
||||
final run = await RunsRepository(widget.gateway).getRun(id);
|
||||
if (!_owns(id)) return null;
|
||||
widget.onRunChanged(run);
|
||||
return canCancelRun(run);
|
||||
} catch (_) {
|
||||
// Unknown server truth: keep the refusal and leave a deliberate retry.
|
||||
return null;
|
||||
} finally {
|
||||
_resync = null;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (cancelRunId(widget.run) == null || !canCancelRun(widget.run)) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
if (_usesCupertino(context)) {
|
||||
return CupertinoButton.filled(
|
||||
key: cancelActionKey,
|
||||
onPressed: _open,
|
||||
child: const Text(cancelActionLabel),
|
||||
);
|
||||
}
|
||||
return FilledButton(
|
||||
key: cancelActionKey,
|
||||
onPressed: _open,
|
||||
child: const Text(cancelActionLabel),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
/// The browser client's cancel wording, kept verbatim.
|
||||
const cancelActionLabel = 'Cancel run';
|
||||
const cancelDialogMessage = 'This asks the server to stop the active run.';
|
||||
const cancelConfirmLabel = 'Cancel run';
|
||||
const cancelKeepLabel = 'Keep';
|
||||
|
||||
/// Stable test/semantics keys shared by the action and its prompt.
|
||||
const cancelActionKey = ValueKey<String>('cancel-run-action');
|
||||
const cancelKeepKey = ValueKey<String>('cancel-run-keep');
|
||||
const cancelConfirmKey = ValueKey<String>('cancel-run-confirm');
|
||||
const cancelErrorKey = ValueKey<String>('cancel-run-error');
|
||||
|
||||
/// The cancel dialog's title: `Cancel run {id}?`.
|
||||
String cancelDialogTitle(num runId) => 'Cancel run $runId?';
|
||||
|
||||
/// The server's refusal, verbatim. Only a blank error gets a generic sentence
|
||||
/// so the prompt never claims a cancellation that did not happen.
|
||||
String describeCancelError(Object error) {
|
||||
final message = '$error'.trim();
|
||||
return message.isEmpty ? 'The server did not cancel the run.' : message;
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../data/runs_repository.dart';
|
||||
import '../domain/run_decisions.dart';
|
||||
import '../domain/run_models.dart';
|
||||
import 'action_refusal.dart';
|
||||
import 'decision_dialog.dart';
|
||||
import 'decision_wording.dart';
|
||||
|
||||
/// The run detail's deliberate human-decision entry point.
|
||||
///
|
||||
/// Renders one native button only while [run] is genuinely waiting on a person.
|
||||
/// Nothing is sent until the operator opens the prompt, chooses an option and
|
||||
/// presses Confirm; cancel, selection and optional feedback stay local. A
|
||||
/// server refusal is shown verbatim in the prompt immediately, the draft is
|
||||
/// preserved and the run is re-read separately so [onRunChanged] still receives
|
||||
/// server truth without locking the prompt while that read is pending.
|
||||
class HumanDecisionAction extends StatefulWidget {
|
||||
const HumanDecisionAction({
|
||||
super.key,
|
||||
required this.run,
|
||||
required this.gateway,
|
||||
required this.onRunChanged,
|
||||
this.cupertino,
|
||||
});
|
||||
|
||||
final JsonMap run;
|
||||
final ApiGateway gateway;
|
||||
final ValueChanged<JsonMap> onRunChanged;
|
||||
|
||||
/// Overrides the platform style; by default it follows the enclosing app.
|
||||
final bool? cupertino;
|
||||
|
||||
@override
|
||||
State<HumanDecisionAction> createState() => _HumanDecisionActionState();
|
||||
}
|
||||
|
||||
class _HumanDecisionActionState extends State<HumanDecisionAction> {
|
||||
PendingDecision? _pending;
|
||||
bool _dialogOpen = false;
|
||||
bool _sending = false;
|
||||
Future<bool?>? _resync;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_pending = pendingDecision(widget.run);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant HumanDecisionAction oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
_pending = pendingDecision(widget.run);
|
||||
}
|
||||
|
||||
bool _usesCupertino(BuildContext context) {
|
||||
if (widget.cupertino != null) return widget.cupertino!;
|
||||
final material = Localizations.of<MaterialLocalizations>(
|
||||
context,
|
||||
MaterialLocalizations,
|
||||
);
|
||||
return material == null;
|
||||
}
|
||||
|
||||
Future<void> _open() async {
|
||||
final decision = _pending;
|
||||
if (decision == null || _dialogOpen) return;
|
||||
_dialogOpen = true;
|
||||
try {
|
||||
await showHumanDecisionPrompt(
|
||||
context: context,
|
||||
decision: decision,
|
||||
cupertino: _usesCupertino(context),
|
||||
onSubmit: (draft) => _submit(decision, draft),
|
||||
);
|
||||
} finally {
|
||||
_dialogOpen = false;
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
}
|
||||
|
||||
Future<ActionRefusal?> _submit(
|
||||
PendingDecision decision,
|
||||
DecisionDraft draft,
|
||||
) async {
|
||||
final option = draft.selected?.trim() ?? '';
|
||||
if (option.isEmpty) return const ActionRefusal(actionOptionRequired);
|
||||
if (_sending) return const ActionRefusal(actionAlreadySending);
|
||||
_sending = true;
|
||||
final repository = RunsRepository(widget.gateway);
|
||||
try {
|
||||
final JsonMap run;
|
||||
try {
|
||||
run = await repository.decideRun(
|
||||
decision.runId,
|
||||
stage: decision.stageKey,
|
||||
option: option,
|
||||
feedback: draft.feedback,
|
||||
);
|
||||
} catch (error) {
|
||||
return ActionRefusal(
|
||||
_describe(error),
|
||||
stillPossible: _resyncRun(decision),
|
||||
);
|
||||
}
|
||||
if (!mounted) return null;
|
||||
if (_owns(decision.runId)) {
|
||||
setState(() => _pending = pendingDecision(run));
|
||||
widget.onRunChanged(run);
|
||||
}
|
||||
return null;
|
||||
} finally {
|
||||
_sending = false;
|
||||
}
|
||||
}
|
||||
|
||||
bool _owns(num id) => mounted && widget.run['id'] == id;
|
||||
|
||||
/// One bounded re-read per refusal. A refusal that arrives while a read is
|
||||
/// already in flight observes that same read instead of starting another.
|
||||
Future<bool?> _resyncRun(PendingDecision decision) {
|
||||
return _resync ??= _readRun(decision);
|
||||
}
|
||||
|
||||
Future<bool?> _readRun(PendingDecision expected) async {
|
||||
try {
|
||||
final run = await RunsRepository(widget.gateway).getRun(expected.runId);
|
||||
if (!_owns(expected.runId)) return null;
|
||||
final next = pendingDecision(run);
|
||||
setState(() => _pending = next);
|
||||
widget.onRunChanged(run);
|
||||
return _stillDecidable(next, expected);
|
||||
} catch (_) {
|
||||
// Unknown server truth: keep the refusal and leave a deliberate retry.
|
||||
return null;
|
||||
} finally {
|
||||
_resync = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the refreshed run offers the same decision the prompt is showing.
|
||||
bool _stillDecidable(PendingDecision? next, PendingDecision expected) {
|
||||
if (next == null ||
|
||||
next.runId != expected.runId ||
|
||||
next.stageKey != expected.stageKey) {
|
||||
return false;
|
||||
}
|
||||
final keys = next.options.map((option) => option.key).toSet();
|
||||
return expected.options.every((option) => keys.contains(option.key));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final decision = _pending;
|
||||
if (decision == null) return const SizedBox.shrink();
|
||||
if (_usesCupertino(context)) {
|
||||
return CupertinoButton.filled(
|
||||
key: decisionActionKey,
|
||||
onPressed: _open,
|
||||
child: const Text(decisionActionLabel),
|
||||
);
|
||||
}
|
||||
return FilledButton(
|
||||
key: decisionActionKey,
|
||||
onPressed: _open,
|
||||
child: const Text(decisionActionLabel),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _describe(Object error) {
|
||||
final message = '$error';
|
||||
return message.trim().isEmpty ? 'The server refused the decision.' : message;
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../domain/run_decisions.dart';
|
||||
import '../domain/run_models.dart';
|
||||
import 'action_refusal.dart';
|
||||
import 'decision_wording.dart';
|
||||
|
||||
/// Sends the draft to the server. Returns null on success, or an
|
||||
/// [ActionRefusal] with the server's words verbatim; the prompt stays open
|
||||
/// with the draft intact and dismissal available immediately.
|
||||
typedef DecisionSubmit = Future<ActionRefusal?> Function(DecisionDraft draft);
|
||||
|
||||
/// Opens the native decision prompt for [decision].
|
||||
Future<void> showHumanDecisionPrompt({
|
||||
required BuildContext context,
|
||||
required PendingDecision decision,
|
||||
required bool cupertino,
|
||||
required DecisionSubmit onSubmit,
|
||||
}) {
|
||||
final prompt = _DecisionPrompt(
|
||||
decision: decision,
|
||||
cupertino: cupertino,
|
||||
onSubmit: onSubmit,
|
||||
);
|
||||
if (cupertino) {
|
||||
return showCupertinoDialog<void>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (_) => prompt,
|
||||
);
|
||||
}
|
||||
return showDialog<void>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (_) => prompt,
|
||||
);
|
||||
}
|
||||
|
||||
class _DecisionPrompt extends StatefulWidget {
|
||||
const _DecisionPrompt({
|
||||
required this.decision,
|
||||
required this.cupertino,
|
||||
required this.onSubmit,
|
||||
});
|
||||
|
||||
final PendingDecision decision;
|
||||
final bool cupertino;
|
||||
final DecisionSubmit onSubmit;
|
||||
|
||||
@override
|
||||
State<_DecisionPrompt> createState() => _DecisionPromptState();
|
||||
}
|
||||
|
||||
class _DecisionPromptState extends State<_DecisionPrompt> {
|
||||
DecisionDraft _draft = const DecisionDraft();
|
||||
late final TextEditingController _feedback = TextEditingController();
|
||||
bool _sending = false;
|
||||
bool _checking = false;
|
||||
bool _blocked = false;
|
||||
String? _error;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_feedback.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _select(String option) {
|
||||
if (_sending) return;
|
||||
setState(() => _draft = _draft.select(option));
|
||||
}
|
||||
|
||||
void _feedbackChanged(String value) => _draft = _draft.withFeedback(value);
|
||||
|
||||
void _cancel() {
|
||||
if (!_sending) Navigator.of(context).pop();
|
||||
}
|
||||
|
||||
Future<void> _confirm() async {
|
||||
if (_sending || _checking || _blocked || !_draft.canSubmit) return;
|
||||
setState(() {
|
||||
_sending = true;
|
||||
_error = null;
|
||||
});
|
||||
final refusal = await widget.onSubmit(_draft);
|
||||
if (!mounted) return;
|
||||
if (refusal == null) {
|
||||
Navigator.of(context).pop();
|
||||
return;
|
||||
}
|
||||
final check = refusal.stillPossible;
|
||||
setState(() {
|
||||
_sending = false;
|
||||
_error = refusal.message;
|
||||
_checking = check != null;
|
||||
});
|
||||
if (check == null) return;
|
||||
bool? stillPossible;
|
||||
try {
|
||||
stillPossible = await check;
|
||||
} catch (_) {
|
||||
// The action reports re-read failures as null; never fabricate one here.
|
||||
}
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_checking = false;
|
||||
_blocked = stillPossible == false;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final dialog = widget.cupertino ? _cupertino(context) : _material(context);
|
||||
return PopScope(canPop: !_sending, child: dialog);
|
||||
}
|
||||
|
||||
bool get _confirmDisabled => _sending || _checking || _blocked;
|
||||
|
||||
Widget _material(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return AlertDialog(
|
||||
scrollable: true,
|
||||
title: const Text(decisionWaitingTitle),
|
||||
content: _body(
|
||||
errorStyle: TextStyle(color: theme.colorScheme.error),
|
||||
options: RadioGroup<String>(
|
||||
groupValue: _draft.selected,
|
||||
onChanged: (value) {
|
||||
if (value != null) _select(value);
|
||||
},
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
for (final option in widget.decision.options)
|
||||
RadioListTile<String>(
|
||||
value: option.key,
|
||||
enabled: !_sending,
|
||||
title: Text(option.key),
|
||||
subtitle: _target(option),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
feedback: TextField(
|
||||
key: decisionFeedbackKey,
|
||||
controller: _feedback,
|
||||
enabled: !_sending,
|
||||
decoration: const InputDecoration(labelText: decisionFeedbackLabel),
|
||||
textInputAction: TextInputAction.done,
|
||||
onChanged: _feedbackChanged,
|
||||
onSubmitted: (_) => _confirm(),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: _sending ? null : _cancel,
|
||||
child: const Text(decisionCancelLabel),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: _confirmDisabled || !_draft.canSubmit ? null : _confirm,
|
||||
child: Text(_sending ? decisionSendingLabel : decisionConfirmLabel),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _cupertino(BuildContext context) {
|
||||
return CupertinoAlertDialog(
|
||||
title: const Text(decisionWaitingTitle),
|
||||
content: _body(
|
||||
errorStyle: TextStyle(
|
||||
color: CupertinoColors.systemRed.resolveFrom(context),
|
||||
),
|
||||
options: RadioGroup<String>(
|
||||
groupValue: _draft.selected,
|
||||
onChanged: (value) {
|
||||
if (value != null) _select(value);
|
||||
},
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
for (final option in widget.decision.options)
|
||||
CupertinoButton(
|
||||
onPressed: _sending ? null : () => _select(option.key),
|
||||
child: Row(
|
||||
children: [
|
||||
CupertinoRadio<String>(
|
||||
value: option.key,
|
||||
useCheckmarkStyle: true,
|
||||
enabled: !_sending,
|
||||
),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(option.key),
|
||||
if (_targetText(option) case final target?)
|
||||
Text(target),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
feedback: CupertinoTextField(
|
||||
key: decisionFeedbackKey,
|
||||
controller: _feedback,
|
||||
enabled: !_sending,
|
||||
placeholder: decisionFeedbackLabel,
|
||||
textInputAction: TextInputAction.done,
|
||||
onChanged: _feedbackChanged,
|
||||
onSubmitted: (_) => _confirm(),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
CupertinoDialogAction(
|
||||
onPressed: _sending ? null : _cancel,
|
||||
child: const Text(decisionCancelLabel),
|
||||
),
|
||||
CupertinoDialogAction(
|
||||
isDefaultAction: true,
|
||||
onPressed: _confirmDisabled || !_draft.canSubmit ? null : _confirm,
|
||||
child: Text(_sending ? decisionSendingLabel : decisionConfirmLabel),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _body({
|
||||
required TextStyle errorStyle,
|
||||
required Widget options,
|
||||
required Widget feedback,
|
||||
}) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(decisionMeta(widget.decision)),
|
||||
if (widget.decision.instructions.trim().isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Text(widget.decision.instructions),
|
||||
),
|
||||
Padding(padding: const EdgeInsets.only(top: 8), child: options),
|
||||
Padding(padding: const EdgeInsets.only(top: 8), child: feedback),
|
||||
if (_error case final error?)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Text(error, key: decisionErrorKey, style: errorStyle),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget? _target(DecisionOption option) {
|
||||
final text = _targetText(option);
|
||||
return text == null ? null : Text(text);
|
||||
}
|
||||
|
||||
String? _targetText(DecisionOption option) {
|
||||
final text = decisionTargetText(option.target);
|
||||
return text.isEmpty ? null : text;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../domain/run_decisions.dart';
|
||||
|
||||
/// The browser client's decision wording, kept verbatim.
|
||||
const decisionWaitingTitle = 'Waiting for your decision';
|
||||
const decisionActionLabel = 'Decide';
|
||||
const decisionFeedbackLabel = 'Feedback (optional)';
|
||||
const decisionCancelLabel = 'Cancel';
|
||||
const decisionConfirmLabel = 'Confirm decision';
|
||||
const decisionSendingLabel = 'Sending…';
|
||||
|
||||
/// Stable test/semantics keys shared by the action and its prompt.
|
||||
const decisionActionKey = ValueKey<String>('human-decision-action');
|
||||
const decisionFeedbackKey = ValueKey<String>('human-decision-feedback');
|
||||
const decisionErrorKey = ValueKey<String>('human-decision-error');
|
||||
|
||||
/// `{stage} · run {id} · {label}`, as the web decision card shows it.
|
||||
String decisionMeta(PendingDecision decision) =>
|
||||
'${decision.stageKey} · run ${decision.runId} · ${decision.runLabel}';
|
||||
|
||||
/// The option's target line, `→ {target}`, or "" when no target was declared.
|
||||
String decisionTargetText(String target) =>
|
||||
target.trim().isEmpty ? '' : '→ $target';
|
||||
@@ -0,0 +1,123 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../data/runs_repository.dart';
|
||||
import 'action_refusal.dart';
|
||||
import 'retry_dialog.dart';
|
||||
import 'retry_eligibility.dart';
|
||||
import 'retry_intent.dart';
|
||||
import 'retry_wording.dart';
|
||||
|
||||
/// The run detail's deliberate retry entry point.
|
||||
///
|
||||
/// Renders one native button only while [run] is a stopped `failed` run. Opening
|
||||
/// the resume or restart confirmation sends nothing; only the confirm action
|
||||
/// asks the server to retry. A refusal is returned to the kept-open prompt
|
||||
/// immediately and the run is re-read separately, so [onRunChanged] still
|
||||
/// receives server truth without locking the prompt while that read is pending.
|
||||
class RetryRunAction extends StatefulWidget {
|
||||
const RetryRunAction({
|
||||
super.key,
|
||||
required this.run,
|
||||
required this.gateway,
|
||||
required this.onRunChanged,
|
||||
});
|
||||
|
||||
final JsonMap run;
|
||||
final ApiGateway gateway;
|
||||
final ValueChanged<JsonMap> onRunChanged;
|
||||
|
||||
@override
|
||||
State<RetryRunAction> createState() => _RetryRunActionState();
|
||||
}
|
||||
|
||||
class _RetryRunActionState extends State<RetryRunAction> {
|
||||
bool _dialogOpen = false;
|
||||
Future<bool?>? _resync;
|
||||
|
||||
bool _usesCupertino(BuildContext context) {
|
||||
final material = Localizations.of<MaterialLocalizations>(
|
||||
context,
|
||||
MaterialLocalizations,
|
||||
);
|
||||
return material == null;
|
||||
}
|
||||
|
||||
Future<void> _open() async {
|
||||
final id = retryRunId(widget.run);
|
||||
if (id == null || !canRetryRun(widget.run) || _dialogOpen) return;
|
||||
_dialogOpen = true;
|
||||
try {
|
||||
await showRetryRunPrompt(
|
||||
context: context,
|
||||
runId: id,
|
||||
cupertino: _usesCupertino(context),
|
||||
onSubmit: (intent) => _submit(id, intent),
|
||||
);
|
||||
} finally {
|
||||
_dialogOpen = false;
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
}
|
||||
|
||||
Future<ActionRefusal?> _submit(num id, RetryIntent intent) async {
|
||||
final repository = RunsRepository(widget.gateway);
|
||||
try {
|
||||
final run = await repository.retryRun(
|
||||
id,
|
||||
requestKey: intent.requestKey,
|
||||
mode: intent.mode.wireMode,
|
||||
);
|
||||
if (!mounted) return null;
|
||||
if (_owns(id)) widget.onRunChanged(run);
|
||||
return null;
|
||||
} catch (error) {
|
||||
return ActionRefusal(
|
||||
describeRetryError(error),
|
||||
stillPossible: _resyncRun(id),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
bool _owns(num id) => mounted && retryRunId(widget.run) == id;
|
||||
|
||||
/// One bounded re-read per refusal. A refusal that arrives while a read is
|
||||
/// already in flight observes that same read instead of starting another.
|
||||
Future<bool?> _resyncRun(num id) {
|
||||
return _resync ??= _readRun(id);
|
||||
}
|
||||
|
||||
Future<bool?> _readRun(num id) async {
|
||||
try {
|
||||
final run = await RunsRepository(widget.gateway).getRun(id);
|
||||
if (!_owns(id)) return null;
|
||||
widget.onRunChanged(run);
|
||||
return canRetryRun(run);
|
||||
} catch (_) {
|
||||
// Unknown server truth: keep the refusal and leave a deliberate retry.
|
||||
return null;
|
||||
} finally {
|
||||
_resync = null;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (retryRunId(widget.run) == null || !canRetryRun(widget.run)) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
if (_usesCupertino(context)) {
|
||||
return CupertinoButton.filled(
|
||||
key: retryActionKey,
|
||||
onPressed: _open,
|
||||
child: const Text(retryActionLabel),
|
||||
);
|
||||
}
|
||||
return FilledButton(
|
||||
key: retryActionKey,
|
||||
onPressed: _open,
|
||||
child: const Text(retryActionLabel),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'action_refusal.dart';
|
||||
import 'retry_intent.dart';
|
||||
import 'retry_wording.dart';
|
||||
|
||||
/// Sends the confirmed retry intent. Returns null once the server has accepted
|
||||
/// it, or an [ActionRefusal] carrying the server's words verbatim; the prompt
|
||||
/// then stays open with dismissal available immediately.
|
||||
typedef RetrySubmit = Future<ActionRefusal?> Function(RetryIntent intent);
|
||||
|
||||
/// Opens the native retry confirmation for [runId].
|
||||
///
|
||||
/// The first confirmation offers resume (the default) and a secondary
|
||||
/// `Restart from start` confirmation, exactly like the browser's retry dialog.
|
||||
/// Nothing is sent until the operator presses a confirm action; `Keep` only
|
||||
/// closes the prompt.
|
||||
Future<void> showRetryRunPrompt({
|
||||
required BuildContext context,
|
||||
required num runId,
|
||||
required bool cupertino,
|
||||
required RetrySubmit onSubmit,
|
||||
}) {
|
||||
final prompt = _RetryPrompt(
|
||||
runId: runId,
|
||||
cupertino: cupertino,
|
||||
onSubmit: onSubmit,
|
||||
);
|
||||
if (cupertino) {
|
||||
return showCupertinoDialog<void>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (_) => prompt,
|
||||
);
|
||||
}
|
||||
return showDialog<void>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (_) => prompt,
|
||||
);
|
||||
}
|
||||
|
||||
class _RetryPrompt extends StatefulWidget {
|
||||
const _RetryPrompt({
|
||||
required this.runId,
|
||||
required this.cupertino,
|
||||
required this.onSubmit,
|
||||
});
|
||||
|
||||
final num runId;
|
||||
final bool cupertino;
|
||||
final RetrySubmit onSubmit;
|
||||
|
||||
@override
|
||||
State<_RetryPrompt> createState() => _RetryPromptState();
|
||||
}
|
||||
|
||||
class _RetryPromptState extends State<_RetryPrompt> {
|
||||
RetryMode _mode = RetryMode.resume;
|
||||
String? _requestKey;
|
||||
bool _sending = false;
|
||||
bool _checking = false;
|
||||
bool _blocked = false;
|
||||
bool _attempted = false;
|
||||
String? _error;
|
||||
|
||||
void _keep() {
|
||||
if (!_sending) Navigator.of(context).pop();
|
||||
}
|
||||
|
||||
void _restart() {
|
||||
if (_sending || _checking || _attempted) return;
|
||||
setState(() {
|
||||
_mode = RetryMode.restart;
|
||||
_error = null;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _confirm() async {
|
||||
if (_sending || _checking || _blocked) return;
|
||||
setState(() {
|
||||
_sending = true;
|
||||
_attempted = true;
|
||||
_error = null;
|
||||
});
|
||||
final intent = RetryIntent(
|
||||
mode: _mode,
|
||||
requestKey: _requestKey ??= newRetryRequestKey(widget.runId),
|
||||
);
|
||||
final refusal = await widget.onSubmit(intent);
|
||||
if (!mounted) return;
|
||||
if (refusal == null) {
|
||||
Navigator.of(context).pop();
|
||||
return;
|
||||
}
|
||||
final check = refusal.stillPossible;
|
||||
setState(() {
|
||||
_sending = false;
|
||||
_error = refusal.message;
|
||||
_checking = check != null;
|
||||
});
|
||||
if (check == null) return;
|
||||
bool? stillPossible;
|
||||
try {
|
||||
stillPossible = await check;
|
||||
} catch (_) {
|
||||
// The action reports re-read failures as null; never fabricate one here.
|
||||
}
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_checking = false;
|
||||
_blocked = stillPossible == false;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final dialog = widget.cupertino ? _cupertino(context) : _material(context);
|
||||
return PopScope(canPop: !_sending, child: dialog);
|
||||
}
|
||||
|
||||
bool get _confirmDisabled => _sending || _checking || _blocked;
|
||||
bool get _showRestart => _mode == RetryMode.resume && !_attempted;
|
||||
|
||||
Widget _material(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return AlertDialog(
|
||||
scrollable: true,
|
||||
title: Text(_dialogTitle),
|
||||
content: _body(errorStyle: TextStyle(color: theme.colorScheme.error)),
|
||||
actions: [
|
||||
if (_showRestart)
|
||||
TextButton(
|
||||
key: retryRestartKey,
|
||||
onPressed: _sending || _checking ? null : _restart,
|
||||
child: const Text(restartConfirmLabel),
|
||||
),
|
||||
TextButton(
|
||||
key: retryKeepKey,
|
||||
onPressed: _sending ? null : _keep,
|
||||
child: const Text(retryKeepLabel),
|
||||
),
|
||||
FilledButton(
|
||||
key: retryConfirmKey,
|
||||
onPressed: _confirmDisabled ? null : _confirm,
|
||||
child: Text(_confirmLabel),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _cupertino(BuildContext context) {
|
||||
return CupertinoAlertDialog(
|
||||
title: Text(_dialogTitle),
|
||||
content: _body(
|
||||
errorStyle: TextStyle(
|
||||
color: CupertinoColors.systemRed.resolveFrom(context),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
if (_showRestart)
|
||||
CupertinoDialogAction(
|
||||
key: retryRestartKey,
|
||||
onPressed: _sending || _checking ? null : _restart,
|
||||
child: const Text(restartConfirmLabel),
|
||||
),
|
||||
CupertinoDialogAction(
|
||||
key: retryKeepKey,
|
||||
onPressed: _sending ? null : _keep,
|
||||
child: const Text(retryKeepLabel),
|
||||
),
|
||||
CupertinoDialogAction(
|
||||
key: retryConfirmKey,
|
||||
isDestructiveAction: _mode == RetryMode.restart,
|
||||
onPressed: _confirmDisabled ? null : _confirm,
|
||||
child: Text(_confirmLabel),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _body({required TextStyle errorStyle}) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(_dialogMessage),
|
||||
if (_error case final error?)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Text(error, key: retryErrorKey, style: errorStyle),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
String get _dialogTitle => _mode == RetryMode.restart
|
||||
? restartDialogTitle(widget.runId)
|
||||
: retryDialogTitle(widget.runId);
|
||||
|
||||
String get _dialogMessage =>
|
||||
_mode == RetryMode.restart ? restartDialogMessage : retryDialogMessage;
|
||||
|
||||
String get _confirmLabel =>
|
||||
_mode == RetryMode.restart ? restartConfirmLabel : retryConfirmLabel;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
/// Whether the operator may retry [run], matching `canRetry` in
|
||||
/// `web/src/actions.js` exactly: a loaded run that is not executing and whose
|
||||
/// status is `failed`. A stale `failed` status while the run still executes is
|
||||
/// not retryable.
|
||||
bool canRetryRun(JsonMap? run) {
|
||||
if (run == null) return false;
|
||||
return run['executing'] != true && run['status'] == 'failed';
|
||||
}
|
||||
|
||||
/// The run id used by the retry request, or null for a malformed run.
|
||||
num? retryRunId(JsonMap run) {
|
||||
final id = run['id'];
|
||||
return id is num ? id : null;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import 'dart:math';
|
||||
|
||||
/// The two deliberate retry choices. `resume` is the server's default, so its
|
||||
/// wire field is omitted; `restart` replays the whole pipeline.
|
||||
enum RetryMode {
|
||||
resume,
|
||||
restart;
|
||||
|
||||
/// The `retry_mode` value to send, or null to let the server resume.
|
||||
String? get wireMode => this == RetryMode.restart ? 'restart' : null;
|
||||
}
|
||||
|
||||
/// One confirmed retry intent: the chosen mode plus the idempotency key that
|
||||
/// belongs to it. Retrying the same uncertain intent reuses [requestKey] so the
|
||||
/// server can dedupe it; a fresh deliberate intent uses a new key.
|
||||
class RetryIntent {
|
||||
const RetryIntent({required this.mode, required this.requestKey});
|
||||
|
||||
final RetryMode mode;
|
||||
final String requestKey;
|
||||
}
|
||||
|
||||
/// A fresh `request_key` for one retry intent. The server requires one and caps
|
||||
/// it at 128 characters; this stays well inside that bound and unique per call.
|
||||
String newRetryRequestKey(num runId, {DateTime? now, int? random}) {
|
||||
final stamp = (now ?? DateTime.now()).microsecondsSinceEpoch;
|
||||
final entropy = random ?? Random().nextInt(1 << 32);
|
||||
return 'app-retry-$runId-$stamp-${entropy.toRadixString(36)}';
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
/// The browser client's retry wording, kept verbatim.
|
||||
const retryActionLabel = 'Retry';
|
||||
const retryDialogMessage =
|
||||
'Only failed runs can be retried. The server starts a new run from the '
|
||||
'same input.';
|
||||
const retryConfirmLabel = 'Retry';
|
||||
const restartDialogMessage =
|
||||
'This replays the whole pipeline from the start instead of resuming the '
|
||||
'failed stage.';
|
||||
const restartConfirmLabel = 'Restart from start';
|
||||
const retryKeepLabel = 'Keep';
|
||||
|
||||
/// Stable test/semantics keys shared by the action and its prompt.
|
||||
const retryActionKey = ValueKey<String>('retry-run-action');
|
||||
const retryKeepKey = ValueKey<String>('retry-run-keep');
|
||||
const retryConfirmKey = ValueKey<String>('retry-run-confirm');
|
||||
const retryRestartKey = ValueKey<String>('retry-run-restart');
|
||||
const retryErrorKey = ValueKey<String>('retry-run-error');
|
||||
|
||||
/// The retry dialog's title: `Retry run {id}?`.
|
||||
String retryDialogTitle(num runId) => 'Retry run $runId?';
|
||||
|
||||
/// The restart dialog's title: `Restart run {id}?`.
|
||||
String restartDialogTitle(num runId) => 'Restart run $runId?';
|
||||
|
||||
/// The server's refusal, verbatim. Only a blank error gets a generic sentence
|
||||
/// so the prompt never claims a retry that did not happen.
|
||||
String describeRetryError(Object error) {
|
||||
final message = '$error'.trim();
|
||||
return message.isEmpty ? 'The server did not retry the run.' : message;
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../data/runs_repository.dart';
|
||||
import 'action_refusal.dart';
|
||||
import 'title_dialog.dart';
|
||||
import 'title_wording.dart';
|
||||
|
||||
/// The run detail's rename entry point, mirroring the browser's rename row.
|
||||
///
|
||||
/// The prompt starts with [run]'s stored title exactly as the server sent it
|
||||
/// (never a prompt or output fallback). Typing and Cancel send nothing; only
|
||||
/// Save sends `set_run_title` with the exact run id and title text. A refusal is
|
||||
/// returned verbatim to the kept-open prompt, and only the server's returned
|
||||
/// `run_detail` is delivered through [onRunChanged], once.
|
||||
class RunTitleAction extends StatefulWidget {
|
||||
const RunTitleAction({
|
||||
super.key,
|
||||
required this.run,
|
||||
required this.gateway,
|
||||
required this.onRunChanged,
|
||||
});
|
||||
|
||||
final JsonMap run;
|
||||
final ApiGateway gateway;
|
||||
final ValueChanged<JsonMap> onRunChanged;
|
||||
|
||||
@override
|
||||
State<RunTitleAction> createState() => _RunTitleActionState();
|
||||
}
|
||||
|
||||
class _RunTitleActionState extends State<RunTitleAction> {
|
||||
bool _dialogOpen = false;
|
||||
bool _saving = false;
|
||||
|
||||
bool _usesCupertino(BuildContext context) {
|
||||
final material = Localizations.of<MaterialLocalizations>(
|
||||
context,
|
||||
MaterialLocalizations,
|
||||
);
|
||||
return material == null;
|
||||
}
|
||||
|
||||
Future<void> _open() async {
|
||||
final id = runTitleId(widget.run);
|
||||
if (id == null || _dialogOpen) return;
|
||||
_dialogOpen = true;
|
||||
try {
|
||||
await showRunTitlePrompt(
|
||||
context: context,
|
||||
runId: id,
|
||||
initialTitle: storedRunTitle(widget.run),
|
||||
cupertino: _usesCupertino(context),
|
||||
onSubmit: (title) => _submit(id, title),
|
||||
);
|
||||
} finally {
|
||||
_dialogOpen = false;
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
}
|
||||
|
||||
Future<ActionRefusal?> _submit(num id, String title) async {
|
||||
if (_saving) return const ActionRefusal(actionAlreadySending);
|
||||
_saving = true;
|
||||
try {
|
||||
final run = await RunsRepository(widget.gateway).setRunTitle(id, title);
|
||||
if (!mounted) return null;
|
||||
if (_owns(id)) widget.onRunChanged(run);
|
||||
return null;
|
||||
} catch (error) {
|
||||
return ActionRefusal(describeTitleError(error));
|
||||
} finally {
|
||||
_saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
bool _owns(num id) => mounted && runTitleId(widget.run) == id;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (runTitleId(widget.run) == null) return const SizedBox.shrink();
|
||||
if (_usesCupertino(context)) {
|
||||
return CupertinoButton(
|
||||
key: runTitleActionKey,
|
||||
onPressed: _open,
|
||||
child: const Text(runTitleActionLabel),
|
||||
);
|
||||
}
|
||||
return OutlinedButton(
|
||||
key: runTitleActionKey,
|
||||
onPressed: _open,
|
||||
child: const Text(runTitleActionLabel),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The run id used by the rename request, or null for a malformed run.
|
||||
num? runTitleId(JsonMap run) {
|
||||
final id = run['id'];
|
||||
return id is num ? id : null;
|
||||
}
|
||||
|
||||
/// The run's stored title exactly as the browser reads it
|
||||
/// (`String(d.title ?? "")`); never inferred from the prompt or output.
|
||||
String storedRunTitle(JsonMap run) {
|
||||
final title = run['title'];
|
||||
return title == null ? '' : '$title';
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'action_refusal.dart';
|
||||
import 'title_wording.dart';
|
||||
|
||||
/// Sends the typed title. Returns null once the server has accepted it, or an
|
||||
/// [ActionRefusal] carrying the server's words verbatim; the prompt then stays
|
||||
/// open with the typed title intact.
|
||||
typedef TitleSubmit = Future<ActionRefusal?> Function(String title);
|
||||
|
||||
/// Opens the native rename prompt for [runId], seeded with the run's stored
|
||||
/// [initialTitle].
|
||||
///
|
||||
/// Typing and the dismiss action send nothing; only Save sends the title. The
|
||||
/// title is passed through exactly as typed, including surrounding whitespace,
|
||||
/// matching `setRunTitle` in `web/src/repository.js`; the server decides whether
|
||||
/// a blank title is acceptable.
|
||||
Future<void> showRunTitlePrompt({
|
||||
required BuildContext context,
|
||||
required num runId,
|
||||
required String initialTitle,
|
||||
required bool cupertino,
|
||||
required TitleSubmit onSubmit,
|
||||
}) {
|
||||
final prompt = _TitlePrompt(
|
||||
runId: runId,
|
||||
initialTitle: initialTitle,
|
||||
cupertino: cupertino,
|
||||
onSubmit: onSubmit,
|
||||
);
|
||||
if (cupertino) {
|
||||
return showCupertinoDialog<void>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (_) => prompt,
|
||||
);
|
||||
}
|
||||
return showDialog<void>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (_) => prompt,
|
||||
);
|
||||
}
|
||||
|
||||
class _TitlePrompt extends StatefulWidget {
|
||||
const _TitlePrompt({
|
||||
required this.runId,
|
||||
required this.initialTitle,
|
||||
required this.cupertino,
|
||||
required this.onSubmit,
|
||||
});
|
||||
|
||||
final num runId;
|
||||
final String initialTitle;
|
||||
final bool cupertino;
|
||||
final TitleSubmit onSubmit;
|
||||
|
||||
@override
|
||||
State<_TitlePrompt> createState() => _TitlePromptState();
|
||||
}
|
||||
|
||||
class _TitlePromptState extends State<_TitlePrompt> {
|
||||
late final TextEditingController _title = TextEditingController(
|
||||
text: widget.initialTitle,
|
||||
);
|
||||
bool _sending = false;
|
||||
String? _error;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_title.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _cancel() {
|
||||
if (!_sending) Navigator.of(context).pop();
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
if (_sending) return;
|
||||
setState(() {
|
||||
_sending = true;
|
||||
_error = null;
|
||||
});
|
||||
final refusal = await widget.onSubmit(_title.text);
|
||||
if (!mounted) return;
|
||||
if (refusal == null) {
|
||||
Navigator.of(context).pop();
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_sending = false;
|
||||
_error = refusal.message;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final dialog = widget.cupertino ? _cupertino(context) : _material(context);
|
||||
return PopScope(canPop: !_sending, child: dialog);
|
||||
}
|
||||
|
||||
Widget _material(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return AlertDialog(
|
||||
scrollable: true,
|
||||
title: const Text(runTitleDialogTitle),
|
||||
content: _body(
|
||||
field: TextField(
|
||||
key: runTitleFieldKey,
|
||||
controller: _title,
|
||||
enabled: !_sending,
|
||||
autofocus: true,
|
||||
decoration: const InputDecoration(labelText: runTitleFieldLabel),
|
||||
textInputAction: TextInputAction.done,
|
||||
onSubmitted: (_) => _save(),
|
||||
),
|
||||
errorStyle: TextStyle(color: theme.colorScheme.error),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
key: runTitleCancelKey,
|
||||
onPressed: _sending ? null : _cancel,
|
||||
child: const Text(runTitleCancelLabel),
|
||||
),
|
||||
FilledButton(
|
||||
key: runTitleSaveKey,
|
||||
onPressed: _sending ? null : _save,
|
||||
child: const Text(runTitleSaveLabel),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _cupertino(BuildContext context) {
|
||||
return CupertinoAlertDialog(
|
||||
title: const Text(runTitleDialogTitle),
|
||||
content: _body(
|
||||
field: CupertinoTextField(
|
||||
key: runTitleFieldKey,
|
||||
controller: _title,
|
||||
enabled: !_sending,
|
||||
autofocus: true,
|
||||
placeholder: runTitleFieldLabel,
|
||||
textInputAction: TextInputAction.done,
|
||||
onSubmitted: (_) => _save(),
|
||||
),
|
||||
errorStyle: TextStyle(
|
||||
color: CupertinoColors.systemRed.resolveFrom(context),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
CupertinoDialogAction(
|
||||
key: runTitleCancelKey,
|
||||
onPressed: _sending ? null : _cancel,
|
||||
child: const Text(runTitleCancelLabel),
|
||||
),
|
||||
CupertinoDialogAction(
|
||||
key: runTitleSaveKey,
|
||||
isDefaultAction: true,
|
||||
onPressed: _sending ? null : _save,
|
||||
child: const Text(runTitleSaveLabel),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _body({required Widget field, required TextStyle errorStyle}) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
field,
|
||||
if (_error case final error?)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Text(error, key: runTitleErrorKey, style: errorStyle),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
/// The browser client's rename wording, kept verbatim.
|
||||
const runTitleActionLabel = 'Rename';
|
||||
const runTitleDialogTitle = 'Rename';
|
||||
const runTitleFieldLabel = 'Run title';
|
||||
const runTitleSaveLabel = 'Save';
|
||||
const runTitleCancelLabel = 'Cancel';
|
||||
|
||||
/// Stable test/semantics keys shared by the action and its prompt.
|
||||
const runTitleActionKey = ValueKey<String>('rename-run-action');
|
||||
const runTitleFieldKey = ValueKey<String>('rename-run-field');
|
||||
const runTitleSaveKey = ValueKey<String>('rename-run-save');
|
||||
const runTitleCancelKey = ValueKey<String>('rename-run-cancel');
|
||||
const runTitleErrorKey = ValueKey<String>('rename-run-error');
|
||||
|
||||
/// The server's refusal, verbatim. Only a blank error gets a generic sentence
|
||||
/// so the prompt never claims a rename that did not happen.
|
||||
String describeTitleError(Object error) {
|
||||
final message = '$error';
|
||||
return message.trim().isEmpty
|
||||
? 'The server did not rename the run.'
|
||||
: message;
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/run_models.dart';
|
||||
|
||||
/// Protocol failure kept separate from transport errors; server error envelopes
|
||||
/// are otherwise propagated unchanged by [ApiGateway].
|
||||
class RunsRepositoryException implements Exception {
|
||||
const RunsRepositoryException(this.message);
|
||||
final String message;
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
/// Run protocol requests over the application's shared gateway.
|
||||
class RunsRepository {
|
||||
RunsRepository(this._gateway);
|
||||
final ApiGateway _gateway;
|
||||
|
||||
Future<RunListResult> listRuns() async {
|
||||
final reply = await _gateway.call('list_runs');
|
||||
final runs = reply['runs'];
|
||||
return RunListResult(
|
||||
runs is List
|
||||
? runs
|
||||
.whereType<Map>()
|
||||
.map((r) => Map<String, dynamic>.from(r))
|
||||
.toList()
|
||||
: const [],
|
||||
reply['usage'] is Map
|
||||
? Map<String, dynamic>.from(reply['usage'] as Map)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
Future<JsonMap> getRun(num id) async =>
|
||||
_required(await _gateway.call('get_run', {'run_id': id}), 'run_detail');
|
||||
Future<JsonMap> cancelRun(num id) async => _required(
|
||||
await _gateway.call('cancel_run', {'run_id': id}),
|
||||
'run_detail',
|
||||
);
|
||||
|
||||
Future<JsonMap> retryRun(
|
||||
num id, {
|
||||
required String requestKey,
|
||||
String? mode,
|
||||
}) async {
|
||||
final fields = <String, dynamic>{'run_id': id, 'request_key': requestKey};
|
||||
if (mode == 'restart') fields['retry_mode'] = mode;
|
||||
return _required(await _gateway.call('retry_run', fields), 'run_detail');
|
||||
}
|
||||
|
||||
Future<JsonMap> decideRun(
|
||||
num id, {
|
||||
String? stage,
|
||||
required String option,
|
||||
String feedback = '',
|
||||
}) async {
|
||||
final selected = option.trim();
|
||||
if (selected.isEmpty) {
|
||||
throw const RunsRepositoryException(
|
||||
'Choose an option before continuing.',
|
||||
);
|
||||
}
|
||||
final fields = <String, dynamic>{'run_id': id, 'option': selected};
|
||||
if (stage != null && stage.trim().isNotEmpty) fields['stage'] = stage;
|
||||
if (feedback.trim().isNotEmpty) fields['feedback'] = feedback.trim();
|
||||
return _required(await _gateway.call('decide_run', fields), 'run_detail');
|
||||
}
|
||||
|
||||
Future<JsonMap> setRunTitle(num id, String title) async => _required(
|
||||
await _gateway.call('set_run_title', {'run_id': id, 'title': title}),
|
||||
'run_detail',
|
||||
);
|
||||
|
||||
Future<JsonMap> startRun({
|
||||
required num pipelineId,
|
||||
required num version,
|
||||
required String prompt,
|
||||
required String workspace,
|
||||
required String requestKey,
|
||||
String title = '',
|
||||
String outputFormat = '',
|
||||
String notifyMode = 'auto',
|
||||
}) async {
|
||||
final fields = <String, dynamic>{
|
||||
'pipeline_id': pipelineId,
|
||||
'version': version,
|
||||
'request_key': requestKey,
|
||||
'workspace': workspace.trim(),
|
||||
'input': {'prompt': prompt},
|
||||
};
|
||||
if (title.trim().isNotEmpty) fields['title'] = title.trim();
|
||||
if (outputFormat.isNotEmpty) fields['output_format'] = outputFormat;
|
||||
final mode = notifyMode.trim().toLowerCase();
|
||||
if (mode == 'on' || mode == 'off') fields['notify_mode'] = mode;
|
||||
return _required(await _gateway.call('run_pipeline', fields), 'run_detail');
|
||||
}
|
||||
|
||||
JsonMap _required(JsonMap reply, String key) {
|
||||
final value = reply[key];
|
||||
if (value is! Map) {
|
||||
throw RunsRepositoryException('The server returned no $key.');
|
||||
}
|
||||
return Map<String, dynamic>.from(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'run_models.dart';
|
||||
|
||||
class PendingDecision {
|
||||
const PendingDecision({
|
||||
required this.runId,
|
||||
required this.runLabel,
|
||||
required this.stageKey,
|
||||
required this.instructions,
|
||||
required this.options,
|
||||
});
|
||||
final num runId;
|
||||
final String runLabel;
|
||||
final String stageKey;
|
||||
final String instructions;
|
||||
final List<DecisionOption> options;
|
||||
}
|
||||
|
||||
JsonMap? lastWaitingStep(List<dynamic> steps) {
|
||||
for (final value in steps.reversed) {
|
||||
if (value is Map && value['status'] == 'waiting') {
|
||||
return Map<String, dynamic>.from(value);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
String waitingPrompt(dynamic output) =>
|
||||
output is Map && output['prompt'] is String
|
||||
? output['prompt'] as String
|
||||
: '';
|
||||
|
||||
List<String> waitingOptions(dynamic output) {
|
||||
final options = output is Map ? output['options'] : null;
|
||||
if (options is! List) return const [];
|
||||
return options
|
||||
.whereType<String>()
|
||||
.where((entry) => entry.trim().isNotEmpty)
|
||||
.toList();
|
||||
}
|
||||
|
||||
List<String> humanOptions(dynamic edges) {
|
||||
if (edges is! Map) return const [];
|
||||
return edges.keys.map((key) => '$key').where((key) => key != 'error').toList()
|
||||
..sort();
|
||||
}
|
||||
|
||||
PendingDecision? pendingDecision(JsonMap? run) {
|
||||
if (run == null ||
|
||||
run['status'] != 'waiting' ||
|
||||
_positive(run['export_pending_sequence'])) {
|
||||
return null;
|
||||
}
|
||||
final steps = run['steps'] is List ? run['steps'] as List : const [];
|
||||
final step = lastWaitingStep(steps);
|
||||
final stage = _string(step?['stage']).trim().isNotEmpty
|
||||
? _string(step?['stage'])
|
||||
: _string(run['current_stage']);
|
||||
if (stage.trim().isEmpty) return null;
|
||||
JsonMap? declaration;
|
||||
final graph = run['graph'];
|
||||
final graphStages = graph is Map ? graph['stages'] : null;
|
||||
if (graphStages is List) {
|
||||
for (final value in graphStages.whereType<Map>()) {
|
||||
if (value['key'] == stage) {
|
||||
declaration = Map<String, dynamic>.from(value);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (declaration?['type'] != null && declaration!['type'] != 'human') {
|
||||
return null;
|
||||
}
|
||||
final edges = declaration?['edges'];
|
||||
final options = waitingOptions(step?['output']);
|
||||
final keys = options.isNotEmpty ? options : humanOptions(edges);
|
||||
if (keys.isEmpty) return null;
|
||||
final instructions = waitingPrompt(step?['output']).trim().isNotEmpty
|
||||
? waitingPrompt(step?['output'])
|
||||
: _string(declaration?['prompt']);
|
||||
return PendingDecision(
|
||||
runId: run['id'] is num ? run['id'] as num : 0,
|
||||
runLabel: runIdentity(run['title'], run['name']).label,
|
||||
stageKey: stage,
|
||||
instructions: instructions,
|
||||
options: keys
|
||||
.map(
|
||||
(key) => DecisionOption(
|
||||
key,
|
||||
target: _targetLabel(key, edges is Map ? edges[key] : null),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
String _targetLabel(String option, dynamic target) {
|
||||
if (target == null || '$target'.trim().isEmpty) return '';
|
||||
final resolved = target == '#'
|
||||
? (option == 'error' ? '#failure' : '#success')
|
||||
: '$target';
|
||||
return switch (resolved) {
|
||||
'#success' => 'SUCCESS',
|
||||
'#failure' => 'FAILURE',
|
||||
_ => resolved,
|
||||
};
|
||||
}
|
||||
|
||||
bool _positive(dynamic value) => value is num && value > 0;
|
||||
String _string(dynamic value) => value == null ? '' : '$value';
|
||||
@@ -0,0 +1,226 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'run_step_evidence.dart';
|
||||
|
||||
const terminalRunStatuses = {'succeeded', 'failed', 'canceled', 'interrupted'};
|
||||
|
||||
bool isTerminalRunStatus(dynamic status) =>
|
||||
terminalRunStatuses.contains(_word(status));
|
||||
bool isWaitingRunStatus(dynamic status) => _word(status) == 'waiting';
|
||||
|
||||
int runLifecycleRank(dynamic status) => switch (_word(status)) {
|
||||
'queued' => 0,
|
||||
'running' || 'waiting' => 1,
|
||||
'succeeded' || 'failed' || 'canceled' || 'interrupted' => 2,
|
||||
_ => -1,
|
||||
};
|
||||
|
||||
int stepLifecycleRank(dynamic status) => switch (_word(status)) {
|
||||
'running' || 'waiting' => 1,
|
||||
'completed' || 'failed' || 'canceled' || 'interrupted' => 2,
|
||||
_ => -1,
|
||||
};
|
||||
|
||||
bool _stale(dynamic current, dynamic incoming, int Function(dynamic) rank) {
|
||||
if (_word(incoming).isEmpty) return false;
|
||||
final oldRank = rank(current);
|
||||
final newRank = rank(incoming);
|
||||
return oldRank >= 0 &&
|
||||
newRank >= 0 &&
|
||||
(newRank < oldRank ||
|
||||
(oldRank == 2 && newRank == 2 && incoming != current));
|
||||
}
|
||||
|
||||
String _advance(dynamic current, dynamic incoming, int Function(dynamic) rank) {
|
||||
if (_word(incoming).isEmpty || incoming == current) return '${current ?? ''}';
|
||||
final oldRank = rank(current);
|
||||
final newRank = rank(incoming);
|
||||
if (oldRank < 0) return '$incoming';
|
||||
if (newRank < 0 || (oldRank == 2 && newRank == 2) || newRank < oldRank) {
|
||||
return '${current ?? ''}';
|
||||
}
|
||||
return '$incoming';
|
||||
}
|
||||
|
||||
bool executingFor(dynamic status, bool current) => switch (_word(status)) {
|
||||
'queued' || 'running' => true,
|
||||
'waiting' || 'succeeded' || 'failed' || 'canceled' || 'interrupted' => false,
|
||||
_ => current,
|
||||
};
|
||||
|
||||
bool _blank(dynamic value) => '${value ?? ''}'.trim().isEmpty;
|
||||
|
||||
JsonMap _scheduleOrigin(JsonMap current, JsonMap frame) {
|
||||
final oldId = _positiveInt(current['schedule_id']);
|
||||
final newId = _positiveInt(frame['schedule_id']);
|
||||
final known =
|
||||
current.containsKey('scheduled') ||
|
||||
frame.containsKey('scheduled') ||
|
||||
oldId > 0 ||
|
||||
newId > 0;
|
||||
if (!known) return {};
|
||||
final id = oldId > 0 ? oldId : newId;
|
||||
final nameConflict = oldId > 0 && newId > 0 && oldId != newId;
|
||||
final name =
|
||||
'${current['schedule_name'] ?? (nameConflict ? '' : frame['schedule_name'] ?? '')}';
|
||||
return {
|
||||
'scheduled':
|
||||
current['scheduled'] == true || frame['scheduled'] == true || id > 0,
|
||||
if (id > 0) 'schedule_id': id,
|
||||
if (name.isNotEmpty) 'schedule_name': name,
|
||||
};
|
||||
}
|
||||
|
||||
int _positiveInt(dynamic value) =>
|
||||
value is num && value > 0 ? value.toInt() : 0;
|
||||
|
||||
JsonMap _mergeRunFields(JsonMap current, JsonMap frame) {
|
||||
if (_stale(current['status'], frame['status'], runLifecycleRank) &&
|
||||
frame['resource_wait_set'] != true) {
|
||||
return current;
|
||||
}
|
||||
final beforeStatus = '${current['status'] ?? ''}';
|
||||
final status =
|
||||
frame['resource_wait_set'] == true &&
|
||||
frame['status'] == 'queued' &&
|
||||
!isTerminalRunStatus(beforeStatus)
|
||||
? 'queued'
|
||||
: _advance(beforeStatus, frame['status'], runLifecycleRank);
|
||||
final merged = <String, dynamic>{
|
||||
...current,
|
||||
..._scheduleOrigin(current, frame),
|
||||
'status': status,
|
||||
'executing': executingFor(status, current['executing'] == true),
|
||||
'completed_steps': _maxInt(
|
||||
current['completed_steps'],
|
||||
frame['completed_steps'],
|
||||
),
|
||||
'resource_wait': isTerminalRunStatus(status)
|
||||
? null
|
||||
: frame['resource_wait_set'] == true
|
||||
? frame['resource_wait']
|
||||
: current['resource_wait'],
|
||||
'notify_mode': _blank(frame['notify_mode'])
|
||||
? current['notify_mode'] ?? 'auto'
|
||||
: frame['notify_mode'],
|
||||
'cancel_requested':
|
||||
current['cancel_requested'] == true ||
|
||||
frame['cancel_requested'] == true,
|
||||
'cleanup_unconfirmed':
|
||||
current['cleanup_unconfirmed'] == true ||
|
||||
frame['cleanup_unconfirmed'] == true,
|
||||
};
|
||||
for (final key in ['outcome', 'current_stage', 'created_at', 'finished_at']) {
|
||||
if (!_blank(frame[key])) merged[key] = frame[key];
|
||||
}
|
||||
final oldExport = _positiveInt(current['export_pending_sequence']);
|
||||
if (oldExport > 0 || frame.containsKey('export_pending_sequence')) {
|
||||
merged['export_pending_sequence'] = _blank(frame['status'])
|
||||
? oldExport
|
||||
: status == 'waiting'
|
||||
? _positiveInt(frame['export_pending_sequence'])
|
||||
: 0;
|
||||
}
|
||||
if (current['steps'] is! List) {
|
||||
final evidence = mergeGraphEvidence(
|
||||
current['graph_evidence'] as JsonMap?,
|
||||
frame,
|
||||
);
|
||||
if (evidence != null) merged['graph_evidence'] = evidence;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
int _maxInt(dynamic a, dynamic b) =>
|
||||
(a is num ? a.toInt() : 0).clamp(b is num ? b.toInt() : 0, 0x7fffffff);
|
||||
|
||||
/// A summary row can be built from a sufficiently identified push; otherwise
|
||||
/// the caller must resync from the server's authoritative list.
|
||||
JsonMap? newRunSummaryFromFrame(JsonMap frame) {
|
||||
final id = frame['run_id'];
|
||||
final pipelineId = frame['pipeline_id'];
|
||||
if (id is! num ||
|
||||
id <= 0 ||
|
||||
pipelineId is! num ||
|
||||
pipelineId <= 0 ||
|
||||
_blank(frame['name'])) {
|
||||
return null;
|
||||
}
|
||||
final row = <String, dynamic>{
|
||||
'id': id,
|
||||
'pipeline_id': pipelineId,
|
||||
'name': frame['name'],
|
||||
'title': _blank(frame['title']) ? null : frame['title'],
|
||||
'version': frame['version'] ?? 0,
|
||||
'notify_mode': frame['notify_mode'] ?? 'auto',
|
||||
'status': frame['status'] ?? '',
|
||||
'executing': executingFor(frame['status'], true),
|
||||
'completed_steps': _maxInt(0, frame['completed_steps']),
|
||||
'created_at': frame['created_at'] ?? '',
|
||||
'finished_at': frame['finished_at'] ?? '',
|
||||
'outcome': frame['outcome'] ?? '',
|
||||
'current_stage': frame['current_stage'] ?? '',
|
||||
'resource_wait': frame['resource_wait'],
|
||||
'cancel_requested': frame['cancel_requested'] == true,
|
||||
'cleanup_unconfirmed': frame['cleanup_unconfirmed'] == true,
|
||||
};
|
||||
row.addAll(_scheduleOrigin({}, frame));
|
||||
final sequence = _positiveInt(frame['export_pending_sequence']);
|
||||
if (sequence > 0) row['export_pending_sequence'] = sequence;
|
||||
final evidence = mergeGraphEvidence(null, frame);
|
||||
if (evidence != null) row['graph_evidence'] = evidence;
|
||||
return row;
|
||||
}
|
||||
|
||||
({List<JsonMap> runs, bool needsResync}) foldRunEvent(
|
||||
List<JsonMap> runs,
|
||||
JsonMap frame,
|
||||
) {
|
||||
final id = frame['run_id'];
|
||||
if (id is! num || id <= 0) return (runs: runs, needsResync: false);
|
||||
final index = runs.indexWhere((run) => run['id'] == id);
|
||||
if (index < 0) {
|
||||
final row = newRunSummaryFromFrame(frame);
|
||||
return row == null
|
||||
? (runs: runs, needsResync: true)
|
||||
: (runs: [row, ...runs], needsResync: false);
|
||||
}
|
||||
final updated = _mergeRunFields(runs[index], frame);
|
||||
if (identical(updated, runs[index])) return (runs: runs, needsResync: false);
|
||||
final next = [...runs];
|
||||
next[index] = updated;
|
||||
return (runs: next, needsResync: false);
|
||||
}
|
||||
|
||||
JsonMap? foldRunEventDetail(JsonMap? detail, JsonMap frame) {
|
||||
if (detail == null || detail['id'] != frame['run_id']) return detail;
|
||||
if (_stale(detail['status'], frame['status'], runLifecycleRank) &&
|
||||
frame['resource_wait_set'] != true) {
|
||||
return detail;
|
||||
}
|
||||
final merged = _mergeRunFields(detail, frame);
|
||||
final steps = frame['step'] is Map
|
||||
? upsertRunStep(
|
||||
detail['steps'] is List
|
||||
? (detail['steps'] as List)
|
||||
.whereType<Map>()
|
||||
.map((s) => Map<String, dynamic>.from(s))
|
||||
.toList()
|
||||
: [],
|
||||
Map<String, dynamic>.from(frame['step'] as Map),
|
||||
)
|
||||
: detail['steps'] ?? [];
|
||||
return {...merged, 'steps': steps};
|
||||
}
|
||||
|
||||
bool runDetailNeedsFullSync(JsonMap frame) {
|
||||
final step = frame['step'];
|
||||
final stepStatus = step is Map ? step['status'] : null;
|
||||
return isTerminalRunStatus(frame['status']) ||
|
||||
isWaitingRunStatus(frame['status']) ||
|
||||
frame['cancel_requested'] == true ||
|
||||
frame['cleanup_unconfirmed'] == true ||
|
||||
isWaitingRunStatus(stepStatus) ||
|
||||
stepLifecycleRank(stepStatus) == 2;
|
||||
}
|
||||
|
||||
String _word(dynamic value) => '${value ?? ''}'.trim().toLowerCase();
|
||||
@@ -0,0 +1,219 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
const runStates = [
|
||||
'queued',
|
||||
'running',
|
||||
'waiting',
|
||||
'succeeded',
|
||||
'failed',
|
||||
'canceled',
|
||||
'interrupted',
|
||||
];
|
||||
|
||||
/// The largest millisecond value [DateTime] supports, and also exactly
|
||||
/// representable by the web's JavaScript numbers. The previous
|
||||
/// `0x7fffffffffffffff` literals failed dart2js compilation.
|
||||
const int _maxMillis = 8640000000000000;
|
||||
|
||||
({String label, String? pipeline}) runIdentity(dynamic title, dynamic name) {
|
||||
final stored = '${title ?? ''}'.trim();
|
||||
return (
|
||||
label: stored.isNotEmpty ? stored : '${name ?? ''}',
|
||||
pipeline: stored.isNotEmpty ? '${name ?? ''}' : null,
|
||||
);
|
||||
}
|
||||
|
||||
String runStateOf(dynamic status) =>
|
||||
switch ('${status ?? ''}'.trim().toLowerCase()) {
|
||||
'queued' ||
|
||||
'running' ||
|
||||
'waiting' ||
|
||||
'active' ||
|
||||
'blocked' ||
|
||||
'skipped' => '${status ?? ''}'.trim().toLowerCase(),
|
||||
'succeeded' || 'success' || 'completed' || 'done' => 'succeeded',
|
||||
'failed' || 'error' => 'failed',
|
||||
'canceled' || 'cancelled' => 'canceled',
|
||||
'interrupted' => 'interrupted',
|
||||
_ => 'unknown',
|
||||
};
|
||||
|
||||
List<JsonMap> filterRuns(
|
||||
List<JsonMap> runs, {
|
||||
Set<String> statuses = const {},
|
||||
int? pipelineId,
|
||||
String timeRange = 'any_time',
|
||||
String scheduled = 'any',
|
||||
DateTime? today,
|
||||
}) => runs.where((run) {
|
||||
if (statuses.isNotEmpty && !statuses.contains(runStateOf(run['status']))) {
|
||||
return false;
|
||||
}
|
||||
if (pipelineId != null && run['pipeline_id'] != pipelineId) {
|
||||
return false;
|
||||
}
|
||||
if (scheduled == 'scheduled' && !_isScheduled(run)) {
|
||||
return false;
|
||||
}
|
||||
if (scheduled == 'unscheduled' &&
|
||||
(run['scheduled'] != false || _isScheduled(run))) {
|
||||
return false;
|
||||
}
|
||||
if (timeRange == 'any_time' || timeRange.isEmpty) {
|
||||
return true;
|
||||
}
|
||||
final created = DateTime.tryParse('${run['created_at'] ?? ''}')?.toLocal();
|
||||
if (created == null) {
|
||||
return false;
|
||||
}
|
||||
final now = today ?? DateTime.now();
|
||||
final start = DateTime(now.year, now.month, now.day);
|
||||
final date = DateTime(created.year, created.month, created.day);
|
||||
if (date.isAfter(start)) {
|
||||
return false;
|
||||
}
|
||||
final days = switch (timeRange) {
|
||||
'today' => 0,
|
||||
'last_7_days' => 6,
|
||||
'last_30_days' => 29,
|
||||
_ => null,
|
||||
};
|
||||
return days == null || !date.isBefore(start.subtract(Duration(days: days)));
|
||||
}).toList();
|
||||
|
||||
bool _isScheduled(JsonMap run) =>
|
||||
run['scheduled'] == true ||
|
||||
(run['schedule_id'] is num && (run['schedule_id'] as num) > 0);
|
||||
|
||||
String runStatusLabel(JsonMap run) {
|
||||
final status = '${run['status'] ?? ''}';
|
||||
if (!{'queued', 'running', 'waiting'}.contains(status)) {
|
||||
return status.isEmpty ? 'unknown' : status;
|
||||
}
|
||||
if (run['cleanup_unconfirmed'] == true) {
|
||||
return 'Cleanup unconfirmed — workspace reserved';
|
||||
}
|
||||
if (run['cancel_requested'] == true) {
|
||||
return 'Stopping — waiting for execution to stop';
|
||||
}
|
||||
if (status == 'waiting' &&
|
||||
(run['export_pending_sequence'] as num? ?? 0) > 0) {
|
||||
return 'Waiting for session export';
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
List<JsonMap> sortRuns(List<JsonMap> runs, {String sort = 'newest_first'}) {
|
||||
final result = [...runs];
|
||||
int? instant(dynamic value) =>
|
||||
DateTime.tryParse('${value ?? ''}')?.millisecondsSinceEpoch;
|
||||
int? duration(JsonMap run) {
|
||||
final from = instant(run['created_at']);
|
||||
final to = instant(run['finished_at']);
|
||||
if (from == null || to == null || to < from) return null;
|
||||
return (to - from) ~/ 1000;
|
||||
}
|
||||
|
||||
int cmp<T extends Comparable<Object>>(T a, T b) => a.compareTo(b);
|
||||
result.sort((a, b) {
|
||||
final at = instant(a['created_at']);
|
||||
final bt = instant(b['created_at']);
|
||||
int primary;
|
||||
switch (sort) {
|
||||
case 'oldest_first':
|
||||
primary = cmp(at ?? _maxMillis, bt ?? _maxMillis);
|
||||
break;
|
||||
case 'longest_duration':
|
||||
primary = cmp(duration(a) == null ? 1 : 0, duration(b) == null ? 1 : 0);
|
||||
if (primary == 0) primary = cmp(duration(b) ?? -1, duration(a) ?? -1);
|
||||
if (primary == 0) {
|
||||
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
|
||||
}
|
||||
break;
|
||||
case 'shortest_duration':
|
||||
primary = cmp(duration(a) == null ? 1 : 0, duration(b) == null ? 1 : 0);
|
||||
if (primary == 0) {
|
||||
primary = cmp(duration(a) ?? _maxMillis, duration(b) ?? _maxMillis);
|
||||
}
|
||||
if (primary == 0) {
|
||||
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
|
||||
}
|
||||
break;
|
||||
case 'pipeline_name':
|
||||
primary = '${a['name'] ?? ''}'.toLowerCase().compareTo(
|
||||
'${b['name'] ?? ''}'.toLowerCase(),
|
||||
);
|
||||
if (primary == 0) {
|
||||
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
|
||||
}
|
||||
break;
|
||||
case 'status':
|
||||
primary = '${a['status'] ?? ''}'.toLowerCase().compareTo(
|
||||
'${b['status'] ?? ''}'.toLowerCase(),
|
||||
);
|
||||
if (primary == 0) {
|
||||
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
|
||||
}
|
||||
return primary == 0
|
||||
? ((b['id'] as num?) ?? 0).compareTo((a['id'] as num?) ?? 0)
|
||||
: primary;
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Null usage means unsupported/unavailable, not zero.
|
||||
class RunListResult {
|
||||
const RunListResult(this.runs, this.usage);
|
||||
final List<JsonMap> runs;
|
||||
final JsonMap? usage;
|
||||
}
|
||||
|
||||
class DecisionOption {
|
||||
const DecisionOption(this.key, {this.target = ''});
|
||||
final String key;
|
||||
final String target;
|
||||
}
|
||||
|
||||
class DecisionDraft {
|
||||
const DecisionDraft({this.selected, this.feedback = ''});
|
||||
final String? selected;
|
||||
final String feedback;
|
||||
bool get canSubmit => selected != null && selected!.trim().isNotEmpty;
|
||||
DecisionDraft select(String option) =>
|
||||
DecisionDraft(selected: option, feedback: feedback);
|
||||
DecisionDraft withFeedback(String value) =>
|
||||
DecisionDraft(selected: selected, feedback: value);
|
||||
}
|
||||
|
||||
String attentionKey(num runId, String kind) => '$runId:$kind';
|
||||
|
||||
List<JsonMap> orderAttention(
|
||||
List<JsonMap> runs, {
|
||||
Set<String> dismissed = const {},
|
||||
}) {
|
||||
final result = runs.where((run) {
|
||||
final waiting = run['status'] == 'waiting';
|
||||
if (waiting && (run['export_pending_sequence'] as num? ?? 0) > 0) {
|
||||
return false;
|
||||
}
|
||||
final kind = waiting ? 'Decision' : 'Failed';
|
||||
return (waiting || run['status'] == 'failed') &&
|
||||
!dismissed.contains(attentionKey(run['id'] as num, kind));
|
||||
}).toList();
|
||||
String recency(JsonMap run) => '${run['finished_at'] ?? ''}'.trim().isNotEmpty
|
||||
? '${run['finished_at']}'
|
||||
: '${run['created_at'] ?? ''}';
|
||||
result.sort((a, b) {
|
||||
final rank = (a['status'] == 'waiting' ? 0 : 1).compareTo(
|
||||
b['status'] == 'waiting' ? 0 : 1,
|
||||
);
|
||||
if (rank != 0) return rank;
|
||||
final date = recency(b).compareTo(recency(a));
|
||||
return date != 0 ? date : (b['id'] as num).compareTo(a['id'] as num);
|
||||
});
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
/// Merge a visit by sequence without allowing stale status or blank sparse
|
||||
/// deltas to erase evidence already held by the detail cache.
|
||||
List<JsonMap> upsertRunStep(List<JsonMap> steps, JsonMap delta) {
|
||||
final sequence = delta['sequence'] is num
|
||||
? (delta['sequence'] as num).toInt()
|
||||
: 0;
|
||||
final index = steps.indexWhere((step) => step['sequence'] == sequence);
|
||||
if (index < 0) {
|
||||
final result = [...steps, _stepFields({}, delta, sequence)];
|
||||
result.sort(
|
||||
(a, b) => ((a['sequence'] as num?) ?? 0).compareTo(
|
||||
(b['sequence'] as num?) ?? 0,
|
||||
),
|
||||
);
|
||||
return result;
|
||||
}
|
||||
final old = steps[index];
|
||||
final incomingStatus = '${delta['status'] ?? ''}';
|
||||
final oldStatus = '${old['status'] ?? ''}';
|
||||
if (_stale(oldStatus, incomingStatus)) return steps;
|
||||
final merged = _stepFields(old, delta, sequence);
|
||||
if (_same(old, merged)) return steps;
|
||||
final result = [...steps];
|
||||
result[index] = merged;
|
||||
return result;
|
||||
}
|
||||
|
||||
JsonMap _stepFields(JsonMap old, JsonMap delta, int sequence) {
|
||||
final oldStatus = '${old['status'] ?? ''}';
|
||||
final incoming = '${delta['status'] ?? ''}';
|
||||
return {
|
||||
...old,
|
||||
'sequence': sequence,
|
||||
for (final key in ['stage', 'outcome', 'target', 'diagnostic'])
|
||||
key: _blank(delta[key]) ? old[key] ?? '' : delta[key],
|
||||
'status': _advance(oldStatus, incoming),
|
||||
};
|
||||
}
|
||||
|
||||
bool _stale(String old, String incoming) {
|
||||
if (_blank(incoming)) return false;
|
||||
final before = _rank(old);
|
||||
final after = _rank(incoming);
|
||||
return before >= 0 &&
|
||||
after >= 0 &&
|
||||
(after < before || (before == 2 && after == 2 && old != incoming));
|
||||
}
|
||||
|
||||
String _advance(String old, String incoming) {
|
||||
if (_blank(incoming)) return old;
|
||||
final before = _rank(old);
|
||||
final after = _rank(incoming);
|
||||
if (before < 0 || (after >= 0 && after > before && before < 2)) {
|
||||
return incoming;
|
||||
}
|
||||
if (before < 2 && after == before) return incoming;
|
||||
return old;
|
||||
}
|
||||
|
||||
int _rank(String status) => switch (status.trim().toLowerCase()) {
|
||||
'running' || 'waiting' => 1,
|
||||
'completed' || 'failed' || 'canceled' || 'interrupted' => 2,
|
||||
_ => -1,
|
||||
};
|
||||
|
||||
bool _same(JsonMap a, JsonMap b) =>
|
||||
a.length == b.length && a.entries.every((e) => b[e.key] == e.value);
|
||||
|
||||
/// Compact graph evidence is intentionally allowlisted. It retains latest
|
||||
/// visit-by-stage and distinct outcome routes, not arbitrary frame diagnostics.
|
||||
JsonMap? mergeGraphEvidence(JsonMap? current, JsonMap frame) {
|
||||
final incomingEvidence = frame['graph_evidence'];
|
||||
final graphVisits = frame['graph_visits'];
|
||||
final step = frame['step'];
|
||||
if (incomingEvidence is! Map && graphVisits is! List && step is! Map) {
|
||||
return current;
|
||||
}
|
||||
var visits = <JsonMap>[];
|
||||
final oldVisits = current?['visits'];
|
||||
if (oldVisits is List) {
|
||||
visits = oldVisits
|
||||
.whereType<Map>()
|
||||
.map((v) => Map<String, dynamic>.from(v))
|
||||
.toList();
|
||||
}
|
||||
final additions = <dynamic>[];
|
||||
if (incomingEvidence is Map && incomingEvidence['visits'] is List) {
|
||||
additions.addAll(incomingEvidence['visits'] as List);
|
||||
}
|
||||
if (graphVisits is List) additions.addAll(graphVisits);
|
||||
if (step is Map) additions.add(step);
|
||||
for (final item in additions.whereType<Map>()) {
|
||||
final delta = Map<String, dynamic>.from(item);
|
||||
visits = upsertRunStep(visits, {
|
||||
'sequence': delta['sequence'],
|
||||
'stage': delta['stage'],
|
||||
'status': delta['status'],
|
||||
'outcome': delta['outcome'],
|
||||
'target': delta['target'],
|
||||
});
|
||||
}
|
||||
final latestByStage = <String, int>{};
|
||||
final routeSequence = <String, int>{};
|
||||
for (final visit in visits) {
|
||||
final sequence = (visit['sequence'] as num?)?.toInt() ?? 0;
|
||||
final stage = '${visit['stage'] ?? ''}';
|
||||
latestByStage[stage] = sequence;
|
||||
if (!_blank(visit['outcome']) && !_blank(visit['target'])) {
|
||||
routeSequence['$stage\u0000${visit['outcome']}\u0000${visit['target']}'] =
|
||||
sequence;
|
||||
}
|
||||
}
|
||||
visits = visits
|
||||
.where((visit) {
|
||||
final sequence = (visit['sequence'] as num?)?.toInt() ?? 0;
|
||||
final stage = '${visit['stage'] ?? ''}';
|
||||
final route = '$stage\u0000${visit['outcome']}\u0000${visit['target']}';
|
||||
return latestByStage[stage] == sequence ||
|
||||
routeSequence[route] == sequence;
|
||||
})
|
||||
.map(
|
||||
(visit) => <String, dynamic>{
|
||||
for (final key in [
|
||||
'sequence',
|
||||
'stage',
|
||||
'status',
|
||||
'outcome',
|
||||
'target',
|
||||
])
|
||||
key: visit[key],
|
||||
},
|
||||
)
|
||||
.toList();
|
||||
final complete =
|
||||
current?['complete'] == true ||
|
||||
(incomingEvidence is Map && incomingEvidence['complete'] == true);
|
||||
return {'complete': complete, 'visits': visits};
|
||||
}
|
||||
|
||||
bool _blank(dynamic value) => '${value ?? ''}'.trim().isEmpty;
|
||||
@@ -0,0 +1,113 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../../core/api_gateway.dart';
|
||||
import 'data/runs_repository.dart';
|
||||
import 'ui/run_detail_view.dart';
|
||||
import 'ui/runs_controller.dart';
|
||||
import 'ui/runs_list.dart';
|
||||
|
||||
/// The runs destination's list/detail switch.
|
||||
///
|
||||
/// The controller's `selectedRunId` is the only selection source, so an
|
||||
/// initial run, a pending detail, a failed detail, Back and a route change all
|
||||
/// navigate the same way. The shell owns the app bar; this screen adds no
|
||||
/// second one.
|
||||
class RunsScreen extends StatefulWidget {
|
||||
const RunsScreen({
|
||||
super.key,
|
||||
required this.gateway,
|
||||
this.initialRunId,
|
||||
this.syncToken = 0,
|
||||
this.onRunSelected,
|
||||
this.onBack,
|
||||
});
|
||||
|
||||
final ApiGateway gateway;
|
||||
|
||||
/// The run the current route names, or null for the list.
|
||||
final int? initialRunId;
|
||||
|
||||
/// Advances when the shared socket is replaced. The loaded screen refreshes
|
||||
/// in place instead of being remounted, so its selection survives.
|
||||
final int syncToken;
|
||||
|
||||
final ValueChanged<int>? onRunSelected;
|
||||
final VoidCallback? onBack;
|
||||
|
||||
@override
|
||||
State<RunsScreen> createState() => _RunsScreenState();
|
||||
}
|
||||
|
||||
class _RunsScreenState extends State<RunsScreen> {
|
||||
late final RunsController controller;
|
||||
num? _shownRunId;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
controller = RunsController(RunsRepository(widget.gateway));
|
||||
controller.listen(widget.gateway.frames);
|
||||
controller.addListener(_selectionChanged);
|
||||
controller.load(widget.initialRunId);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant RunsScreen oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (widget.syncToken != oldWidget.syncToken) {
|
||||
controller.resync();
|
||||
}
|
||||
if (widget.initialRunId != oldWidget.initialRunId) {
|
||||
final id = widget.initialRunId;
|
||||
if (id == null) {
|
||||
if (controller.selectedRunId != null) controller.back();
|
||||
} else if (controller.selectedRunId != id) {
|
||||
controller.select(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuild the switch only when the selection changes. Detail progress and
|
||||
/// live updates are already watched by [RunDetailView] and [RunsList], so
|
||||
/// this avoids a second whole-detail rebuild per notification.
|
||||
void _selectionChanged() {
|
||||
final selected = controller.selectedRunId;
|
||||
if (selected == _shownRunId) return;
|
||||
_shownRunId = selected;
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
|
||||
void _select(num id) {
|
||||
controller.select(id);
|
||||
widget.onRunSelected?.call(id.toInt());
|
||||
}
|
||||
|
||||
void _back() {
|
||||
controller.back();
|
||||
widget.onBack?.call();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
controller.removeListener(_selectionChanged);
|
||||
controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final selected = controller.selectedRunId != null;
|
||||
return Stack(
|
||||
children: [
|
||||
AnimatedBuilder(
|
||||
animation: controller,
|
||||
builder: (context, _) => Offstage(
|
||||
offstage: selected,
|
||||
child: RunsList(controller: controller, onSelected: _select),
|
||||
),
|
||||
),
|
||||
if (selected) RunDetailView(controller: controller, onBack: _back),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/run_models.dart';
|
||||
|
||||
/// One labelled value in the run detail's metrics block.
|
||||
typedef DetailMetric = ({String label, String value});
|
||||
|
||||
/// One recorded visit in the run detail's timeline.
|
||||
typedef DetailVisit = ({String title, String subtitle});
|
||||
|
||||
/// The run's primary label: the stored title, else the pipeline name, and only
|
||||
/// then the numeric identity.
|
||||
String detailTitle(JsonMap run) {
|
||||
final identity = runIdentity(run['title'], run['name']);
|
||||
return identity.label.trim().isEmpty ? 'Run ${run['id']}' : identity.label;
|
||||
}
|
||||
|
||||
String detailPipeline(JsonMap run) {
|
||||
final name = '${run['name'] ?? ''}'.trim();
|
||||
return name.isEmpty ? 'unavailable' : name;
|
||||
}
|
||||
|
||||
/// The original prompt exactly as the server stored it; never trimmed or
|
||||
/// replaced by another field.
|
||||
String? detailPrompt(JsonMap run) {
|
||||
final input = run['input'];
|
||||
return input is Map && input['prompt'] is String
|
||||
? input['prompt'] as String
|
||||
: null;
|
||||
}
|
||||
|
||||
/// Nested input/output shown as formatted, selectable JSON.
|
||||
String detailJson(dynamic value) =>
|
||||
const JsonEncoder.withIndent(' ').convert(value);
|
||||
|
||||
bool detailEmpty(dynamic value) => value is! Map || value.isEmpty;
|
||||
|
||||
/// Reported run metrics. A present zero with a reporting stage count is a real
|
||||
/// zero; a zero without that evidence is unavailable, never a measured zero.
|
||||
List<DetailMetric> detailUsageMetrics(dynamic raw) {
|
||||
if (raw is! Map || raw.isEmpty) return const [];
|
||||
final usage = Map<String, dynamic>.from(raw);
|
||||
final stages = _int(usage['stages']);
|
||||
final tokenStages = _int(usage['tokens_known_stages']) ?? 0;
|
||||
final costStages = _int(usage['cost_known_stages']) ?? 0;
|
||||
final totalTokens = _int(usage['tokens_total']);
|
||||
final splitKnown = usage['split_known'] == true && tokenStages > 0;
|
||||
final rows = <DetailMetric>[
|
||||
if (stages != null) (label: 'Stages', value: '$stages'),
|
||||
(
|
||||
label: 'Total tokens',
|
||||
value: tokenStages == 0 || totalTokens == null
|
||||
? 'Unavailable'
|
||||
: '$totalTokens',
|
||||
),
|
||||
(
|
||||
label: 'Input tokens',
|
||||
value: splitKnown ? '${_int(usage['tokens_in']) ?? 0}' : 'Unavailable',
|
||||
),
|
||||
(
|
||||
label: 'Output tokens',
|
||||
value: splitKnown ? '${_int(usage['tokens_out']) ?? 0}' : 'Unavailable',
|
||||
),
|
||||
(
|
||||
label: 'Reported cost',
|
||||
// cost_usd is omitted by the server when zero, so a known stage count
|
||||
// makes an absent value a real $0.000000 rather than an unknown cost.
|
||||
value: costStages == 0
|
||||
? 'Unavailable'
|
||||
: '\$${((usage['cost_usd'] as num?) ?? 0).toStringAsFixed(6)}',
|
||||
),
|
||||
];
|
||||
if (stages != null && tokenStages < stages) {
|
||||
rows.add((
|
||||
label: 'Token reporting',
|
||||
value: '$tokenStages of $stages stages',
|
||||
));
|
||||
}
|
||||
if (stages != null && costStages < stages) {
|
||||
rows.add((label: 'Cost reporting', value: '$costStages of $stages stages'));
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/// Every recorded visit with its server sequence, in recorded order.
|
||||
List<DetailVisit> detailTimeline(dynamic steps) {
|
||||
if (steps is! List) return const [];
|
||||
return [
|
||||
for (final step in steps.whereType<Map>())
|
||||
(
|
||||
title:
|
||||
'${_text(step['stage'], 'Stage unavailable')} · visit '
|
||||
'${step['sequence'] is num ? (step['sequence'] as num).toInt() : 'unavailable'}',
|
||||
subtitle: _visitSubtitle(step),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
String _visitSubtitle(Map step) {
|
||||
final status = _text(step['status'], 'Status unavailable');
|
||||
final outcome = '${step['outcome'] ?? ''}'.trim();
|
||||
final target = '${step['target'] ?? ''}'.trim();
|
||||
return [
|
||||
status,
|
||||
if (outcome.isNotEmpty) outcome,
|
||||
if (target.isNotEmpty) '→ $target',
|
||||
].join(' · ');
|
||||
}
|
||||
|
||||
String _text(dynamic value, String fallback) {
|
||||
final text = '${value ?? ''}'.trim();
|
||||
return text.isEmpty ? fallback : text;
|
||||
}
|
||||
|
||||
int? _int(dynamic value) => value is num ? value.toInt() : null;
|
||||
@@ -0,0 +1,203 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/run_models.dart';
|
||||
import 'run_detail_content.dart';
|
||||
|
||||
/// The runs detail with standard Cupertino controls. It has no Material
|
||||
/// ancestor: sections use native Cupertino expansion tiles and grouped list
|
||||
/// sections, and copy feedback is an inline live-region status.
|
||||
Widget buildCupertinoRunDetail({
|
||||
required BuildContext context,
|
||||
required JsonMap run,
|
||||
required bool detailLoading,
|
||||
required String? error,
|
||||
required bool copying,
|
||||
required String? copyStatus,
|
||||
required VoidCallback onBack,
|
||||
required VoidCallback onCopy,
|
||||
}) {
|
||||
final theme = CupertinoTheme.of(context);
|
||||
final prompt = detailPrompt(run);
|
||||
final visits = detailTimeline(run['steps']);
|
||||
final metrics = detailUsageMetrics(run['usage']);
|
||||
return ListView(
|
||||
key: ValueKey<String>('run-detail-${run['id']}'),
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0),
|
||||
child: Row(
|
||||
children: [
|
||||
CupertinoButton(
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: onBack,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(CupertinoIcons.back),
|
||||
const SizedBox(width: 4),
|
||||
const Text('Back'),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
if (copying) const CupertinoActivityIndicator(),
|
||||
],
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
detailTitle(run),
|
||||
style: theme.textTheme.navLargeTitleTextStyle,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(runStatusLabel(run)),
|
||||
Text('Run ${run['id']} · Pipeline ${detailPipeline(run)}'),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (detailLoading) const _CupertinoNotice('Refreshing run details…'),
|
||||
if (error != null) _CupertinoNotice(error),
|
||||
if (prompt != null)
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 16, 16, 0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Wrap(
|
||||
alignment: WrapAlignment.spaceBetween,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
spacing: 8,
|
||||
runSpacing: 4,
|
||||
children: [
|
||||
Text(
|
||||
'Original prompt',
|
||||
style: theme.textTheme.navTitleTextStyle,
|
||||
),
|
||||
CupertinoButton(
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: copying ? null : onCopy,
|
||||
child: const Text('Copy prompt'),
|
||||
),
|
||||
],
|
||||
),
|
||||
_CupertinoSelectableText(prompt),
|
||||
if (copyStatus != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Semantics(liveRegion: true, child: Text(copyStatus)),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
_fieldSection('Input', run['input'], 'No input recorded.'),
|
||||
_fieldSection('Output', run['output'], 'No output recorded.'),
|
||||
CupertinoListSection.insetGrouped(
|
||||
header: const Text('Timeline'),
|
||||
children: [
|
||||
if (visits.isEmpty)
|
||||
const CupertinoListTile(title: Text('No visits recorded.'))
|
||||
else
|
||||
for (final visit in visits)
|
||||
CupertinoListTile(
|
||||
leading: const Icon(CupertinoIcons.circle),
|
||||
title: Text(visit.title),
|
||||
subtitle: Text(visit.subtitle),
|
||||
),
|
||||
],
|
||||
),
|
||||
CupertinoListSection.insetGrouped(
|
||||
children: [
|
||||
CupertinoExpansionTile(
|
||||
title: const Text('Metrics'),
|
||||
child: Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (metrics.isEmpty)
|
||||
const Text('No reported usage.')
|
||||
else
|
||||
for (final metric in metrics)
|
||||
CupertinoListTile(
|
||||
title: Text(metric.label),
|
||||
subtitle: Text(metric.value),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _fieldSection(String title, dynamic value, String empty) {
|
||||
final text = detailEmpty(value) ? empty : detailJson(value);
|
||||
return CupertinoListSection.insetGrouped(
|
||||
children: [
|
||||
CupertinoExpansionTile(
|
||||
title: Text(title),
|
||||
child: Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 16),
|
||||
child: _CupertinoSelectableText(text),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
class _CupertinoNotice extends StatelessWidget {
|
||||
const _CupertinoNotice(this.text);
|
||||
final String text;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0),
|
||||
child: Semantics(liveRegion: true, child: Text(text)),
|
||||
);
|
||||
}
|
||||
|
||||
/// A read-only Cupertino text control: plain, selectable text without a
|
||||
/// Material dependency, while keeping native selection and copy affordances.
|
||||
class _CupertinoSelectableText extends StatefulWidget {
|
||||
const _CupertinoSelectableText(this.text);
|
||||
final String text;
|
||||
|
||||
@override
|
||||
State<_CupertinoSelectableText> createState() =>
|
||||
_CupertinoSelectableTextState();
|
||||
}
|
||||
|
||||
class _CupertinoSelectableTextState extends State<_CupertinoSelectableText> {
|
||||
late final TextEditingController _controller = TextEditingController(
|
||||
text: widget.text,
|
||||
);
|
||||
|
||||
@override
|
||||
void didUpdateWidget(_CupertinoSelectableText oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (widget.text != oldWidget.text) _controller.text = widget.text;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => CupertinoTextField(
|
||||
controller: _controller,
|
||||
readOnly: true,
|
||||
maxLines: null,
|
||||
padding: EdgeInsets.zero,
|
||||
decoration: const BoxDecoration(),
|
||||
style: CupertinoTheme.of(context).textTheme.textStyle,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/run_models.dart';
|
||||
import 'run_detail_content.dart';
|
||||
|
||||
/// The runs detail with standard Material controls.
|
||||
Widget buildMaterialRunDetail({
|
||||
required BuildContext context,
|
||||
required JsonMap run,
|
||||
required bool detailLoading,
|
||||
required String? error,
|
||||
required bool copying,
|
||||
required String? copyStatus,
|
||||
required VoidCallback onBack,
|
||||
required VoidCallback onCopy,
|
||||
}) {
|
||||
final theme = Theme.of(context);
|
||||
final prompt = detailPrompt(run);
|
||||
final visits = detailTimeline(run['steps']);
|
||||
final metrics = detailUsageMetrics(run['usage']);
|
||||
return ListView(
|
||||
key: ValueKey<String>('run-detail-${run['id']}'),
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: TextButton.icon(
|
||||
onPressed: onBack,
|
||||
icon: const Icon(Icons.arrow_back),
|
||||
label: const Text('Back to list'),
|
||||
),
|
||||
),
|
||||
Text(detailTitle(run), style: theme.textTheme.headlineSmall),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 4,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
Chip(label: Text(runStatusLabel(run))),
|
||||
Text('Run ${run['id']}'),
|
||||
Text('Pipeline ${detailPipeline(run)}'),
|
||||
],
|
||||
),
|
||||
if (detailLoading) const _Notice('Refreshing run details…'),
|
||||
if (error != null) _Notice(error),
|
||||
if (prompt != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Original prompt',
|
||||
style: theme.textTheme.titleMedium,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: 'Copy prompt',
|
||||
onPressed: copying ? null : onCopy,
|
||||
icon: const Icon(Icons.copy),
|
||||
),
|
||||
],
|
||||
),
|
||||
SelectableText(prompt),
|
||||
if (copyStatus != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Semantics(liveRegion: true, child: Text(copyStatus)),
|
||||
),
|
||||
],
|
||||
_fieldSection('Input', run['input'], 'No input recorded.'),
|
||||
_fieldSection('Output', run['output'], 'No output recorded.'),
|
||||
Text('Timeline', style: theme.textTheme.titleLarge),
|
||||
if (visits.isEmpty)
|
||||
const Text('No visits recorded.')
|
||||
else
|
||||
...visits.map(
|
||||
(visit) => ListTile(
|
||||
leading: const Icon(Icons.circle_outlined),
|
||||
title: Text(visit.title),
|
||||
subtitle: Text(visit.subtitle),
|
||||
),
|
||||
),
|
||||
ExpansionTile(
|
||||
title: const Text('Metrics'),
|
||||
children: [
|
||||
if (metrics.isEmpty)
|
||||
const Padding(
|
||||
padding: EdgeInsets.all(16),
|
||||
child: Text('No reported usage.'),
|
||||
)
|
||||
else
|
||||
...metrics.map(
|
||||
(metric) => ListTile(
|
||||
title: Text(metric.label),
|
||||
subtitle: Text(metric.value),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _fieldSection(String title, dynamic value, String empty) {
|
||||
final text = detailEmpty(value) ? empty : detailJson(value);
|
||||
return ExpansionTile(
|
||||
title: Text(title),
|
||||
children: [
|
||||
Padding(padding: const EdgeInsets.all(16), child: SelectableText(text)),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
class _Notice extends StatelessWidget {
|
||||
const _Notice(this.text);
|
||||
final String text;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Semantics(liveRegion: true, child: Text(text)),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import 'run_detail_content.dart';
|
||||
import 'run_detail_cupertino.dart';
|
||||
import 'run_detail_material.dart';
|
||||
import 'runs_controller.dart';
|
||||
|
||||
class RunDetailView extends StatefulWidget {
|
||||
const RunDetailView({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.onBack,
|
||||
});
|
||||
|
||||
final RunsController controller;
|
||||
final VoidCallback onBack;
|
||||
|
||||
@override
|
||||
State<RunDetailView> createState() => _RunDetailViewState();
|
||||
}
|
||||
|
||||
class _RunDetailViewState extends State<RunDetailView> {
|
||||
bool _copying = false;
|
||||
String? _copyStatus;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => AnimatedBuilder(
|
||||
animation: widget.controller,
|
||||
builder: (context, _) {
|
||||
final cupertino = usesCupertinoHost(context);
|
||||
final run = widget.controller.detail;
|
||||
if (run == null) return _placeholder(context, cupertino: cupertino);
|
||||
final prompt = detailPrompt(run);
|
||||
return cupertino
|
||||
? buildCupertinoRunDetail(
|
||||
context: context,
|
||||
run: run,
|
||||
detailLoading: widget.controller.detailLoading,
|
||||
error: widget.controller.error,
|
||||
copying: _copying,
|
||||
copyStatus: _copyStatus,
|
||||
onBack: widget.onBack,
|
||||
onCopy: () => _copyPrompt(prompt ?? '', cupertino: true),
|
||||
)
|
||||
: buildMaterialRunDetail(
|
||||
context: context,
|
||||
run: run,
|
||||
detailLoading: widget.controller.detailLoading,
|
||||
error: widget.controller.error,
|
||||
copying: _copying,
|
||||
copyStatus: _copyStatus,
|
||||
onBack: widget.onBack,
|
||||
onCopy: () => _copyPrompt(prompt ?? '', cupertino: false),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
Widget _placeholder(BuildContext context, {required bool cupertino}) {
|
||||
final loading = widget.controller.detailLoading;
|
||||
final message = loading
|
||||
? 'Loading run details…'
|
||||
: widget.controller.error ?? 'Run details unavailable.';
|
||||
// Back stays available while the detail is pending as well as after a
|
||||
// failure, so a slow or refused request can never trap the destination.
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (loading) ...[
|
||||
if (cupertino)
|
||||
const CupertinoActivityIndicator()
|
||||
else
|
||||
const CircularProgressIndicator(),
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24),
|
||||
child: Text(message, textAlign: TextAlign.center),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
if (cupertino)
|
||||
CupertinoButton(
|
||||
onPressed: widget.onBack,
|
||||
child: const Text('Back to list'),
|
||||
)
|
||||
else
|
||||
FilledButton(
|
||||
onPressed: widget.onBack,
|
||||
child: const Text('Back to list'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Copies the stored prompt byte-for-byte. A refusal is surfaced, never
|
||||
/// replaced by copying a title or the formatted detail.
|
||||
Future<void> _copyPrompt(String prompt, {required bool cupertino}) async {
|
||||
if (_copying) return;
|
||||
setState(() => _copying = true);
|
||||
String message;
|
||||
try {
|
||||
await Clipboard.setData(ClipboardData(text: prompt));
|
||||
message = 'Prompt copied to clipboard.';
|
||||
} catch (_) {
|
||||
message = 'Could not copy prompt to clipboard.';
|
||||
}
|
||||
if (!mounted) return;
|
||||
final scaffold = cupertino ? null : Scaffold.maybeOf(context);
|
||||
final inline = cupertino || scaffold == null;
|
||||
setState(() {
|
||||
_copying = false;
|
||||
_copyStatus = inline ? message : null;
|
||||
});
|
||||
if (!cupertino && scaffold != null) {
|
||||
ScaffoldMessenger.maybeOf(
|
||||
context,
|
||||
)?.showSnackBar(SnackBar(content: Text(message)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../data/runs_repository.dart';
|
||||
import '../domain/run_events.dart';
|
||||
import '../domain/run_models.dart';
|
||||
|
||||
class RunsController extends ChangeNotifier {
|
||||
RunsController(this.repository);
|
||||
final RunsRepository repository;
|
||||
StreamSubscription<JsonMap>? _subscription;
|
||||
List<JsonMap> runs = [];
|
||||
JsonMap? detail, usage;
|
||||
String? error;
|
||||
bool loading = false, detailLoading = false;
|
||||
String query = '',
|
||||
sort = 'newest_first',
|
||||
scheduled = 'any',
|
||||
timeRange = 'any_time';
|
||||
final Set<String> statuses = {};
|
||||
int? pipelineId;
|
||||
// List and detail requests advance independent generations so neither can
|
||||
// make the other's in-flight reply stale.
|
||||
int _listGeneration = 0, _detailGeneration = 0;
|
||||
num? _selectedId;
|
||||
Timer? _detailRefresh;
|
||||
bool _listResyncing = false, _listAgain = false;
|
||||
bool _detailRefreshing = false, _detailAgain = false;
|
||||
bool _disposed = false;
|
||||
|
||||
num? get selectedRunId => _selectedId;
|
||||
|
||||
void listen(Stream<JsonMap> frames) {
|
||||
_subscription?.cancel();
|
||||
_subscription = frames
|
||||
.where((f) => f['type'] == 'run_event')
|
||||
.listen(_event);
|
||||
}
|
||||
|
||||
Future<void> load([int? initialId]) async {
|
||||
final token = ++_listGeneration;
|
||||
_listAgain = false;
|
||||
loading = true;
|
||||
error = null;
|
||||
notifyListeners();
|
||||
try {
|
||||
final result = await repository.listRuns();
|
||||
if (!_listOwned(token)) return;
|
||||
runs = result.runs;
|
||||
usage = result.usage;
|
||||
} catch (e) {
|
||||
if (!_listOwned(token)) return;
|
||||
error = '$e';
|
||||
}
|
||||
if (!_listOwned(token)) return;
|
||||
loading = false;
|
||||
notifyListeners();
|
||||
// A run event may have arrived while the list request was in flight; one
|
||||
// resync after it keeps the pushed state without dropping the event.
|
||||
_resyncAgainIfNeeded();
|
||||
if (initialId != null) await select(initialId);
|
||||
}
|
||||
|
||||
/// Re-reads the list and the open detail after the socket was replaced.
|
||||
///
|
||||
/// The selection is kept, so a reconnect refreshes in place instead of
|
||||
/// discarding the detail the operator had open.
|
||||
Future<void> resync() async {
|
||||
final selected = _selectedId;
|
||||
await load();
|
||||
if (selected != null && _selectedId == selected) await select(selected);
|
||||
}
|
||||
|
||||
Future<void> select(num id) async {
|
||||
final token = ++_detailGeneration;
|
||||
_cancelDetailRefresh();
|
||||
// Keep a same-run detail while it refreshes, but never present the previous
|
||||
// run as if it were the newly selected one.
|
||||
if (_selectedId != id) detail = null;
|
||||
_selectedId = id;
|
||||
detailLoading = true;
|
||||
error = null;
|
||||
notifyListeners();
|
||||
try {
|
||||
final value = await repository.getRun(id);
|
||||
if (!_detailOwned(id, token)) return;
|
||||
detail = value;
|
||||
} catch (e) {
|
||||
if (!_detailOwned(id, token)) return;
|
||||
error = '$e';
|
||||
}
|
||||
if (!_detailOwned(id, token)) return;
|
||||
detailLoading = false;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void back() {
|
||||
++_detailGeneration;
|
||||
_cancelDetailRefresh();
|
||||
_selectedId = null;
|
||||
detail = null;
|
||||
detailLoading = false;
|
||||
error = null;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void setQuery(String value) {
|
||||
query = value;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void setStatus(String? value) {
|
||||
if (value == null) {
|
||||
statuses.clear();
|
||||
} else if (!statuses.add(value)) {
|
||||
statuses.remove(value);
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void setPipeline(int? value) {
|
||||
pipelineId = value;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void setScheduled(String value) {
|
||||
scheduled = value;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void setSort(String value) {
|
||||
sort = value;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _event(JsonMap frame) {
|
||||
final folded = foldRunEvent(runs, frame);
|
||||
runs = folded.runs;
|
||||
if (detail?['id'] == frame['run_id']) {
|
||||
detail = foldRunEventDetail(detail, frame);
|
||||
}
|
||||
if (frame['run_id'] == null || folded.needsResync) {
|
||||
_scheduleListRefresh();
|
||||
}
|
||||
final selected = _selectedId;
|
||||
if (selected != null &&
|
||||
frame['run_id'] == selected &&
|
||||
(folded.needsResync || runDetailNeedsFullSync(frame))) {
|
||||
_scheduleDetailRefresh(selected);
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _scheduleListRefresh() {
|
||||
if (_disposed) return;
|
||||
if (_listResyncing || loading) {
|
||||
_listAgain = true;
|
||||
return;
|
||||
}
|
||||
_listResyncing = true;
|
||||
loading = true;
|
||||
notifyListeners();
|
||||
unawaited(_reloadList());
|
||||
}
|
||||
|
||||
Future<void> _reloadList() async {
|
||||
final token = ++_listGeneration;
|
||||
_listAgain = false;
|
||||
try {
|
||||
final result = await repository.listRuns();
|
||||
if (!_listOwned(token)) return;
|
||||
runs = result.runs;
|
||||
usage = result.usage;
|
||||
error = null;
|
||||
} catch (e) {
|
||||
if (_listOwned(token)) error = '$e';
|
||||
} finally {
|
||||
_listResyncing = false;
|
||||
if (_listOwned(token)) {
|
||||
loading = false;
|
||||
notifyListeners();
|
||||
}
|
||||
// A followup may have been requested while this (possibly superseded)
|
||||
// request was still the one marked in flight.
|
||||
_resyncAgainIfNeeded();
|
||||
}
|
||||
}
|
||||
|
||||
void _resyncAgainIfNeeded() {
|
||||
if (_disposed || !_listAgain) return;
|
||||
_listAgain = false;
|
||||
_scheduleListRefresh();
|
||||
}
|
||||
|
||||
void _scheduleDetailRefresh(num id) {
|
||||
if (_disposed || _selectedId != id) return;
|
||||
if (_detailRefreshing) {
|
||||
_detailAgain = true;
|
||||
return;
|
||||
}
|
||||
_detailRefresh?.cancel();
|
||||
_detailRefresh = Timer(
|
||||
const Duration(milliseconds: 150),
|
||||
() => _refreshDetail(id, _detailGeneration),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _refreshDetail(num id, int token) async {
|
||||
_detailRefresh = null;
|
||||
if (!_detailOwned(id, token)) return;
|
||||
_detailRefreshing = true;
|
||||
try {
|
||||
final value = await repository.getRun(id);
|
||||
if (_detailOwned(id, token)) {
|
||||
detail = value;
|
||||
notifyListeners();
|
||||
}
|
||||
} catch (e) {
|
||||
if (_detailOwned(id, token)) {
|
||||
error = '$e';
|
||||
notifyListeners();
|
||||
}
|
||||
} finally {
|
||||
if (_detailOwned(id, token)) {
|
||||
_detailRefreshing = false;
|
||||
if (_detailAgain) {
|
||||
_detailAgain = false;
|
||||
unawaited(_refreshDetail(id, token));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _cancelDetailRefresh() {
|
||||
_detailRefresh?.cancel();
|
||||
_detailRefresh = null;
|
||||
_detailAgain = false;
|
||||
_detailRefreshing = false;
|
||||
}
|
||||
|
||||
bool _listOwned(int token) => !_disposed && token == _listGeneration;
|
||||
|
||||
bool _detailOwned(num id, int token) =>
|
||||
!_disposed && token == _detailGeneration && _selectedId == id;
|
||||
|
||||
List<JsonMap> get visibleRuns => sortRuns(
|
||||
filterRuns(
|
||||
runs,
|
||||
statuses: statuses,
|
||||
pipelineId: pipelineId,
|
||||
scheduled: scheduled,
|
||||
timeRange: timeRange,
|
||||
)
|
||||
.where(
|
||||
(r) => '${r['title'] ?? r['name'] ?? ''}'.toLowerCase().contains(
|
||||
query.toLowerCase(),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
sort: sort,
|
||||
);
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
_subscription?.cancel();
|
||||
_detailRefresh?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import '../domain/run_models.dart';
|
||||
import 'runs_controller.dart';
|
||||
|
||||
class RunsList extends StatelessWidget {
|
||||
const RunsList({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.onSelected,
|
||||
});
|
||||
|
||||
final RunsController controller;
|
||||
final ValueChanged<num> onSelected;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (controller.loading && controller.runs.isEmpty) {
|
||||
return Center(
|
||||
child: usesCupertinoHost(context)
|
||||
? const CupertinoActivityIndicator()
|
||||
: const CircularProgressIndicator(),
|
||||
);
|
||||
}
|
||||
if (controller.error != null && controller.runs.isEmpty) {
|
||||
return _emptyError(context);
|
||||
}
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (controller.usage != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: Text('Usage: ${controller.usage}'),
|
||||
),
|
||||
if (controller.error != null) _inlineError(context),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: usesCupertinoHost(context)
|
||||
? CupertinoSearchTextField(
|
||||
placeholder: 'Filter runs',
|
||||
onChanged: controller.setQuery,
|
||||
)
|
||||
: TextField(
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Filter runs',
|
||||
prefixIcon: Icon(Icons.search),
|
||||
),
|
||||
onChanged: controller.setQuery,
|
||||
),
|
||||
),
|
||||
_selectors(context),
|
||||
Expanded(
|
||||
child: controller.visibleRuns.isEmpty
|
||||
? const Center(child: Text('No runs found.'))
|
||||
: ListView.builder(
|
||||
itemCount: controller.visibleRuns.length,
|
||||
itemBuilder: (context, index) =>
|
||||
_runTile(context, controller.visibleRuns[index]),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _emptyError(BuildContext context) => Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(controller.error!),
|
||||
const SizedBox(height: 8),
|
||||
usesCupertinoHost(context)
|
||||
? CupertinoButton(
|
||||
onPressed: controller.load,
|
||||
child: const Text('Retry'),
|
||||
)
|
||||
: FilledButton(
|
||||
onPressed: controller.load,
|
||||
child: const Text('Retry'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
Widget _inlineError(BuildContext context) => Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(child: Text(controller.error!)),
|
||||
if (usesCupertinoHost(context))
|
||||
CupertinoButton(
|
||||
onPressed: controller.load,
|
||||
child: const Text('Retry'),
|
||||
)
|
||||
else
|
||||
TextButton(onPressed: controller.load, child: const Text('Retry')),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
Widget _selectors(BuildContext context) {
|
||||
if (usesCupertinoHost(context)) {
|
||||
return Wrap(
|
||||
spacing: 8,
|
||||
children: [
|
||||
CupertinoButton(
|
||||
onPressed: () => _choose(
|
||||
context,
|
||||
'Sort runs',
|
||||
_sorts,
|
||||
controller.sort,
|
||||
controller.setSort,
|
||||
),
|
||||
child: Text('Sort: ${_sortLabel(controller.sort)}'),
|
||||
),
|
||||
CupertinoButton(
|
||||
onPressed: () => _choose(
|
||||
context,
|
||||
'Schedule',
|
||||
_schedules,
|
||||
controller.scheduled,
|
||||
controller.setScheduled,
|
||||
),
|
||||
child: Text('Schedule: ${_scheduleLabel(controller.scheduled)}'),
|
||||
),
|
||||
for (final status in _statuses)
|
||||
CupertinoButton(
|
||||
onPressed: () => controller.setStatus(status),
|
||||
child: Text(
|
||||
'${controller.statuses.contains(status) ? '✓ ' : ''}${_title(status)}',
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return Wrap(
|
||||
spacing: 8,
|
||||
children: [
|
||||
DropdownButton<String>(
|
||||
value: controller.sort,
|
||||
isExpanded: true,
|
||||
onChanged: (v) {
|
||||
if (v != null) controller.setSort(v);
|
||||
},
|
||||
items: _sorts
|
||||
.map((e) => DropdownMenuItem(value: e.$1, child: Text(e.$2)))
|
||||
.toList(),
|
||||
),
|
||||
DropdownButton<String>(
|
||||
value: controller.scheduled,
|
||||
isExpanded: true,
|
||||
onChanged: (v) {
|
||||
if (v != null) controller.setScheduled(v);
|
||||
},
|
||||
items: _schedules
|
||||
.map((e) => DropdownMenuItem(value: e.$1, child: Text(e.$2)))
|
||||
.toList(),
|
||||
),
|
||||
for (final status in _statuses)
|
||||
FilterChip(
|
||||
label: Text(_title(status)),
|
||||
selected: controller.statuses.contains(status),
|
||||
onSelected: (_) => controller.setStatus(status),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _choose(
|
||||
BuildContext context,
|
||||
String title,
|
||||
List<(String, String)> values,
|
||||
String selected,
|
||||
ValueChanged<String> onSelected,
|
||||
) async {
|
||||
final value = await showCupertinoModalPopup<String>(
|
||||
context: context,
|
||||
builder: (context) => CupertinoActionSheet(
|
||||
title: Text(title),
|
||||
actions: [
|
||||
for (final option in values)
|
||||
CupertinoActionSheetAction(
|
||||
onPressed: () => Navigator.pop(context, option.$1),
|
||||
child: Text(option.$2),
|
||||
),
|
||||
],
|
||||
cancelButton: CupertinoActionSheetAction(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (value != null && value != selected) onSelected(value);
|
||||
}
|
||||
|
||||
Widget _runTile(BuildContext context, JsonMap run) {
|
||||
final identity = runIdentity(run['title'], run['name']);
|
||||
final id = run['id'];
|
||||
final title = identity.label.isEmpty ? 'Run $id' : identity.label;
|
||||
final subtitle =
|
||||
'${run['name'] ?? 'Pipeline unavailable'} · ${run['created_at'] ?? 'Time unavailable'}${run['scheduled'] == true ? ' · Scheduled' : ''}';
|
||||
if (usesCupertinoHost(context)) {
|
||||
return CupertinoListTile(
|
||||
title: Text(title),
|
||||
subtitle: Text(subtitle),
|
||||
additionalInfo: Text(runStatusLabel(run)),
|
||||
trailing: const CupertinoListTileChevron(),
|
||||
onTap: id is num ? () => onSelected(id) : null,
|
||||
);
|
||||
}
|
||||
return ListTile(
|
||||
title: Text(title),
|
||||
subtitle: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [Text(subtitle), Text(runStatusLabel(run))],
|
||||
),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: id is num ? () => onSelected(id) : null,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const _sorts = [
|
||||
('newest_first', 'Newest'),
|
||||
('oldest_first', 'Oldest'),
|
||||
('pipeline_name', 'Pipeline'),
|
||||
('status', 'Status'),
|
||||
];
|
||||
const _schedules = [
|
||||
('any', 'Any schedule'),
|
||||
('scheduled', 'Scheduled'),
|
||||
('unscheduled', 'Unscheduled'),
|
||||
];
|
||||
const _statuses = ['queued', 'running', 'waiting', 'succeeded', 'failed'];
|
||||
String _sortLabel(String value) =>
|
||||
_sorts.firstWhere((e) => e.$1 == value, orElse: () => _sorts.first).$2;
|
||||
String _scheduleLabel(String value) => _schedules
|
||||
.firstWhere((e) => e.$1 == value, orElse: () => _schedules.first)
|
||||
.$2;
|
||||
String _title(String value) => '${value[0].toUpperCase()}${value.substring(1)}';
|
||||
@@ -0,0 +1,116 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/saved_schedule.dart';
|
||||
import '../domain/schedule_json.dart';
|
||||
|
||||
/// Client-side protocol failure. Server refusals and transport errors are not
|
||||
/// wrapped: [ApiGateway] already surfaces their exact text.
|
||||
class SchedulesRepositoryException implements Exception {
|
||||
const SchedulesRepositoryException(this.message);
|
||||
final String message;
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
/// The saved-schedule commands of the current web client.
|
||||
///
|
||||
/// These are run configurations, not pipeline definitions: this repository
|
||||
/// never submits, validates or publishes a workflow, and it never starts or
|
||||
/// polls a run. Timer execution belongs to the server.
|
||||
class SchedulesRepository {
|
||||
SchedulesRepository(this._gateway);
|
||||
|
||||
final ApiGateway _gateway;
|
||||
|
||||
/// Lists saved schedules, optionally for one pipeline.
|
||||
///
|
||||
/// An explicit empty reply is a valid empty list. A reply without the
|
||||
/// `schedules` type is not: that is an older/unsupported server and must be
|
||||
/// reported rather than shown as "no schedules".
|
||||
Future<List<SavedSchedule>> listSchedules({int? pipelineId}) async {
|
||||
final fields = <String, dynamic>{};
|
||||
if (pipelineId != null) {
|
||||
if (!_isPositiveId(pipelineId)) {
|
||||
throw const SchedulesRepositoryException(
|
||||
'A positive pipeline ID is required.',
|
||||
);
|
||||
}
|
||||
fields['pipeline_id'] = pipelineId;
|
||||
}
|
||||
final reply = await _gateway.call('list_schedules', fields);
|
||||
final schedules = reply['schedules'];
|
||||
if (reply['type'] != 'schedules' ||
|
||||
(schedules != null && schedules is! List)) {
|
||||
throw const SchedulesRepositoryException(
|
||||
'The server returned no schedules response.',
|
||||
);
|
||||
}
|
||||
if (schedules == null) return const [];
|
||||
return [
|
||||
for (final item in schedules as List)
|
||||
if (item is Map)
|
||||
SavedSchedule(Map<String, dynamic>.from(item))
|
||||
else
|
||||
throw const SchedulesRepositoryException(
|
||||
'The server returned an invalid schedule record.',
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/// Creates or updates one saved schedule.
|
||||
///
|
||||
/// Creation sends the web client's sentinel record (`id` 0, no revision) and
|
||||
/// may carry a stable request key so a lost reply is retried instead of
|
||||
/// creating a duplicate. Updating sends the record read from the server,
|
||||
/// whose `revision` is the compare-and-swap token; the key is omitted, as in
|
||||
/// the web client. A stale revision is refused by the server and propagated
|
||||
/// unchanged, never overwritten locally.
|
||||
Future<SavedSchedule> saveSchedule(
|
||||
JsonMap schedule, {
|
||||
String? requestKey,
|
||||
}) async {
|
||||
if (requestKey != null && requestKey.length > 128) {
|
||||
throw const SchedulesRepositoryException(
|
||||
'Schedule request keys must be strings of at most 128 characters.',
|
||||
);
|
||||
}
|
||||
final fields = <String, dynamic>{'schedule': cloneJsonMap(schedule)};
|
||||
if (requestKey != null && requestKey.isNotEmpty) {
|
||||
fields['request_key'] = requestKey;
|
||||
}
|
||||
final reply = await _gateway.call('save_schedule', fields);
|
||||
final saved = reply['schedule'];
|
||||
if (saved is! Map) {
|
||||
throw const SchedulesRepositoryException(
|
||||
'The server returned no saved schedule.',
|
||||
);
|
||||
}
|
||||
return SavedSchedule(Map<String, dynamic>.from(saved));
|
||||
}
|
||||
|
||||
/// Deletes exactly the revision the caller read.
|
||||
///
|
||||
/// Both identity and revision are required before any request is sent; a
|
||||
/// confirmation for a different schedule is treated as a failed delete.
|
||||
Future<void> deleteSchedule(int id, int revision) async {
|
||||
if (!_isPositiveId(id) || !_isPositiveId(revision)) {
|
||||
throw const SchedulesRepositoryException(
|
||||
'An exact schedule ID and revision are required.',
|
||||
);
|
||||
}
|
||||
final reply = await _gateway.call('delete_schedule', {
|
||||
'schedule_id': id,
|
||||
'expected_revision': revision,
|
||||
});
|
||||
if (reply['type'] != 'schedule_deleted' || reply['schedule_id'] != id) {
|
||||
throw const SchedulesRepositoryException(
|
||||
'The server did not confirm deletion of this schedule.',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// JSON/JavaScript integers are safe up to 2^53-1; the web client checks
|
||||
/// `Number.isSafeInteger` before sending an identity.
|
||||
const _maxSafeInteger = 9007199254740991;
|
||||
|
||||
bool _isPositiveId(int value) => value > 0 && value <= _maxSafeInteger;
|
||||
@@ -0,0 +1,87 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'schedule_json.dart';
|
||||
import 'schedule_rule.dart';
|
||||
|
||||
/// One saved run configuration from `list_schedules` or `save_schedule`.
|
||||
///
|
||||
/// A saved schedule is a complete run request pinned to one pipeline version.
|
||||
/// It is deliberately not a pipeline definition: nothing here is published,
|
||||
/// validated as a graph or treated as the pipeline's current version.
|
||||
///
|
||||
/// [raw] keeps the exact server record, including fields this client does not
|
||||
/// know yet. Typed getters are views; they never rewrite [raw].
|
||||
class SavedSchedule {
|
||||
SavedSchedule(JsonMap raw) : raw = cloneJsonMap(raw);
|
||||
|
||||
final JsonMap raw;
|
||||
|
||||
/// Server identity; null when an older reply omits it. Never defaulted to 0,
|
||||
/// because 0 is the create sentinel rather than a saved identity.
|
||||
int? get id => _integer(raw['id']);
|
||||
|
||||
/// Compare-and-swap token. Updates reuse it and deletes send it as
|
||||
/// `expected_revision`; this client never invents or increments it.
|
||||
int? get revision => _integer(raw['revision']);
|
||||
|
||||
int? get pipelineId => _integer(raw['pipeline_id']);
|
||||
int? get version => _integer(raw['version']);
|
||||
String get name => _text(raw['name']);
|
||||
bool get enabled => raw['enabled'] == true;
|
||||
|
||||
JsonMap get input => _map(raw['input']);
|
||||
String get prompt => _text(input['prompt']);
|
||||
String get workspace => _text(raw['workspace']);
|
||||
ScheduleRule get rule => ScheduleRule(_map(raw['rule']));
|
||||
|
||||
List<String> get writePaths => _texts(raw['write_paths']);
|
||||
bool get allowTools => raw['allow_tools'] == true;
|
||||
String get model => _text(raw['model']);
|
||||
Map<String, String> get stageModels => {
|
||||
for (final entry in _map(raw['stage_models']).entries)
|
||||
if (entry.value is String) entry.key: entry.value as String,
|
||||
};
|
||||
String get notifyMode => _text(raw['notify_mode']);
|
||||
String get title => _text(raw['title']);
|
||||
String get outputFormat => _text(raw['output_format']);
|
||||
|
||||
String get nextDue => _text(raw['next_due']);
|
||||
String get createdAt => _text(raw['created_at']);
|
||||
String get updatedAt => _text(raw['updated_at']);
|
||||
|
||||
/// The record to pass to `save_schedule`, deep-copied so callers cannot
|
||||
/// mutate this snapshot by aliasing.
|
||||
JsonMap toJson() => cloneJsonMap(raw);
|
||||
|
||||
/// Pause/enable copy. Identity, revision and every unknown field are kept so
|
||||
/// the update still targets the revision this record was read at.
|
||||
SavedSchedule withEnabled(bool value) {
|
||||
final copy = toJson();
|
||||
copy['enabled'] = value;
|
||||
return SavedSchedule(copy);
|
||||
}
|
||||
}
|
||||
|
||||
int? _integer(dynamic value) {
|
||||
if (value is int) return value;
|
||||
if (value is num && value.isFinite && value == value.truncateToDouble()) {
|
||||
return value.toInt();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
String _text(dynamic value) => value is String ? value : '';
|
||||
|
||||
JsonMap _map(dynamic value) {
|
||||
if (value is! Map) return <String, dynamic>{};
|
||||
return <String, dynamic>{
|
||||
for (final entry in value.entries)
|
||||
'${entry.key}': cloneJsonValue(entry.value),
|
||||
};
|
||||
}
|
||||
|
||||
List<String> _texts(dynamic value) => value is List
|
||||
? [
|
||||
for (final item in value)
|
||||
if (item is String) item,
|
||||
]
|
||||
: const [];
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user