Merge branch 'main' into flutter/start-pipeline
This commit is contained in:
+4
-4
@@ -38,7 +38,7 @@ or scratch servers only, never real operator sessions/runs/workflows.
|
||||
| Changes/diffs | Preview via run detail | settled-run aggregate gate, recorded file/diff/close/back verified in the real app; per-visit capture entry and paging remain |
|
||||
| Artifact groups | Preview: run detail → recorded groups, selection facts, external Open/Copy link | present the visit's turn documents (input.md/memory.md/output.md, session.html) as gallery entries; in-app viewer next |
|
||||
| Artifact preview | Preview: image + markdown/text in-app through the chat renderer, paging, honest unsupported/external/HTTP states | video and HTML remain external-only |
|
||||
| Artifact actions | Source safe URL resolution | separate external-open/copy/download; SHARE REAL NAMED MIME FILES, not links; slow activation/cancel/errors |
|
||||
| Artifact actions | Preview: external Open, Copy link, download and native share carry the recorded name/MIME bytes; progress, cancel, HTTP failure and unsupported-share states | OS share/download on Android/iOS remain unverified until the final build |
|
||||
| Session audit/export repair facts | Missing UI | session.html read-only open, partial/missing/skipped/repair choices without fabricating complete evidence |
|
||||
| Chat session management | Preview list + open session; actions from the list | directory groups/search, shared rename/star/close/reopen/create, local hide/undo/seen state, create dialog in the shell |
|
||||
| Chat history/live transport | Preview: `/chat` list and `/chat/:id` history, paging, live failure notice | run-detail-style reconnect verification in the real app, then composer integration |
|
||||
@@ -46,13 +46,13 @@ or scratch servers only, never real operator sessions/runs/workflows.
|
||||
| Chat activity/reasoning/tools | Source raw fields only | one activity line, compaction, native reasoning/tools overlays, lifecycle/input/output/error/duration/edit diff |
|
||||
| Chat composer | Preview: field, Send/Stop, persisted draft, queued/refusal lines; one verified send in the real app flow | attachments, paste and slash palette remain |
|
||||
| Chat attachments | Source request facade | picker/paste, latest1MiB total wire bound, base64 files, removable named chips, exact history reconciliation |
|
||||
| Chat permissions/questions | Source request facade | native approval/risk cards and form option/free-text answers; pending/resolved/stale/error states |
|
||||
| Chat permissions/questions | Source: native approval/risk and question cards in the conversation view | authenticated smoke with a real pending approval/question; live multi-client resolution; no production decision sent |
|
||||
| Chat model/Info/background tasks | Source request facade | current-model selection, numeric Info modal (unknown !=0), bounded running shell pages |
|
||||
| Chat commands/notices/scroll | Missing | slash palette/actions, unknown-command send-as-message, dismissible local notices, saved scroll/follow intent |
|
||||
| Saved schedule list | Source | pipeline entry and route registration, exact timer provenance vocabulary |
|
||||
| Schedule editor | Source draft74+CAS guard; active form78 | save/pause/delete wiring, conflict keeps draft, Schedule this run seed |
|
||||
| Schedule editor | Preview: pipeline Summary section creates/edits/pauses/deletes with the lossless draft and revision guard; conflict keeps the draft and shows the server words | Schedule-this-run seeding, schedules list entry/route |
|
||||
| Search | Preview: shell entry, /search route, focused field, restore on close | result target routing for pipeline/version/field/visit/artifact hits |
|
||||
| Needs you | Source model + native bell/sheet; wiring90 | in-app count from list rows, dismiss persistence and live transitions |
|
||||
| Needs you | Preview: runs-list bell/count from the same list rows, native sheet, open/dismiss/clear persistence, live fold and reconnect reseed | notification permission/transition notices, authenticated preview smoke |
|
||||
| Notifications | Missing | explicit permission/rationale, secure/unsupported/denied states, transition-only dedupe, background question notices |
|
||||
| Mobile replacement build | Scaffold only | Android build at end; all source portable to iOS, isolated IDs; device/OS behavior clearly separate |
|
||||
|
||||
|
||||
+64
-2
@@ -49,7 +49,8 @@ All work under app/. Existing applications remain running and unchanged.
|
||||
| Stage definition | run77 retained/d88213d | review result-validation failure; manager verified retained slice and drove both-host probe (5 captures each) | merged main; ancestry verified | graph hook85 next |
|
||||
| Attention model | run82 /38f8576c + manager224f8ee |13min;44 tests; manager namespaced dismissals to this client and re-ran tests | merged main; ancestry verified | bell/sheet UI84 next |
|
||||
| Pipeline graph | Graph tab + stage pane wiring | run85 retained/0176720 | Code deadline recovery;62 pipelines tests + both-host probe; bounded measured canvas opens pinned definition | merged main; ancestry verified | published8096 |
|
||||
| Needs you UI | Bell + native sheet | run84 retained/ee93d4f | review visit limit;72 tests; snapshot clear/dismiss both hosts | merged main; ancestry verified | Runs wiring90 |
|
||||
| Needs you UI | Bell + native sheet | run84 retained/ee93d4f | review visit limit;72 tests; snapshot clear/dismiss both hosts | merged main; ancestry verified | published8096 |
|
||||
| Needs you wiring | Live bell over the Runs list | run90 /a309d9d5 (rebased) | evidence bug blocked the run; manager rebased onto main, resolved PARITY, ran239 attention/runs tests; probe 4 captures both hosts at 320/2x | merged main; ancestry verified | notification permission/transitions |
|
||||
| Chat screen | Live Chat destination + read-only history | run79 retained/86a9b4a | deadline recovery;110 focused tests + both-host probes; real app probe verifies /chat/ses route and stored turn | merged main; ancestry verified | published8096 |
|
||||
| Retry/restart | Retry and restart in actual detail | run80 /2de1c90 base |50min; focused suites; accepted-run navigation verified | merged main; ancestry verified | published8096 |
|
||||
| Artifact gallery | Recorded visit groups in run detail | run81 retained/df6524c | Code deadline recovery;29 tests +16 fixture captures; real app probe verifies list/selection | merged main; ancestry verified | published8096 |
|
||||
@@ -62,7 +63,9 @@ All work under app/. Existing applications remain running and unchanged.
|
||||
| Search entry | Register Search in the shell | run88 retained/fd380ef | server storage bug blocked the run; manager ran45 tests + real-app probe; route restores prior screen | merged main; ancestry verified | published8096 |
|
||||
| Run graph | Run-mode executed-route canvas | run89 retained/5b833e7 | server storage bug blocked the run; manager ran43 graph tests; recorded visits only, legend | merged main; ancestry verified | published8096 |
|
||||
| Run graph tab | Graph tab + recorded-stage selection | run92 retained/d74e5c5 | evidence bug blocked the run; manager ran147 runs tests + both-host probe (7 checks, graph/legend/selection/missing wording) | merged main; ancestry verified | preview republish pending |
|
||||
| Schedule form | Native schedule draft editor | run78 /flutter/schedule-form | binds74, no save engine | running | pending |
|
||||
| Schedule form | Native schedule draft editor | run78 /flutter/schedule-form | binds74, no save engine | merged main; ancestry verified | published8096 |
|
||||
| Artifact files | Download/share named bytes | run99 retained/841dd50 | Code deadline recovery; manager ran123 artifacts tests + analyze + 27-check/32-capture probe; exact name, MIME and byte length both hosts | merged main; ancestry verified | preview republish pending |
|
||||
| Pipeline schedules | Saved schedules in pipeline Summary | run93 /ea2179cd | evidence bug blocked the run after commit; manager ran141 schedules/pipelines tests + 15-check/13-capture both-host probe; create/edit/pause/delete with CAS | merged main; ancestry verified | preview republish pending |
|
||||
|
||||
## Next ready work
|
||||
### Current execution target (user correction)
|
||||
@@ -471,3 +474,62 @@ resuming or retrying; preserve partial work. On success inspect actual diff and
|
||||
checks, integrate, verify ancestry, then launch the next ready item. Do not
|
||||
rerun completed work just because session export or landing failed. Keep source,
|
||||
tests, landing and preview states separate. No production cutover in this phase.
|
||||
## Remaining queue after the 95-101 wave
|
||||
Autonomous target: finish every row in `PARITY.md` except the mobile build, which
|
||||
stays last by agreement. Each item is one reviewed slice with focused tests and a
|
||||
both-host browser probe where it is visible.
|
||||
|
||||
In flight: 95 recorded visit pane; 96 chat permission/question cards; 97 start a
|
||||
pipeline; 98 chat list create/rename/star/close; 99 artifact download/share as
|
||||
named files; 100 notification capability + transition dedupe; 101 graph
|
||||
pan/zoom/expanded view.
|
||||
|
||||
Then, in dependency order:
|
||||
1. Manager wiring: notification permission tile into Settings and transition
|
||||
notifications from the Runs attention controller; graph expanded view opened
|
||||
from the pipeline Graph tab.
|
||||
2. Search result target routing (pipeline/version/field/visit/artifact) in
|
||||
`application/search_destination.dart` plus the minimum public selection APIs in
|
||||
the owning features.
|
||||
3. Chat attachments: picker + paste, 1 MiB bounded envelope, named removable
|
||||
chips, history reconciliation.
|
||||
4. Chat activity/reasoning/tools overlays with lifecycle, input/output, error,
|
||||
duration and edit diff.
|
||||
5. Chat model selection, numeric Info (unknown != 0) and bounded background-task
|
||||
pages.
|
||||
6. Chat slash command palette, unknown-command send-as-message, dismissible local
|
||||
notices, saved scroll/follow.
|
||||
7. Run summary fields and exact empty/unknown wording; changes per-visit capture
|
||||
entry and paging; session audit/export repair facts.
|
||||
8. Artifact turn documents in the gallery (input/memory/output/session.html).
|
||||
9. Pipeline list summary metadata/miniatures and pinned detail URLs; schedules
|
||||
list entry/route, timer provenance and schedule-this-run seeding.
|
||||
10. Deep links: pipeline/version/stage/template/chat URLs and action/visit
|
||||
queries; transport foreground recovery, persisted endpoint boot, protocol
|
||||
warning, complete refresh semantics.
|
||||
11. Templates link from a run detail; authenticated preview smoke notes.
|
||||
12. Android testing build, iOS portability audit, device verification.
|
||||
|
||||
Standing rules: keep the preview published with a rollback after each landing;
|
||||
never claim authenticated production mutations, OS sharing/notifications on
|
||||
mobile or device behaviour from web fixture evidence; keep mobile labelled
|
||||
unverified until the final build.
|
||||
## Lane contract (corrected after 30-60 minute overruns)
|
||||
|
||||
The oversized slice was mine, not the model's: prompts bundled 5-8 behaviours plus
|
||||
a two-host browser probe and a note file. A probe means two web builds plus
|
||||
Chrome/OCR, so Code alone exceeded the 30-minute stage budget and Review retries
|
||||
pushed runs past an hour.
|
||||
|
||||
Every new lane now gets ONE behaviour:
|
||||
- At most 2 source files (+1) and 1 focused test file.
|
||||
- No `flutter build`, no browser probe, no note file, no `flutter analyze` - the
|
||||
manager runs the probe once per area, writes the note and runs the integrated
|
||||
checks.
|
||||
- Exact web wording and request shape named in the prompt; native controls and
|
||||
theme roles only; no fixed sizes or palettes.
|
||||
- Target: Code under 10 minutes, run under 20.
|
||||
|
||||
Manager per wave: merge each branch, run the focused suite, one area probe, then
|
||||
the full suite/analyze and one preview publish. Probes and full checks are
|
||||
batched, not repeated per lane.
|
||||
|
||||
@@ -247,3 +247,14 @@ class PipelinesClient implements ApiGateway {
|
||||
await _states.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// The configured server origin of [gateway], or blank when the gateway does
|
||||
/// not expose one (a feature fixture).
|
||||
///
|
||||
/// Relative artifact and session urls resolve only against this origin; an
|
||||
/// absolute recorded http(s) url still resolves without it. The cast lives here
|
||||
/// so callers never repeat it.
|
||||
String configuredGatewayEndpoint(ApiGateway gateway) {
|
||||
final client = gateway is PipelinesClient ? gateway : null;
|
||||
return client?.endpoint?.toString() ?? '';
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import '../domain/artifact_record.dart';
|
||||
|
||||
/// A recorded artifact's exact bytes, named and typed as the host must save or
|
||||
/// share them.
|
||||
///
|
||||
/// The name is the recorded file name's basename, never a url or a directory
|
||||
/// path. The MIME type is the recorded media type without parameters. Only when
|
||||
/// the recorded value is missing or malformed does the fallback apply: the
|
||||
/// server url's basename, then `artifact`, and `application/octet-stream`.
|
||||
class ArtifactFile {
|
||||
const ArtifactFile({
|
||||
required this.name,
|
||||
required this.mimeType,
|
||||
required this.bytes,
|
||||
});
|
||||
|
||||
final String name;
|
||||
final String mimeType;
|
||||
final Uint8List bytes;
|
||||
|
||||
int get byteLength => bytes.length;
|
||||
}
|
||||
|
||||
const String artifactFileFallbackName = 'artifact';
|
||||
const String artifactFileFallbackMimeType = 'application/octet-stream';
|
||||
|
||||
/// Names and types one recorded artifact's fetched bytes for a file transfer.
|
||||
ArtifactFile artifactFileFor({
|
||||
required ArtifactRecord artifact,
|
||||
required Uri url,
|
||||
required Uint8List bytes,
|
||||
}) => ArtifactFile(
|
||||
name: artifactFileName(artifact, url),
|
||||
mimeType: artifactFileMimeType(artifact),
|
||||
bytes: bytes,
|
||||
);
|
||||
|
||||
/// The recorded name without any `public/` prefix or directory component, with
|
||||
/// control characters replaced. An absent, dot-only or unusable name falls
|
||||
/// back to the resolved url's last path segment and then to `artifact`.
|
||||
String artifactFileName(ArtifactRecord artifact, Uri url) {
|
||||
final recorded = _usableBasename(artifact.name);
|
||||
if (recorded.isNotEmpty) return recorded;
|
||||
final fromUrl = _usableBasename(
|
||||
url.pathSegments.isEmpty ? '' : url.pathSegments.last,
|
||||
);
|
||||
return fromUrl.isEmpty ? artifactFileFallbackName : fromUrl;
|
||||
}
|
||||
|
||||
/// The recorded MIME type without parameters, lowercased, or
|
||||
/// `application/octet-stream` when nothing usable was recorded.
|
||||
String artifactFileMimeType(ArtifactRecord artifact) {
|
||||
final mediaType = artifact.contentType.split(';').first.trim().toLowerCase();
|
||||
return _mediaType.hasMatch(mediaType)
|
||||
? mediaType
|
||||
: artifactFileFallbackMimeType;
|
||||
}
|
||||
|
||||
final RegExp _mediaType = RegExp(
|
||||
r"^[a-z0-9!#$&'*+.^_`|~-]+/[a-z0-9!#$&'*+.^_`|~-]+$",
|
||||
);
|
||||
|
||||
/// Whether the record carries a usable file name of its own.
|
||||
bool hasRecordedArtifactName(ArtifactRecord artifact) =>
|
||||
_usableBasename(artifact.name).isNotEmpty;
|
||||
|
||||
/// Whether the record carries a usable MIME type of its own.
|
||||
bool hasRecordedArtifactMimeType(ArtifactRecord artifact) {
|
||||
final mediaType = artifact.contentType.split(';').first.trim().toLowerCase();
|
||||
return _mediaType.hasMatch(mediaType);
|
||||
}
|
||||
|
||||
/// An explicit note when the recorded name or MIME type cannot be used, so the
|
||||
/// fallback file name/type is never silent. Null for a complete record.
|
||||
String? artifactFileRecordingNotice(ArtifactRecord artifact, Uri url) {
|
||||
final nameMissing = !hasRecordedArtifactName(artifact);
|
||||
final typeMissing = !hasRecordedArtifactMimeType(artifact);
|
||||
if (!nameMissing && !typeMissing) return null;
|
||||
final name = artifactFileName(artifact, url);
|
||||
if (nameMissing && typeMissing) {
|
||||
return 'No usable recorded name or MIME type; the file is saved as '
|
||||
'$name ($artifactFileFallbackMimeType).';
|
||||
}
|
||||
if (nameMissing) {
|
||||
return 'No usable recorded name; the file is saved as $name.';
|
||||
}
|
||||
return 'No usable recorded MIME type; the file is saved as '
|
||||
'$artifactFileFallbackMimeType.';
|
||||
}
|
||||
|
||||
String _usableBasename(String value) {
|
||||
final segments = value.trim().split(RegExp(r'[\\/]'));
|
||||
final name = segments.isEmpty ? '' : segments.last;
|
||||
final cleaned = name.replaceAll(RegExp(r'[\x00-\x1f\x7f]'), '_').trim();
|
||||
if (cleaned == '.' || cleaned == '..') return '';
|
||||
return cleaned;
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import '../domain/artifact_record.dart';
|
||||
import '../domain/artifact_url.dart';
|
||||
import '../ui/artifact_viewer_fetch.dart';
|
||||
import 'artifact_file.dart';
|
||||
import 'artifact_file_bridge.dart';
|
||||
import 'artifact_file_controller.dart';
|
||||
|
||||
/// Download and Share for one selected artifact, backed by its exact bytes.
|
||||
///
|
||||
/// The controls are standard native buttons. Download creates a named file;
|
||||
/// Share passes a named file to the host share sheet and never falls back to
|
||||
/// the artifact url. A host without a capability shows a disabled control and
|
||||
/// the exact reason, while the other action keeps working. One tap starts at
|
||||
/// most one transfer; a slow fetch shows progress and can be cancelled.
|
||||
class ArtifactFileActions extends StatefulWidget {
|
||||
const ArtifactFileActions({
|
||||
super.key,
|
||||
required this.artifact,
|
||||
required this.resolved,
|
||||
this.fetch = fetchArtifact,
|
||||
this.bridge = const ArtifactFileBridge(),
|
||||
});
|
||||
|
||||
final ArtifactRecord artifact;
|
||||
final ResolvedArtifactUrl resolved;
|
||||
final ArtifactFetch fetch;
|
||||
final ArtifactFileBridge bridge;
|
||||
|
||||
@override
|
||||
State<ArtifactFileActions> createState() => _ArtifactFileActionsState();
|
||||
}
|
||||
|
||||
class _ArtifactFileActionsState extends State<ArtifactFileActions> {
|
||||
late ArtifactFileActionsController _controller;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller = _create();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant ArtifactFileActions oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.resolved.url != widget.resolved.url ||
|
||||
oldWidget.artifact.url != widget.artifact.url ||
|
||||
oldWidget.artifact.name != widget.artifact.name ||
|
||||
oldWidget.artifact.contentType != widget.artifact.contentType ||
|
||||
oldWidget.fetch != widget.fetch ||
|
||||
oldWidget.bridge != widget.bridge) {
|
||||
_controller.dispose();
|
||||
_controller = _create();
|
||||
}
|
||||
}
|
||||
|
||||
ArtifactFileActionsController _create() => ArtifactFileActionsController(
|
||||
artifact: widget.artifact,
|
||||
resolved: widget.resolved,
|
||||
fetch: widget.fetch,
|
||||
bridge: widget.bridge,
|
||||
);
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListenableBuilder(
|
||||
listenable: _controller,
|
||||
builder: (context, _) => _ActionBar(
|
||||
controller: _controller,
|
||||
cupertino: usesCupertinoHost(context),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ActionBar extends StatelessWidget {
|
||||
const _ActionBar({required this.controller, required this.cupertino});
|
||||
|
||||
final ArtifactFileActionsController controller;
|
||||
final bool cupertino;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final status = controller.status;
|
||||
final notice = artifactFileRecordingNotice(
|
||||
controller.artifact,
|
||||
controller.resolved.uri,
|
||||
);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 4,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
_button(
|
||||
label: 'Download',
|
||||
icon: Icons.download_outlined,
|
||||
onPressed: controller.canDownload && !controller.busy
|
||||
? controller.download
|
||||
: null,
|
||||
),
|
||||
_button(
|
||||
label: 'Share',
|
||||
icon: Icons.ios_share,
|
||||
onPressed: controller.canShare && !controller.busy
|
||||
? controller.share
|
||||
: null,
|
||||
),
|
||||
if (controller.canCancel)
|
||||
_button(
|
||||
label: 'Cancel',
|
||||
icon: Icons.close,
|
||||
onPressed: controller.cancel,
|
||||
),
|
||||
],
|
||||
),
|
||||
if (controller.busy && status != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 6),
|
||||
child: Semantics(
|
||||
liveRegion: true,
|
||||
container: true,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (cupertino)
|
||||
const CupertinoActivityIndicator(radius: 8)
|
||||
else
|
||||
const SizedBox(
|
||||
width: 14,
|
||||
height: 14,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Flexible(child: Text(status)),
|
||||
],
|
||||
),
|
||||
),
|
||||
)
|
||||
else if (status != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 6),
|
||||
child: Semantics(liveRegion: true, child: Text(status)),
|
||||
),
|
||||
if (!controller.canDownload)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 6),
|
||||
child: Text(controller.bridge.downloadUnavailableMessage),
|
||||
),
|
||||
if (!controller.canShare)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 6),
|
||||
child: Text(controller.bridge.shareUnavailableMessage),
|
||||
),
|
||||
if (notice != null)
|
||||
Padding(padding: const EdgeInsets.only(top: 6), child: Text(notice)),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _button({
|
||||
required String label,
|
||||
required IconData icon,
|
||||
required VoidCallback? onPressed,
|
||||
}) {
|
||||
if (cupertino) {
|
||||
return CupertinoButton(onPressed: onPressed, child: Text(label));
|
||||
}
|
||||
return TextButton.icon(
|
||||
onPressed: onPressed,
|
||||
icon: Icon(icon, size: 18),
|
||||
label: Text(label),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import 'artifact_file.dart';
|
||||
import 'artifact_transfer.dart';
|
||||
|
||||
/// The host file capabilities one action row uses.
|
||||
///
|
||||
/// The defaults are the real conditional-import bridge: a web Blob/anchor
|
||||
/// download plus `navigator.share`, and honest `unsupported` results on native
|
||||
/// hosts until a platform launcher exists. Tests inject both functions and the
|
||||
/// capability flags without touching a browser.
|
||||
class ArtifactFileBridge {
|
||||
const ArtifactFileBridge({
|
||||
this.download,
|
||||
this.share,
|
||||
this.downloadSupported,
|
||||
this.shareSupported,
|
||||
this.downloadUnsupportedMessage,
|
||||
this.shareUnsupportedMessage,
|
||||
});
|
||||
|
||||
final ArtifactSaveFile? download;
|
||||
final ArtifactShareFile? share;
|
||||
final bool? downloadSupported;
|
||||
final bool? shareSupported;
|
||||
final String? downloadUnsupportedMessage;
|
||||
final String? shareUnsupportedMessage;
|
||||
|
||||
bool get canDownload => downloadSupported ?? artifactDownloadSupported;
|
||||
|
||||
bool get canShare => shareSupported ?? artifactShareSupported;
|
||||
|
||||
String get downloadUnavailableMessage =>
|
||||
downloadUnsupportedMessage ?? artifactDownloadUnsupportedMessage;
|
||||
|
||||
String get shareUnavailableMessage =>
|
||||
shareUnsupportedMessage ?? artifactShareUnsupportedMessage;
|
||||
|
||||
Future<ArtifactTransferResult> saveFile(ArtifactFile file) =>
|
||||
(download ?? saveArtifactFile)(file);
|
||||
|
||||
Future<ArtifactTransferResult> shareFile(ArtifactFile file) =>
|
||||
(share ?? shareArtifactFile)(file);
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../domain/artifact_record.dart';
|
||||
import '../domain/artifact_url.dart';
|
||||
import '../ui/artifact_viewer_fetch.dart';
|
||||
import 'artifact_file.dart';
|
||||
import 'artifact_file_bridge.dart';
|
||||
import 'artifact_transfer.dart';
|
||||
|
||||
/// Which host file action is currently in flight.
|
||||
enum ArtifactFileAction { download, share }
|
||||
|
||||
/// The words shown while bytes are being fetched.
|
||||
const String artifactPreparingFile = 'Preparing file…';
|
||||
|
||||
/// Saves or shares one selected artifact's fetched bytes.
|
||||
///
|
||||
/// The controller owns exactly one transfer at a time: a tap while [busy] is
|
||||
/// ignored, so a double tap cannot start two fetches or two share sheets. The
|
||||
/// same fetch seam the viewer uses obtains the bytes, so the same-origin
|
||||
/// credential policy and HTTP status handling apply. Fetched bytes are kept
|
||||
/// after a ready/blocked/canceled share so the next tap can retry with a fresh
|
||||
/// user activation without another transfer.
|
||||
///
|
||||
/// Cancelling stops the action from continuing: a late fetch result is ignored
|
||||
/// by generation, and the host transfer is never started. The underlying HTTP
|
||||
/// request is not aborted because the shared fetch seam has no cancellation
|
||||
/// token; the app never reports those bytes as a completed transfer.
|
||||
class ArtifactFileActionsController extends ChangeNotifier {
|
||||
ArtifactFileActionsController({
|
||||
required this.artifact,
|
||||
required this.resolved,
|
||||
required this.fetch,
|
||||
this.bridge = const ArtifactFileBridge(),
|
||||
});
|
||||
|
||||
final ArtifactRecord artifact;
|
||||
final ResolvedArtifactUrl resolved;
|
||||
final ArtifactFileBridge bridge;
|
||||
|
||||
final ArtifactFetch fetch;
|
||||
ArtifactFile? _prepared;
|
||||
String? _preparedUrl;
|
||||
ArtifactFileAction? _active;
|
||||
bool _preparing = false;
|
||||
int _generation = 0;
|
||||
bool _disposed = false;
|
||||
String? _status;
|
||||
|
||||
String? get status => _status;
|
||||
|
||||
bool get busy => _active != null;
|
||||
|
||||
/// Cancel is offered only while the fetch is still running; once the host
|
||||
/// share sheet is open the OS owns the transfer.
|
||||
bool get canCancel => _active != null && _preparing;
|
||||
|
||||
bool get canDownload => bridge.canDownload;
|
||||
|
||||
bool get canShare => bridge.canShare;
|
||||
|
||||
Future<void> download() async {
|
||||
if (busy) return;
|
||||
if (!canDownload) {
|
||||
_setStatus(bridge.downloadUnavailableMessage);
|
||||
return;
|
||||
}
|
||||
final generation = _begin(ArtifactFileAction.download);
|
||||
final file = await _prepare(generation);
|
||||
if (file == null || generation != _generation) return;
|
||||
_preparing = false;
|
||||
_notify();
|
||||
ArtifactTransferResult result;
|
||||
try {
|
||||
result = await bridge.saveFile(file);
|
||||
} catch (_) {
|
||||
_fail(generation, 'Could not download the file. Try again.');
|
||||
return;
|
||||
}
|
||||
if (generation != _generation) return;
|
||||
_active = null;
|
||||
_status = result.state == ArtifactTransferState.saved
|
||||
? 'Downloaded ${file.name}.'
|
||||
: result.message;
|
||||
_notify();
|
||||
}
|
||||
|
||||
Future<void> share() async {
|
||||
if (busy) return;
|
||||
if (!canShare) {
|
||||
_setStatus(bridge.shareUnavailableMessage);
|
||||
return;
|
||||
}
|
||||
final generation = _begin(ArtifactFileAction.share);
|
||||
final file = await _prepare(generation);
|
||||
if (file == null || generation != _generation) return;
|
||||
_preparing = false;
|
||||
_notify();
|
||||
ArtifactTransferResult result;
|
||||
try {
|
||||
result = await bridge.shareFile(file);
|
||||
} catch (_) {
|
||||
_fail(
|
||||
generation,
|
||||
'Could not share the file. Use Download to save it, or try Share again.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (generation != _generation) return;
|
||||
_active = null;
|
||||
_status = result.state == ArtifactTransferState.shared
|
||||
? 'File shared.'
|
||||
: result.message;
|
||||
_notify();
|
||||
}
|
||||
|
||||
/// Stops waiting for the fetch. Nothing is handed to the host afterwards.
|
||||
void cancel() {
|
||||
if (!canCancel) return;
|
||||
final action = _active;
|
||||
_generation += 1;
|
||||
_active = null;
|
||||
_preparing = false;
|
||||
_status = action == ArtifactFileAction.share
|
||||
? 'Sharing canceled.'
|
||||
: 'Download canceled.';
|
||||
_notify();
|
||||
}
|
||||
|
||||
int _begin(ArtifactFileAction action) {
|
||||
final generation = ++_generation;
|
||||
_active = action;
|
||||
_preparing = true;
|
||||
_status = artifactPreparingFile;
|
||||
_notify();
|
||||
return generation;
|
||||
}
|
||||
|
||||
Future<ArtifactFile?> _prepare(int generation) async {
|
||||
final cached = _prepared;
|
||||
if (cached != null && _preparedUrl == resolved.url) {
|
||||
_preparing = false;
|
||||
_notify();
|
||||
return cached;
|
||||
}
|
||||
try {
|
||||
final fetched = await fetch(resolved.uri);
|
||||
if (generation != _generation) return null;
|
||||
if (!fetched.ok) {
|
||||
_fail(
|
||||
generation,
|
||||
'Could not fetch the artifact (HTTP ${fetched.status}).',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
final file = artifactFileFor(
|
||||
artifact: artifact,
|
||||
url: resolved.uri,
|
||||
bytes: fetched.bytes,
|
||||
);
|
||||
_prepared = file;
|
||||
_preparedUrl = resolved.url;
|
||||
return file;
|
||||
} on ArtifactFetchException catch (error) {
|
||||
_fail(generation, 'Could not fetch the artifact: ${error.message}');
|
||||
return null;
|
||||
} catch (error) {
|
||||
_fail(generation, 'Could not fetch the artifact: $error');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
void _fail(int generation, String message) {
|
||||
if (generation != _generation) return;
|
||||
_active = null;
|
||||
_preparing = false;
|
||||
_status = message;
|
||||
_notify();
|
||||
}
|
||||
|
||||
void _setStatus(String message) {
|
||||
_status = message;
|
||||
_notify();
|
||||
}
|
||||
|
||||
void _notify() {
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
_generation += 1;
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import 'artifact_file.dart';
|
||||
import 'artifact_transfer_stub.dart'
|
||||
if (dart.library.js_interop) 'artifact_transfer_web.dart'
|
||||
as impl;
|
||||
|
||||
/// The outcome of a host file transfer.
|
||||
enum ArtifactTransferState {
|
||||
/// The host accepted a browser download.
|
||||
saved,
|
||||
|
||||
/// The host share sheet accepted the file.
|
||||
shared,
|
||||
|
||||
/// The bytes are ready but the browser needed a fresh user activation.
|
||||
ready,
|
||||
|
||||
/// The operator or the host canceled the transfer.
|
||||
canceled,
|
||||
|
||||
/// The host cannot save/share this file.
|
||||
unsupported,
|
||||
|
||||
/// The host refused the share for a policy or activation reason.
|
||||
blocked,
|
||||
|
||||
/// The transfer failed for any other reason.
|
||||
failed,
|
||||
}
|
||||
|
||||
/// A transfer result plus the exact words the action row reports.
|
||||
class ArtifactTransferResult {
|
||||
const ArtifactTransferResult(this.state, this.message);
|
||||
|
||||
final ArtifactTransferState state;
|
||||
final String message;
|
||||
}
|
||||
|
||||
typedef ArtifactSaveFile =
|
||||
Future<ArtifactTransferResult> Function(ArtifactFile file);
|
||||
typedef ArtifactShareFile =
|
||||
Future<ArtifactTransferResult> Function(ArtifactFile file);
|
||||
|
||||
/// Whether the host can save an artifact's bytes as a named file.
|
||||
bool get artifactDownloadSupported => impl.artifactDownloadSupported;
|
||||
|
||||
/// Whether the host can share a file (not merely a link).
|
||||
bool get artifactShareSupported => impl.artifactShareSupported;
|
||||
|
||||
String get artifactDownloadUnsupportedMessage =>
|
||||
impl.artifactDownloadUnsupportedMessage;
|
||||
|
||||
String get artifactShareUnsupportedMessage =>
|
||||
impl.artifactShareUnsupportedMessage;
|
||||
|
||||
/// Saves [file] through the host's download capability.
|
||||
Future<ArtifactTransferResult> saveArtifactFile(ArtifactFile file) =>
|
||||
impl.saveArtifactFile(file);
|
||||
|
||||
/// Shares [file] through the host's file-sharing capability.
|
||||
Future<ArtifactTransferResult> shareArtifactFile(ArtifactFile file) =>
|
||||
impl.shareArtifactFile(file);
|
||||
@@ -0,0 +1,29 @@
|
||||
import 'artifact_file.dart';
|
||||
import 'artifact_transfer.dart';
|
||||
|
||||
/// Native fallback for artifact file actions.
|
||||
///
|
||||
/// A save/share plugin is not a dependency of this slice, so a non-web host
|
||||
/// reports `unsupported` instead of pretending to save a file. The action row
|
||||
/// disables the control and shows this exact explanation.
|
||||
bool get artifactDownloadSupported => false;
|
||||
|
||||
bool get artifactShareSupported => false;
|
||||
|
||||
String get artifactDownloadUnsupportedMessage =>
|
||||
'Downloading files is not supported on this platform yet.';
|
||||
|
||||
String get artifactShareUnsupportedMessage =>
|
||||
'File sharing is not supported on this platform yet.';
|
||||
|
||||
Future<ArtifactTransferResult> saveArtifactFile(ArtifactFile file) async =>
|
||||
ArtifactTransferResult(
|
||||
ArtifactTransferState.unsupported,
|
||||
artifactDownloadUnsupportedMessage,
|
||||
);
|
||||
|
||||
Future<ArtifactTransferResult> shareArtifactFile(ArtifactFile file) async =>
|
||||
ArtifactTransferResult(
|
||||
ArtifactTransferState.unsupported,
|
||||
artifactShareUnsupportedMessage,
|
||||
);
|
||||
@@ -0,0 +1,206 @@
|
||||
import 'dart:async';
|
||||
import 'dart:js_interop';
|
||||
import 'dart:js_interop_unsafe';
|
||||
|
||||
import 'artifact_file.dart';
|
||||
import 'artifact_transfer.dart';
|
||||
|
||||
/// Web file actions: the artifact's bytes become a named `Blob`/`File`.
|
||||
///
|
||||
/// Download creates an object url and clicks a native anchor with the recorded
|
||||
/// name; share passes a real `File` to `navigator.share`. Neither path ever
|
||||
/// substitutes the artifact url or opens a blob page. No package:web import is
|
||||
/// used, so the same source compiles for JavaScript and WebAssembly.
|
||||
@JS('document')
|
||||
external _Document get _document;
|
||||
|
||||
@JS('navigator')
|
||||
external _Navigator get _navigator;
|
||||
|
||||
@JS('URL.createObjectURL')
|
||||
external JSString _createObjectUrl(JSObject blob);
|
||||
|
||||
@JS('URL.revokeObjectURL')
|
||||
external void _revokeObjectUrl(JSString url);
|
||||
|
||||
extension type _Document._(JSObject _) implements JSObject {
|
||||
external _Anchor createElement(JSString tag);
|
||||
external _Element get body;
|
||||
}
|
||||
|
||||
extension type _Anchor._(JSObject _) implements JSObject {
|
||||
external set href(JSString value);
|
||||
external set download(JSString value);
|
||||
external void click();
|
||||
external void remove();
|
||||
}
|
||||
|
||||
extension type _Element._(JSObject _) implements JSObject {
|
||||
external void appendChild(JSObject node);
|
||||
}
|
||||
|
||||
extension type _BlobOptions._(JSObject _) implements JSObject {
|
||||
external factory _BlobOptions({JSString type});
|
||||
}
|
||||
|
||||
@JS('Blob')
|
||||
extension type _Blob._(JSObject _) implements JSObject {
|
||||
external factory _Blob(JSArray<JSAny> parts, _BlobOptions options);
|
||||
}
|
||||
|
||||
extension type _FileOptions._(JSObject _) implements JSObject {
|
||||
external factory _FileOptions({JSString type});
|
||||
}
|
||||
|
||||
@JS('File')
|
||||
extension type _File._(JSObject _) implements JSObject {
|
||||
external factory _File(
|
||||
JSArray<JSAny> parts,
|
||||
JSString name,
|
||||
_FileOptions options,
|
||||
);
|
||||
}
|
||||
|
||||
extension type _ShareData._(JSObject _) implements JSObject {
|
||||
external factory _ShareData({JSArray<JSAny> files});
|
||||
}
|
||||
|
||||
extension type _UserActivation._(JSObject _) implements JSObject {
|
||||
external bool get isActive;
|
||||
}
|
||||
|
||||
extension type _Navigator._(JSObject _) implements JSObject {
|
||||
external JSPromise<JSAny?> share(_ShareData data);
|
||||
external bool canShare(_ShareData data);
|
||||
external _UserActivation? get userActivation;
|
||||
}
|
||||
|
||||
bool get artifactDownloadSupported => true;
|
||||
|
||||
bool get artifactShareSupported =>
|
||||
_hasFunction('share') && _hasFunction('canShare');
|
||||
|
||||
String get artifactDownloadUnsupportedMessage =>
|
||||
'Downloading files is not supported in this browser.';
|
||||
|
||||
String get artifactShareUnsupportedMessage =>
|
||||
'File sharing is not supported in this browser. Use Download to save the file.';
|
||||
|
||||
const String _fileReadyMessage =
|
||||
'File ready. Tap Share again to choose where to send it.';
|
||||
|
||||
Future<ArtifactTransferResult> saveArtifactFile(ArtifactFile file) async {
|
||||
try {
|
||||
final blob = _blobFor(file);
|
||||
final url = _createObjectUrl(blob);
|
||||
final anchor = _document.createElement('a'.toJS)
|
||||
..href = url
|
||||
..download = file.name.toJS;
|
||||
_document.body.appendChild(anchor);
|
||||
try {
|
||||
anchor.click();
|
||||
} finally {
|
||||
anchor.remove();
|
||||
// Revoking immediately can cancel a download in some browsers.
|
||||
unawaited(
|
||||
Future<void>.delayed(
|
||||
const Duration(seconds: 1),
|
||||
() => _revokeObjectUrl(url),
|
||||
),
|
||||
);
|
||||
}
|
||||
return ArtifactTransferResult(
|
||||
ArtifactTransferState.saved,
|
||||
'Downloaded ${file.name}.',
|
||||
);
|
||||
} catch (_) {
|
||||
return const ArtifactTransferResult(
|
||||
ArtifactTransferState.failed,
|
||||
'Could not download the file. Try again.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<ArtifactTransferResult> shareArtifactFile(ArtifactFile file) async {
|
||||
if (!artifactShareSupported) {
|
||||
return ArtifactTransferResult(
|
||||
ArtifactTransferState.unsupported,
|
||||
artifactShareUnsupportedMessage,
|
||||
);
|
||||
}
|
||||
final data = _ShareData(files: <JSAny>[_fileFor(file)].toJS);
|
||||
try {
|
||||
if (!_navigator.canShare(data)) {
|
||||
return ArtifactTransferResult(
|
||||
ArtifactTransferState.unsupported,
|
||||
'This browser cannot share this file type. Use Download to save the file.',
|
||||
);
|
||||
}
|
||||
} catch (_) {
|
||||
return ArtifactTransferResult(
|
||||
ArtifactTransferState.unsupported,
|
||||
artifactShareUnsupportedMessage,
|
||||
);
|
||||
}
|
||||
// Fetching may outlast the browser's transient activation. Do not attempt a
|
||||
// doomed share or substitute a url: the prepared bytes stay cached in the
|
||||
// controller and the next tap shares them.
|
||||
final activation = _navigator.userActivation;
|
||||
if (activation != null && !activation.isActive) {
|
||||
return const ArtifactTransferResult(
|
||||
ArtifactTransferState.ready,
|
||||
_fileReadyMessage,
|
||||
);
|
||||
}
|
||||
try {
|
||||
await _navigator.share(data).toDart;
|
||||
return const ArtifactTransferResult(
|
||||
ArtifactTransferState.shared,
|
||||
'File shared.',
|
||||
);
|
||||
} catch (error) {
|
||||
final name = _errorName(error);
|
||||
if (name == 'AbortError') {
|
||||
return const ArtifactTransferResult(
|
||||
ArtifactTransferState.canceled,
|
||||
'Sharing canceled.',
|
||||
);
|
||||
}
|
||||
if (name == 'NotAllowedError') {
|
||||
return const ArtifactTransferResult(
|
||||
ArtifactTransferState.blocked,
|
||||
'Sharing was blocked. Tap Share again, or use Download to save the file.',
|
||||
);
|
||||
}
|
||||
return const ArtifactTransferResult(
|
||||
ArtifactTransferState.failed,
|
||||
'Could not share the file. Use Download to save it, or try Share again.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
_Blob _blobFor(ArtifactFile file) => _Blob(
|
||||
<JSAny>[file.bytes.toJS].toJS,
|
||||
_BlobOptions(type: file.mimeType.toJS),
|
||||
);
|
||||
|
||||
_File _fileFor(ArtifactFile file) => _File(
|
||||
<JSAny>[_blobFor(file)].toJS,
|
||||
file.name.toJS,
|
||||
_FileOptions(type: file.mimeType.toJS),
|
||||
);
|
||||
|
||||
bool _hasFunction(String name) {
|
||||
final value = _navigator.getProperty<JSAny?>(name.toJS);
|
||||
return value != null && value.isA<JSFunction>();
|
||||
}
|
||||
|
||||
String? _errorName(Object error) {
|
||||
// A rejected JS promise arrives as a Dart error whose text carries the DOM
|
||||
// exception name; the web's AbortError/NotAllowedError branches use those.
|
||||
final text = '$error';
|
||||
for (final candidate in const <String>['AbortError', 'NotAllowedError']) {
|
||||
if (text.contains(candidate)) return candidate;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -107,3 +107,25 @@ List<ArtifactRecord> visitArtifacts(JsonMap step, List<JsonMap> runSteps) {
|
||||
if (!artifact.isPublicName || !seen.contains(artifact.name)) artifact,
|
||||
];
|
||||
}
|
||||
|
||||
/// The gallery group of exactly one recorded visit, addressed by its index in
|
||||
/// [runSteps]. The whole run is still read so a shared `public/` file stays with
|
||||
/// the visit that first recorded it and the group keeps the run's own visit
|
||||
/// numbering. Null when the index is out of range or the visit recorded no
|
||||
/// presentable stage artifact.
|
||||
ArtifactGroup? visitArtifactGroup(List<JsonMap> runSteps, int index) {
|
||||
if (index < 0 || index >= runSteps.length) return null;
|
||||
final step = runSteps[index];
|
||||
final stage = '${step['stage'] ?? ''}';
|
||||
final visits = visitsByStage(runSteps)[stage];
|
||||
if (visits == null) return null;
|
||||
// The pane passes the index of the same parsed list, so the recorded map is
|
||||
// the identical instance the stage grouping holds.
|
||||
final position = visits.indexOf(step);
|
||||
if (position < 0) return null;
|
||||
final visit = displayVisit(step, position);
|
||||
for (final group in artifactGroups(runSteps)) {
|
||||
if (group.stageKey == stage && group.visit == visit) return group;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -35,15 +35,6 @@ bool _runExecuting(JsonMap run) =>
|
||||
run['executing'] == true ||
|
||||
_executingStatuses.contains('${run['status'] ?? ''}'.trim().toLowerCase());
|
||||
|
||||
/// The configured endpoint from the app's shared transport, when the gateway
|
||||
/// exposes it. Feature fixtures without an endpoint leave it blank, which only
|
||||
/// disables relative url resolution: an absolute recorded http(s) url still
|
||||
/// resolves. The url rules themselves live in `artifact_url.dart`.
|
||||
String _gatewayEndpoint(ApiGateway gateway) {
|
||||
final endpoint = gateway is PipelinesClient ? gateway.endpoint : null;
|
||||
return endpoint?.toString() ?? '';
|
||||
}
|
||||
|
||||
/// The run detail's standard native action that opens the recorded artifact
|
||||
/// groups. It is composed only when [showRunArtifactsAction] is true.
|
||||
class RunArtifactsButton extends StatelessWidget {
|
||||
@@ -63,7 +54,7 @@ class RunArtifactsButton extends StatelessWidget {
|
||||
context,
|
||||
steps: steps,
|
||||
executing: _runExecuting(run),
|
||||
configuredEndpoint: _gatewayEndpoint(gateway),
|
||||
configuredEndpoint: configuredGatewayEndpoint(gateway),
|
||||
);
|
||||
if (usesCupertinoHost(context)) {
|
||||
return CupertinoButton.tinted(
|
||||
@@ -86,12 +77,14 @@ class RunArtifactsButton extends StatelessWidget {
|
||||
Future<void> showArtifactGallery(
|
||||
BuildContext context, {
|
||||
required List<JsonMap> steps,
|
||||
int? focusIndex,
|
||||
bool executing = false,
|
||||
String configuredEndpoint = '',
|
||||
ArtifactExternalOpen openExternal = openArtifactExternally,
|
||||
}) {
|
||||
final page = ArtifactGalleryPage(
|
||||
steps: List<JsonMap>.unmodifiable(steps),
|
||||
focusIndex: focusIndex,
|
||||
executing: executing,
|
||||
configuredEndpoint: configuredEndpoint,
|
||||
openExternal: openExternal,
|
||||
|
||||
@@ -5,6 +5,8 @@ import 'package:flutter/services.dart';
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import '../../chat/ui/transcript/chat_markdown_view.dart';
|
||||
import '../actions/artifact_file_actions.dart';
|
||||
import '../actions/artifact_file_bridge.dart';
|
||||
import '../domain/artifact_groups.dart';
|
||||
import '../domain/artifact_kind.dart';
|
||||
import '../domain/artifact_record.dart';
|
||||
@@ -28,25 +30,38 @@ const String artifactGalleryTitle = 'Artifacts';
|
||||
/// never fetched); any other selection opens a native dialog with the recorded
|
||||
/// name, MIME and size, the visit's capture facts and, only when the recorded
|
||||
/// url resolves through [resolveArtifactUrl], native `Open` and `Copy link`
|
||||
/// actions. Markdown previews use the same chat markdown renderer by default.
|
||||
/// It never downloads, shares or filters.
|
||||
/// actions plus file `Download`/`Share` for a server-served url. Markdown
|
||||
/// previews use the same chat markdown renderer by default. It never filters,
|
||||
/// and an external url is never fetched for preview or file transfer.
|
||||
///
|
||||
/// [focusIndex] limits the page to the visited `steps` index's attributed
|
||||
/// group. The whole run is still passed so shared `public/` files keep their
|
||||
/// first visit and the group keeps the run's visit numbering; the page then
|
||||
/// lists exactly what the opening pane listed.
|
||||
class ArtifactGalleryPage extends StatefulWidget {
|
||||
const ArtifactGalleryPage({
|
||||
super.key,
|
||||
required this.steps,
|
||||
this.focusIndex,
|
||||
this.executing = false,
|
||||
this.configuredEndpoint = '',
|
||||
this.openExternal = openArtifactExternally,
|
||||
this.fetch = fetchArtifact,
|
||||
this.markdownBuilder = chatMarkdownText,
|
||||
this.fileBridge = const ArtifactFileBridge(),
|
||||
});
|
||||
|
||||
final List<JsonMap> steps;
|
||||
|
||||
/// The `steps` index whose group this page shows, or null for every group.
|
||||
final int? focusIndex;
|
||||
|
||||
final bool executing;
|
||||
final String configuredEndpoint;
|
||||
final ArtifactExternalOpen openExternal;
|
||||
final ArtifactFetch fetch;
|
||||
final ArtifactMarkdownBuilder markdownBuilder;
|
||||
final ArtifactFileBridge fileBridge;
|
||||
|
||||
@override
|
||||
State<ArtifactGalleryPage> createState() => _ArtifactGalleryPageState();
|
||||
@@ -56,10 +71,16 @@ class _ArtifactGalleryPageState extends State<ArtifactGalleryPage> {
|
||||
late final Map<String, JsonMap> _stepsByGroup = recordedStepsByGroup(
|
||||
widget.steps,
|
||||
);
|
||||
late final List<ArtifactGroup> _groups = artifactGroups(widget.steps);
|
||||
late final List<ArtifactGroup> _groups = _groupsOf(widget.focusIndex);
|
||||
String? _selectedIdentity;
|
||||
String? _status;
|
||||
|
||||
List<ArtifactGroup> _groupsOf(int? focusIndex) {
|
||||
if (focusIndex == null) return artifactGroups(widget.steps);
|
||||
final group = visitArtifactGroup(widget.steps, focusIndex);
|
||||
return group == null ? const <ArtifactGroup>[] : <ArtifactGroup>[group];
|
||||
}
|
||||
|
||||
Future<void> _select(ArtifactGroup group, ArtifactRecord artifact) async {
|
||||
final identity = artifactVisitIdentity(group, artifact);
|
||||
final resolved = artifact.hasUrl
|
||||
@@ -89,6 +110,7 @@ class _ArtifactGalleryPageState extends State<ArtifactGalleryPage> {
|
||||
openExternal: widget.openExternal,
|
||||
fetch: widget.fetch,
|
||||
markdownBuilder: widget.markdownBuilder,
|
||||
fileBridge: widget.fileBridge,
|
||||
),
|
||||
)
|
||||
: MaterialPageRoute<void>(
|
||||
@@ -99,6 +121,7 @@ class _ArtifactGalleryPageState extends State<ArtifactGalleryPage> {
|
||||
openExternal: widget.openExternal,
|
||||
fetch: widget.fetch,
|
||||
markdownBuilder: widget.markdownBuilder,
|
||||
fileBridge: widget.fileBridge,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -120,12 +143,31 @@ class _ArtifactGalleryPageState extends State<ArtifactGalleryPage> {
|
||||
step: step,
|
||||
resolved: resolved,
|
||||
);
|
||||
final content = Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
facts,
|
||||
if (resolved != null && !resolved.external) ...[
|
||||
const SizedBox(height: 12),
|
||||
ArtifactFileActions(
|
||||
key: ValueKey<String>(
|
||||
'artifact-files-${artifactVisitIdentity(group, artifact)}',
|
||||
),
|
||||
artifact: artifact,
|
||||
resolved: resolved,
|
||||
fetch: widget.fetch,
|
||||
bridge: widget.fileBridge,
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
if (usesCupertinoHost(context)) {
|
||||
return showCupertinoDialog<void>(
|
||||
context: context,
|
||||
builder: (dialogContext) => CupertinoAlertDialog(
|
||||
title: Text(artifactDisplayName(artifact)),
|
||||
content: facts,
|
||||
content: content,
|
||||
actions: [
|
||||
if (resolved != null)
|
||||
CupertinoDialogAction(
|
||||
@@ -150,7 +192,7 @@ class _ArtifactGalleryPageState extends State<ArtifactGalleryPage> {
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: Text(artifactDisplayName(artifact)),
|
||||
content: SingleChildScrollView(child: facts),
|
||||
content: SingleChildScrollView(child: content),
|
||||
actions: [
|
||||
if (resolved != null)
|
||||
TextButton(
|
||||
@@ -201,12 +243,28 @@ class _ArtifactGalleryPageState extends State<ArtifactGalleryPage> {
|
||||
setState(() => _status = message);
|
||||
}
|
||||
|
||||
/// The page's one summary line: a focused visit uses its own capture summary,
|
||||
/// a run-level page uses the run header, and an empty reply says so.
|
||||
String _summary(List<ArtifactGroup> groups) {
|
||||
final focusIndex = widget.focusIndex;
|
||||
if (focusIndex != null &&
|
||||
focusIndex >= 0 &&
|
||||
focusIndex < widget.steps.length) {
|
||||
final focused = widget.steps[focusIndex];
|
||||
final count = groups.fold<int>(
|
||||
0,
|
||||
(total, group) => total + group.artifacts.length,
|
||||
);
|
||||
return artifactsSummary(focused, count: count);
|
||||
}
|
||||
if (widget.steps.isEmpty) return 'No steps recorded for this run.';
|
||||
return artifactsHeader(widget.steps, executing: widget.executing);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final groups = _groups;
|
||||
final summary = widget.steps.isEmpty
|
||||
? 'No steps recorded for this run.'
|
||||
: artifactsHeader(widget.steps, executing: widget.executing);
|
||||
final summary = _summary(groups);
|
||||
final body = Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
|
||||
@@ -4,17 +4,21 @@ import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import '../actions/artifact_file_actions.dart';
|
||||
import '../actions/artifact_file_bridge.dart';
|
||||
import '../domain/artifact_preview.dart';
|
||||
import '../domain/artifact_url.dart';
|
||||
import '../domain/gallery_navigation.dart';
|
||||
import 'artifact_selection_facts.dart';
|
||||
import 'artifact_viewer_content.dart';
|
||||
import 'artifact_viewer_fetch.dart';
|
||||
|
||||
/// One viewer page: the recorded facts, position, live status, preview surface,
|
||||
/// external actions and paging controls.
|
||||
/// file transfer actions, external actions and paging controls.
|
||||
///
|
||||
/// It is stateless so the page owns loading, fetch generations and focus; this
|
||||
/// surface only draws the current page and reports the operator's intent.
|
||||
/// surface only draws the current page and reports the operator's intent. The
|
||||
/// page content scrolls as one column at large text sizes; paging stays fixed.
|
||||
class ArtifactViewerBody extends StatelessWidget {
|
||||
const ArtifactViewerBody({
|
||||
super.key,
|
||||
@@ -28,6 +32,8 @@ class ArtifactViewerBody extends StatelessWidget {
|
||||
required this.onNext,
|
||||
required this.onOpen,
|
||||
required this.onCopy,
|
||||
this.fetch = fetchArtifact,
|
||||
this.fileBridge = const ArtifactFileBridge(),
|
||||
this.text,
|
||||
this.bytes,
|
||||
this.error,
|
||||
@@ -44,6 +50,8 @@ class ArtifactViewerBody extends StatelessWidget {
|
||||
final VoidCallback onNext;
|
||||
final VoidCallback onOpen;
|
||||
final VoidCallback onCopy;
|
||||
final ArtifactFetch fetch;
|
||||
final ArtifactFileBridge fileBridge;
|
||||
final String? text;
|
||||
final Uint8List? bytes;
|
||||
final String? error;
|
||||
@@ -54,42 +62,67 @@ class ArtifactViewerBody extends StatelessWidget {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 4),
|
||||
child: ArtifactSelectionFacts(
|
||||
group: page.group,
|
||||
artifact: page.artifact,
|
||||
step: null,
|
||||
resolved: plan.resolved,
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 16, 4),
|
||||
child: Text(
|
||||
artifactViewerPositionLabel(
|
||||
index,
|
||||
count,
|
||||
page.artifact.contentType,
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 4),
|
||||
child: ArtifactSelectionFacts(
|
||||
group: page.group,
|
||||
artifact: page.artifact,
|
||||
step: null,
|
||||
resolved: plan.resolved,
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 16, 4),
|
||||
child: Text(
|
||||
artifactViewerPositionLabel(
|
||||
index,
|
||||
count,
|
||||
page.artifact.contentType,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (status != null)
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 4),
|
||||
child: Semantics(liveRegion: true, child: Text(status!)),
|
||||
),
|
||||
ArtifactPreviewBody(
|
||||
plan: plan,
|
||||
loading: loading,
|
||||
markdownBuilder: markdownBuilder,
|
||||
text: text,
|
||||
bytes: bytes,
|
||||
error: error,
|
||||
),
|
||||
if (plan.resolved != null && !plan.resolved!.external)
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 16, 4),
|
||||
child: ArtifactFileActions(
|
||||
key: ValueKey<String>(
|
||||
'viewer-files-${page.group.stageKey}\u0000'
|
||||
'${page.group.visit}\u0000${page.artifact.url}',
|
||||
),
|
||||
artifact: page.artifact,
|
||||
resolved: plan.resolved!,
|
||||
fetch: fetch,
|
||||
bridge: fileBridge,
|
||||
),
|
||||
),
|
||||
if (plan.resolved != null)
|
||||
_Actions(
|
||||
resolved: plan.resolved!,
|
||||
onOpen: onOpen,
|
||||
onCopy: onCopy,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
if (status != null)
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 4),
|
||||
child: Semantics(liveRegion: true, child: Text(status!)),
|
||||
),
|
||||
Expanded(
|
||||
child: ArtifactPreviewBody(
|
||||
plan: plan,
|
||||
loading: loading,
|
||||
markdownBuilder: markdownBuilder,
|
||||
text: text,
|
||||
bytes: bytes,
|
||||
error: error,
|
||||
),
|
||||
),
|
||||
if (plan.resolved != null)
|
||||
_Actions(resolved: plan.resolved!, onOpen: onOpen, onCopy: onCopy),
|
||||
_Pager(
|
||||
index: index,
|
||||
count: count,
|
||||
|
||||
@@ -62,9 +62,9 @@ class ArtifactPreviewBody extends StatelessWidget {
|
||||
),
|
||||
);
|
||||
case ArtifactPreviewKind.text:
|
||||
return _ScrollingText(child: SelectableText(text ?? ''));
|
||||
return _PreviewPadding(child: SelectableText(text ?? ''));
|
||||
case ArtifactPreviewKind.markdown:
|
||||
return _ScrollingText(child: markdownBuilder(context, text ?? ''));
|
||||
return _PreviewPadding(child: markdownBuilder(context, text ?? ''));
|
||||
case ArtifactPreviewKind.unsupported:
|
||||
case ArtifactPreviewKind.unavailable:
|
||||
return const SizedBox.shrink();
|
||||
@@ -93,14 +93,16 @@ class _Loading extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
class _ScrollingText extends StatelessWidget {
|
||||
const _ScrollingText({required this.child});
|
||||
/// Preview text at its natural height; the viewer body owns the page scroll so
|
||||
/// a long document and its actions scroll together instead of nested scrolls.
|
||||
class _PreviewPadding extends StatelessWidget {
|
||||
const _PreviewPadding({required this.child});
|
||||
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SingleChildScrollView(
|
||||
return Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 16),
|
||||
child: child,
|
||||
);
|
||||
|
||||
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import '../actions/artifact_file_bridge.dart';
|
||||
import '../domain/artifact_groups.dart';
|
||||
import '../domain/artifact_preview.dart';
|
||||
import '../domain/artifact_url.dart';
|
||||
@@ -24,8 +25,9 @@ const String artifactViewerTitle = 'Artifact viewer';
|
||||
/// `text/plain` artifact is selectable text, and a `.md`/`.markdown` or
|
||||
/// `text/markdown` artifact is handed to [markdownBuilder]. The selected page
|
||||
/// keeps its recorded facts visible and offers the existing external Open and
|
||||
/// Copy link actions. Previous/Next walk the same filtered list the gallery
|
||||
/// draws and stop at both ends; closing returns to the gallery row.
|
||||
/// Copy link actions plus Download/Share of the same-origin bytes as a named
|
||||
/// file. Previous/Next walk the same filtered list the gallery draws and stop at
|
||||
/// both ends; closing returns to the gallery row.
|
||||
///
|
||||
/// Nothing is ever drawn for an external, unsafe or unsupported url: the viewer
|
||||
/// reports the exact state instead. External urls are never fetched.
|
||||
@@ -38,6 +40,7 @@ class ArtifactViewerPage extends StatefulWidget {
|
||||
this.fetch = fetchArtifact,
|
||||
this.markdownBuilder = defaultArtifactMarkdown,
|
||||
this.openExternal = openArtifactExternally,
|
||||
this.fileBridge = const ArtifactFileBridge(),
|
||||
});
|
||||
|
||||
final List<ArtifactGroup> groups;
|
||||
@@ -49,6 +52,7 @@ class ArtifactViewerPage extends StatefulWidget {
|
||||
final ArtifactFetch fetch;
|
||||
final ArtifactMarkdownBuilder markdownBuilder;
|
||||
final ArtifactExternalOpen openExternal;
|
||||
final ArtifactFileBridge fileBridge;
|
||||
|
||||
@override
|
||||
State<ArtifactViewerPage> createState() => _ArtifactViewerPageState();
|
||||
@@ -228,6 +232,8 @@ class _ArtifactViewerPageState extends State<ArtifactViewerPage> {
|
||||
bytes: _fetched?.bytes,
|
||||
error: _error,
|
||||
status: _status,
|
||||
fetch: widget.fetch,
|
||||
fileBridge: widget.fileBridge,
|
||||
onPrevious: () => _step(-1),
|
||||
onNext: () => _step(1),
|
||||
onOpen: plan.resolved == null ? () {} : () => _open(plan.resolved!),
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import 'notification_bridge_stub.dart'
|
||||
if (dart.library.js_interop) 'notification_bridge_web.dart'
|
||||
as impl;
|
||||
import 'notification_models.dart';
|
||||
|
||||
/// Where the notification capability actually posts.
|
||||
///
|
||||
/// The controller depends on this, not on any platform, so the dedupe, the
|
||||
/// permission rules and the content are all testable without a browser. A bridge
|
||||
/// answers the platform's real facts and never guesses: [environment] returns
|
||||
/// what the platform says (including "unsupported"), [requestPermission] is only
|
||||
/// called from an explicit gesture, and [show] reports whether the platform
|
||||
/// accepted the notification.
|
||||
abstract interface class NotificationBridge {
|
||||
/// The platform's own facts: support, secure context and permission word.
|
||||
NotificationEnvironment environment();
|
||||
|
||||
/// Asks the platform, from an explicit operator gesture, and returns its own
|
||||
/// answer word. Never a guess, and never called by the controller on its own.
|
||||
Future<String> requestPermission();
|
||||
|
||||
/// Shows one notification, attaching [onTap] as its tap intent when given.
|
||||
/// Returns whether the platform accepted it.
|
||||
bool show(NotificationMessage message, {void Function()? onTap});
|
||||
}
|
||||
|
||||
/// The bridge for the current platform: the browser `Notification` on the web,
|
||||
/// an honest "unsupported" elsewhere.
|
||||
NotificationBridge createNotificationBridge() =>
|
||||
impl.createNotificationBridge();
|
||||
@@ -0,0 +1,27 @@
|
||||
import 'notification_bridge.dart';
|
||||
import 'notification_models.dart';
|
||||
|
||||
/// The non-web bridge: there is no browser Notification API to reach.
|
||||
///
|
||||
/// It reports `unsupported` honestly rather than pretending a notification was
|
||||
/// shown, so the surface falls back to the in-app `Needs you` channel. A native
|
||||
/// platform notifier would replace this through the same seam.
|
||||
class UnsupportedNotificationBridge implements NotificationBridge {
|
||||
const UnsupportedNotificationBridge();
|
||||
|
||||
@override
|
||||
NotificationEnvironment environment() => const NotificationEnvironment(
|
||||
supported: false,
|
||||
secureContext: false,
|
||||
permission: 'default',
|
||||
);
|
||||
|
||||
@override
|
||||
Future<String> requestPermission() async => 'default';
|
||||
|
||||
@override
|
||||
bool show(NotificationMessage message, {void Function()? onTap}) => false;
|
||||
}
|
||||
|
||||
NotificationBridge createNotificationBridge() =>
|
||||
const UnsupportedNotificationBridge();
|
||||
@@ -0,0 +1,95 @@
|
||||
import 'dart:js_interop';
|
||||
import 'dart:js_interop_unsafe';
|
||||
|
||||
import 'notification_bridge.dart';
|
||||
import 'notification_models.dart';
|
||||
|
||||
/// The browser's `Notification` constructor.
|
||||
///
|
||||
/// Declared with `dart:js_interop` rather than `dart:html`, so the same source
|
||||
/// compiles for the JavaScript and WebAssembly web targets. Every member is
|
||||
/// reached only after [_supported] has confirmed the global exists, so an
|
||||
/// unsupported browser never touches it.
|
||||
@JS('Notification')
|
||||
extension type _Notification._(JSObject _) implements JSObject {
|
||||
external factory _Notification(JSString title, _NotificationOptions options);
|
||||
|
||||
external static JSString get permission;
|
||||
|
||||
external static JSPromise<JSString> requestPermission();
|
||||
|
||||
external set onclick(JSFunction? handler);
|
||||
}
|
||||
|
||||
/// The `{ body, tag }` options object one notification is created with.
|
||||
extension type _NotificationOptions._(JSObject _) implements JSObject {
|
||||
external factory _NotificationOptions({JSString body, JSString tag});
|
||||
}
|
||||
|
||||
/// Whether `globalThis.Notification` is really a constructor right now.
|
||||
bool _supported() =>
|
||||
globalContext.getProperty<JSAny?>('Notification'.toJS).isA<JSFunction>();
|
||||
|
||||
/// The browser's own secure-context flag; anything but a real boolean is false.
|
||||
bool _secureContext() {
|
||||
final value = globalContext.getProperty<JSAny?>('isSecureContext'.toJS);
|
||||
return value.isA<JSBoolean>() && (value as JSBoolean).toDart;
|
||||
}
|
||||
|
||||
/// The browser bridge: the real `Notification` API, reached through
|
||||
/// `dart:js_interop`.
|
||||
///
|
||||
/// Nothing is fabricated. [environment] reports the constructor's own
|
||||
/// `permission` word and the page's own `isSecureContext`; an unsupported
|
||||
/// browser is reported as unsupported rather than as a default grant.
|
||||
class WebNotificationBridge implements NotificationBridge {
|
||||
const WebNotificationBridge();
|
||||
|
||||
@override
|
||||
NotificationEnvironment environment() {
|
||||
if (!_supported()) {
|
||||
return const NotificationEnvironment(
|
||||
supported: false,
|
||||
secureContext: false,
|
||||
permission: 'default',
|
||||
);
|
||||
}
|
||||
final raw = _Notification.permission.toDart;
|
||||
return NotificationEnvironment(
|
||||
supported: true,
|
||||
secureContext: _secureContext(),
|
||||
permission: raw == 'granted' || raw == 'denied' ? raw : 'default',
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<String> requestPermission() async {
|
||||
if (!_supported()) return 'default';
|
||||
try {
|
||||
return (await _Notification.requestPermission().toDart).toDart;
|
||||
} catch (_) {
|
||||
// A browser that refuses the request keeps the honest fallback wording.
|
||||
return 'default';
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool show(NotificationMessage message, {void Function()? onTap}) {
|
||||
if (!_supported()) return false;
|
||||
try {
|
||||
final notification = _Notification(
|
||||
message.title.toJS,
|
||||
_NotificationOptions(body: message.body.toJS, tag: message.tag.toJS),
|
||||
);
|
||||
final open = onTap;
|
||||
if (open != null) notification.onclick = (() => open()).toJS;
|
||||
return true;
|
||||
} catch (_) {
|
||||
// Some browsers can throw even with permission granted; the in-app Needs
|
||||
// you surface remains the only honest channel and nothing is faked.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
NotificationBridge createNotificationBridge() => const WebNotificationBridge();
|
||||
@@ -0,0 +1,250 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../domain/attention_transitions.dart';
|
||||
import 'notification_bridge.dart';
|
||||
import 'notification_ledger.dart';
|
||||
import 'notification_models.dart';
|
||||
import 'notification_store.dart';
|
||||
|
||||
/// The live notification capability behind the `Needs you` surface.
|
||||
///
|
||||
/// It never invents a permission: [permission] is the platform's own answer,
|
||||
/// read from the [NotificationBridge], and `granted` is only ever reported when
|
||||
/// the platform said so. Nothing asks for permission on its own —
|
||||
/// [requestPermission] is the one explicit call — and a denied answer is never
|
||||
/// re-asked.
|
||||
///
|
||||
/// Only live attention transitions raise a notification: the caller publishes
|
||||
/// the transitions the attention model raised (never the initial seed), and one
|
||||
/// identity is posted at most once per entry into its run's qualifying state,
|
||||
/// including across a reconnect, because the ledger records the identity before
|
||||
/// the platform is asked to show it. A dismissed identity is recorded but never
|
||||
/// shown.
|
||||
///
|
||||
/// The manager wires it: set [onOpenRun] to open a run, call [load] once, and
|
||||
/// after *every* authoritative read and pushed frame call [publishTransitions]
|
||||
/// with the attention controller's accumulated transitions, its current rows
|
||||
/// (through [notificationQualifyingKeys]) and its dismissed set. Publishing the
|
||||
/// frame that leaves a state is what forgets the old identity, so the next gate
|
||||
/// or retry is a new announcement. The call is idempotent, so passing the whole
|
||||
/// accumulated list is safe.
|
||||
class NotificationController extends ChangeNotifier {
|
||||
NotificationController({required this.store, NotificationBridge? bridge})
|
||||
: bridge = bridge ?? createNotificationBridge();
|
||||
|
||||
/// The most notifications one publish posts, so a burst cannot flood the tray.
|
||||
static const maxNotificationsPerBatch = 5;
|
||||
|
||||
final NotificationStore store;
|
||||
final NotificationBridge bridge;
|
||||
|
||||
/// The tap seam: the manager sets this to open a run. Nothing here navigates.
|
||||
void Function(int runId)? onOpenRun;
|
||||
|
||||
NotificationLedger _ledger = const NotificationLedger();
|
||||
NotificationPermissionState _permission =
|
||||
NotificationPermissionState.unsupported;
|
||||
bool _loaded = false;
|
||||
bool _disposed = false;
|
||||
int _posted = 0;
|
||||
|
||||
/// The transition instance announced this session for each identity: a new
|
||||
/// instance means the run entered the state again.
|
||||
final Map<String, AttentionTransition> _announced = {};
|
||||
|
||||
/// The queued ledger writes, so an older snapshot cannot land after a newer one.
|
||||
Future<void> _writes = Future<void>.value();
|
||||
|
||||
/// The platform's own permission state for this page.
|
||||
NotificationPermissionState get permission => _permission;
|
||||
|
||||
/// True once the persisted ledger and the platform facts have been read.
|
||||
bool get loaded => _loaded;
|
||||
|
||||
/// Whether the operator has ever been asked for permission.
|
||||
bool get asked => _ledger.asked;
|
||||
|
||||
/// A copy of the transition identities this client has already announced.
|
||||
/// Returned unmodifiable, so a caller cannot mutate the ledger behind
|
||||
/// [publishTransitions]' back.
|
||||
Set<String> get notified => Set<String>.unmodifiable(_ledger.notified);
|
||||
|
||||
/// True only when the platform itself reported `granted`.
|
||||
bool get canNotify => _permission == NotificationPermissionState.granted;
|
||||
|
||||
/// How many notifications this session has actually posted.
|
||||
int get postedCount => _posted;
|
||||
|
||||
/// Reads the persisted ledger and the platform's real permission facts once.
|
||||
Future<void> load() async {
|
||||
NotificationLedger ledger;
|
||||
try {
|
||||
ledger = decodeNotificationLedger(await store.read());
|
||||
} catch (_) {
|
||||
ledger = const NotificationLedger();
|
||||
}
|
||||
if (_disposed) return;
|
||||
_ledger = ledger;
|
||||
_announced.clear();
|
||||
_permission = notificationStateOf(bridge.environment());
|
||||
_loaded = true;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Re-reads the platform's facts without asking anything, for example after
|
||||
/// the browser's site settings changed and the page regained focus.
|
||||
void refreshPermission() {
|
||||
if (_disposed) return;
|
||||
final next = notificationStateOf(bridge.environment());
|
||||
if (next == _permission) return;
|
||||
_permission = next;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// The one explicit request, only ever called from an operator gesture.
|
||||
///
|
||||
/// A supported, secure page that has not decided is asked, and every other
|
||||
/// state answers with the platform's own word instead of prompting again. The
|
||||
/// request is issued before any await, so it stays inside the gesture that
|
||||
/// triggered it.
|
||||
Future<NotificationPermissionState> requestPermission() async {
|
||||
if (_disposed) return _permission;
|
||||
final environment = bridge.environment();
|
||||
_permission = notificationStateOf(environment);
|
||||
if (_permission != NotificationPermissionState.notRequested) {
|
||||
notifyListeners();
|
||||
return _permission;
|
||||
}
|
||||
// The operator was asked, whatever the answer; persisted without awaiting so
|
||||
// the platform request stays in this gesture's frame.
|
||||
_ledger = _ledger.withAsked(true);
|
||||
unawaited(_persist(_ledger));
|
||||
notifyListeners();
|
||||
|
||||
String answer;
|
||||
try {
|
||||
answer = await bridge.requestPermission();
|
||||
} catch (_) {
|
||||
answer = '';
|
||||
}
|
||||
if (_disposed) return _permission;
|
||||
final word = answer.trim().toLowerCase();
|
||||
_permission = notificationStateOf(
|
||||
NotificationEnvironment(
|
||||
supported: environment.supported,
|
||||
secureContext: environment.secureContext,
|
||||
permission: word == 'granted' || word == 'denied'
|
||||
? word
|
||||
: environment.permission,
|
||||
),
|
||||
);
|
||||
notifyListeners();
|
||||
return _permission;
|
||||
}
|
||||
|
||||
/// Posts one notification per live transition, in order.
|
||||
///
|
||||
/// [qualifying] is [notificationQualifyingKeys] for the *same* snapshot as
|
||||
/// [transitions]: a transition whose run has left the state is stale and
|
||||
/// neither posts nor records anything, then every recorded identity outside
|
||||
/// [qualifying] is forgotten so the next gate can notify. Only the latest
|
||||
/// entry per run+kind in a backlog is announced.
|
||||
///
|
||||
/// A caller that misses the leaving frame still gets the new transition: the
|
||||
/// detector creates one instance per genuine transition, so an identity
|
||||
/// announced earlier this session with a different instance is a new
|
||||
/// occurrence; the same instance, and an identity loaded from the store before
|
||||
/// this session, stay silent.
|
||||
///
|
||||
/// The initial seed raises no transition. A transition the operator dismissed,
|
||||
/// one already recorded and one past [maxNotificationsPerBatch] post nothing.
|
||||
/// Returns how many notifications the platform accepted.
|
||||
int publishTransitions(
|
||||
Iterable<AttentionTransition> transitions, {
|
||||
required Set<String> qualifying,
|
||||
Set<String> dismissed = const {},
|
||||
}) {
|
||||
if (_disposed) return 0;
|
||||
var posted = 0;
|
||||
var changed = false;
|
||||
// A backlog may hold several entries for one run+kind; only the latest one
|
||||
// describes the state that is current, so a coalesced burst notifies once.
|
||||
final latest = <String, AttentionTransition>{};
|
||||
for (final transition in transitions) {
|
||||
latest[notificationIdentity(transition)] = transition;
|
||||
}
|
||||
for (final transition in latest.values) {
|
||||
if (posted >= maxNotificationsPerBatch) break;
|
||||
final identity = notificationIdentity(transition);
|
||||
// Older than the snapshot: the run already left this state.
|
||||
if (!qualifying.contains(identity)) continue;
|
||||
final announced = _announced[identity];
|
||||
if (identical(announced, transition)) continue;
|
||||
if (announced == null && _ledger.hasNotified(identity)) {
|
||||
// Restored from the store before this session: adopt the instance so a
|
||||
// republish is recognized, but do not announce it again.
|
||||
_announced[identity] = transition;
|
||||
continue;
|
||||
}
|
||||
// A new instance for an identity announced this session is a later entry.
|
||||
if (!_ledger.hasNotified(identity)) {
|
||||
_ledger = _ledger.recording(identity);
|
||||
changed = true;
|
||||
}
|
||||
_announced[identity] = transition;
|
||||
if (dismissed.contains(identity)) continue;
|
||||
if (!canNotify) continue;
|
||||
final open = onOpenRun;
|
||||
final message = NotificationMessage(
|
||||
runId: transition.runId,
|
||||
title: notificationAlertTitle(transition.kind),
|
||||
body: notificationAlertBody(transition.entry),
|
||||
tag: identity,
|
||||
);
|
||||
var shown = false;
|
||||
try {
|
||||
shown = bridge.show(
|
||||
message,
|
||||
onTap: open == null ? null : () => open(transition.runId),
|
||||
);
|
||||
} catch (_) {
|
||||
shown = false;
|
||||
}
|
||||
if (shown) {
|
||||
posted++;
|
||||
_posted++;
|
||||
}
|
||||
}
|
||||
final pruned = _ledger.pruning(qualifying);
|
||||
if (!identical(pruned, _ledger)) {
|
||||
_ledger = pruned;
|
||||
changed = true;
|
||||
}
|
||||
if (changed) unawaited(_persist(_ledger));
|
||||
return posted;
|
||||
}
|
||||
|
||||
/// Writes the ledger without ever throwing into the caller's frame, one write
|
||||
/// at a time so their order matches the calls.
|
||||
Future<void> _persist(NotificationLedger ledger) {
|
||||
final encoded = encodeNotificationLedger(ledger);
|
||||
final write = _writes.then((_) async {
|
||||
if (_disposed) return;
|
||||
try {
|
||||
await store.write(encoded);
|
||||
} catch (_) {
|
||||
// The in-memory ledger still applies for this session.
|
||||
}
|
||||
});
|
||||
_writes = write;
|
||||
return write;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/attention_models.dart';
|
||||
import '../domain/attention_transitions.dart';
|
||||
|
||||
/// This client's own storage key for the notification ledger, namespaced like
|
||||
/// the rest of the app. It is deliberately not the legacy web key, so neither
|
||||
/// client rewrites the other's local state on a shared origin.
|
||||
const notificationStorageKey = 'pipelines.next.notify.v1';
|
||||
|
||||
/// The identity of one announced transition: the run and kind, exactly the
|
||||
/// attention surface's own key and the browser's `alertKey`.
|
||||
///
|
||||
/// It is deliberately *not* keyed by a timestamp. A waiting run has no
|
||||
/// `finished_at`, and its creation time never changes, so a marker derived from
|
||||
/// them cannot tell a run's first decision gate from a later one. Instead the
|
||||
/// ledger only holds identities for the runs that are qualifying *right now*:
|
||||
/// [notificationQualifyingKeys] supplies that set, and an identity is forgotten
|
||||
/// as soon as its run leaves the qualifying state (see [NotificationLedger.pruning]).
|
||||
/// The next entry into the same state is therefore a new announcement, exactly
|
||||
/// as in `web/src/notify.js`.
|
||||
String notificationIdentity(AttentionTransition transition) => transition.key;
|
||||
|
||||
/// The `{runId}:{Kind}` identities of the runs currently in a qualifying state,
|
||||
/// built from the same rows the attention surface draws.
|
||||
///
|
||||
/// Dismissals and the local-day window are deliberately ignored: a dismissal
|
||||
/// does not stop a run qualifying, and an old failure is still the same
|
||||
/// announced transition rather than a new one.
|
||||
Set<String> notificationQualifyingKeys(Iterable<JsonMap>? runs) {
|
||||
final keys = <String>{};
|
||||
for (final run in runs ?? const <JsonMap>[]) {
|
||||
final runId = attentionRunId(run['run_id']) ?? attentionRunId(run['id']);
|
||||
final kind = attentionKindForRun(run);
|
||||
if (runId == null || kind == null) continue;
|
||||
keys.add(attentionKey(runId, kind));
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
/// What this client has already announced, plus whether the operator has ever
|
||||
/// been asked.
|
||||
///
|
||||
/// The ledger is pure: it records identities, decides whether one is new and
|
||||
/// drops the ones whose run no longer qualifies. Persistence is the store's job.
|
||||
///
|
||||
/// An identity lives only while its run is in the qualifying state it announced:
|
||||
/// publishing the same list again is idempotent, a reconnect cannot repeat a
|
||||
/// notification, and a genuinely new transition (a second decision gate, or a
|
||||
/// later failure of a new run id) notifies once more because leaving the state
|
||||
/// dropped the old identity. This is the browser's `forget` model; unlike a
|
||||
/// timestamp marker it can tell two decision gates of one run apart.
|
||||
class NotificationLedger {
|
||||
const NotificationLedger({
|
||||
this.notified = const <String>{},
|
||||
this.asked = false,
|
||||
});
|
||||
|
||||
/// The transition identities already recorded, in no particular order.
|
||||
final Set<String> notified;
|
||||
|
||||
/// Whether the operator has ever been asked for permission.
|
||||
final bool asked;
|
||||
|
||||
bool hasNotified(String identity) => notified.contains(identity);
|
||||
|
||||
/// The ledger with [identity] recorded.
|
||||
NotificationLedger recording(String identity) =>
|
||||
NotificationLedger(notified: {...notified, identity}, asked: asked);
|
||||
|
||||
NotificationLedger withAsked(bool value) =>
|
||||
NotificationLedger(notified: notified, asked: value);
|
||||
|
||||
/// The ledger with every identity outside [qualifying] dropped.
|
||||
///
|
||||
/// A run that is no longer failed or waiting has left its announced state, so
|
||||
/// a later entry is a new event and must be able to notify again. Keeping only
|
||||
/// the current qualifying identities also bounds the ledger to the runs the
|
||||
/// surface currently holds instead of growing with every event ever seen.
|
||||
NotificationLedger pruning(Set<String> qualifying) {
|
||||
final kept = notified.where(qualifying.contains).toSet();
|
||||
if (kept.length == notified.length) return this;
|
||||
return NotificationLedger(notified: kept, asked: asked);
|
||||
}
|
||||
}
|
||||
|
||||
/// The one-line JSON the ledger is stored as. The identities are sorted so an
|
||||
/// unchanged ledger always encodes to the same bytes.
|
||||
String encodeNotificationLedger(NotificationLedger ledger) {
|
||||
final identities = ledger.notified.where((id) => id.isNotEmpty).toList()
|
||||
..sort();
|
||||
return jsonEncode({'asked': ledger.asked, 'notified': identities});
|
||||
}
|
||||
|
||||
/// Decodes a stored value into a ledger. Total: blank text, unreadable JSON, a
|
||||
/// non-map, a non-boolean `asked` and non-string members all decode to the
|
||||
/// members that can be read, and a malformed value never throws.
|
||||
///
|
||||
/// A value written by an older build may still contain timestamped identities;
|
||||
/// they simply stop matching [notificationQualifyingKeys] and are dropped on the
|
||||
/// next publish, so no migration step is needed.
|
||||
NotificationLedger decodeNotificationLedger(String? stored) {
|
||||
final text = (stored ?? '').trim();
|
||||
if (text.isEmpty) return const NotificationLedger();
|
||||
dynamic parsed;
|
||||
try {
|
||||
parsed = jsonDecode(text);
|
||||
} catch (_) {
|
||||
return const NotificationLedger();
|
||||
}
|
||||
if (parsed is! Map) return const NotificationLedger();
|
||||
final raw = parsed['notified'];
|
||||
return NotificationLedger(
|
||||
notified: {
|
||||
if (raw is List)
|
||||
for (final value in raw)
|
||||
if (value is String && value.isNotEmpty) value,
|
||||
},
|
||||
asked: parsed['asked'] == true,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
import '../domain/attention_models.dart';
|
||||
|
||||
/// The permission state the notification surface reports.
|
||||
///
|
||||
/// The Dart names are this client's; [wireName] is the browser model's own word
|
||||
/// (`unsupported` | `insecure` | `default` | `granted` | `denied`) so the two
|
||||
/// clients' vocabularies stay traceable. [notRequested] is the Notification
|
||||
/// API's `default`: supported and secure, but the operator has not decided yet.
|
||||
enum NotificationPermissionState {
|
||||
unsupported('unsupported'),
|
||||
needsSecureContext('insecure'),
|
||||
notRequested('default'),
|
||||
granted('granted'),
|
||||
denied('denied');
|
||||
|
||||
const NotificationPermissionState(this.wireName);
|
||||
|
||||
/// The browser model's own word for this state (`web/src/notify.js`).
|
||||
final String wireName;
|
||||
}
|
||||
|
||||
/// The platform's own notification facts, as the bridge answers them.
|
||||
///
|
||||
/// [permission] is the Notification API's raw word; anything unrecognised is
|
||||
/// read as `default` rather than guessed, exactly as the browser does.
|
||||
class NotificationEnvironment {
|
||||
const NotificationEnvironment({
|
||||
required this.supported,
|
||||
required this.secureContext,
|
||||
required this.permission,
|
||||
});
|
||||
|
||||
final bool supported;
|
||||
final bool secureContext;
|
||||
final String permission;
|
||||
}
|
||||
|
||||
/// The permission state for one environment.
|
||||
///
|
||||
/// Only the platform's own answers decide it: an unsupported API and an
|
||||
/// insecure page are reported before the permission word, and `granted` is never
|
||||
/// assumed — a page that has not been granted stays [notRequested].
|
||||
NotificationPermissionState notificationStateOf(
|
||||
NotificationEnvironment environment,
|
||||
) {
|
||||
if (!environment.supported) return NotificationPermissionState.unsupported;
|
||||
if (!environment.secureContext) {
|
||||
return NotificationPermissionState.needsSecureContext;
|
||||
}
|
||||
switch (environment.permission) {
|
||||
case 'granted':
|
||||
return NotificationPermissionState.granted;
|
||||
case 'denied':
|
||||
return NotificationPermissionState.denied;
|
||||
default:
|
||||
return NotificationPermissionState.notRequested;
|
||||
}
|
||||
}
|
||||
|
||||
/// Android's NOTIFICATION_RATIONALE, verbatim (`RunAlerts.kt`, `notify.js`).
|
||||
const notificationRationale =
|
||||
'Pipelines can notify you when a run is waiting for your decision or has '
|
||||
'failed. Without it, those runs still appear in the in-app Needs you '
|
||||
'surface.';
|
||||
|
||||
/// The Settings section heading and the explicit-gesture action label.
|
||||
const notificationSectionTitle = 'Notifications';
|
||||
const notificationRequestLabel = 'Enable notifications';
|
||||
|
||||
/// The honest wording for every state, verbatim from `web/src/notify.js`; each
|
||||
/// says plainly that the in-app `Needs you` surface is the only channel when the
|
||||
/// platform cannot notify.
|
||||
const notificationUnsupportedCopy =
|
||||
'This browser does not support notifications. The in-app Needs you surface '
|
||||
'is the only channel.';
|
||||
const notificationInsecureCopy =
|
||||
'Notifications need a secure context (https or localhost). This page is not '
|
||||
'secure, so the in-app Needs you surface is the only channel.';
|
||||
const notificationGrantedCopy =
|
||||
'Notifications are on. Failed and waiting runs will raise a browser '
|
||||
'notification.';
|
||||
const notificationDeniedCopy =
|
||||
'Notifications are blocked for this site. Allow them in the browser\'s site '
|
||||
'settings to use them; until then the in-app Needs you surface is the only '
|
||||
'channel.';
|
||||
const notificationDefaultCopy =
|
||||
'Notifications are off. Enable them to be told when a run fails or needs '
|
||||
'your decision.';
|
||||
const notificationDefaultAskedCopy =
|
||||
'Notifications are still off. Your browser did not grant permission when '
|
||||
'asked; you can ask again, or the in-app Needs you surface remains the only '
|
||||
'channel.';
|
||||
|
||||
/// The total permission view for the Settings tile.
|
||||
///
|
||||
/// Only a supported, secure page whose permission is still `default` offers the
|
||||
/// request control, and [asked] only changes the honest wording — nothing here
|
||||
/// asks for permission on its own.
|
||||
class NotificationPermissionView {
|
||||
const NotificationPermissionView({
|
||||
required this.state,
|
||||
required this.body,
|
||||
required this.canRequest,
|
||||
required this.actionLabel,
|
||||
required this.asked,
|
||||
});
|
||||
|
||||
final NotificationPermissionState state;
|
||||
final String body;
|
||||
final bool canRequest;
|
||||
final String? actionLabel;
|
||||
final bool asked;
|
||||
}
|
||||
|
||||
/// The view for one state, with the browser's own copy for it.
|
||||
NotificationPermissionView notificationPermissionView(
|
||||
NotificationPermissionState state, {
|
||||
bool asked = false,
|
||||
}) {
|
||||
final canRequest = state == NotificationPermissionState.notRequested;
|
||||
final body = switch (state) {
|
||||
NotificationPermissionState.unsupported => notificationUnsupportedCopy,
|
||||
NotificationPermissionState.needsSecureContext => notificationInsecureCopy,
|
||||
NotificationPermissionState.granted => notificationGrantedCopy,
|
||||
NotificationPermissionState.denied => notificationDeniedCopy,
|
||||
NotificationPermissionState.notRequested =>
|
||||
asked ? notificationDefaultAskedCopy : notificationDefaultCopy,
|
||||
};
|
||||
return NotificationPermissionView(
|
||||
state: state,
|
||||
body: body,
|
||||
canRequest: canRequest,
|
||||
actionLabel: canRequest ? notificationRequestLabel : null,
|
||||
asked: asked,
|
||||
);
|
||||
}
|
||||
|
||||
/// The short headline one kind shows; the browser's `alertTitle` verbatim.
|
||||
String notificationAlertTitle(AttentionKind kind) => switch (kind) {
|
||||
AttentionKind.decision => 'A run needs your decision',
|
||||
AttentionKind.failed => 'A run failed',
|
||||
};
|
||||
|
||||
/// The line naming the run: its label, then the pipeline it belongs to.
|
||||
///
|
||||
/// The words are the entry's own — a blank or equal pipeline is never repeated,
|
||||
/// so there is no trailing separator and nothing is invented.
|
||||
String notificationAlertBody(AttentionEntry entry) {
|
||||
final pipeline = entry.pipeline;
|
||||
final label = entry.label;
|
||||
if (pipeline.isEmpty || pipeline == label) return label;
|
||||
return '$label \u00b7 $pipeline';
|
||||
}
|
||||
|
||||
/// One notification the platform is asked to show: the entry's own words, plus
|
||||
/// the stable identity used as the browser's coalescing tag.
|
||||
class NotificationMessage {
|
||||
const NotificationMessage({
|
||||
required this.runId,
|
||||
required this.title,
|
||||
required this.body,
|
||||
required this.tag,
|
||||
});
|
||||
|
||||
final int runId;
|
||||
final String title;
|
||||
final String body;
|
||||
final String tag;
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'notification_ledger.dart';
|
||||
|
||||
/// The persistence seam for the notification ledger.
|
||||
///
|
||||
/// The controller only ever hands over the exact string produced by
|
||||
/// [encodeNotificationLedger], so a store cannot invent a different format.
|
||||
/// Both directions are allowed to fail: a caller treats a null read as "nothing
|
||||
/// recorded yet" and a false write as "this session only".
|
||||
abstract interface class NotificationStore {
|
||||
Future<String?> read();
|
||||
|
||||
Future<bool> write(String value);
|
||||
}
|
||||
|
||||
/// `shared_preferences` storage under the ledger's own key.
|
||||
///
|
||||
/// Reads and writes are total: an unavailable plugin, a disabled store or a full
|
||||
/// disk returns null/false instead of throwing into the caller's frame. Only the
|
||||
/// documented [notificationStorageKey] is touched, never the attention key or the
|
||||
/// legacy web key.
|
||||
class SharedPreferencesNotificationStore implements NotificationStore {
|
||||
const SharedPreferencesNotificationStore();
|
||||
|
||||
Future<SharedPreferences?> _preferences() async {
|
||||
try {
|
||||
return await SharedPreferences.getInstance();
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<String?> read() async {
|
||||
final preferences = await _preferences();
|
||||
if (preferences == null) return null;
|
||||
try {
|
||||
return preferences.getString(notificationStorageKey);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> write(String value) async {
|
||||
final preferences = await _preferences();
|
||||
if (preferences == null) return false;
|
||||
try {
|
||||
return await preferences.setString(notificationStorageKey, value);
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An in-memory store for tests and isolated fixtures.
|
||||
///
|
||||
/// It never touches the platform store, so a probe or widget test cannot mutate
|
||||
/// a real operator's persisted ledger. [failReads] and [failWrites] reproduce an
|
||||
/// unavailable store without throwing.
|
||||
class MemoryNotificationStore implements NotificationStore {
|
||||
MemoryNotificationStore({this.stored});
|
||||
|
||||
String? stored;
|
||||
bool failReads = false;
|
||||
bool failWrites = false;
|
||||
int writes = 0;
|
||||
|
||||
@override
|
||||
Future<String?> read() async {
|
||||
if (failReads) throw StateError('notification store unavailable');
|
||||
return stored;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> write(String value) async {
|
||||
writes++;
|
||||
if (failWrites) throw StateError('notification store is read-only');
|
||||
stored = value;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../runs/domain/run_events.dart';
|
||||
import '../domain/attention_models.dart';
|
||||
import '../domain/attention_transitions.dart';
|
||||
import 'attention_store.dart';
|
||||
|
||||
/// The live `Needs you` state behind the Runs-list bell.
|
||||
///
|
||||
/// Entries are derived from the same `list_runs` rows the Runs destination
|
||||
/// already holds: no poll and no extra request is made here. Pushed
|
||||
/// `run_event` frames are folded with the runs feature's own [foldRunEvent], so
|
||||
/// a run that becomes failed or waiting while the screen is open appears without
|
||||
/// a reload, exactly as the browser's attention surface does.
|
||||
///
|
||||
/// Dismissals are kept in memory for immediate feedback and written through
|
||||
/// [AttentionStore] without blocking the caller. A failed read or write leaves
|
||||
/// the in-memory set in force for this session; neither direction can throw into
|
||||
/// the UI.
|
||||
class AttentionController extends ChangeNotifier {
|
||||
AttentionController({required this.store, DateTime Function()? now})
|
||||
: _now = now ?? DateTime.now;
|
||||
|
||||
final AttentionStore store;
|
||||
final DateTime Function() _now;
|
||||
final AttentionTransitionDetector _detector = AttentionTransitionDetector();
|
||||
final List<AttentionTransition> _transitions = [];
|
||||
|
||||
List<JsonMap> _rows = const [];
|
||||
Set<String> _dismissed = <String>{};
|
||||
bool _loaded = false;
|
||||
bool _dirty = false;
|
||||
bool _disposed = false;
|
||||
|
||||
/// The summaries the surface currently draws from.
|
||||
List<JsonMap> get rows => _rows;
|
||||
|
||||
/// The identities the operator has dismissed in this session or storage.
|
||||
Set<String> get dismissed => {..._dismissed};
|
||||
|
||||
/// True once the persisted set has been read (successfully or not).
|
||||
bool get loaded => _loaded;
|
||||
|
||||
/// Transition facts raised by pushed frames, kept for notification wiring.
|
||||
List<AttentionTransition> get transitions =>
|
||||
List<AttentionTransition>.unmodifiable(_transitions);
|
||||
|
||||
/// Today's ordered rows, minus explicitly dismissed identities.
|
||||
///
|
||||
/// The local-day cutoff is the model's [startOfLocalDay]: yesterday's failures
|
||||
/// are history, not a badge that follows every device for ever. A caller that
|
||||
/// needs a different window should use [entriesSince] rather than a second
|
||||
/// ordering implementation.
|
||||
List<AttentionEntry> get entries =>
|
||||
entriesSince(startOfLocalDay(now: _now()));
|
||||
|
||||
/// The ordered rows within an explicit [since] window.
|
||||
List<AttentionEntry> entriesSince(DateTime? since) =>
|
||||
attentionEntries(_rows, dismissed: _dismissed, since: since);
|
||||
|
||||
/// Reads the persisted dismissals once. Unreadable storage means "none".
|
||||
Future<void> load() async {
|
||||
Set<String> stored;
|
||||
try {
|
||||
stored = decodeAttentionDismissals(await store.read());
|
||||
} catch (_) {
|
||||
stored = <String>{};
|
||||
}
|
||||
if (_disposed) return;
|
||||
_loaded = true;
|
||||
// A dismissal made while the read was in flight must not be reverted by the
|
||||
// older stored value; the in-memory set is the operator's latest intent.
|
||||
if (!_dirty) _dismissed = stored;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Replaces the drawn rows with an authoritative read.
|
||||
///
|
||||
/// The transition detector is seeded rather than observed, so the initial list
|
||||
/// and a reconnect cannot announce work that was already there. With
|
||||
/// [reconnect] the status baseline is dropped first, while emitted keys are
|
||||
/// retained by the model so the gap cannot re-notify.
|
||||
void seedRows(Iterable<JsonMap> rows, {bool reconnect = false}) {
|
||||
if (_disposed) return;
|
||||
_rows = List<JsonMap>.unmodifiable(rows);
|
||||
if (reconnect) {
|
||||
_detector.reseed(_rows);
|
||||
} else {
|
||||
_detector.seed(_rows);
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Called when the shared socket drops, before the next [seedRows].
|
||||
void resetForReconnect() {
|
||||
if (_disposed) return;
|
||||
_detector.resetForReconnect();
|
||||
}
|
||||
|
||||
/// Folds one pushed run summary into the drawn entries.
|
||||
///
|
||||
/// A frame that cannot build a complete summary asks the Runs controller for
|
||||
/// its usual resync; this surface never issues a request of its own. The
|
||||
/// transition (if any) is recorded for the notification wiring but a dismissed
|
||||
/// identity never emits.
|
||||
void observeFrame(JsonMap frame) {
|
||||
if (_disposed) return;
|
||||
final transition = _detector.observe(frame, dismissed: _dismissed);
|
||||
if (transition != null) _transitions.add(transition);
|
||||
final folded = foldRunEvent(_rows, frame);
|
||||
final changed = !folded.needsResync && !identical(folded.runs, _rows);
|
||||
if (changed) {
|
||||
_rows = List<JsonMap>.unmodifiable(
|
||||
_withAttentionText(folded.runs, frame),
|
||||
);
|
||||
}
|
||||
if (changed || transition != null) notifyListeners();
|
||||
}
|
||||
|
||||
/// The runs fold deliberately carries only lifecycle fields, but the attention
|
||||
/// row's wording comes from `title`/`name`/`diagnostic`. Keep those summary
|
||||
/// fields from the same push so a failure announces its real reason without
|
||||
/// waiting for the next list read. Only non-blank pushed values win; the source
|
||||
/// or other unknown fields are left untouched.
|
||||
List<JsonMap> _withAttentionText(List<JsonMap> rows, JsonMap frame) {
|
||||
final id = frame['run_id'];
|
||||
final index = rows.indexWhere((row) => row['id'] == id);
|
||||
if (index < 0) return rows;
|
||||
final current = rows[index];
|
||||
final merged = <String, dynamic>{...current};
|
||||
var changed = false;
|
||||
for (final key in const ['title', 'name', 'diagnostic']) {
|
||||
final value = frame[key];
|
||||
if ('${value ?? ''}'.trim().isEmpty || value == current[key]) continue;
|
||||
merged[key] = value;
|
||||
changed = true;
|
||||
}
|
||||
if (!changed) return rows;
|
||||
final next = [...rows];
|
||||
next[index] = merged;
|
||||
return next;
|
||||
}
|
||||
|
||||
/// Dismisses exactly one identity and persists the new set.
|
||||
///
|
||||
/// The in-memory set and the bell update before the store is touched, so a
|
||||
/// slow or failed write never blocks the sheet. The returned future reports
|
||||
/// whether the write succeeded; callers that do not need it may ignore it.
|
||||
Future<bool> dismiss(AttentionEntry entry) =>
|
||||
_commit(attentionDismiss(_dismissed, entry.key));
|
||||
|
||||
/// Applies only the identities captured when the sheet opened.
|
||||
Future<bool> clearAll(Iterable<AttentionEntry> snapshot) =>
|
||||
_commit(attentionDismissAll(_dismissed, snapshot));
|
||||
|
||||
Future<bool> _commit(Set<String> next) async {
|
||||
final unchanged =
|
||||
next.length == _dismissed.length && next.containsAll(_dismissed);
|
||||
if (unchanged) return true;
|
||||
_dismissed = next;
|
||||
_dirty = true;
|
||||
notifyListeners();
|
||||
if (_disposed) return false;
|
||||
try {
|
||||
return await store.write(encodeAttentionDismissals(_dismissed));
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../domain/attention_models.dart';
|
||||
|
||||
/// The persistence seam for the `Needs you` dismissal identities.
|
||||
///
|
||||
/// The controller only ever hands over the exact string produced by
|
||||
/// [encodeAttentionDismissals], so a store cannot invent a different identity
|
||||
/// format. Both directions are allowed to fail: a caller treats a null read as
|
||||
/// "nothing dismissed yet" and a false write as "this session only".
|
||||
abstract interface class AttentionStore {
|
||||
Future<String?> read();
|
||||
|
||||
Future<bool> write(String value);
|
||||
}
|
||||
|
||||
/// `shared_preferences` storage under the attention model's own key.
|
||||
///
|
||||
/// Reads and writes are total: an unavailable plugin, a disabled store or a full
|
||||
/// disk returns null/false instead of throwing into the caller's frame. Only the
|
||||
/// documented [attentionStorageKey] is touched, never the legacy web key.
|
||||
class SharedPreferencesAttentionStore implements AttentionStore {
|
||||
const SharedPreferencesAttentionStore();
|
||||
|
||||
Future<SharedPreferences?> _preferences() async {
|
||||
try {
|
||||
return await SharedPreferences.getInstance();
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<String?> read() async {
|
||||
final preferences = await _preferences();
|
||||
if (preferences == null) return null;
|
||||
try {
|
||||
return preferences.getString(attentionStorageKey);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> write(String value) async {
|
||||
final preferences = await _preferences();
|
||||
if (preferences == null) return false;
|
||||
try {
|
||||
return await preferences.setString(attentionStorageKey, value);
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An in-memory store for tests and isolated fixtures.
|
||||
///
|
||||
/// It never touches the platform store, so a probe or widget test cannot mutate
|
||||
/// a real operator's persisted dismissals. [failReads] and [failWrites] reproduce
|
||||
/// an unavailable store without throwing.
|
||||
class MemoryAttentionStore implements AttentionStore {
|
||||
MemoryAttentionStore({this.stored});
|
||||
|
||||
String? stored;
|
||||
bool failReads = false;
|
||||
bool failWrites = false;
|
||||
int writes = 0;
|
||||
|
||||
@override
|
||||
Future<String?> read() async {
|
||||
if (failReads) throw StateError('attention store unavailable');
|
||||
return stored;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> write(String value) async {
|
||||
writes++;
|
||||
if (failWrites) throw StateError('attention store is read-only');
|
||||
stored = value;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/attention_models.dart';
|
||||
import '../runtime/attention_controller.dart';
|
||||
import '../runtime/attention_store.dart';
|
||||
import 'needs_you_bell.dart';
|
||||
|
||||
/// The `Needs you` bell as it appears in the Runs list heading.
|
||||
///
|
||||
/// It owns the live attention state for this destination: [rows] are the
|
||||
/// already-loaded `list_runs` summaries and [frames] is the shared gateway's
|
||||
/// unsolicited stream, so it never polls or issues an attention request. The
|
||||
/// bell has no built-in host choice; the ambient app host (or [cupertino] in a
|
||||
/// fixture) selects the native Material or Cupertino action and sheet.
|
||||
class NeedsYouRunsHeading extends StatefulWidget {
|
||||
const NeedsYouRunsHeading({
|
||||
super.key,
|
||||
required this.rows,
|
||||
required this.frames,
|
||||
required this.onOpen,
|
||||
this.syncToken = 0,
|
||||
this.store = const SharedPreferencesAttentionStore(),
|
||||
this.now,
|
||||
this.cupertino,
|
||||
});
|
||||
|
||||
/// The run summaries the Runs destination already holds.
|
||||
final List<JsonMap> rows;
|
||||
|
||||
/// The shared gateway's frames; only `run_event` envelopes are folded.
|
||||
final Stream<JsonMap> frames;
|
||||
|
||||
/// Opens an entry's run. A Failed entry is dismissed by the bell first.
|
||||
final ValueChanged<AttentionEntry> onOpen;
|
||||
|
||||
/// Advances when the shared socket is replaced. The detector rebaselines
|
||||
/// without replaying a transition that happened during the gap.
|
||||
final int syncToken;
|
||||
|
||||
final AttentionStore store;
|
||||
|
||||
/// Injected clock for deterministic local-day windows.
|
||||
final DateTime Function()? now;
|
||||
|
||||
/// Forces the native host in tests and fixtures.
|
||||
final bool? cupertino;
|
||||
|
||||
@override
|
||||
State<NeedsYouRunsHeading> createState() => _NeedsYouRunsHeadingState();
|
||||
}
|
||||
|
||||
class _NeedsYouRunsHeadingState extends State<NeedsYouRunsHeading> {
|
||||
late final AttentionController _attention = AttentionController(
|
||||
store: widget.store,
|
||||
now: widget.now,
|
||||
);
|
||||
StreamSubscription<JsonMap>? _frames;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_attention.seedRows(widget.rows);
|
||||
unawaited(_attention.load());
|
||||
_listen();
|
||||
}
|
||||
|
||||
void _listen() {
|
||||
_frames = widget.frames
|
||||
.where((frame) => frame['type'] == 'run_event')
|
||||
.listen(_attention.observeFrame);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant NeedsYouRunsHeading oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (!identical(oldWidget.frames, widget.frames)) {
|
||||
unawaited(_frames?.cancel());
|
||||
_frames = null;
|
||||
_listen();
|
||||
}
|
||||
if (oldWidget.syncToken != widget.syncToken) {
|
||||
_attention.resetForReconnect();
|
||||
_attention.seedRows(widget.rows, reconnect: true);
|
||||
return;
|
||||
}
|
||||
if (!identical(oldWidget.rows, widget.rows)) {
|
||||
_attention.seedRows(widget.rows);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
unawaited(_frames?.cancel());
|
||||
_attention.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AnimatedBuilder(
|
||||
animation: _attention,
|
||||
builder: (context, _) => NeedsYouBell(
|
||||
entries: _attention.entries,
|
||||
cupertino: widget.cupertino,
|
||||
onOpen: widget.onOpen,
|
||||
onDismiss: (entry) {
|
||||
unawaited(_attention.dismiss(entry));
|
||||
},
|
||||
onClearAll: (snapshot) {
|
||||
unawaited(_attention.clearAll(snapshot));
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import '../notify/notification_models.dart';
|
||||
|
||||
/// The permission tile's root, so a caller can find it whichever host draws it.
|
||||
const notificationTileKey = ValueKey<String>('notification-permission-tile');
|
||||
|
||||
/// The explicit-gesture Enable action, present only when a request is possible.
|
||||
const notificationEnableKey = ValueKey<String>(
|
||||
'notification-permission-enable',
|
||||
);
|
||||
|
||||
/// The honest state line, which says plainly when the in-app surface is the
|
||||
/// only channel.
|
||||
const notificationStateKey = ValueKey<String>('notification-permission-state');
|
||||
|
||||
/// The reusable Notifications permission tile for Settings.
|
||||
///
|
||||
/// It renders the platform's own [state] with the browser's own copy, shows the
|
||||
/// Android rationale verbatim, and offers the [notificationRequestLabel] action
|
||||
/// only while a request is still possible. Nothing here asks for permission on
|
||||
/// its own — [onRequest] is the caller's explicit-gesture handler, and the tile
|
||||
/// never guesses a grant.
|
||||
///
|
||||
/// The caller owns the surrounding section/card and passes the live state; the
|
||||
/// tile reads no store, bridge or clock.
|
||||
class NotificationPermissionTile extends StatelessWidget {
|
||||
const NotificationPermissionTile({
|
||||
super.key,
|
||||
required this.state,
|
||||
this.asked = false,
|
||||
this.onRequest,
|
||||
this.cupertino,
|
||||
});
|
||||
|
||||
final NotificationPermissionState state;
|
||||
|
||||
/// Whether the operator has already been asked; only changes the wording.
|
||||
final bool asked;
|
||||
|
||||
/// The explicit-gesture handler. Absent means no action is drawn even when a
|
||||
/// request would be possible.
|
||||
final VoidCallback? onRequest;
|
||||
|
||||
/// Forces the native host in tests and fixtures; otherwise the ambient
|
||||
/// [usesCupertinoHost] decides.
|
||||
final bool? cupertino;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final view = notificationPermissionView(state, asked: asked);
|
||||
final native = cupertino ?? usesCupertinoHost(context);
|
||||
final action = view.canRequest && onRequest != null
|
||||
? _action(native, view.actionLabel!, onRequest!)
|
||||
: null;
|
||||
final bodyStyle = native
|
||||
? CupertinoTheme.of(context).textTheme.textStyle.copyWith(
|
||||
color: CupertinoColors.secondaryLabel.resolveFrom(context),
|
||||
)
|
||||
: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
native
|
||||
? CupertinoListTile(
|
||||
key: notificationTileKey,
|
||||
leading: const Icon(CupertinoIcons.bell),
|
||||
title: const Text(notificationSectionTitle),
|
||||
)
|
||||
: ListTile(
|
||||
key: notificationTileKey,
|
||||
leading: const Icon(Icons.notifications_outlined),
|
||||
title: const Text(notificationSectionTitle),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(notificationRationale, style: bodyStyle),
|
||||
const SizedBox(height: 8),
|
||||
Semantics(
|
||||
liveRegion: true,
|
||||
child: Text(
|
||||
view.body,
|
||||
key: notificationStateKey,
|
||||
style: bodyStyle,
|
||||
),
|
||||
),
|
||||
// The action sits on its own row, as the browser's settings
|
||||
// section does: a native button in a row's trailing slot would
|
||||
// squeeze the section title to one character per line at large
|
||||
// text, and its label is too long to share the row.
|
||||
if (action != null) ...[
|
||||
const SizedBox(height: 8),
|
||||
Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: action,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _action(bool native, String label, VoidCallback onRequest) {
|
||||
if (native) {
|
||||
return CupertinoButton(
|
||||
key: notificationEnableKey,
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: onRequest,
|
||||
child: Text(label),
|
||||
);
|
||||
}
|
||||
return TextButton(
|
||||
key: notificationEnableKey,
|
||||
onPressed: onRequest,
|
||||
child: Text(label),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Host-native typography and colour for the approval and question cards.
|
||||
///
|
||||
/// The cards share one hierarchy: the card title uses the host's title style,
|
||||
/// field/answer labels sit visibly below it, and recorded prose uses the body
|
||||
/// style. Keeping the styles here stops each card file from inventing its own
|
||||
/// size and colour; everything still comes from the active Material/Cupertino
|
||||
/// theme, so light, dark and text scaling follow the host.
|
||||
TextStyle? chatCardTitleStyle(BuildContext context, bool cupertino) =>
|
||||
cupertino
|
||||
? CupertinoTheme.of(context).textTheme.navTitleTextStyle
|
||||
: Theme.of(context).textTheme.titleMedium;
|
||||
|
||||
TextStyle? chatCardBodyStyle(BuildContext context, bool cupertino) => cupertino
|
||||
? CupertinoTheme.of(context).textTheme.textStyle
|
||||
: Theme.of(context).textTheme.bodyMedium;
|
||||
|
||||
/// A field or recorded-answer label. Under Cupertino the system tab-label style
|
||||
/// (the same subordinate style the rest of the app uses for secondary copy)
|
||||
/// keeps labels from reading as extra headings; Material keeps `titleSmall`.
|
||||
TextStyle? chatCardLabelStyle(BuildContext context, bool cupertino) => cupertino
|
||||
? CupertinoTheme.of(
|
||||
context,
|
||||
).textTheme.tabLabelTextStyle.copyWith(color: chatCardSecondaryColor(context, true))
|
||||
: Theme.of(context).textTheme.titleSmall;
|
||||
|
||||
/// Body text that supports a control, such as a field description.
|
||||
TextStyle? chatCardSecondaryStyle(BuildContext context, bool cupertino) =>
|
||||
(chatCardBodyStyle(context, cupertino) ?? const TextStyle()).copyWith(
|
||||
color: chatCardSecondaryColor(context, cupertino),
|
||||
);
|
||||
|
||||
Color chatCardSecondaryColor(BuildContext context, bool cupertino) => cupertino
|
||||
? CupertinoColors.secondaryLabel.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.onSurfaceVariant;
|
||||
|
||||
Color chatCardErrorColor(BuildContext context, bool cupertino) => cupertino
|
||||
? CupertinoColors.systemRed.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.error;
|
||||
|
||||
/// The amber risk hue: the host's warning role, never a bespoke palette.
|
||||
Color chatCardWarningColor(BuildContext context, bool cupertino) => cupertino
|
||||
? CupertinoColors.systemOrange.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.tertiary;
|
||||
|
||||
/// A quiet inset surface for resource blocks and risk panels.
|
||||
Color chatCardFillColor(BuildContext context, bool cupertino) => cupertino
|
||||
? CupertinoColors.secondarySystemFill.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.surfaceContainerHighest;
|
||||
|
||||
Color chatCardWarningFillColor(BuildContext context, bool cupertino) =>
|
||||
cupertino
|
||||
? CupertinoColors.secondarySystemFill.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.tertiaryContainer;
|
||||
@@ -0,0 +1,233 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../ui/sessions/chat_adaptive.dart';
|
||||
import '../ui/transcript/native_disclosure.dart';
|
||||
import 'chat_card_styles.dart';
|
||||
import 'chat_permission_card_model.dart';
|
||||
|
||||
/// One recorded permission request as a native card.
|
||||
///
|
||||
/// The headline is the request's action (or its recorded outcome), the status
|
||||
/// line is the server's own note where present, and the once/always/reject
|
||||
/// controls appear only while the request is still open. Every server string is
|
||||
/// rendered as text, never parsed as markup.
|
||||
class ChatPermissionCard extends StatelessWidget {
|
||||
const ChatPermissionCard({
|
||||
super.key,
|
||||
required this.card,
|
||||
required this.onDecision,
|
||||
this.error,
|
||||
});
|
||||
|
||||
final ChatPermissionCardData card;
|
||||
final Future<void> Function(String decision) onDecision;
|
||||
final String? error;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) =>
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino
|
||||
? _cupertino(context)
|
||||
: _material(context);
|
||||
|
||||
Widget _body(BuildContext context, {required bool cupertino}) {
|
||||
final body = Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.only(end: 12),
|
||||
child: Icon(
|
||||
cupertino
|
||||
? CupertinoIcons.exclamationmark_shield
|
||||
: Icons.shield_outlined,
|
||||
color: chatCardWarningColor(context, cupertino),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
card.headline,
|
||||
style: chatCardTitleStyle(context, cupertino),
|
||||
),
|
||||
Text(
|
||||
card.statusLine,
|
||||
style: chatCardSecondaryStyle(context, cupertino),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (card.resourceText.isNotEmpty) ...[
|
||||
const SizedBox(height: 12),
|
||||
DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: chatCardFillColor(context, cupertino),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: Text(
|
||||
card.resourceText,
|
||||
maxLines: chatApprovalMaxResourceLines,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (card.resources.join('\n') != card.resourceText)
|
||||
NativeDisclosure(
|
||||
label: 'Show full request',
|
||||
childBuilder: (context) =>
|
||||
SelectableText(card.resources.join('\n')),
|
||||
),
|
||||
],
|
||||
if (card.showRisk && card.risk.trim().isNotEmpty) ...[
|
||||
const SizedBox(height: 12),
|
||||
_risk(context, cupertino),
|
||||
],
|
||||
if (error != null && error!.trim().isNotEmpty) ...[
|
||||
const SizedBox(height: 12),
|
||||
Semantics(
|
||||
liveRegion: true,
|
||||
child: Text(
|
||||
error!,
|
||||
style: chatCardBodyStyle(
|
||||
context,
|
||||
cupertino,
|
||||
)?.copyWith(color: chatCardErrorColor(context, cupertino)),
|
||||
),
|
||||
),
|
||||
],
|
||||
if (card.actionable) ...[
|
||||
const SizedBox(height: 12),
|
||||
_controls(context, cupertino),
|
||||
],
|
||||
],
|
||||
);
|
||||
return cupertino
|
||||
? DefaultTextStyle.merge(
|
||||
style: CupertinoTheme.of(context).textTheme.textStyle,
|
||||
child: body,
|
||||
)
|
||||
: body;
|
||||
}
|
||||
|
||||
Widget _risk(BuildContext context, bool cupertino) {
|
||||
final tint = chatCardWarningColor(context, cupertino);
|
||||
return DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: chatCardWarningFillColor(context, cupertino),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
cupertino
|
||||
? CupertinoIcons.exclamationmark_shield
|
||||
: Icons.shield_outlined,
|
||||
size: 16,
|
||||
color: tint,
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Expanded(
|
||||
child: Text(
|
||||
chatRiskReviewLabel,
|
||||
style: chatCardLabelStyle(
|
||||
context,
|
||||
cupertino,
|
||||
)?.copyWith(color: tint),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(card.risk, style: chatCardBodyStyle(context, cupertino)),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _controls(BuildContext context, bool cupertino) {
|
||||
final always = card.alwaysLabel;
|
||||
if (cupertino) {
|
||||
return Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
CupertinoButton.filled(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
onPressed: () => onDecision(chatDecisionOnce),
|
||||
child: const Text(chatApprovalOnceLabel),
|
||||
),
|
||||
CupertinoButton(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
onPressed: () => onDecision(chatDecisionAlways),
|
||||
child: Text(always),
|
||||
),
|
||||
CupertinoButton(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
onPressed: () => onDecision(chatDecisionReject),
|
||||
child: Text(
|
||||
chatApprovalRejectLabel,
|
||||
style: TextStyle(
|
||||
color: CupertinoColors.systemRed.resolveFrom(context),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
FilledButton(
|
||||
onPressed: () => onDecision(chatDecisionOnce),
|
||||
child: const Text(chatApprovalOnceLabel),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => onDecision(chatDecisionAlways),
|
||||
child: Text(always),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => onDecision(chatDecisionReject),
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
child: const Text(chatApprovalRejectLabel),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _material(BuildContext context) => Card(
|
||||
// Consecutive cards must read as separate surfaces; the row itself adds only
|
||||
// the horizontal inset.
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: _body(context, cupertino: false),
|
||||
),
|
||||
);
|
||||
|
||||
Widget _cupertino(BuildContext context) => CupertinoListSection.insetGrouped(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: _body(context, cupertino: true),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
/// Permission approval cards: the model behind one `chat_permission` frame.
|
||||
///
|
||||
/// The web's `approvalCard`/`permissionRiskText`/`decisionLabel` are the target.
|
||||
/// A card is derived from the server frame plus the operator's local answer, so
|
||||
/// a server resolution always outranks a stale local decision.
|
||||
library;
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
const chatDecisionOnce = 'once';
|
||||
const chatDecisionAlways = 'always';
|
||||
const chatDecisionReject = 'reject';
|
||||
const chatDecisions = [
|
||||
chatDecisionOnce,
|
||||
chatDecisionAlways,
|
||||
chatDecisionReject,
|
||||
];
|
||||
|
||||
const chatApprovalBlankAction = 'tool call';
|
||||
const chatApprovalHeadlineResolved = 'Already resolved';
|
||||
const chatApprovalStatusPending = 'Waiting for your response';
|
||||
const chatApprovalStatusAnswered = 'Waiting for the agent to continue…';
|
||||
const chatApprovalStatusResolved =
|
||||
'Another client already answered this request.';
|
||||
const chatRiskReviewLabel = 'RISK REVIEW';
|
||||
const chatApprovalOnceLabel = 'Allow once';
|
||||
const chatApprovalAlwaysLabel = 'Always allow';
|
||||
const chatApprovalRejectLabel = 'Reject';
|
||||
const chatApprovalMaxResourceLines = 6;
|
||||
|
||||
/// How one approval request stands. `stale` is a server-resolved request whose
|
||||
/// recorded decision is blank: the card can say only that it is already over.
|
||||
enum ChatPermissionState { pending, answered, resolved, stale }
|
||||
|
||||
String chatDecisionLabel(String decision) => switch (decision) {
|
||||
chatDecisionOnce => 'Allowed once',
|
||||
chatDecisionAlways => 'Always allowed',
|
||||
chatDecisionReject => 'Rejected',
|
||||
_ => 'Resolved',
|
||||
};
|
||||
|
||||
/// The amber risk sentence. The server's own summary wins; otherwise name the
|
||||
/// action so the panel is never blank.
|
||||
String chatPermissionRiskText(JsonMap permission) {
|
||||
final message = _text(permission['message']);
|
||||
if (message.isNotEmpty) return message;
|
||||
final action = _text(permission['action']);
|
||||
final what = action.isEmpty ? 'a tool call' : action;
|
||||
return 'The agent is asking to run $what; review the request before allowing.';
|
||||
}
|
||||
|
||||
/// The request's non-blank resources, in the server's own order.
|
||||
///
|
||||
/// A resource's recorded text is kept verbatim: the web filters blanks but never
|
||||
/// trims, so an indented command or YAML block keeps its indentation in both the
|
||||
/// six-line view and the expanded request.
|
||||
List<String> chatPermissionResources(JsonMap permission) {
|
||||
final resources = permission['resources'];
|
||||
if (resources is! List) return const [];
|
||||
return [
|
||||
for (final resource in resources)
|
||||
if (_text(resource).isNotEmpty) '${resource ?? ''}',
|
||||
];
|
||||
}
|
||||
|
||||
/// The resource block capped at six lines, an embedded newline counting as a
|
||||
/// line. The full list stays available on the card for expansion.
|
||||
String chatPermissionResourceText(JsonMap permission) {
|
||||
final lines = [
|
||||
for (final resource in chatPermissionResources(permission))
|
||||
...resource.split('\n'),
|
||||
];
|
||||
if (lines.length <= chatApprovalMaxResourceLines) return lines.join('\n');
|
||||
final kept = lines.take(chatApprovalMaxResourceLines).toList();
|
||||
kept[kept.length - 1] = '${kept.last}…';
|
||||
return kept.join('\n');
|
||||
}
|
||||
|
||||
/// One rendered request. [resources] keeps every recorded entry; [resourceText]
|
||||
/// is only the six-line view.
|
||||
class ChatPermissionCardData {
|
||||
const ChatPermissionCardData({
|
||||
required this.requestId,
|
||||
required this.resources,
|
||||
required this.resourceText,
|
||||
required this.risk,
|
||||
required this.state,
|
||||
required this.decision,
|
||||
required this.note,
|
||||
required this.alwaysLabel,
|
||||
required this.headline,
|
||||
required this.statusLine,
|
||||
});
|
||||
|
||||
final String requestId;
|
||||
final List<String> resources;
|
||||
final String resourceText;
|
||||
final String risk;
|
||||
final ChatPermissionState state;
|
||||
final String decision;
|
||||
final String note;
|
||||
final String alwaysLabel;
|
||||
final String headline;
|
||||
final String statusLine;
|
||||
|
||||
bool get actionable => state == ChatPermissionState.pending;
|
||||
bool get showRisk =>
|
||||
state == ChatPermissionState.pending ||
|
||||
(state == ChatPermissionState.answered && decision == chatDecisionReject);
|
||||
}
|
||||
|
||||
/// The card for [permission], or null when there is no request to show.
|
||||
ChatPermissionCardData? chatPermissionCard(
|
||||
JsonMap? permission, [
|
||||
String answer = '',
|
||||
]) {
|
||||
if (permission == null) return null;
|
||||
final requestId = _text(permission['request_id']);
|
||||
if (requestId.isEmpty) return null;
|
||||
final resolvedByServer =
|
||||
permission['resolved'] == true ||
|
||||
_text(permission['decision']).isNotEmpty;
|
||||
final answerText = answer.trim();
|
||||
final state = resolvedByServer
|
||||
? (_text(permission['decision']).isEmpty
|
||||
? ChatPermissionState.stale
|
||||
: ChatPermissionState.resolved)
|
||||
: answerText.isNotEmpty
|
||||
? ChatPermissionState.answered
|
||||
: ChatPermissionState.pending;
|
||||
final decision = resolvedByServer
|
||||
? _text(permission['decision'])
|
||||
: answerText;
|
||||
final note = resolvedByServer ? _text(permission['message']) : '';
|
||||
final action = _text(permission['action']);
|
||||
final alwaysLabel = _text(permission['always_label']);
|
||||
final headline = switch (state) {
|
||||
ChatPermissionState.pending =>
|
||||
'Approve ${action.isEmpty ? chatApprovalBlankAction : action}',
|
||||
ChatPermissionState.answered || ChatPermissionState.resolved =>
|
||||
decision == chatDecisionAlways && alwaysLabel == 'Allow for session'
|
||||
? 'Allowed for session'
|
||||
: chatDecisionLabel(decision),
|
||||
ChatPermissionState.stale => chatApprovalHeadlineResolved,
|
||||
};
|
||||
final statusLine = switch (state) {
|
||||
ChatPermissionState.pending => chatApprovalStatusPending,
|
||||
ChatPermissionState.answered => chatApprovalStatusAnswered,
|
||||
ChatPermissionState.resolved || ChatPermissionState.stale =>
|
||||
note.isEmpty ? chatApprovalStatusResolved : note,
|
||||
};
|
||||
return ChatPermissionCardData(
|
||||
requestId: requestId,
|
||||
resources: chatPermissionResources(permission),
|
||||
resourceText: chatPermissionResourceText(permission),
|
||||
risk: chatPermissionRiskText(permission),
|
||||
state: state,
|
||||
decision: decision,
|
||||
note: note,
|
||||
alwaysLabel: alwaysLabel.isEmpty ? chatApprovalAlwaysLabel : alwaysLabel,
|
||||
headline: headline,
|
||||
statusLine: statusLine,
|
||||
);
|
||||
}
|
||||
|
||||
/// A stable id for one confirmed reply. The id never changes across a retry of
|
||||
/// the same request and decision, so the send gate can recognise a double tap.
|
||||
String chatPermissionReplyId(String requestId, String decision) =>
|
||||
'chat-reply:${requestId.trim()}:${decision.trim()}';
|
||||
|
||||
/// A one-shot gate for confirmed actions. [start] returns false while the same
|
||||
/// stable id is already in flight or already accepted; [release] reopens an id
|
||||
/// after a refused send so the operator can retry it.
|
||||
class ChatActionGate {
|
||||
final Set<String> _started = {};
|
||||
|
||||
bool start(String id) => _started.add(id);
|
||||
|
||||
void release(String id) => _started.remove(id);
|
||||
|
||||
bool isStarted(String id) => _started.contains(id);
|
||||
|
||||
void clear() => _started.clear();
|
||||
}
|
||||
|
||||
String _text(Object? value) => '${value ?? ''}'.trim();
|
||||
@@ -0,0 +1,230 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../ui/sessions/chat_adaptive.dart';
|
||||
import 'chat_card_styles.dart';
|
||||
import 'chat_question_card_controls.dart';
|
||||
import 'chat_question_card_fields.dart';
|
||||
import 'chat_question_card_model.dart';
|
||||
import 'chat_question_recorded_answers.dart';
|
||||
import 'chat_question_validation.dart';
|
||||
|
||||
/// One recorded agent question as a native card.
|
||||
///
|
||||
/// A pending question keeps the operator's choices locally until Send answer;
|
||||
/// the answer map is field-keyed, exactly as `chat_answer` expects. Resolved
|
||||
/// and expired questions show the recorded answers read-only.
|
||||
class ChatQuestionCard extends StatefulWidget {
|
||||
const ChatQuestionCard({
|
||||
super.key,
|
||||
required this.form,
|
||||
required this.onSubmit,
|
||||
this.error,
|
||||
});
|
||||
|
||||
final JsonMap form;
|
||||
final Future<void> Function(Map<String, dynamic> answers, String action)
|
||||
onSubmit;
|
||||
final String? error;
|
||||
|
||||
@override
|
||||
State<ChatQuestionCard> createState() => _ChatQuestionCardState();
|
||||
}
|
||||
|
||||
class _ChatQuestionCardState extends State<ChatQuestionCard> {
|
||||
late final List<JsonMap> _fields = chatFormFields(widget.form);
|
||||
late final Map<String, dynamic> _answers = _initialAnswers();
|
||||
final Map<String, TextEditingController> _controllers = {};
|
||||
String _localError = '';
|
||||
bool _sending = false;
|
||||
|
||||
bool get _pending => chatFormPending(widget.form);
|
||||
|
||||
Map<String, dynamic> _initialAnswers() {
|
||||
final recorded = widget.form['answers'];
|
||||
final answers = recorded is Map
|
||||
? Map<String, dynamic>.from(recorded)
|
||||
: <String, dynamic>{};
|
||||
for (final field in _fields) {
|
||||
final key = '${field['key'] ?? ''}'.trim();
|
||||
if (key.isEmpty || answers.containsKey(key)) continue;
|
||||
if (field['default'] != null) answers[key] = field['default'];
|
||||
}
|
||||
return answers;
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
for (final field in _fields) {
|
||||
if (!chatQuestionFieldNeedsInput(field)) continue;
|
||||
final key = '${field['key'] ?? ''}'.trim();
|
||||
if (key.isEmpty) continue;
|
||||
final value = _answers[key];
|
||||
final options = chatQuestionOptions(
|
||||
field,
|
||||
).map(chatQuestionOptionValue).toSet();
|
||||
final custom = value is List
|
||||
? value.where((entry) => !options.contains('$entry')).join(', ')
|
||||
: (value is String && !options.contains(value) ? value : '');
|
||||
final controller = TextEditingController(text: custom);
|
||||
_controllers[key] = controller;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
for (final controller in _controllers.values) {
|
||||
controller.dispose();
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _changed(String key, Object? value) {
|
||||
setState(() {
|
||||
if (value == null) {
|
||||
_answers.remove(key);
|
||||
} else {
|
||||
_answers[key] = value;
|
||||
}
|
||||
_localError = '';
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _submit() async {
|
||||
if (_sending || !_pending) return;
|
||||
final reason = chatFormAnswerError(_fields, _answers);
|
||||
if (reason.isNotEmpty) {
|
||||
setState(() => _localError = reason);
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_sending = true;
|
||||
_localError = '';
|
||||
});
|
||||
final accept =
|
||||
widget.form['actions'] is List &&
|
||||
(widget.form['actions'] as List).contains('accept');
|
||||
await widget.onSubmit(
|
||||
chatVisibleFormAnswers(_fields, _answers),
|
||||
accept ? 'accept' : '',
|
||||
);
|
||||
if (mounted) setState(() => _sending = false);
|
||||
}
|
||||
|
||||
Future<void> _action(String action) async {
|
||||
if (_sending || !_pending) return;
|
||||
setState(() {
|
||||
_sending = true;
|
||||
_localError = '';
|
||||
});
|
||||
await widget.onSubmit(const {}, action);
|
||||
if (mounted) setState(() => _sending = false);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final cupertino =
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
||||
final body = _body(context, cupertino);
|
||||
final wrapped = cupertino
|
||||
? DefaultTextStyle.merge(
|
||||
style: CupertinoTheme.of(context).textTheme.textStyle,
|
||||
child: body,
|
||||
)
|
||||
: body;
|
||||
if (cupertino) {
|
||||
return CupertinoListSection.insetGrouped(
|
||||
children: [Padding(padding: const EdgeInsets.all(16), child: wrapped)],
|
||||
);
|
||||
}
|
||||
return Card(
|
||||
// Keep consecutive cards visually separate; the transcript row only
|
||||
// supplies the horizontal inset.
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
child: Padding(padding: const EdgeInsets.all(16), child: wrapped),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _body(BuildContext context, bool cupertino) {
|
||||
final actions = widget.form['actions'];
|
||||
final error = widget.error?.trim().isNotEmpty == true
|
||||
? widget.error!.trim()
|
||||
: _localError;
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
'${widget.form['title'] ?? ''}'.trim().isEmpty
|
||||
? 'Question'
|
||||
: '${widget.form['title']}'.trim(),
|
||||
style: chatCardTitleStyle(context, cupertino),
|
||||
),
|
||||
Text(
|
||||
_statusLine(),
|
||||
style: chatCardSecondaryStyle(context, cupertino),
|
||||
),
|
||||
if (error.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Semantics(
|
||||
liveRegion: true,
|
||||
child: Text(
|
||||
error,
|
||||
style: chatCardBodyStyle(
|
||||
context,
|
||||
cupertino,
|
||||
)?.copyWith(color: chatCardErrorColor(context, cupertino)),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (_pending)
|
||||
...chatQuestionFieldWidgets(
|
||||
context: context,
|
||||
fields: _fields,
|
||||
answers: _answers,
|
||||
cupertino: cupertino,
|
||||
controllers: _controllers,
|
||||
onChanged: _changed,
|
||||
)
|
||||
else
|
||||
...chatQuestionRecordedAnswers(
|
||||
context: context,
|
||||
form: widget.form,
|
||||
cupertino: cupertino,
|
||||
),
|
||||
if (_pending) ...[
|
||||
const SizedBox(height: 12),
|
||||
chatQuestionControls(
|
||||
context: context,
|
||||
cupertino: cupertino,
|
||||
actions: actions,
|
||||
submitLabel: _submitLabel,
|
||||
sending: _sending,
|
||||
onSubmit: _submit,
|
||||
onAction: _action,
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
String _statusLine() {
|
||||
if (_pending) return chatQuestionWaiting;
|
||||
if (widget.form['cancelled'] == true) return chatQuestionExpired;
|
||||
final answers = widget.form['answers'];
|
||||
return answers is Map && answers.isNotEmpty
|
||||
? chatQuestionAnswered
|
||||
: chatQuestionClosed;
|
||||
}
|
||||
|
||||
String get _submitLabel {
|
||||
final allExternal =
|
||||
_fields.isNotEmpty &&
|
||||
_fields.every((field) => '${field['type'] ?? ''}' == 'external');
|
||||
return allExternal ? chatQuestionConfirm : chatQuestionSubmit;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Submit and optional decline/cancel controls for a pending question.
|
||||
///
|
||||
/// The web shows `Confirm completion` when every field is external, otherwise
|
||||
/// `Send answer`, and offers only the actions the form records. The labels are
|
||||
/// passed in so this file stays layout only.
|
||||
Widget chatQuestionControls({
|
||||
required BuildContext context,
|
||||
required bool cupertino,
|
||||
required Object? actions,
|
||||
required String submitLabel,
|
||||
required bool sending,
|
||||
required VoidCallback onSubmit,
|
||||
required void Function(String action) onAction,
|
||||
}) {
|
||||
final canDecline = actions is List && actions.contains('decline');
|
||||
final canCancel = actions is List && actions.contains('cancel');
|
||||
if (cupertino) {
|
||||
return Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
CupertinoButton.filled(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
onPressed: sending ? null : onSubmit,
|
||||
child: Text(sending ? 'Sending…' : submitLabel),
|
||||
),
|
||||
if (canDecline)
|
||||
CupertinoButton(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
onPressed: sending ? null : () => onAction('decline'),
|
||||
child: const Text('Decline'),
|
||||
),
|
||||
if (canCancel)
|
||||
CupertinoButton(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
onPressed: sending ? null : () => onAction('cancel'),
|
||||
child: const Text('Cancel question'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
FilledButton(
|
||||
onPressed: sending ? null : onSubmit,
|
||||
child: Text(sending ? 'Sending…' : submitLabel),
|
||||
),
|
||||
if (canDecline)
|
||||
TextButton(
|
||||
onPressed: sending ? null : () => onAction('decline'),
|
||||
child: const Text('Decline'),
|
||||
),
|
||||
if (canCancel)
|
||||
TextButton(
|
||||
onPressed: sending ? null : () => onAction('cancel'),
|
||||
child: const Text('Cancel question'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'chat_card_styles.dart';
|
||||
import 'chat_question_card_model.dart';
|
||||
import 'chat_question_option_controls.dart';
|
||||
|
||||
/// A free-text input is part of a field when the form allows an answer outside
|
||||
/// its option list, or when the field has no options at all.
|
||||
bool chatQuestionFieldNeedsInput(JsonMap field) =>
|
||||
field['custom'] == true || chatQuestionOptions(field).isEmpty;
|
||||
|
||||
/// The editable controls for one form. [onChanged] receives the protocol value
|
||||
/// (`false`/`0` preserved), or null when the input was cleared.
|
||||
List<Widget> chatQuestionFieldWidgets({
|
||||
required BuildContext context,
|
||||
required List<JsonMap> fields,
|
||||
required Map<String, dynamic> answers,
|
||||
required bool cupertino,
|
||||
required Map<String, TextEditingController> controllers,
|
||||
required void Function(String key, Object? value) onChanged,
|
||||
}) {
|
||||
final widgets = <Widget>[];
|
||||
for (final field in fields) {
|
||||
if (!chatFormFieldVisible(field, answers)) continue;
|
||||
final key = '${field['key'] ?? ''}'.trim();
|
||||
if (key.isEmpty) continue;
|
||||
widgets.add(
|
||||
_field(
|
||||
context: context,
|
||||
field: field,
|
||||
keyName: key,
|
||||
answers: answers,
|
||||
cupertino: cupertino,
|
||||
controllers: controllers,
|
||||
onChanged: onChanged,
|
||||
),
|
||||
);
|
||||
}
|
||||
return widgets;
|
||||
}
|
||||
|
||||
Widget _field({
|
||||
required BuildContext context,
|
||||
required JsonMap field,
|
||||
required String keyName,
|
||||
required Map<String, dynamic> answers,
|
||||
required bool cupertino,
|
||||
required Map<String, TextEditingController> controllers,
|
||||
required void Function(String key, Object? value) onChanged,
|
||||
}) {
|
||||
final title = '${field['title'] ?? ''}'.trim();
|
||||
final description = '${field['description'] ?? ''}'.trim();
|
||||
final label = title.isNotEmpty
|
||||
? title
|
||||
: (description.isNotEmpty ? description : keyName);
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(top: 12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(label, style: chatCardLabelStyle(context, cupertino)),
|
||||
if (description.isNotEmpty && description != title)
|
||||
Text(
|
||||
description,
|
||||
style: chatCardSecondaryStyle(context, cupertino),
|
||||
),
|
||||
if ('${field['type'] ?? ''}' == 'external')
|
||||
_external(context, field, cupertino)
|
||||
else if ('${field['type'] ?? ''}' == 'boolean')
|
||||
chatQuestionBooleanField(
|
||||
context: context,
|
||||
field: field,
|
||||
keyName: keyName,
|
||||
answers: answers,
|
||||
cupertino: cupertino,
|
||||
onChanged: onChanged,
|
||||
)
|
||||
else ...[
|
||||
chatQuestionOptionsField(
|
||||
context: context,
|
||||
field: field,
|
||||
keyName: keyName,
|
||||
answers: answers,
|
||||
cupertino: cupertino,
|
||||
onChanged: onChanged,
|
||||
),
|
||||
if (chatQuestionFieldNeedsInput(field))
|
||||
_input(
|
||||
context: context,
|
||||
field: field,
|
||||
label: label,
|
||||
keyName: keyName,
|
||||
controller: controllers[keyName]!,
|
||||
cupertino: cupertino,
|
||||
hasOptions: chatQuestionOptions(field).isNotEmpty,
|
||||
onChanged: (value) => onChanged(
|
||||
keyName,
|
||||
chatQuestionTextValue(field, value, answers),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _input({
|
||||
required BuildContext context,
|
||||
required JsonMap field,
|
||||
required String label,
|
||||
required String keyName,
|
||||
required TextEditingController controller,
|
||||
required bool cupertino,
|
||||
required bool hasOptions,
|
||||
required ValueChanged<String> onChanged,
|
||||
}) {
|
||||
final placeholder = '${field['placeholder'] ?? ''}'.trim().isNotEmpty
|
||||
? '${field['placeholder']}'.trim()
|
||||
: (hasOptions ? 'Type another answer' : 'Your answer');
|
||||
final secret = field['secret'] == true;
|
||||
final type = '${field['type'] ?? ''}';
|
||||
final format = '${field['format'] ?? ''}';
|
||||
final keyboard = type == 'number' || type == 'integer'
|
||||
? TextInputType.number
|
||||
: format == 'email'
|
||||
? TextInputType.emailAddress
|
||||
: format == 'uri'
|
||||
? TextInputType.url
|
||||
: format == 'date'
|
||||
? TextInputType.datetime
|
||||
: TextInputType.text;
|
||||
// The visual label sits above the input; the same words must also reach the
|
||||
// input's own semantics node, as the web's `aria-label` does.
|
||||
final input = cupertino
|
||||
? CupertinoTextField(
|
||||
key: ValueKey<String>('chat-question-input-$keyName'),
|
||||
controller: controller,
|
||||
placeholder: placeholder,
|
||||
obscureText: secret,
|
||||
keyboardType: keyboard,
|
||||
padding: const EdgeInsets.all(8),
|
||||
onChanged: onChanged,
|
||||
)
|
||||
: TextField(
|
||||
key: ValueKey<String>('chat-question-input-$keyName'),
|
||||
controller: controller,
|
||||
obscureText: secret,
|
||||
keyboardType: keyboard,
|
||||
decoration: InputDecoration(hintText: placeholder),
|
||||
onChanged: onChanged,
|
||||
);
|
||||
return Semantics(label: label, child: input);
|
||||
}
|
||||
|
||||
Widget _external(BuildContext context, JsonMap field, bool cupertino) {
|
||||
final raw = '${field['url'] ?? ''}'.trim();
|
||||
if (!chatExternalUrlIsSafe(raw)) {
|
||||
return Text(
|
||||
'This form has an unsupported external URL.',
|
||||
style: chatCardBodyStyle(
|
||||
context,
|
||||
cupertino,
|
||||
)?.copyWith(color: chatCardErrorColor(context, cupertino)),
|
||||
);
|
||||
}
|
||||
return SelectableText(raw);
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
/// Agent question forms: field visibility, values and option lists.
|
||||
///
|
||||
/// These rules mirror the web's `chatForms.js`. `false` and `0` are valid
|
||||
/// answers, never "missing". Validation lives in `chat_question_validation.dart`
|
||||
/// so this file stays a protocol model; option values are kept exactly as
|
||||
/// recorded because they travel back in `chat_answer`.
|
||||
library;
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
const chatQuestionWaiting = 'The agent is waiting for your answer.';
|
||||
const chatQuestionExpired = 'This question expired.';
|
||||
const chatQuestionAnswered = 'Answer recorded.';
|
||||
const chatQuestionClosed = 'Question closed.';
|
||||
const chatQuestionSubmit = 'Send answer';
|
||||
const chatQuestionConfirm = 'Confirm completion';
|
||||
|
||||
bool chatFormFieldVisible(JsonMap field, Map<String, dynamic> answers) {
|
||||
if (field['hidden'] == true) return false;
|
||||
final when = field['when'];
|
||||
if (when is! List) return true;
|
||||
for (final condition in when) {
|
||||
if (condition is! Map) continue;
|
||||
final key = _text(condition['key']);
|
||||
final expected = condition['value'];
|
||||
final actual = answers[key];
|
||||
final matches = actual == expected;
|
||||
if (_text(condition['op']) == 'neq' ? matches : !matches) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// A protocol-preserving field value; null means the input was cleared.
|
||||
///
|
||||
/// An integer answer is stored as a Dart `int`, so `"1.0"`/`"1e3"` cannot travel
|
||||
/// as `1.0`/`1000.0` the way the web's `Number()` never does.
|
||||
Object? chatFormFieldValue(JsonMap field, String raw) {
|
||||
if (raw.isEmpty) return null;
|
||||
final type = _text(field['type']);
|
||||
switch (type) {
|
||||
case 'boolean':
|
||||
return raw == 'true';
|
||||
case 'number':
|
||||
case 'integer':
|
||||
final parsed = num.tryParse(raw);
|
||||
if (parsed == null) return double.nan;
|
||||
final integral =
|
||||
parsed.isFinite && parsed == parsed.roundToDouble();
|
||||
return type == 'integer' && integral ? parsed.toInt() : parsed;
|
||||
default:
|
||||
return raw;
|
||||
}
|
||||
}
|
||||
|
||||
/// Only visible, non-external, answered fields travel in `chat_answer`.
|
||||
Map<String, dynamic> chatVisibleFormAnswers(
|
||||
List<JsonMap> fields,
|
||||
Map<String, dynamic> answers,
|
||||
) {
|
||||
final result = <String, dynamic>{};
|
||||
for (final field in fields) {
|
||||
if (!chatFormFieldVisible(field, answers)) continue;
|
||||
if (_text(field['type']) == 'external') continue;
|
||||
final key = _text(field['key']);
|
||||
if (!answers.containsKey(key)) continue;
|
||||
result[key] = answers[key];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
List<JsonMap> chatFormFields(JsonMap form) {
|
||||
final fields = form['fields'];
|
||||
if (fields is! List) return const [];
|
||||
return [
|
||||
for (final field in fields)
|
||||
if (field is Map) Map<String, dynamic>.from(field),
|
||||
];
|
||||
}
|
||||
|
||||
/// A free-text edit as the protocol value. A multi-select input edits only the
|
||||
/// options it already knows plus the comma-separated custom entries, matching
|
||||
/// the web's question input.
|
||||
Object? chatQuestionTextValue(
|
||||
JsonMap field,
|
||||
String raw,
|
||||
Map<String, dynamic> answers,
|
||||
) {
|
||||
final key = _text(field['key']);
|
||||
if (_text(field['type']) != 'multiselect') {
|
||||
return chatFormFieldValue(field, raw);
|
||||
}
|
||||
final known = chatQuestionFieldOptionValues(field);
|
||||
final selected = answers[key] is List
|
||||
? (answers[key] as List).map((entry) => '$entry').where(known.contains)
|
||||
: const <String>[];
|
||||
final custom = raw
|
||||
.split(',')
|
||||
.map((entry) => entry.trim())
|
||||
.where((entry) => entry.isNotEmpty);
|
||||
return [...selected, ...custom];
|
||||
}
|
||||
|
||||
List<String> chatQuestionFieldOptionValues(JsonMap field) => [
|
||||
for (final option in chatQuestionOptions(field))
|
||||
chatQuestionOptionValue(option),
|
||||
];
|
||||
|
||||
/// The field's selectable options. The web skips an option whose recorded value
|
||||
/// is empty rather than rendering a blank control.
|
||||
List<JsonMap> chatQuestionOptions(JsonMap field) {
|
||||
final options = field['options'];
|
||||
if (options is! List) return const [];
|
||||
final result = <JsonMap>[];
|
||||
for (final option in options) {
|
||||
if (option is! Map) continue;
|
||||
final converted = Map<String, dynamic>.from(option);
|
||||
if (chatQuestionOptionValue(converted).isEmpty) continue;
|
||||
result.add(converted);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// The option's exact recorded value, never trimmed: it is the protocol value
|
||||
/// sent back in `chat_answer`.
|
||||
String chatQuestionOptionValue(JsonMap option) =>
|
||||
'${option['value'] ?? option['label'] ?? ''}';
|
||||
|
||||
String chatQuestionOptionLabel(JsonMap option) {
|
||||
final label = _text(option['label']);
|
||||
return label.isEmpty ? chatQuestionOptionValue(option) : label;
|
||||
}
|
||||
|
||||
bool chatFormPending(JsonMap form) =>
|
||||
form['resolved'] != true && form['cancelled'] != true;
|
||||
|
||||
/// True when an external form URL is one this app can safely show. Mirrors the
|
||||
/// web's `safeFormURL`: an absolute HTTP(S) URL with a real host and no spaces.
|
||||
bool chatExternalUrlIsSafe(String raw) {
|
||||
if (raw.trim() != raw || RegExp(r'\s').hasMatch(raw)) return false;
|
||||
final uri = Uri.tryParse(raw);
|
||||
return uri != null &&
|
||||
(uri.scheme == 'http' || uri.scheme == 'https') &&
|
||||
uri.host.isNotEmpty;
|
||||
}
|
||||
|
||||
/// Fold one `form` frame into the retained forms, keyed by id. A resolved or
|
||||
/// cancelled update keeps the recorded answers so the card can show them
|
||||
/// read-only instead of dropping evidence.
|
||||
Map<String, JsonMap> chatFoldQuestionFrame(
|
||||
Map<String, JsonMap> current,
|
||||
JsonMap? form,
|
||||
) {
|
||||
if (form == null) return current;
|
||||
final id = _text(form['id']);
|
||||
if (id.isEmpty) return current;
|
||||
final existing = current[id];
|
||||
final next = <String, JsonMap>{...current};
|
||||
next[id] = existing == null
|
||||
? Map<String, dynamic>.from(form)
|
||||
: {...existing, ...Map<String, dynamic>.from(form)};
|
||||
return next;
|
||||
}
|
||||
|
||||
/// A stable id for one confirmed answer action on a form. Reusing the same id
|
||||
/// across a retry lets the send gate recognise a double tap.
|
||||
String chatQuestionReplyId(String formId, {String action = ''}) =>
|
||||
'chat-answer:${formId.trim()}:${action.trim().isEmpty ? 'answer' : action.trim()}';
|
||||
|
||||
String _text(Object? value) => '${value ?? ''}'.trim();
|
||||
@@ -0,0 +1,150 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'chat_card_styles.dart';
|
||||
import 'chat_question_card_model.dart';
|
||||
|
||||
/// Native option controls for one question field. Single-select uses the host's
|
||||
/// radio/checklist pattern, multi-select toggles choices, and `onChanged`
|
||||
/// receives the protocol value with `false`/`0` preserved.
|
||||
Widget chatQuestionOptionsField({
|
||||
required BuildContext context,
|
||||
required JsonMap field,
|
||||
required String keyName,
|
||||
required Map<String, dynamic> answers,
|
||||
required bool cupertino,
|
||||
required void Function(String key, Object? value) onChanged,
|
||||
}) {
|
||||
final options = chatQuestionOptions(field);
|
||||
if (options.isEmpty) return const SizedBox.shrink();
|
||||
final multi = '${field['type'] ?? ''}' == 'multiselect';
|
||||
final value = answers[keyName];
|
||||
final selected = multi
|
||||
? (value is List ? value.map((entry) => '$entry').toSet() : <String>{})
|
||||
: <String>{if (value is String) value};
|
||||
if (cupertino) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
for (final option in options)
|
||||
CupertinoButton(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
onPressed: () => onChanged(
|
||||
keyName,
|
||||
multi
|
||||
? _toggle(selected, chatQuestionOptionValue(option))
|
||||
: chatQuestionOptionValue(option),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(chatQuestionOptionLabel(option)),
|
||||
if ('${option['description'] ?? ''}'.trim().isNotEmpty)
|
||||
Text(
|
||||
'${option['description']}'.trim(),
|
||||
style: chatCardSecondaryStyle(context, cupertino),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (selected.contains(chatQuestionOptionValue(option)))
|
||||
const Icon(CupertinoIcons.checkmark),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
if (multi) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
for (final option in options)
|
||||
CheckboxListTile(
|
||||
value: selected.contains(chatQuestionOptionValue(option)),
|
||||
title: Text(chatQuestionOptionLabel(option)),
|
||||
subtitle: '${option['description'] ?? ''}'.trim().isEmpty
|
||||
? null
|
||||
: Text('${option['description']}'.trim()),
|
||||
contentPadding: EdgeInsets.zero,
|
||||
controlAffinity: ListTileControlAffinity.leading,
|
||||
onChanged: (on) => onChanged(
|
||||
keyName,
|
||||
_toggle(selected, chatQuestionOptionValue(option)),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return RadioGroup<String>(
|
||||
groupValue: value is String ? value : null,
|
||||
onChanged: (next) => onChanged(keyName, next),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
for (final option in options)
|
||||
RadioListTile<String>(
|
||||
value: chatQuestionOptionValue(option),
|
||||
title: Text(chatQuestionOptionLabel(option)),
|
||||
subtitle: '${option['description'] ?? ''}'.trim().isEmpty
|
||||
? null
|
||||
: Text('${option['description']}'.trim()),
|
||||
contentPadding: EdgeInsets.zero,
|
||||
controlAffinity: ListTileControlAffinity.leading,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Yes/No for a boolean field: native checkmarks under Cupertino, the web's
|
||||
/// explicit "Choose Yes or No" menu under Material.
|
||||
Widget chatQuestionBooleanField({
|
||||
required BuildContext context,
|
||||
required JsonMap field,
|
||||
required String keyName,
|
||||
required Map<String, dynamic> answers,
|
||||
required bool cupertino,
|
||||
required void Function(String key, Object? value) onChanged,
|
||||
}) {
|
||||
final value = answers[keyName];
|
||||
if (cupertino) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
for (final entry in const [('Yes', true), ('No', false)])
|
||||
CupertinoButton(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
onPressed: () => onChanged(keyName, entry.$2),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(child: Text(entry.$1)),
|
||||
if (value == entry.$2) const Icon(CupertinoIcons.checkmark),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return DropdownButtonFormField<String>(
|
||||
initialValue: value is bool ? '$value' : null,
|
||||
hint: const Text('Choose Yes or No'),
|
||||
items: const [
|
||||
DropdownMenuItem(value: 'true', child: Text('Yes')),
|
||||
DropdownMenuItem(value: 'false', child: Text('No')),
|
||||
],
|
||||
onChanged: (next) =>
|
||||
onChanged(keyName, chatFormFieldValue(field, next ?? '')),
|
||||
);
|
||||
}
|
||||
|
||||
List<String> _toggle(Set<String> selected, String value) {
|
||||
final next = {...selected};
|
||||
if (!next.add(value)) next.remove(value);
|
||||
return next.toList();
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'chat_card_styles.dart';
|
||||
import 'chat_question_card_model.dart';
|
||||
|
||||
/// Recorded answers, read-only. Every answer key is shown, including ones the
|
||||
/// form fields no longer describe, so no recorded text is dropped.
|
||||
List<Widget> chatQuestionRecordedAnswers({
|
||||
required BuildContext context,
|
||||
required JsonMap form,
|
||||
required bool cupertino,
|
||||
}) {
|
||||
final answers = form['answers'] is Map
|
||||
? Map<String, dynamic>.from(form['answers'] as Map)
|
||||
: <String, dynamic>{};
|
||||
final shown = <String>{};
|
||||
final widgets = <Widget>[];
|
||||
for (final field in chatFormFields(form)) {
|
||||
final key = '${field['key'] ?? ''}'.trim();
|
||||
if (key.isEmpty || !answers.containsKey(key)) continue;
|
||||
shown.add(key);
|
||||
widgets.add(
|
||||
_recorded(
|
||||
context,
|
||||
_fieldLabel(field, key),
|
||||
_answerText(field, answers[key]),
|
||||
cupertino,
|
||||
),
|
||||
);
|
||||
}
|
||||
for (final entry in answers.entries) {
|
||||
if (shown.contains(entry.key)) continue;
|
||||
widgets.add(
|
||||
_recorded(
|
||||
context,
|
||||
entry.key,
|
||||
_answerText(null, entry.value),
|
||||
cupertino,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (widgets.isEmpty) {
|
||||
return [
|
||||
Text(
|
||||
'No answer was recorded.',
|
||||
style: chatCardSecondaryStyle(context, cupertino),
|
||||
),
|
||||
];
|
||||
}
|
||||
return widgets;
|
||||
}
|
||||
|
||||
/// The field's display label, falling back past blank recorded strings the same
|
||||
/// way the pending field does.
|
||||
String _fieldLabel(JsonMap field, String key) {
|
||||
for (final candidate in [field['title'], field['description']]) {
|
||||
final text = '${candidate ?? ''}'.trim();
|
||||
if (text.isNotEmpty) return text;
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
Widget _recorded(
|
||||
BuildContext context,
|
||||
String label,
|
||||
String value,
|
||||
bool cupertino,
|
||||
) => Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(label, style: chatCardLabelStyle(context, cupertino)),
|
||||
Text(value, style: chatCardBodyStyle(context, cupertino)),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
String _answerText(JsonMap? field, Object? value) {
|
||||
final values = value is List ? value : [value];
|
||||
final boolean = field != null && '${field['type'] ?? ''}' == 'boolean';
|
||||
return values
|
||||
.map((entry) {
|
||||
// The editable control says Yes/No; the recorded view must use the same
|
||||
// words instead of exposing the raw protocol boolean.
|
||||
if (boolean && entry is bool) return entry ? 'Yes' : 'No';
|
||||
if (field == null) return '${entry ?? ''}';
|
||||
for (final option in chatQuestionOptions(field)) {
|
||||
if ('${entry ?? ''}' == chatQuestionOptionValue(option)) {
|
||||
return chatQuestionOptionLabel(option);
|
||||
}
|
||||
}
|
||||
return '${entry ?? ''}';
|
||||
})
|
||||
.join(', ');
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/// Validation shared by the question card and its tests.
|
||||
///
|
||||
/// These are the web's `formAnswerError` rules plus the browser input
|
||||
/// constraints the card cannot delegate to Flutter: `pattern`, `format=email`,
|
||||
/// `format=uri` and `format=date`. The browser's localised `validationMessage`
|
||||
/// has no portable equivalent, so the fixed English sentences below stand in
|
||||
/// for it and are documented as an app addition.
|
||||
library;
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'chat_question_card_model.dart';
|
||||
|
||||
const _patternError = 'does not match the required format';
|
||||
const _emailError = 'is not a valid email address';
|
||||
const _urlError = 'is not a valid URL';
|
||||
const _dateError = 'is not a valid date';
|
||||
|
||||
/// The web's validation messages, in field order. An empty string is valid.
|
||||
String chatFormAnswerError(List<JsonMap> fields, Map<String, dynamic> answers) {
|
||||
for (final field in fields) {
|
||||
if (!chatFormFieldVisible(field, answers)) continue;
|
||||
if (_text(field['type']) == 'external') continue;
|
||||
final key = _text(field['key']);
|
||||
final value = answers[key];
|
||||
final missing =
|
||||
value == null || value == '' || (value is List && value.isEmpty);
|
||||
final label = _text(field['title']).isEmpty ? key : _text(field['title']);
|
||||
if (missing) {
|
||||
if (field['required'] == true) {
|
||||
return 'Answer $label before sending.';
|
||||
}
|
||||
continue;
|
||||
}
|
||||
final type = _text(field['type']);
|
||||
if (type == 'number' || type == 'integer') {
|
||||
final number = value is num ? value : null;
|
||||
final finite = number != null && number.isFinite;
|
||||
final integral =
|
||||
type != 'integer' ||
|
||||
(number != null && number is int) ||
|
||||
(number != null && number == number.roundToDouble());
|
||||
if (!finite || !integral) return '$label needs a valid $type.';
|
||||
final minimum = field['minimum'];
|
||||
final maximum = field['maximum'];
|
||||
if (minimum is num && number < minimum) {
|
||||
return '$label must be at least $minimum.';
|
||||
}
|
||||
if (maximum is num && number > maximum) {
|
||||
return '$label must be at most $maximum.';
|
||||
}
|
||||
}
|
||||
if (type == 'boolean' && value is! bool) {
|
||||
return '$label needs Yes or No.';
|
||||
}
|
||||
if (value is String) {
|
||||
final minLength = field['min_length'];
|
||||
final maxLength = field['max_length'];
|
||||
if (minLength is num && value.length < minLength) {
|
||||
return '$label is too short.';
|
||||
}
|
||||
if (maxLength is num && value.length > maxLength) {
|
||||
return '$label is too long.';
|
||||
}
|
||||
final pattern = _text(field['pattern']);
|
||||
if (pattern.isNotEmpty && !_matchesPattern(pattern, value)) {
|
||||
return '$label $_patternError.';
|
||||
}
|
||||
final formatError = _formatError(_text(field['format']), value);
|
||||
if (formatError.isNotEmpty) return '$label $formatError.';
|
||||
}
|
||||
if (value is List) {
|
||||
final minItems = field['min_items'];
|
||||
final maxItems = field['max_items'];
|
||||
if (minItems is num && value.length < minItems) {
|
||||
return 'Select at least $minItems choices for $label.';
|
||||
}
|
||||
if (maxItems is num && value.length > maxItems) {
|
||||
return 'Select at most $maxItems choices for $label.';
|
||||
}
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/// HTML's `pattern` attribute matches the whole value, not a substring.
|
||||
bool _matchesPattern(String pattern, String value) {
|
||||
try {
|
||||
return RegExp('^(?:$pattern)\$').hasMatch(value);
|
||||
} catch (_) {
|
||||
// An unparseable server pattern constrains nothing, exactly as an invalid
|
||||
// `pattern` attribute is ignored by the browser.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
String _formatError(String format, String value) {
|
||||
switch (format) {
|
||||
case 'email':
|
||||
return RegExp(r'^[^@\s]+@[^@\s]+\.[^@\s]+$').hasMatch(value)
|
||||
? ''
|
||||
: _emailError;
|
||||
case 'uri':
|
||||
final uri = Uri.tryParse(value);
|
||||
return uri != null && uri.hasScheme && !RegExp(r'\s').hasMatch(value)
|
||||
? ''
|
||||
: _urlError;
|
||||
case 'date':
|
||||
return _isDate(value) ? '' : _dateError;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
bool _isDate(String value) {
|
||||
final match = RegExp(r'^(\d{4})-(\d{2})-(\d{2})$').firstMatch(value);
|
||||
if (match == null) return false;
|
||||
final year = int.parse(match.group(1)!);
|
||||
final month = int.parse(match.group(2)!);
|
||||
final day = int.parse(match.group(3)!);
|
||||
final date = DateTime(year, month, day);
|
||||
return date.year == year && date.month == month && date.day == day;
|
||||
}
|
||||
|
||||
String _text(Object? value) => '${value ?? ''}'.trim();
|
||||
@@ -0,0 +1,190 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../data/chat_repository.dart';
|
||||
import 'chat_permission_card_model.dart';
|
||||
import 'chat_question_card_model.dart';
|
||||
|
||||
/// The open conversation's recorded approval requests and question forms.
|
||||
///
|
||||
/// This is the transcript controller's card collaborator: it owns frame folding,
|
||||
/// the operator's optimistic answers, server refusals and the one-shot send
|
||||
/// gates, so the controller itself stays about messages and live turn state.
|
||||
///
|
||||
/// The web drops an approval or form once it is resolved. This app keeps the
|
||||
/// latest settled cards as read-only evidence, which is an intentional addition;
|
||||
/// [settledLimit] bounds that history so a long session cannot grow without
|
||||
/// limit while pending cards are never dropped.
|
||||
class ChatThreadCards {
|
||||
ChatThreadCards({
|
||||
required this.repository,
|
||||
required this.sessionId,
|
||||
required this.notify,
|
||||
required this.isAlive,
|
||||
});
|
||||
|
||||
static const settledLimit = 20;
|
||||
|
||||
final ChatRepository repository;
|
||||
final String sessionId;
|
||||
final void Function() notify;
|
||||
final bool Function() isAlive;
|
||||
|
||||
final List<JsonMap> _permissions = [];
|
||||
final Map<String, JsonMap> _forms = {};
|
||||
final Map<String, String> _answers = {};
|
||||
final Map<String, String> _permissionErrors = {};
|
||||
final Map<String, String> _formErrors = {};
|
||||
final ChatActionGate _permissionGate = ChatActionGate();
|
||||
final ChatActionGate _questionGate = ChatActionGate();
|
||||
|
||||
/// Every retained permission request, settled or still open, in server order.
|
||||
List<JsonMap> get permissions => List.unmodifiable(_permissions);
|
||||
|
||||
/// Every retained question form, including answered and expired ones.
|
||||
List<JsonMap> get forms => List.unmodifiable(_forms.values);
|
||||
|
||||
String answerFor(String requestId) => _answers[requestId] ?? '';
|
||||
|
||||
String? permissionErrorFor(String requestId) =>
|
||||
_permissionErrors[requestId];
|
||||
|
||||
String? formErrorFor(String formId) => _formErrors[formId];
|
||||
|
||||
/// Answer one pending approval. The local decision settles the card before
|
||||
/// the reply lands; a refusal reopens the same request with the server's
|
||||
/// reason so an unaccepted decision is never shown as accepted. A second tap
|
||||
/// of the same confirmed action is ignored until it settles.
|
||||
Future<void> replyPermission(String requestId, String decision) async {
|
||||
final id = requestId.trim();
|
||||
if (id.isEmpty || !chatDecisions.contains(decision)) return;
|
||||
final frame = _permissionFrame(id);
|
||||
if (frame == null || frame['resolved'] == true) return;
|
||||
final replyId = chatPermissionReplyId(id, decision);
|
||||
if (!_permissionGate.start(replyId)) return;
|
||||
_answers[id] = decision;
|
||||
_permissionErrors.remove(id);
|
||||
notify();
|
||||
try {
|
||||
await repository.replyPermission(sessionId, id, decision);
|
||||
if (!isAlive()) return;
|
||||
// A previous refusal's reason no longer describes an accepted reply.
|
||||
if (_permissionErrors.remove(id) != null) notify();
|
||||
} catch (error) {
|
||||
if (!isAlive()) return;
|
||||
final current = _permissionFrame(id);
|
||||
// A server resolution that raced the refusal wins: do not reopen it.
|
||||
if (current == null || current['resolved'] == true) return;
|
||||
_answers.remove(id);
|
||||
_permissionErrors[id] = '$error';
|
||||
_permissionGate.release(replyId);
|
||||
notify();
|
||||
}
|
||||
}
|
||||
|
||||
/// Answer or close a pending question with the web's field-keyed body. A
|
||||
/// refusal keeps the card open and reports the server's reason.
|
||||
Future<void> answerQuestion(
|
||||
String formId,
|
||||
Map<String, dynamic> answers,
|
||||
String action,
|
||||
) async {
|
||||
final id = formId.trim();
|
||||
final form = _forms[id];
|
||||
if (id.isEmpty || form == null || !chatFormPending(form)) return;
|
||||
final replyId = chatQuestionReplyId(id, action: action);
|
||||
if (!_questionGate.start(replyId)) return;
|
||||
_formErrors.remove(id);
|
||||
notify();
|
||||
try {
|
||||
await repository.answerForm(
|
||||
sessionId,
|
||||
id,
|
||||
Map<String, dynamic>.from(answers),
|
||||
action: action,
|
||||
);
|
||||
if (!isAlive()) return;
|
||||
_forms[id] = {
|
||||
...form,
|
||||
'resolved': true,
|
||||
if (answers.isNotEmpty)
|
||||
'answers': Map<String, dynamic>.from(answers),
|
||||
};
|
||||
_pruneSettledForms();
|
||||
notify();
|
||||
} catch (error) {
|
||||
if (!isAlive()) return;
|
||||
_formErrors[id] = '$error';
|
||||
_questionGate.release(replyId);
|
||||
notify();
|
||||
}
|
||||
}
|
||||
|
||||
/// Fold one pushed `chat_permission` frame. A repeat for the same request
|
||||
/// replaces the recorded frame (a server resolution then wins over any local
|
||||
/// answer); a frame for a new request is added after the held cards.
|
||||
void foldPermission(JsonMap frame) {
|
||||
final id = '${frame['request_id'] ?? ''}'.trim();
|
||||
if (id.isEmpty) return;
|
||||
final index = _permissions.indexWhere(
|
||||
(held) => '${held['request_id'] ?? ''}'.trim() == id,
|
||||
);
|
||||
if (index < 0) {
|
||||
_permissions.add(frame);
|
||||
} else {
|
||||
_permissions[index] = frame;
|
||||
}
|
||||
if (frame['resolved'] == true) _permissionErrors.remove(id);
|
||||
_pruneSettledPermissions();
|
||||
notify();
|
||||
}
|
||||
|
||||
/// Fold one `form` event. A folded update keeps a settled form's recorded
|
||||
/// answers for the read-only card.
|
||||
void foldForm(JsonMap form) {
|
||||
final id = '${form['id'] ?? ''}'.trim();
|
||||
if (id.isEmpty) return;
|
||||
final next = chatFoldQuestionFrame(_forms, form);
|
||||
if (identical(next, _forms)) return;
|
||||
_forms
|
||||
..clear()
|
||||
..addAll(next);
|
||||
_formErrors.remove(id);
|
||||
_pruneSettledForms();
|
||||
notify();
|
||||
}
|
||||
|
||||
JsonMap? _permissionFrame(String requestId) {
|
||||
for (final frame in _permissions) {
|
||||
if ('${frame['request_id'] ?? ''}'.trim() == requestId) return frame;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
bool _permissionSettled(JsonMap frame) =>
|
||||
frame['resolved'] == true ||
|
||||
'${frame['decision'] ?? ''}'.trim().isNotEmpty;
|
||||
|
||||
void _pruneSettledPermissions() {
|
||||
final settled = _permissions.where(_permissionSettled).toList();
|
||||
final excess = settled.length - settledLimit;
|
||||
if (excess <= 0) return;
|
||||
for (final frame in settled.take(excess)) {
|
||||
_permissions.remove(frame);
|
||||
final id = '${frame['request_id'] ?? ''}'.trim();
|
||||
_answers.remove(id);
|
||||
_permissionErrors.remove(id);
|
||||
}
|
||||
}
|
||||
|
||||
void _pruneSettledForms() {
|
||||
final settled = [
|
||||
for (final entry in _forms.entries)
|
||||
if (!chatFormPending(entry.value)) entry.key,
|
||||
];
|
||||
final excess = settled.length - settledLimit;
|
||||
if (excess <= 0) return;
|
||||
for (final id in settled.take(excess)) {
|
||||
_forms.remove(id);
|
||||
_formErrors.remove(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import 'package:flutter/foundation.dart';
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../data/chat_repository.dart';
|
||||
import '../domain/chat_transcript.dart';
|
||||
import 'chat_thread_cards.dart';
|
||||
|
||||
/// One open conversation's transcript and live turn state.
|
||||
///
|
||||
@@ -15,6 +16,9 @@ import '../domain/chat_transcript.dart';
|
||||
/// instead of merging stale state. The server detaches subscriptions when the
|
||||
/// socket closes, so disposal only cancels the local stream (there is no
|
||||
/// `chat_unsubscribe`).
|
||||
///
|
||||
/// Approval requests and question forms are recorded cards rather than
|
||||
/// messages; [ChatThreadCards] owns their frames, answers and send gates.
|
||||
class ChatThreadController extends ChangeNotifier {
|
||||
ChatThreadController(this.gateway, this.sessionId) {
|
||||
_subscription = gateway.frames.listen(_onFrame);
|
||||
@@ -23,6 +27,12 @@ class ChatThreadController extends ChangeNotifier {
|
||||
final ApiGateway gateway;
|
||||
final String sessionId;
|
||||
late final ChatRepository _repository = ChatRepository(gateway);
|
||||
late final ChatThreadCards _cards = ChatThreadCards(
|
||||
repository: _repository,
|
||||
sessionId: sessionId,
|
||||
notify: _notify,
|
||||
isAlive: () => !_disposed,
|
||||
);
|
||||
StreamSubscription<JsonMap>? _subscription;
|
||||
|
||||
List<JsonMap> _messages = const [];
|
||||
@@ -53,6 +63,30 @@ class ChatThreadController extends ChangeNotifier {
|
||||
bool get subscribed => _subscribed;
|
||||
String? get subscriptionError => _subscriptionError;
|
||||
|
||||
/// Every retained permission request, settled or still open, in server order.
|
||||
List<JsonMap> get permissionFrames => _cards.permissions;
|
||||
|
||||
/// Every retained question form, including answered and expired ones.
|
||||
List<JsonMap> get questionForms => _cards.forms;
|
||||
|
||||
String permissionAnswerFor(String requestId) => _cards.answerFor(requestId);
|
||||
|
||||
String? permissionErrorFor(String requestId) =>
|
||||
_cards.permissionErrorFor(requestId);
|
||||
|
||||
String? questionErrorFor(String formId) => _cards.formErrorFor(formId);
|
||||
|
||||
/// Answer one pending approval through the card collaborator.
|
||||
Future<void> replyPermission(String requestId, String decision) =>
|
||||
_cards.replyPermission(requestId, decision);
|
||||
|
||||
/// Answer or close a pending question through the card collaborator.
|
||||
Future<void> answerQuestion(
|
||||
String formId,
|
||||
Map<String, dynamic> answers,
|
||||
String action,
|
||||
) => _cards.answerQuestion(formId, answers, action);
|
||||
|
||||
/// Subscribes this session, then loads its newest history page.
|
||||
Future<void> load() async {
|
||||
if (_disposed) return;
|
||||
@@ -174,12 +208,26 @@ class ChatThreadController extends ChangeNotifier {
|
||||
|
||||
void _onFrame(JsonMap envelope) {
|
||||
if (_disposed) return;
|
||||
if (envelope['type'] == 'chat_permission') {
|
||||
final permission = envelope['chat_permission'];
|
||||
if (permission is! Map) return;
|
||||
final frame = Map<String, dynamic>.from(permission);
|
||||
if ('${frame['session_id'] ?? ''}' != sessionId) return;
|
||||
_cards.foldPermission(frame);
|
||||
return;
|
||||
}
|
||||
final body = _eventBody(envelope);
|
||||
if (body == null || body['session_id'] != sessionId) return;
|
||||
if (body['kind'] == 'resync') {
|
||||
unawaited(resync());
|
||||
return;
|
||||
}
|
||||
if (body['kind'] == 'form') {
|
||||
final form = body['form'];
|
||||
if (form is! Map) return;
|
||||
_cards.foldForm(Map<String, dynamic>.from(form));
|
||||
return;
|
||||
}
|
||||
final current = _thread;
|
||||
final next = applyChatEvent(current, body);
|
||||
if (identical(next, current)) return;
|
||||
|
||||
@@ -13,6 +13,7 @@ import 'chat_composer_controller.dart';
|
||||
import 'chat_draft_store.dart';
|
||||
import 'chat_row_keys.dart';
|
||||
import 'chat_thread_controller.dart';
|
||||
import 'chat_transcript_card.dart';
|
||||
|
||||
/// One read-only conversation: the controller's transcript in the order the
|
||||
/// server reports it, rendered by the existing [ChatMessageView].
|
||||
@@ -149,7 +150,18 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
builder: (context, _) {
|
||||
final cupertino =
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
||||
final rows = transcriptRows(_visibleMessages());
|
||||
final cards = chatCardRows(
|
||||
permissions: _controller.permissionFrames,
|
||||
forms: _controller.questionForms,
|
||||
answerFor: _controller.permissionAnswerFor,
|
||||
permissionErrorFor: _controller.permissionErrorFor,
|
||||
formErrorFor: _controller.questionErrorFor,
|
||||
);
|
||||
// A pending approval/question means the turn is waiting on the operator,
|
||||
// not generating, so the transcript indicator and its live region stand
|
||||
// down; the composer's Stop control still follows `running`.
|
||||
final awaiting = cards.any(chatCardAwaitingOperator);
|
||||
final rows = transcriptRows(_visibleMessages(), trailing: cards);
|
||||
// Older pages prepend messages and a live frame can append one, so a
|
||||
// folded assistant turn's first message id is not a stable identity.
|
||||
// ChatRowKeys carries a turn's key forward while it still holds any of
|
||||
@@ -242,12 +254,20 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
Padding(
|
||||
key: ValueKey<String>(keys[index]),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: ChatMessageView(
|
||||
row: rows[index],
|
||||
textBuilder: chatMarkdownText,
|
||||
),
|
||||
child:
|
||||
rows[index]['kind'] == 'permission' ||
|
||||
rows[index]['kind'] == 'question'
|
||||
? ChatTranscriptCard(
|
||||
row: rows[index],
|
||||
onPermissionDecision: _controller.replyPermission,
|
||||
onQuestionAnswer: _controller.answerQuestion,
|
||||
)
|
||||
: ChatMessageView(
|
||||
row: rows[index],
|
||||
textBuilder: chatMarkdownText,
|
||||
),
|
||||
),
|
||||
if (_controller.running)
|
||||
if (_controller.running && !awaiting)
|
||||
Padding(
|
||||
key: const Key('chat-running'),
|
||||
padding: const EdgeInsets.all(16),
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'chat_permission_card.dart';
|
||||
import 'chat_permission_card_model.dart';
|
||||
import 'chat_question_card.dart';
|
||||
import 'chat_question_card_model.dart';
|
||||
|
||||
/// Build transcript card rows for recorded permission requests and questions.
|
||||
///
|
||||
/// Cards are not transcript messages: they keep the server's order and follow
|
||||
/// the message rows. Their keys are the server ids, so a streaming repaint
|
||||
/// keeps an open disclosure or a half-typed answer attached to the same card.
|
||||
List<JsonMap> chatCardRows({
|
||||
required Iterable<JsonMap> permissions,
|
||||
required Iterable<JsonMap> forms,
|
||||
required String Function(String requestId) answerFor,
|
||||
required String? Function(String requestId) permissionErrorFor,
|
||||
required String? Function(String formId) formErrorFor,
|
||||
}) {
|
||||
final rows = <JsonMap>[];
|
||||
for (final permission in permissions) {
|
||||
final id = '${permission['request_id'] ?? ''}'.trim();
|
||||
if (id.isEmpty) continue;
|
||||
rows.add({
|
||||
'kind': 'permission',
|
||||
'key': 'chat-permission-$id',
|
||||
'frame': permission,
|
||||
'answer': answerFor(id),
|
||||
'error': permissionErrorFor(id),
|
||||
});
|
||||
}
|
||||
for (final form in forms) {
|
||||
final id = '${form['id'] ?? ''}'.trim();
|
||||
if (id.isEmpty) continue;
|
||||
rows.add({
|
||||
'kind': 'question',
|
||||
'key': 'chat-question-$id',
|
||||
'form': form,
|
||||
'error': formErrorFor(id),
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/// True while one card still needs the operator: an open approval request or a
|
||||
/// pending question form.
|
||||
///
|
||||
/// A turn blocked on the operator is not generating, so the transcript's running
|
||||
/// indicator stands down while this is true (the web does the same); the
|
||||
/// composer's Stop control remains driven by the turn alone.
|
||||
bool chatCardAwaitingOperator(JsonMap row) {
|
||||
final kind = '${row['kind'] ?? ''}';
|
||||
if (kind == 'permission') {
|
||||
final frame = row['frame'];
|
||||
if (frame is! Map) return false;
|
||||
final card = chatPermissionCard(
|
||||
Map<String, dynamic>.from(frame),
|
||||
'${row['answer'] ?? ''}',
|
||||
);
|
||||
return card?.actionable == true;
|
||||
}
|
||||
if (kind == 'question') {
|
||||
final form = row['form'];
|
||||
return form is Map && chatFormPending(Map<String, dynamic>.from(form));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Small dispatcher: render one card row with the host's native controls.
|
||||
class ChatTranscriptCard extends StatelessWidget {
|
||||
const ChatTranscriptCard({
|
||||
super.key,
|
||||
required this.row,
|
||||
required this.onPermissionDecision,
|
||||
required this.onQuestionAnswer,
|
||||
});
|
||||
|
||||
final JsonMap row;
|
||||
final Future<void> Function(String requestId, String decision)
|
||||
onPermissionDecision;
|
||||
final Future<void> Function(
|
||||
String formId,
|
||||
Map<String, dynamic> answers,
|
||||
String action,
|
||||
)
|
||||
onQuestionAnswer;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final kind = '${row['kind'] ?? ''}';
|
||||
if (kind == 'permission') {
|
||||
final frame = row['frame'] is Map
|
||||
? Map<String, dynamic>.from(row['frame'] as Map)
|
||||
: null;
|
||||
final card = chatPermissionCard(frame, '${row['answer'] ?? ''}');
|
||||
if (card == null) return const SizedBox.shrink();
|
||||
return ChatPermissionCard(
|
||||
card: card,
|
||||
error: row['error'] as String?,
|
||||
onDecision: (decision) =>
|
||||
onPermissionDecision(card.requestId, decision),
|
||||
);
|
||||
}
|
||||
if (kind == 'question') {
|
||||
final form = row['form'] is Map
|
||||
? Map<String, dynamic>.from(row['form'] as Map)
|
||||
: null;
|
||||
if (form == null || '${form['id'] ?? ''}'.trim().isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
final id = '${form['id']}'.trim();
|
||||
return ChatQuestionCard(
|
||||
form: form,
|
||||
error: row['error'] as String?,
|
||||
onSubmit: (answers, action) => onQuestionAnswer(id, answers, action),
|
||||
);
|
||||
}
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,14 @@ JsonMap mergeChatHistory(JsonMap previous, JsonMap page, {bool older = false}) {
|
||||
/// identity uses `messageIds`. That list carries every message the folded turn
|
||||
/// currently holds so the view can keep the same row element while the turn
|
||||
/// grows at either end.
|
||||
List<JsonMap> transcriptRows(List<JsonMap> messages) {
|
||||
///
|
||||
/// [trailing] rows are conversation cards (permission requests and questions),
|
||||
/// not messages. They keep the server's order after the transcript, the way the
|
||||
/// web renders approvals and forms at the end of the conversation.
|
||||
List<JsonMap> transcriptRows(
|
||||
List<JsonMap> messages, {
|
||||
List<JsonMap> trailing = const [],
|
||||
}) {
|
||||
final rows = <JsonMap>[];
|
||||
String? key;
|
||||
final ids = <String>[];
|
||||
@@ -73,6 +80,7 @@ List<JsonMap> transcriptRows(List<JsonMap> messages) {
|
||||
}
|
||||
}
|
||||
flush();
|
||||
rows.addAll(trailing);
|
||||
return rows;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import 'graph_viewport.dart';
|
||||
import 'graph_viewport_controller.dart';
|
||||
|
||||
/// The expanded presentation's close wording (`Close`).
|
||||
const String graphExpandedClose = 'Close';
|
||||
|
||||
/// Builds the same canvas for another viewport, with the selection that
|
||||
/// presentation is showing.
|
||||
typedef GraphExpandedCanvasBuilder =
|
||||
Widget Function(
|
||||
BuildContext context,
|
||||
String? selectedStage,
|
||||
ValueChanged<String> onSelected,
|
||||
);
|
||||
|
||||
/// A native full-screen presentation of one graph canvas.
|
||||
///
|
||||
/// It fits the graph into the larger box (as the web does when its panel
|
||||
/// expands), keeps the selected node selected, and lets a tap in the larger
|
||||
/// canvas update that selection through [onSelected]. Closing pops the route;
|
||||
/// the inline canvas was never changed, so it returns to its previous state.
|
||||
class GraphExpandedView extends StatefulWidget {
|
||||
const GraphExpandedView({
|
||||
super.key,
|
||||
required this.contentSize,
|
||||
required this.canvasBuilder,
|
||||
required this.title,
|
||||
required this.onSelected,
|
||||
this.selectedStage,
|
||||
this.header,
|
||||
});
|
||||
|
||||
/// The measured graph extent, as in the inline canvas.
|
||||
final Size contentSize;
|
||||
|
||||
final GraphExpandedCanvasBuilder canvasBuilder;
|
||||
|
||||
/// The presentation's native title, e.g. `Run graph`.
|
||||
final String title;
|
||||
|
||||
/// Reports a node activated in the expanded canvas.
|
||||
final ValueChanged<String> onSelected;
|
||||
|
||||
/// Optional fixed content above the canvas, e.g. a legend that explains the
|
||||
/// graph's marks. It stays outside the pan/zoom transform.
|
||||
final Widget? header;
|
||||
|
||||
final String? selectedStage;
|
||||
|
||||
@override
|
||||
State<GraphExpandedView> createState() => _GraphExpandedViewState();
|
||||
}
|
||||
|
||||
class _GraphExpandedViewState extends State<GraphExpandedView> {
|
||||
final GraphViewportController _controller = GraphViewportController();
|
||||
late String? _selected = widget.selectedStage;
|
||||
|
||||
@override
|
||||
void didUpdateWidget(GraphExpandedView oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (widget.selectedStage != oldWidget.selectedStage) {
|
||||
_selected = widget.selectedStage;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _select(String key) {
|
||||
setState(() => _selected = key);
|
||||
widget.onSelected(key);
|
||||
}
|
||||
|
||||
void _close() => Navigator.of(context).maybePop();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final viewport = GraphViewport(
|
||||
key: const Key('graph-expanded-viewport'),
|
||||
controller: _controller,
|
||||
contentSize: widget.contentSize,
|
||||
// The larger box fits the whole graph, as the web does when its panel
|
||||
// expands; a later resize re-fits until the reader pans or zooms, then
|
||||
// only clamps.
|
||||
child: widget.canvasBuilder(context, _selected, _select),
|
||||
);
|
||||
final body = widget.header == null
|
||||
? viewport
|
||||
: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
widget.header!,
|
||||
Expanded(child: viewport),
|
||||
],
|
||||
);
|
||||
if (usesCupertinoHost(context)) {
|
||||
return CupertinoPageScaffold(
|
||||
navigationBar: CupertinoNavigationBar(
|
||||
automaticallyImplyLeading: false,
|
||||
middle: Text(widget.title),
|
||||
trailing: CupertinoButton(
|
||||
key: const Key('graph-expanded-close'),
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: _close,
|
||||
child: const Text(graphExpandedClose),
|
||||
),
|
||||
),
|
||||
child: SafeArea(child: body),
|
||||
);
|
||||
}
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(widget.title),
|
||||
automaticallyImplyLeading: false,
|
||||
actions: [
|
||||
TextButton(
|
||||
key: const Key('graph-expanded-close'),
|
||||
onPressed: _close,
|
||||
child: const Text(graphExpandedClose),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: SafeArea(child: body),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Pushes [GraphExpandedView] with the host's native full-screen transition.
|
||||
///
|
||||
/// This is the seam a Graph tab or run detail can call: pass the measured
|
||||
/// content size and a builder that draws the same canvas for the supplied
|
||||
/// selection. The expanded canvas fits that size; the inline canvas is
|
||||
/// untouched.
|
||||
Future<void> openGraphExpanded(
|
||||
BuildContext context, {
|
||||
required Size contentSize,
|
||||
required GraphExpandedCanvasBuilder canvasBuilder,
|
||||
required String title,
|
||||
required ValueChanged<String> onSelected,
|
||||
String? selectedStage,
|
||||
Widget? header,
|
||||
}) {
|
||||
final page = GraphExpandedView(
|
||||
contentSize: contentSize,
|
||||
canvasBuilder: canvasBuilder,
|
||||
title: title,
|
||||
onSelected: onSelected,
|
||||
selectedStage: selectedStage,
|
||||
header: header,
|
||||
);
|
||||
final route = usesCupertinoHost(context)
|
||||
? CupertinoPageRoute<void>(fullscreenDialog: true, builder: (_) => page)
|
||||
: MaterialPageRoute<void>(fullscreenDialog: true, builder: (_) => page);
|
||||
return Navigator.of(context).push(route);
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import 'graph_viewport_controller.dart';
|
||||
|
||||
/// The fit control's web wording (`Fit graph to view`).
|
||||
const String graphFitLabel = 'Fit graph to view';
|
||||
|
||||
/// The expand control's web wording (`Expand graph`).
|
||||
const String graphExpandLabel = 'Expand graph';
|
||||
|
||||
/// A bounded graph canvas with the host's own pan, pinch, wheel and trackpad
|
||||
/// zoom, plus a fit control and an optional expanded presentation.
|
||||
///
|
||||
/// [controller] owns the transform, so a caller can read or restore a
|
||||
/// [GraphViewportSnapshot]. Gestures are consumed only inside this widget's
|
||||
/// box: an ancestor scroll view keeps scrolling everywhere else, and a tap
|
||||
/// that does not move still reaches the native node under the pointer.
|
||||
class GraphViewport extends StatefulWidget {
|
||||
const GraphViewport({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.contentSize,
|
||||
required this.child,
|
||||
this.onExpand,
|
||||
});
|
||||
|
||||
final GraphViewportController controller;
|
||||
|
||||
/// The measured graph extent; the canvas never invents a fixed size.
|
||||
final Size contentSize;
|
||||
|
||||
/// The measured, already-routed graph content.
|
||||
final Widget child;
|
||||
|
||||
/// Opens the expanded presentation. Null hides the expand control.
|
||||
final VoidCallback? onExpand;
|
||||
|
||||
@override
|
||||
State<GraphViewport> createState() => _GraphViewportState();
|
||||
}
|
||||
|
||||
class _GraphViewportState extends State<GraphViewport> {
|
||||
Size? _scheduledViewport;
|
||||
Size? _scheduledContent;
|
||||
|
||||
@override
|
||||
void didUpdateWidget(GraphViewport oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.controller != widget.controller) {
|
||||
_scheduledViewport = null;
|
||||
_scheduledContent = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Attaches the current extents after layout, never during build.
|
||||
void _scheduleAttach(Size viewport) {
|
||||
if (viewport == _scheduledViewport &&
|
||||
widget.contentSize == _scheduledContent) {
|
||||
return;
|
||||
}
|
||||
_scheduledViewport = viewport;
|
||||
_scheduledContent = widget.contentSize;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
widget.controller.attach(viewport: viewport, content: widget.contentSize);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final viewport =
|
||||
constraints.hasBoundedWidth && constraints.hasBoundedHeight
|
||||
? constraints.biggest
|
||||
: widget.contentSize;
|
||||
if (!widget.controller.isAttached) {
|
||||
// The very first layout has no `InteractiveViewer` listening yet, so
|
||||
// fitting here applies before the first paint instead of flashing an
|
||||
// identity transform for one frame.
|
||||
widget.controller.attach(
|
||||
viewport: viewport,
|
||||
content: widget.contentSize,
|
||||
);
|
||||
_scheduledViewport = viewport;
|
||||
_scheduledContent = widget.contentSize;
|
||||
} else {
|
||||
_scheduleAttach(viewport);
|
||||
}
|
||||
return Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
Positioned.fill(
|
||||
child: InteractiveViewer(
|
||||
key: const Key('graph-viewport'),
|
||||
transformationController: widget.controller.transformation,
|
||||
constrained: false,
|
||||
// The graph owns its own bounds (fit and the visible-pan clamp),
|
||||
// so the viewer must not impose a second, cover-the-viewport
|
||||
// boundary that would fight the fit scale.
|
||||
boundaryMargin: const EdgeInsets.all(double.infinity),
|
||||
minScale: widget.controller.minScale,
|
||||
maxScale: widget.controller.maxScale,
|
||||
clipBehavior: Clip.hardEdge,
|
||||
child: SizedBox.fromSize(
|
||||
size: widget.contentSize,
|
||||
child: widget.child,
|
||||
),
|
||||
),
|
||||
),
|
||||
PositionedDirectional(
|
||||
top: 8,
|
||||
end: 8,
|
||||
child: Wrap(
|
||||
spacing: 8,
|
||||
children: [
|
||||
_ViewportButton(
|
||||
buttonKey: const Key('graph-fit'),
|
||||
icon: _fitIcon(context),
|
||||
label: graphFitLabel,
|
||||
onPressed: widget.controller.fitToViewport,
|
||||
),
|
||||
if (widget.onExpand != null)
|
||||
_ViewportButton(
|
||||
buttonKey: const Key('graph-expand'),
|
||||
icon: _expandIcon(context),
|
||||
label: graphExpandLabel,
|
||||
onPressed: widget.onExpand,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
IconData _fitIcon(BuildContext context) =>
|
||||
usesCupertinoHost(context) ? CupertinoIcons.resize : Icons.fit_screen;
|
||||
|
||||
IconData _expandIcon(BuildContext context) =>
|
||||
usesCupertinoHost(context) ? CupertinoIcons.fullscreen : Icons.fullscreen;
|
||||
}
|
||||
|
||||
/// One native graph control: a tinted icon button on either host.
|
||||
///
|
||||
/// The label and the button's own tap action must reach the same semantics
|
||||
/// node: the icon is the only excluded child, and [MergeSemantics] folds the
|
||||
/// host button's action into the labelled node, so a screen reader can activate
|
||||
/// Fit and Expand on either host. A hand-written `Semantics` sibling around an
|
||||
/// excluded button would announce the control with no action at all.
|
||||
class _ViewportButton extends StatelessWidget {
|
||||
const _ViewportButton({
|
||||
required this.buttonKey,
|
||||
required this.icon,
|
||||
required this.label,
|
||||
required this.onPressed,
|
||||
});
|
||||
|
||||
final Key buttonKey;
|
||||
final IconData icon;
|
||||
final String label;
|
||||
final VoidCallback? onPressed;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MergeSemantics(
|
||||
child: Semantics(
|
||||
button: true,
|
||||
label: label,
|
||||
child: usesCupertinoHost(context)
|
||||
? CupertinoButton.tinted(
|
||||
key: buttonKey,
|
||||
padding: const EdgeInsets.all(8),
|
||||
onPressed: onPressed,
|
||||
child: ExcludeSemantics(child: Icon(icon)),
|
||||
)
|
||||
: Tooltip(
|
||||
message: label,
|
||||
// The merged node already carries the label; the tooltip is
|
||||
// only the pointer affordance.
|
||||
excludeFromSemantics: true,
|
||||
child: IconButton.filledTonal(
|
||||
key: buttonKey,
|
||||
onPressed: onPressed,
|
||||
icon: ExcludeSemantics(child: Icon(icon)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import 'graph_viewport_math.dart';
|
||||
|
||||
/// One graph viewport's scale and offset, independent of any viewport size.
|
||||
///
|
||||
/// A snapshot is what the expanded presentation carries over: the same scale
|
||||
/// and offset the inline canvas is showing, so opening and closing it never
|
||||
/// loses the reader's place.
|
||||
@immutable
|
||||
class GraphViewportSnapshot {
|
||||
const GraphViewportSnapshot({required this.scale, required this.offset});
|
||||
|
||||
final double scale;
|
||||
final Offset offset;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is GraphViewportSnapshot &&
|
||||
other.scale == scale &&
|
||||
other.offset == offset;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(scale, offset);
|
||||
|
||||
@override
|
||||
String toString() => 'GraphViewportSnapshot(scale: $scale, offset: $offset)';
|
||||
}
|
||||
|
||||
/// Owns one graph canvas's transform.
|
||||
///
|
||||
/// Pan and pinch stay the host's own gestures ([InteractiveViewer] drives the
|
||||
/// [transformation]); this controller only supplies the graph's bounds: a fit
|
||||
/// with padding, the min/max scale and a pan clamp that keeps part of the graph
|
||||
/// visible. It never changes a node, route or label. A snapshot lets a caller
|
||||
/// read or restore a place; the expanded presentation owns its own controller,
|
||||
/// so closing it leaves this transform exactly as it was.
|
||||
class GraphViewportController extends ChangeNotifier {
|
||||
GraphViewportController({
|
||||
this.minScale = graphMinScale,
|
||||
this.maxScale = graphMaxScale,
|
||||
this.fitPadding = graphFitPadding,
|
||||
this.minVisible = graphMinVisible,
|
||||
}) : assert(minScale > 0),
|
||||
assert(maxScale >= minScale),
|
||||
_transformation = TransformationController() {
|
||||
_transformation.addListener(_handleTransform);
|
||||
}
|
||||
|
||||
/// The native pan/zoom transform handed to [InteractiveViewer].
|
||||
final TransformationController _transformation;
|
||||
|
||||
TransformationController get transformation => _transformation;
|
||||
|
||||
final double minScale;
|
||||
final double maxScale;
|
||||
final double fitPadding;
|
||||
final double minVisible;
|
||||
|
||||
Size? _viewport;
|
||||
Size? _content;
|
||||
bool _userAdjusted = false;
|
||||
bool _applying = false;
|
||||
|
||||
/// The current uniform scale (`getMaxScaleOnAxis` of the transform).
|
||||
double get scale => _transformation.value.getMaxScaleOnAxis();
|
||||
|
||||
/// The current graph-space translation of the transform.
|
||||
Offset get offset {
|
||||
final translation = _transformation.value.getTranslation();
|
||||
return Offset(translation.x, translation.y);
|
||||
}
|
||||
|
||||
GraphViewportSnapshot get snapshot =>
|
||||
GraphViewportSnapshot(scale: scale, offset: offset);
|
||||
|
||||
/// Whether this controller has seen a viewport and content extent yet.
|
||||
bool get isAttached => _viewport != null && _content != null;
|
||||
|
||||
/// Records the current viewport and content extents.
|
||||
///
|
||||
/// The first attach (and any later resize before the reader interacts) fits
|
||||
/// the graph with [fitPadding]. Once the reader has panned or zoomed, a
|
||||
/// resize keeps their place and only re-clamps it.
|
||||
void attach({required Size viewport, required Size content}) {
|
||||
if (viewport == _viewport && content == _content) return;
|
||||
_viewport = viewport;
|
||||
_content = content;
|
||||
if (!_userAdjusted) {
|
||||
fitToViewport();
|
||||
} else {
|
||||
_clamp();
|
||||
}
|
||||
}
|
||||
|
||||
/// Fits the whole graph in the current viewport and clears the user-adjusted
|
||||
/// flag, so a later resize fits again.
|
||||
void fitToViewport() {
|
||||
final viewport = _viewport;
|
||||
final content = _content;
|
||||
if (viewport == null || content == null) return;
|
||||
final scale = graphFitScale(
|
||||
viewport,
|
||||
content,
|
||||
padding: fitPadding,
|
||||
minScale: minScale,
|
||||
maxScale: maxScale,
|
||||
);
|
||||
final scaled = Size(content.width * scale, content.height * scale);
|
||||
_apply(
|
||||
graphClampOffset(
|
||||
graphCenteredOffset(scaled, viewport),
|
||||
scaled,
|
||||
viewport,
|
||||
minVisible: minVisible,
|
||||
),
|
||||
scale,
|
||||
);
|
||||
_userAdjusted = false;
|
||||
}
|
||||
|
||||
/// Applies an explicit snapshot, e.g. when a caller restores a viewport.
|
||||
void applySnapshot(GraphViewportSnapshot snapshot) {
|
||||
_userAdjusted = true;
|
||||
_apply(snapshot.offset, snapshot.scale.clamp(minScale, maxScale));
|
||||
}
|
||||
|
||||
void _apply(Offset offset, double scale) {
|
||||
_applying = true;
|
||||
_transformation.value = graphViewportMatrix(offset, scale);
|
||||
_applying = false;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Keeps every externally driven transform (a gesture, a wheel or a trackpad
|
||||
/// pinch) inside the graph's scale and pan bounds.
|
||||
void _handleTransform() {
|
||||
if (_applying) return;
|
||||
_userAdjusted = true;
|
||||
_clamp();
|
||||
}
|
||||
|
||||
void _clamp() {
|
||||
final viewport = _viewport;
|
||||
final content = _content;
|
||||
if (viewport == null || content == null) return;
|
||||
final currentScale = scale;
|
||||
final boundedScale = currentScale.clamp(minScale, maxScale);
|
||||
final scaled = Size(
|
||||
content.width * boundedScale,
|
||||
content.height * boundedScale,
|
||||
);
|
||||
final currentOffset = offset;
|
||||
final boundedOffset = graphClampOffset(
|
||||
currentOffset,
|
||||
scaled,
|
||||
viewport,
|
||||
minVisible: minVisible,
|
||||
);
|
||||
if (boundedScale != currentScale || boundedOffset != currentOffset) {
|
||||
_apply(boundedOffset, boundedScale);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_transformation.removeListener(_handleTransform);
|
||||
_transformation.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/widgets.dart' show Matrix4, Offset, Size;
|
||||
|
||||
/// The smallest scale a graph viewport may reach (`MIN_SCALE`).
|
||||
const double graphMinScale = 0.3;
|
||||
|
||||
/// The largest scale a graph viewport may reach (`MAX_SCALE`).
|
||||
const double graphMaxScale = 3;
|
||||
|
||||
/// Padding kept around a fitted graph, in graph-space pixels
|
||||
/// (`GRAPH_FIT_PADDING`).
|
||||
const double graphFitPadding = 24;
|
||||
|
||||
/// The least amount of the scaled graph kept inside the viewport on each axis,
|
||||
/// so a pan can never leave an empty canvas (`GRAPH_MIN_VISIBLE`).
|
||||
const double graphMinVisible = 40;
|
||||
|
||||
/// The transform that draws graph space at `offset + point * scale`.
|
||||
Matrix4 graphViewportMatrix(Offset offset, double scale) => Matrix4.identity()
|
||||
..translateByDouble(offset.dx, offset.dy, 0, 1)
|
||||
..scaleByDouble(scale, scale, scale, 1);
|
||||
|
||||
/// Uniform scale that fits [content] inside [viewport] with [padding] on every
|
||||
/// side, never upscaling above 1:1 and never leaving the scale bounds.
|
||||
///
|
||||
/// Degenerate or non-finite sizes return 1 rather than dividing by zero, so no
|
||||
/// NaN or infinity ever reaches a transform. This is the web graph's
|
||||
/// `fitScale` rule.
|
||||
double graphFitScale(
|
||||
Size viewport,
|
||||
Size content, {
|
||||
double padding = graphFitPadding,
|
||||
double minScale = graphMinScale,
|
||||
double maxScale = graphMaxScale,
|
||||
}) {
|
||||
final availableWidth = viewport.width - 2 * padding;
|
||||
final availableHeight = viewport.height - 2 * padding;
|
||||
final finite =
|
||||
viewport.width.isFinite &&
|
||||
viewport.height.isFinite &&
|
||||
content.width.isFinite &&
|
||||
content.height.isFinite;
|
||||
if (!finite ||
|
||||
content.width <= 0 ||
|
||||
content.height <= 0 ||
|
||||
availableWidth <= 0 ||
|
||||
availableHeight <= 0) {
|
||||
return 1;
|
||||
}
|
||||
final scale = math.min(
|
||||
1.0,
|
||||
math.min(availableWidth / content.width, availableHeight / content.height),
|
||||
);
|
||||
return scale.clamp(minScale, maxScale);
|
||||
}
|
||||
|
||||
/// Bounds [offset] so at least [minVisible] pixels of the already scaled
|
||||
/// [scaledContent] stay inside [viewport] on each axis.
|
||||
///
|
||||
/// The web graph's `clampOffset`: `offset.x` stays in
|
||||
/// `[minVisible - width, viewport.width - minVisible]`. Degenerate content or
|
||||
/// an empty range returns the input unchanged.
|
||||
Offset graphClampOffset(
|
||||
Offset offset,
|
||||
Size scaledContent,
|
||||
Size viewport, {
|
||||
double minVisible = graphMinVisible,
|
||||
}) {
|
||||
if (scaledContent.width <= 0 ||
|
||||
scaledContent.height <= 0 ||
|
||||
!scaledContent.width.isFinite ||
|
||||
!scaledContent.height.isFinite ||
|
||||
!viewport.width.isFinite ||
|
||||
!viewport.height.isFinite) {
|
||||
return offset;
|
||||
}
|
||||
final minX = minVisible - scaledContent.width;
|
||||
final maxX = viewport.width - minVisible;
|
||||
final minY = minVisible - scaledContent.height;
|
||||
final maxY = viewport.height - minVisible;
|
||||
return Offset(
|
||||
minX <= maxX ? offset.dx.clamp(minX, maxX) : offset.dx,
|
||||
minY <= maxY ? offset.dy.clamp(minY, maxY) : offset.dy,
|
||||
);
|
||||
}
|
||||
|
||||
/// The centered offset that puts [scaledContent] in the middle of [viewport].
|
||||
Offset graphCenteredOffset(Size scaledContent, Size viewport) => Offset(
|
||||
(viewport.width - scaledContent.width) / 2,
|
||||
(viewport.height - scaledContent.height) / 2,
|
||||
);
|
||||
@@ -0,0 +1,76 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../domain/graph_definition.dart';
|
||||
import '../layout/layout_models.dart';
|
||||
import '../painting/graph_edge_layer.dart';
|
||||
import '../routing/route_models.dart';
|
||||
import 'graph_canvas_style.dart';
|
||||
import 'graph_stage_node.dart';
|
||||
|
||||
/// The measured definition canvas at any viewport size and selection.
|
||||
///
|
||||
/// Used by both the inline [GraphViewport] and the expanded presentation: the
|
||||
/// passive edge layer paints behind the native nodes and outcome labels, and
|
||||
/// every node reports selection through [onSelected].
|
||||
class DefinitionGraphCanvas extends StatelessWidget {
|
||||
const DefinitionGraphCanvas({
|
||||
super.key,
|
||||
required this.nodes,
|
||||
required this.layout,
|
||||
required this.routing,
|
||||
required this.style,
|
||||
required this.selectedStage,
|
||||
required this.onSelected,
|
||||
});
|
||||
|
||||
final List<GraphNode> nodes;
|
||||
final GraphLayout layout;
|
||||
final GraphRouting routing;
|
||||
final GraphCanvasStyle style;
|
||||
final String? selectedStage;
|
||||
final ValueChanged<String> onSelected;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final nodesByKey = <String, GraphNode>{
|
||||
for (final node in nodes) node.key: node,
|
||||
};
|
||||
final size = Size(routing.width, routing.height);
|
||||
return Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
// The passive layer comes first so every edge paints behind the native
|
||||
// nodes and labels without taking their input.
|
||||
Positioned.fill(
|
||||
child: GraphEdgeLayer(
|
||||
routes: routing.routes,
|
||||
canvasSize: size,
|
||||
color: style.edgeColor,
|
||||
strokeWidth: style.edgeWidth,
|
||||
),
|
||||
),
|
||||
for (final box in layout.nodes)
|
||||
Positioned(
|
||||
left: box.x,
|
||||
top: box.y,
|
||||
width: box.width,
|
||||
height: box.height,
|
||||
child: GraphStageNode(
|
||||
node: nodesByKey[box.key]!,
|
||||
selected: box.key == selectedStage,
|
||||
onSelected: onSelected,
|
||||
),
|
||||
),
|
||||
for (final label in routing.labels)
|
||||
Positioned(
|
||||
left: label.x,
|
||||
top: label.y,
|
||||
child: Text(
|
||||
routing.routeFor(label.edgeId)!.label,
|
||||
style: style.labelStyle,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -5,23 +5,29 @@ import '../../../core/api_gateway.dart';
|
||||
import '../domain/graph_definition.dart';
|
||||
import '../layout/graph_node_layout.dart';
|
||||
import '../layout/layout_models.dart';
|
||||
import '../painting/graph_edge_layer.dart';
|
||||
import '../routing/graph_edge_routing.dart';
|
||||
import '../routing/route_models.dart';
|
||||
import '../viewport/graph_expanded_view.dart';
|
||||
import '../viewport/graph_viewport.dart';
|
||||
import '../viewport/graph_viewport_controller.dart';
|
||||
import 'definition_graph_canvas.dart';
|
||||
import 'graph_canvas_style.dart';
|
||||
import 'graph_stage_node.dart';
|
||||
import 'graph_measurements.dart';
|
||||
|
||||
/// The definition's own empty-state wording (web `PIPELINE_GRAPH_EMPTY`).
|
||||
const String definitionGraphEmpty = 'This pipeline has no stages.';
|
||||
|
||||
/// The expanded definition presentation's title.
|
||||
const String definitionGraphExpandedTitle = 'Pipeline graph';
|
||||
|
||||
/// One pipeline definition as a readable native graph: measured stage nodes,
|
||||
/// routed passive edges behind them and native outcome labels on their boxes.
|
||||
///
|
||||
/// [selectedStage] is a node key (including `#success`/`#failure`) and
|
||||
/// [onSelected] reports the exact key activated. Nothing reads run evidence:
|
||||
/// nodes show no status and terminals stay plain, so no visit is implied. The
|
||||
/// view fills bounded caller constraints with a stock [InteractiveViewer].
|
||||
/// view fills bounded caller constraints with a pan/zoom [GraphViewport] and can
|
||||
/// present the same canvas full screen without losing the selection.
|
||||
class DefinitionGraphView extends StatefulWidget {
|
||||
const DefinitionGraphView({
|
||||
super.key,
|
||||
@@ -41,9 +47,16 @@ class DefinitionGraphView extends StatefulWidget {
|
||||
class _DefinitionGraphViewState extends State<DefinitionGraphView> {
|
||||
final Map<String, Size> _nodeSizes = {};
|
||||
final Map<String, Size> _labelSizes = {};
|
||||
final GraphViewportController _viewport = GraphViewportController();
|
||||
TextScaler? _scaler;
|
||||
bool _rebuildScheduled = false;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_viewport.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeDependencies() {
|
||||
super.didChangeDependencies();
|
||||
@@ -159,56 +172,22 @@ class _DefinitionGraphViewState extends State<DefinitionGraphView> {
|
||||
GraphRouting routing,
|
||||
GraphCanvasStyle style,
|
||||
) {
|
||||
final nodesByKey = <String, GraphNode>{
|
||||
for (final node in nodes) node.key: node,
|
||||
};
|
||||
final size = Size(routing.width, routing.height);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Expanded(
|
||||
child: InteractiveViewer(
|
||||
constrained: false,
|
||||
minScale: 0.3,
|
||||
maxScale: 3,
|
||||
child: SizedBox.fromSize(
|
||||
size: size,
|
||||
child: Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
// The passive layer comes first so every edge paints behind
|
||||
// the native nodes and labels without taking their input.
|
||||
Positioned.fill(
|
||||
child: GraphEdgeLayer(
|
||||
routes: routing.routes,
|
||||
canvasSize: size,
|
||||
color: style.edgeColor,
|
||||
strokeWidth: style.edgeWidth,
|
||||
),
|
||||
),
|
||||
for (final box in layout.nodes)
|
||||
Positioned(
|
||||
left: box.x,
|
||||
top: box.y,
|
||||
width: box.width,
|
||||
height: box.height,
|
||||
child: GraphStageNode(
|
||||
node: nodesByKey[box.key]!,
|
||||
selected: box.key == widget.selectedStage,
|
||||
onSelected: widget.onSelected,
|
||||
),
|
||||
),
|
||||
for (final label in routing.labels)
|
||||
Positioned(
|
||||
left: label.x,
|
||||
top: label.y,
|
||||
child: Text(
|
||||
routing.routeFor(label.edgeId)!.label,
|
||||
style: style.labelStyle,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: GraphViewport(
|
||||
controller: _viewport,
|
||||
contentSize: size,
|
||||
onExpand: () => _openExpanded(nodes, layout, routing, size),
|
||||
child: DefinitionGraphCanvas(
|
||||
nodes: nodes,
|
||||
layout: layout,
|
||||
routing: routing,
|
||||
style: style,
|
||||
selectedStage: widget.selectedStage,
|
||||
onSelected: widget.onSelected,
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -228,4 +207,28 @@ class _DefinitionGraphViewState extends State<DefinitionGraphView> {
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// Opens the same measured canvas full screen, keeping the selection.
|
||||
void _openExpanded(
|
||||
List<GraphNode> nodes,
|
||||
GraphLayout layout,
|
||||
GraphRouting routing,
|
||||
Size size,
|
||||
) {
|
||||
openGraphExpanded(
|
||||
context,
|
||||
contentSize: size,
|
||||
title: definitionGraphExpandedTitle,
|
||||
selectedStage: widget.selectedStage,
|
||||
onSelected: widget.onSelected,
|
||||
canvasBuilder: (context, selected, onSelected) => DefinitionGraphCanvas(
|
||||
nodes: nodes,
|
||||
layout: layout,
|
||||
routing: routing,
|
||||
style: GraphCanvasStyle.of(context),
|
||||
selectedStage: selected,
|
||||
onSelected: onSelected,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -159,7 +159,8 @@ class RunGraphEdgePainter extends CustomPainter {
|
||||
/// outcome labels only for routes the run actually took.
|
||||
///
|
||||
/// [layout] and [routing] are the caller's measured geometry. The canvas never
|
||||
/// changes them and never assumes a node size.
|
||||
/// changes them and never assumes a node size; the caller supplies the pan/zoom
|
||||
/// viewport around this content.
|
||||
class RunGraphCanvas extends StatelessWidget {
|
||||
const RunGraphCanvas({
|
||||
super.key,
|
||||
@@ -202,55 +203,47 @@ class RunGraphCanvas extends StatelessWidget {
|
||||
final executedColor = cupertino
|
||||
? CupertinoTheme.of(context).primaryColor
|
||||
: Theme.of(context).colorScheme.primary;
|
||||
return InteractiveViewer(
|
||||
constrained: false,
|
||||
minScale: 0.3,
|
||||
maxScale: 3,
|
||||
child: SizedBox.fromSize(
|
||||
size: size,
|
||||
child: Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
Positioned.fill(
|
||||
child: RunGraphEdgeLayer(
|
||||
executedRoutes: executed,
|
||||
untakenRoutes: untaken,
|
||||
canvasSize: size,
|
||||
executedColor: executedColor,
|
||||
untakenColor: style.edgeColor,
|
||||
strokeWidth: style.edgeWidth,
|
||||
return Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
Positioned.fill(
|
||||
child: RunGraphEdgeLayer(
|
||||
executedRoutes: executed,
|
||||
untakenRoutes: untaken,
|
||||
canvasSize: size,
|
||||
executedColor: executedColor,
|
||||
untakenColor: style.edgeColor,
|
||||
strokeWidth: style.edgeWidth,
|
||||
),
|
||||
),
|
||||
for (final box in layout.nodes)
|
||||
Positioned(
|
||||
left: box.x,
|
||||
top: box.y,
|
||||
width: box.width,
|
||||
height: box.height,
|
||||
child: RunGraphNode(
|
||||
node: nodesByKey[box.key]!,
|
||||
recordedStatus: recordedStatuses[box.key],
|
||||
selected: box.key == selectedStage,
|
||||
opensVisit:
|
||||
!nodesByKey[box.key]!.terminal &&
|
||||
state.isStageVisited(box.key),
|
||||
onSelected: onStageSelected,
|
||||
),
|
||||
),
|
||||
// A run labels only the routes that actually happened.
|
||||
for (final label in routing.labels)
|
||||
if (executedIds.contains(label.edgeId))
|
||||
Positioned(
|
||||
left: label.x,
|
||||
top: label.y,
|
||||
child: Text(
|
||||
routing.routeFor(label.edgeId)!.label,
|
||||
style: style.labelStyle,
|
||||
),
|
||||
),
|
||||
for (final box in layout.nodes)
|
||||
Positioned(
|
||||
left: box.x,
|
||||
top: box.y,
|
||||
width: box.width,
|
||||
height: box.height,
|
||||
child: RunGraphNode(
|
||||
node: nodesByKey[box.key]!,
|
||||
recordedStatus: recordedStatuses[box.key],
|
||||
selected: box.key == selectedStage,
|
||||
opensVisit:
|
||||
!nodesByKey[box.key]!.terminal &&
|
||||
state.isStageVisited(box.key),
|
||||
onSelected: onStageSelected,
|
||||
),
|
||||
),
|
||||
// A run labels only the routes that actually happened.
|
||||
for (final label in routing.labels)
|
||||
if (executedIds.contains(label.edgeId))
|
||||
Positioned(
|
||||
left: label.x,
|
||||
top: label.y,
|
||||
child: Text(
|
||||
routing.routeFor(label.edgeId)!.label,
|
||||
style: style.labelStyle,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import '../domain/run_graph_state.dart';
|
||||
import 'graph_canvas_style.dart';
|
||||
|
||||
/// The run legend's route-class words (web graph legend).
|
||||
const String runGraphExecuted = 'Executed';
|
||||
const String runGraphNotExecuted = 'Not executed';
|
||||
|
||||
/// The run canvas' fixed header: the route legend, plus the elapsed line while
|
||||
/// the run is still executing.
|
||||
///
|
||||
/// It is shared by the inline view and the full-screen presentation so the
|
||||
/// expanded canvas explains its solid and dashed routes the way the web keeps
|
||||
/// its legend inside the graph panel.
|
||||
class RunGraphHeader extends StatelessWidget {
|
||||
const RunGraphHeader({
|
||||
super.key,
|
||||
required this.state,
|
||||
required this.style,
|
||||
this.now,
|
||||
});
|
||||
|
||||
final RunGraphState state;
|
||||
final GraphCanvasStyle style;
|
||||
|
||||
/// Injectable clock for deterministic elapsed labels; defaults to now.
|
||||
final DateTime Function()? now;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final cupertino = usesCupertinoHost(context);
|
||||
final executedColor = cupertino
|
||||
? CupertinoTheme.of(context).primaryColor
|
||||
: Theme.of(context).colorScheme.primary;
|
||||
final mutedColor = style.edgeColor;
|
||||
final active = state.activeStage;
|
||||
return Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(12, 8, 12, 0),
|
||||
child: Wrap(
|
||||
spacing: 16,
|
||||
runSpacing: 4,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
Semantics(
|
||||
container: true,
|
||||
label: 'Route kinds',
|
||||
child: Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 4,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
_LegendEntry(
|
||||
icon: cupertino
|
||||
? CupertinoIcons.arrow_right
|
||||
: Icons.arrow_forward,
|
||||
label: runGraphExecuted,
|
||||
color: executedColor,
|
||||
),
|
||||
_LegendEntry(
|
||||
icon: cupertino ? CupertinoIcons.minus : Icons.remove,
|
||||
label: runGraphNotExecuted,
|
||||
color: mutedColor,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (active != null)
|
||||
_elapsed(context, active, state.currentStageStartedAt),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _elapsed(BuildContext context, String active, String? startedAt) {
|
||||
final started = startedAt == null ? null : DateTime.tryParse(startedAt);
|
||||
final duration = started == null
|
||||
? null
|
||||
: _formatElapsed((now ?? DateTime.now)().difference(started));
|
||||
final text = duration == null
|
||||
? 'Current stage $active'
|
||||
: 'Current stage $active · elapsed $duration';
|
||||
return Text(text, style: GraphCanvasStyle.of(context).labelStyle);
|
||||
}
|
||||
}
|
||||
|
||||
class _LegendEntry extends StatelessWidget {
|
||||
const _LegendEntry({
|
||||
required this.icon,
|
||||
required this.label,
|
||||
required this.color,
|
||||
});
|
||||
|
||||
final IconData icon;
|
||||
final String label;
|
||||
final Color color;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Wrap(
|
||||
spacing: 4,
|
||||
runSpacing: 2,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
ExcludeSemantics(child: Icon(icon, color: color)),
|
||||
Text(label),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
String _formatElapsed(Duration duration) {
|
||||
final seconds = duration.inSeconds < 0 ? 0 : duration.inSeconds;
|
||||
if (seconds < 60) return '${seconds}s';
|
||||
if (seconds < 3600) return '${seconds ~/ 60}m ${seconds % 60}s';
|
||||
return '${seconds ~/ 3600}h ${(seconds % 3600) ~/ 60}m';
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import '../domain/graph_definition.dart';
|
||||
import '../domain/run_graph_state.dart';
|
||||
import '../domain/stage_visits.dart';
|
||||
@@ -10,15 +8,20 @@ import '../layout/graph_node_layout.dart';
|
||||
import '../layout/layout_models.dart';
|
||||
import '../routing/graph_edge_routing.dart';
|
||||
import '../routing/route_models.dart';
|
||||
import '../viewport/graph_expanded_view.dart';
|
||||
import '../viewport/graph_viewport.dart';
|
||||
import '../viewport/graph_viewport_controller.dart';
|
||||
import 'graph_canvas_style.dart';
|
||||
import 'run_graph_canvas.dart';
|
||||
import 'run_graph_header.dart';
|
||||
|
||||
export 'run_graph_header.dart' show runGraphExecuted, runGraphNotExecuted;
|
||||
|
||||
/// The run tab's exact missing-graph wording (web `RUN_GRAPH_MISSING`).
|
||||
const String runGraphMissing = 'This server did not include the run graph.';
|
||||
|
||||
/// The run legend's route-class words (web graph legend).
|
||||
const String runGraphExecuted = 'Executed';
|
||||
const String runGraphNotExecuted = 'Not executed';
|
||||
/// The expanded run presentation's title.
|
||||
const String runGraphExpandedTitle = 'Run graph';
|
||||
|
||||
/// One run's definition drawn as evidence: visited stages carry their recorded
|
||||
/// status, only taken routes are solid and arrowed, and every other route stays
|
||||
@@ -32,9 +35,10 @@ const String runGraphNotExecuted = 'Not executed';
|
||||
/// shown with the outcome that resolved there but have no recorded visit to
|
||||
/// open, so they stay non-interactive.
|
||||
///
|
||||
/// The view fills its bounded constraints with a stock [InteractiveViewer] for
|
||||
/// pan and zoom; the elapsed line appears only while the run is executing and
|
||||
/// is static (no invented progress or timer).
|
||||
/// The view fills its bounded constraints with a pan/zoom [GraphViewport]; the
|
||||
/// elapsed line appears only while the run is executing and is static (no
|
||||
/// invented progress or timer). The same canvas can be opened full screen with
|
||||
/// its selection preserved and the route legend still explaining its marks.
|
||||
class RunGraphView extends StatefulWidget {
|
||||
const RunGraphView({
|
||||
super.key,
|
||||
@@ -67,9 +71,16 @@ class _RunGraphViewState extends State<RunGraphView> {
|
||||
final Map<String, Size> _nodeSizes = {};
|
||||
final Map<String, Size> _labelSizes = {};
|
||||
final Map<String, String?> _measuredStatuses = {};
|
||||
final GraphViewportController _viewport = GraphViewportController();
|
||||
TextScaler? _scaler;
|
||||
bool _rebuildScheduled = false;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_viewport.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeDependencies() {
|
||||
super.didChangeDependencies();
|
||||
@@ -188,21 +199,32 @@ class _RunGraphViewState extends State<RunGraphView> {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
_header(state, style),
|
||||
RunGraphHeader(state: state, style: style, now: widget.now),
|
||||
Expanded(
|
||||
child: Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
if (geometry != null)
|
||||
RunGraphCanvas(
|
||||
nodes: nodes,
|
||||
layout: geometry.$1,
|
||||
routing: geometry.$2,
|
||||
state: state,
|
||||
style: style,
|
||||
recordedStatuses: statuses,
|
||||
selectedStage: widget.selectedStage,
|
||||
onStageSelected: widget.onStageSelected,
|
||||
GraphViewport(
|
||||
controller: _viewport,
|
||||
contentSize: Size(geometry.$2.width, geometry.$2.height),
|
||||
onExpand: () => _openExpanded(
|
||||
nodes,
|
||||
geometry.$1,
|
||||
geometry.$2,
|
||||
state,
|
||||
statuses,
|
||||
),
|
||||
child: _runCanvas(
|
||||
nodes: nodes,
|
||||
layout: geometry.$1,
|
||||
routing: geometry.$2,
|
||||
state: state,
|
||||
style: style,
|
||||
statuses: statuses,
|
||||
selectedStage: widget.selectedStage,
|
||||
onStageSelected: widget.onStageSelected,
|
||||
),
|
||||
)
|
||||
else
|
||||
const SizedBox.shrink(),
|
||||
@@ -245,87 +267,58 @@ class _RunGraphViewState extends State<RunGraphView> {
|
||||
),
|
||||
);
|
||||
|
||||
Widget _header(RunGraphState state, GraphCanvasStyle style) {
|
||||
final cupertino = usesCupertinoHost(context);
|
||||
final executedColor = cupertino
|
||||
? CupertinoTheme.of(context).primaryColor
|
||||
: Theme.of(context).colorScheme.primary;
|
||||
final mutedColor = style.edgeColor;
|
||||
final active = state.activeStage;
|
||||
return Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(12, 8, 12, 0),
|
||||
child: Wrap(
|
||||
spacing: 16,
|
||||
runSpacing: 4,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
Semantics(
|
||||
container: true,
|
||||
label: 'Route kinds',
|
||||
child: Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 4,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
_LegendEntry(
|
||||
icon: cupertino
|
||||
? CupertinoIcons.arrow_right
|
||||
: Icons.arrow_forward,
|
||||
label: runGraphExecuted,
|
||||
color: executedColor,
|
||||
),
|
||||
_LegendEntry(
|
||||
icon: cupertino ? CupertinoIcons.minus : Icons.remove,
|
||||
label: runGraphNotExecuted,
|
||||
color: mutedColor,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (active != null) _elapsed(active, state.currentStageStartedAt),
|
||||
],
|
||||
/// The same measured run canvas at any viewport size and selection, used by
|
||||
/// the inline viewport and the expanded presentation.
|
||||
Widget _runCanvas({
|
||||
required List<GraphNode> nodes,
|
||||
required GraphLayout layout,
|
||||
required GraphRouting routing,
|
||||
required RunGraphState state,
|
||||
required GraphCanvasStyle style,
|
||||
required Map<String, String?> statuses,
|
||||
required String? selectedStage,
|
||||
required ValueChanged<String> onStageSelected,
|
||||
}) => RunGraphCanvas(
|
||||
nodes: nodes,
|
||||
layout: layout,
|
||||
routing: routing,
|
||||
state: state,
|
||||
style: style,
|
||||
recordedStatuses: statuses,
|
||||
selectedStage: selectedStage,
|
||||
onStageSelected: onStageSelected,
|
||||
);
|
||||
|
||||
void _openExpanded(
|
||||
List<GraphNode> nodes,
|
||||
GraphLayout layout,
|
||||
GraphRouting routing,
|
||||
RunGraphState state,
|
||||
Map<String, String?> statuses,
|
||||
) {
|
||||
openGraphExpanded(
|
||||
context,
|
||||
contentSize: Size(routing.width, routing.height),
|
||||
title: runGraphExpandedTitle,
|
||||
selectedStage: widget.selectedStage,
|
||||
onSelected: widget.onStageSelected,
|
||||
// The full-screen canvas draws solid and dashed routes; the legend that
|
||||
// explains them must travel with it, as it does on the web.
|
||||
header: RunGraphHeader(
|
||||
state: state,
|
||||
style: GraphCanvasStyle.of(context),
|
||||
now: widget.now,
|
||||
),
|
||||
canvasBuilder: (context, selected, onSelected) => _runCanvas(
|
||||
nodes: nodes,
|
||||
layout: layout,
|
||||
routing: routing,
|
||||
state: state,
|
||||
style: GraphCanvasStyle.of(context),
|
||||
statuses: statuses,
|
||||
selectedStage: selected,
|
||||
onStageSelected: onSelected,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _elapsed(String active, String? startedAt) {
|
||||
final started = startedAt == null ? null : DateTime.tryParse(startedAt);
|
||||
final duration = started == null
|
||||
? null
|
||||
: _formatElapsed((widget.now ?? DateTime.now)().difference(started));
|
||||
final text = duration == null
|
||||
? 'Current stage $active'
|
||||
: 'Current stage $active · elapsed $duration';
|
||||
return Text(text, style: GraphCanvasStyle.of(context).labelStyle);
|
||||
}
|
||||
}
|
||||
|
||||
class _LegendEntry extends StatelessWidget {
|
||||
const _LegendEntry({
|
||||
required this.icon,
|
||||
required this.label,
|
||||
required this.color,
|
||||
});
|
||||
|
||||
final IconData icon;
|
||||
final String label;
|
||||
final Color color;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Wrap(
|
||||
spacing: 4,
|
||||
runSpacing: 2,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
ExcludeSemantics(child: Icon(icon, color: color)),
|
||||
Text(label),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
String _formatElapsed(Duration duration) {
|
||||
final seconds = duration.inSeconds < 0 ? 0 : duration.inSeconds;
|
||||
if (seconds < 60) return '${seconds}s';
|
||||
if (seconds < 3600) return '${seconds ~/ 60}m ${seconds % 60}s';
|
||||
return '${seconds ~/ 3600}h ${(seconds % 3600) ~/ 60}m';
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../../core/api_gateway.dart';
|
||||
import '../attention/runtime/attention_store.dart';
|
||||
import 'data/runs_repository.dart';
|
||||
import 'ui/run_detail_view.dart';
|
||||
import 'ui/runs_controller.dart';
|
||||
@@ -21,6 +22,8 @@ class RunsScreen extends StatefulWidget {
|
||||
this.listRefreshToken = 0,
|
||||
this.onRunSelected,
|
||||
this.onBack,
|
||||
this.attentionStore = const SharedPreferencesAttentionStore(),
|
||||
this.attentionNow,
|
||||
});
|
||||
|
||||
final ApiGateway gateway;
|
||||
@@ -39,6 +42,11 @@ class RunsScreen extends StatefulWidget {
|
||||
final ValueChanged<int>? onRunSelected;
|
||||
final VoidCallback? onBack;
|
||||
|
||||
/// Persisted attention dismissals and the clock for its local-day window.
|
||||
/// The app uses SharedPreferences; tests and fixtures inject a memory store.
|
||||
final AttentionStore attentionStore;
|
||||
final DateTime Function()? attentionNow;
|
||||
|
||||
@override
|
||||
State<RunsScreen> createState() => _RunsScreenState();
|
||||
}
|
||||
@@ -114,7 +122,13 @@ class _RunsScreenState extends State<RunsScreen> {
|
||||
animation: controller,
|
||||
builder: (context, _) => Offstage(
|
||||
offstage: selected,
|
||||
child: RunsList(controller: controller, onSelected: _select),
|
||||
child: RunsList(
|
||||
controller: controller,
|
||||
onSelected: _select,
|
||||
syncToken: widget.syncToken,
|
||||
attentionStore: widget.attentionStore,
|
||||
attentionNow: widget.attentionNow,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (selected)
|
||||
|
||||
@@ -20,6 +20,7 @@ Widget buildCupertinoRunDetail({
|
||||
required String? copyStatus,
|
||||
required VoidCallback onBack,
|
||||
required VoidCallback onCopy,
|
||||
required String configuredEndpoint,
|
||||
}) {
|
||||
final theme = CupertinoTheme.of(context);
|
||||
return RunDetailTabs(
|
||||
@@ -28,6 +29,7 @@ Widget buildCupertinoRunDetail({
|
||||
copying: copying,
|
||||
copyStatus: copyStatus,
|
||||
onCopy: onCopy,
|
||||
configuredEndpoint: configuredEndpoint,
|
||||
header: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
|
||||
@@ -20,6 +20,7 @@ Widget buildMaterialRunDetail({
|
||||
required String? copyStatus,
|
||||
required VoidCallback onBack,
|
||||
required VoidCallback onCopy,
|
||||
required String configuredEndpoint,
|
||||
}) {
|
||||
final theme = Theme.of(context);
|
||||
return RunDetailTabs(
|
||||
@@ -28,6 +29,7 @@ Widget buildMaterialRunDetail({
|
||||
copying: copying,
|
||||
copyStatus: copyStatus,
|
||||
onCopy: onCopy,
|
||||
configuredEndpoint: configuredEndpoint,
|
||||
header: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
|
||||
@@ -55,7 +55,7 @@ class _RunDetailTabStripState extends State<RunDetailTabStrip> {
|
||||
final cupertino = usesCupertinoHost(context);
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: _ScrollWhenOverflowing(
|
||||
child: ScrollWhenOverflowing(
|
||||
child: KeyedSubtree(
|
||||
key: const Key('run-detail-tabs'),
|
||||
child: cupertino ? _cupertinoControl() : _materialControl(),
|
||||
@@ -97,8 +97,11 @@ class _RunDetailTabStripState extends State<RunDetailTabStrip> {
|
||||
|
||||
/// Gives [child] at least the pane width, then scrolls instead of squeezing it
|
||||
/// below its content width.
|
||||
class _ScrollWhenOverflowing extends StatelessWidget {
|
||||
const _ScrollWhenOverflowing({required this.child});
|
||||
///
|
||||
/// The run detail's tab strips both use this, so the pointer-drag rule and the
|
||||
/// minimum-width rule live in one place.
|
||||
class ScrollWhenOverflowing extends StatelessWidget {
|
||||
const ScrollWhenOverflowing({super.key, required this.child});
|
||||
|
||||
final Widget child;
|
||||
|
||||
|
||||
@@ -9,6 +9,8 @@ import 'run_detail_tab.dart';
|
||||
import 'run_detail_tab_bodies.dart';
|
||||
import 'run_detail_tab_strip.dart';
|
||||
import 'run_detail_timeline.dart';
|
||||
import 'run_detail_visit.dart';
|
||||
import 'run_detail_visit_facts.dart';
|
||||
|
||||
/// The least height the selected tab keeps for its own content.
|
||||
///
|
||||
@@ -23,7 +25,7 @@ const double kRunDetailMinContentHeight = 240;
|
||||
///
|
||||
/// The Graph tab fills its slot with [RunGraphView] from the run's own pinned
|
||||
/// graph and recorded steps. A visited stage click selects that stage's latest
|
||||
/// recorded visit and switches to Timeline, where the row is highlighted. A
|
||||
/// recorded visit and switches to Timeline, where that visit's pane opens. A
|
||||
/// node with no recorded visit reports nothing, so no visit is invented.
|
||||
class RunDetailTabs extends StatefulWidget {
|
||||
const RunDetailTabs({
|
||||
@@ -34,6 +36,7 @@ class RunDetailTabs extends StatefulWidget {
|
||||
required this.copying,
|
||||
required this.copyStatus,
|
||||
required this.onCopy,
|
||||
required this.configuredEndpoint,
|
||||
});
|
||||
|
||||
final JsonMap run;
|
||||
@@ -47,6 +50,10 @@ class RunDetailTabs extends StatefulWidget {
|
||||
final String? copyStatus;
|
||||
final VoidCallback onCopy;
|
||||
|
||||
/// The configured server origin used to resolve a recorded session export
|
||||
/// through the landed safe-link helper. Blank leaves relative urls unresolved.
|
||||
final String configuredEndpoint;
|
||||
|
||||
@override
|
||||
State<RunDetailTabs> createState() => _RunDetailTabsState();
|
||||
}
|
||||
@@ -71,15 +78,24 @@ class _RunDetailTabsState extends State<RunDetailTabs> {
|
||||
/// Selects the stage's latest recorded visit. An unvisited stage has none,
|
||||
/// so the detail stays where it is rather than fabricating a visit.
|
||||
void _openStage(String stageKey) {
|
||||
final visit = latestDetailVisit(widget.run['steps'], stageKey);
|
||||
if (visit == null) return;
|
||||
final index = latestDetailVisitIndex(widget.run['steps'], stageKey);
|
||||
if (index == null) return;
|
||||
setState(() {
|
||||
_selectedStage = stageKey;
|
||||
_selectedVisit = visit.sequence;
|
||||
_selectedVisit = index;
|
||||
_tab = RunDetailTab.timeline;
|
||||
});
|
||||
}
|
||||
|
||||
/// Opens one recorded timeline row. The row index is also the index into the
|
||||
/// detail's own steps, so the pane reads exactly the visit it came from.
|
||||
void _openVisit(int index) {
|
||||
if (detailVisitStepAt(widget.run, index) == null) return;
|
||||
setState(() => _selectedVisit = index);
|
||||
}
|
||||
|
||||
void _closeVisit() => setState(() => _selectedVisit = null);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return LayoutBuilder(
|
||||
@@ -151,10 +167,33 @@ class _RunDetailTabsState extends State<RunDetailTabs> {
|
||||
cupertino: widget.cupertino,
|
||||
);
|
||||
case RunDetailTab.timeline:
|
||||
final visits = detailTimeline(widget.run['steps']);
|
||||
final index = _selectedVisit;
|
||||
if (index != null && index >= 0 && index < visits.length) {
|
||||
final step = detailVisitStepAt(widget.run, index);
|
||||
if (step != null) {
|
||||
return KeyedSubtree(
|
||||
key: const Key('run-detail-tab-body-timeline'),
|
||||
child: RunVisitPane(
|
||||
run: widget.run,
|
||||
visit: visits[index],
|
||||
visitIndex: index,
|
||||
step: step,
|
||||
runSteps: detailRunSteps(widget.run),
|
||||
configuredEndpoint: widget.configuredEndpoint,
|
||||
cupertino: widget.cupertino,
|
||||
onClose: _closeVisit,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
return RunTimelineList(
|
||||
visits: detailTimeline(widget.run['steps']),
|
||||
selectedSequence: _selectedVisit,
|
||||
visits: visits,
|
||||
selectedSequence: index != null && index >= 0 && index < visits.length
|
||||
? visits[index].sequence
|
||||
: null,
|
||||
cupertino: widget.cupertino,
|
||||
onSelected: _openVisit,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,20 +5,25 @@ import 'run_detail_content.dart';
|
||||
|
||||
/// The Timeline tab's recorded visits, one native row per visit.
|
||||
///
|
||||
/// [selectedSequence] is the server sequence of the visit selected from the
|
||||
/// Graph tab. Only an actual recorded visit can match, so an unvisited stage
|
||||
/// leaves every row unselected.
|
||||
/// [onSelected] receives the row's index in [visits], so the caller opens
|
||||
/// exactly the recorded step it was built from. [selectedSequence] highlights a
|
||||
/// row when a selection is applied while the list is rendered; the current
|
||||
/// flow replaces the rows with the pane, so it only matters for a defensive
|
||||
/// host that keeps both visible. Only an actual recorded visit can match, so an
|
||||
/// unvisited stage leaves every row unselected.
|
||||
class RunTimelineList extends StatelessWidget {
|
||||
const RunTimelineList({
|
||||
super.key,
|
||||
required this.visits,
|
||||
required this.cupertino,
|
||||
this.selectedSequence,
|
||||
this.onSelected,
|
||||
});
|
||||
|
||||
final List<DetailVisit> visits;
|
||||
final bool cupertino;
|
||||
final int? selectedSequence;
|
||||
final ValueChanged<int>? onSelected;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -38,6 +43,7 @@ class RunTimelineList extends StatelessWidget {
|
||||
visit: visits[index],
|
||||
selected: visits[index].sequence == selectedSequence,
|
||||
cupertino: cupertino,
|
||||
onTap: onSelected == null ? null : () => onSelected!(index),
|
||||
),
|
||||
];
|
||||
if (cupertino) {
|
||||
@@ -59,19 +65,22 @@ class RunTimelineList extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
/// One recorded visit. [selected] highlights the row the Graph tab selected;
|
||||
/// it is never true for a stage with no recorded visit.
|
||||
/// One recorded visit. [selected] marks the row an applied selection identifies;
|
||||
/// the current flow opens the pane instead of leaving a highlighted row. It is
|
||||
/// never true for a stage with no recorded visit.
|
||||
class RunTimelineRow extends StatelessWidget {
|
||||
const RunTimelineRow({
|
||||
super.key,
|
||||
required this.visit,
|
||||
required this.selected,
|
||||
required this.cupertino,
|
||||
this.onTap,
|
||||
});
|
||||
|
||||
final DetailVisit visit;
|
||||
final bool selected;
|
||||
final bool cupertino;
|
||||
final VoidCallback? onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -93,6 +102,7 @@ class RunTimelineRow extends StatelessWidget {
|
||||
context,
|
||||
)
|
||||
: null,
|
||||
onTap: onTap,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -101,6 +111,7 @@ class RunTimelineRow extends StatelessWidget {
|
||||
leading: Icon(selected ? Icons.check_circle : Icons.circle_outlined),
|
||||
title: Text(visit.title),
|
||||
subtitle: Text(visit.subtitle),
|
||||
onTap: onTap,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../../core/transport/pipelines_client.dart';
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import 'run_detail_actions.dart';
|
||||
import 'run_detail_content.dart';
|
||||
@@ -45,6 +46,7 @@ class _RunDetailViewState extends State<RunDetailView> {
|
||||
final run = widget.controller.detail;
|
||||
if (run == null) return _placeholder(context, cupertino: cupertino);
|
||||
final prompt = detailPrompt(run);
|
||||
final endpoint = configuredGatewayEndpoint(widget.gateway);
|
||||
final headerActions = RunDetailActions(
|
||||
run: run,
|
||||
gateway: widget.gateway,
|
||||
@@ -62,6 +64,7 @@ class _RunDetailViewState extends State<RunDetailView> {
|
||||
copyStatus: _copyStatus,
|
||||
onBack: widget.onBack,
|
||||
onCopy: () => _copyPrompt(prompt ?? '', cupertino: true),
|
||||
configuredEndpoint: endpoint,
|
||||
)
|
||||
: buildMaterialRunDetail(
|
||||
context: context,
|
||||
@@ -73,6 +76,7 @@ class _RunDetailViewState extends State<RunDetailView> {
|
||||
copyStatus: _copyStatus,
|
||||
onBack: widget.onBack,
|
||||
onCopy: () => _copyPrompt(prompt ?? '', cupertino: false),
|
||||
configuredEndpoint: endpoint,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import 'run_detail_content.dart';
|
||||
import 'run_detail_visit_facts.dart';
|
||||
import 'run_detail_visit_sections.dart';
|
||||
|
||||
/// The selected recorded visit inside the Timeline tab.
|
||||
///
|
||||
/// It leads with the visit's own headline facts, then native tabbed sections.
|
||||
/// A fact the reply did not record is not drawn at all; a blank verdict or
|
||||
/// diagnostic is not rendered as an empty decision.
|
||||
class RunVisitPane extends StatefulWidget {
|
||||
const RunVisitPane({
|
||||
super.key,
|
||||
required this.run,
|
||||
required this.visit,
|
||||
required this.visitIndex,
|
||||
required this.step,
|
||||
required this.runSteps,
|
||||
required this.configuredEndpoint,
|
||||
required this.cupertino,
|
||||
required this.onClose,
|
||||
});
|
||||
|
||||
final JsonMap run;
|
||||
final DetailVisit visit;
|
||||
|
||||
/// The visit's index in [runSteps], so the artifacts section can open exactly
|
||||
/// this visit's gallery group.
|
||||
final int visitIndex;
|
||||
|
||||
final JsonMap step;
|
||||
final List<JsonMap> runSteps;
|
||||
final String configuredEndpoint;
|
||||
final bool cupertino;
|
||||
final VoidCallback onClose;
|
||||
|
||||
@override
|
||||
State<RunVisitPane> createState() => _RunVisitPaneState();
|
||||
}
|
||||
|
||||
class _RunVisitPaneState extends State<RunVisitPane> {
|
||||
RunVisitSection _section = RunVisitSection.input;
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant RunVisitPane oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
// A different visit starts at its first section, like a newly opened pane.
|
||||
if (oldWidget.visit.sequence != widget.visit.sequence ||
|
||||
oldWidget.visit.stage != widget.visit.stage) {
|
||||
_section = RunVisitSection.input;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final style = _VisitStyle.of(context);
|
||||
final facts = detailVisitFacts(widget.step);
|
||||
final verdict = detailVisitVerdict(widget.step);
|
||||
final diagnostic = detailVisitDiagnostic(widget.step);
|
||||
return Column(
|
||||
key: const Key('run-visit-pane'),
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Flexible(
|
||||
flex: 3,
|
||||
fit: FlexFit.loose,
|
||||
child: SingleChildScrollView(
|
||||
key: const Key('run-visit-facts'),
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 8),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_bar(style),
|
||||
for (final fact in facts) _FactRow(fact: fact, style: style),
|
||||
if (verdict != null) ...[
|
||||
const SizedBox(height: 8),
|
||||
Text('Verdict', style: style.heading),
|
||||
if (verdict.option != null) Text(verdict.option!),
|
||||
if (verdict.reason != null)
|
||||
Text(verdict.reason!, style: style.value),
|
||||
],
|
||||
if (diagnostic != null) ...[
|
||||
const SizedBox(height: 8),
|
||||
Text('Diagnostic', style: style.heading),
|
||||
Text(diagnostic, style: style.value),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
RunVisitSectionStrip(
|
||||
selected: _section,
|
||||
onSelected: (section) => setState(() => _section = section),
|
||||
),
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: runVisitSectionBody(
|
||||
section: _section,
|
||||
run: widget.run,
|
||||
step: widget.step,
|
||||
visitIndex: widget.visitIndex,
|
||||
stageKey: widget.visit.stage,
|
||||
runSteps: widget.runSteps,
|
||||
configuredEndpoint: widget.configuredEndpoint,
|
||||
cupertino: widget.cupertino,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _bar(_VisitStyle style) {
|
||||
final close = widget.cupertino
|
||||
? CupertinoButton(
|
||||
key: const Key('run-visit-back'),
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: widget.onClose,
|
||||
child: const Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(CupertinoIcons.back),
|
||||
SizedBox(width: 4),
|
||||
Flexible(child: Text('Back to timeline')),
|
||||
],
|
||||
),
|
||||
)
|
||||
: TextButton.icon(
|
||||
key: const Key('run-visit-back'),
|
||||
onPressed: widget.onClose,
|
||||
icon: const Icon(Icons.arrow_back),
|
||||
label: const Text('Back to timeline'),
|
||||
);
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Align(alignment: AlignmentDirectional.centerStart, child: close),
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(8, 0, 0, 0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
widget.visit.title,
|
||||
key: const Key('run-visit-title'),
|
||||
style: style.heading,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _FactRow extends StatelessWidget {
|
||||
const _FactRow({required this.fact, required this.style});
|
||||
|
||||
final VisitFact fact;
|
||||
final _VisitStyle style;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Text.rich(
|
||||
TextSpan(
|
||||
children: [
|
||||
TextSpan(text: '${fact.label}: ', style: style.muted),
|
||||
TextSpan(text: fact.value, style: style.value),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Host text roles only: no palette, font family or explicit size.
|
||||
class _VisitStyle {
|
||||
const _VisitStyle({
|
||||
required this.value,
|
||||
required this.muted,
|
||||
required this.heading,
|
||||
});
|
||||
|
||||
factory _VisitStyle.of(BuildContext context) {
|
||||
if (usesCupertinoHost(context)) {
|
||||
final theme = CupertinoTheme.of(context);
|
||||
final secondary = CupertinoColors.secondaryLabel.resolveFrom(context);
|
||||
return _VisitStyle(
|
||||
value: theme.textTheme.textStyle,
|
||||
muted: theme.textTheme.textStyle.copyWith(color: secondary),
|
||||
heading: theme.textTheme.navTitleTextStyle,
|
||||
);
|
||||
}
|
||||
final theme = Theme.of(context);
|
||||
return _VisitStyle(
|
||||
value: theme.textTheme.bodyMedium ?? const TextStyle(),
|
||||
muted: (theme.textTheme.bodySmall ?? const TextStyle()).copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
heading: theme.textTheme.titleSmall ?? const TextStyle(),
|
||||
);
|
||||
}
|
||||
|
||||
final TextStyle value;
|
||||
final TextStyle muted;
|
||||
final TextStyle heading;
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import '../../artifacts/domain/artifact_groups.dart';
|
||||
import '../../artifacts/domain/artifact_record.dart';
|
||||
import '../../artifacts/domain/artifact_summary.dart';
|
||||
import '../../artifacts/ui/artifact_gallery_action.dart';
|
||||
import '../../artifacts/ui/artifact_visit_list.dart';
|
||||
|
||||
/// The visit's recorded stage artifacts, in recorded order.
|
||||
///
|
||||
/// Selecting a row opens the existing artifact gallery page for exactly this
|
||||
/// visit, so the pane never grows a second viewer or a link-only substitute.
|
||||
/// The page receives the whole run so a shared `public/` file stays with the
|
||||
/// visit that first recorded it, and it lists exactly the rows shown here.
|
||||
///
|
||||
/// An empty list is never described as "nothing recorded" on its own: the
|
||||
/// existing capture semantics say whether the capture is unavailable, still
|
||||
/// pending or explicitly empty for this visit.
|
||||
class RunVisitArtifacts extends StatelessWidget {
|
||||
const RunVisitArtifacts({
|
||||
super.key,
|
||||
required this.step,
|
||||
required this.visitIndex,
|
||||
required this.runSteps,
|
||||
required this.configuredEndpoint,
|
||||
});
|
||||
|
||||
final JsonMap step;
|
||||
|
||||
/// The visit's index in [runSteps], so the opened page is the same group.
|
||||
final int visitIndex;
|
||||
|
||||
final List<JsonMap> runSteps;
|
||||
final String configuredEndpoint;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final artifacts = visitArtifacts(step, runSteps);
|
||||
final notes = artifactCaptureNotes(step);
|
||||
if (artifacts.isEmpty) {
|
||||
return ListView(
|
||||
key: const Key('run-visit-body-artifacts'),
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
Text(artifactsSummary(step, count: 0)),
|
||||
for (final note in notes)
|
||||
Padding(padding: const EdgeInsets.only(top: 4), child: Text(note)),
|
||||
],
|
||||
);
|
||||
}
|
||||
void open() => showArtifactGallery(
|
||||
context,
|
||||
steps: runSteps.isEmpty ? <JsonMap>[step] : runSteps,
|
||||
focusIndex: runSteps.isEmpty ? 0 : visitIndex,
|
||||
configuredEndpoint: configuredEndpoint,
|
||||
);
|
||||
final noteRows = [
|
||||
for (final note in notes)
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0),
|
||||
child: Text(note),
|
||||
),
|
||||
];
|
||||
if (usesCupertinoHost(context)) {
|
||||
return ListView(
|
||||
key: const Key('run-visit-body-artifacts'),
|
||||
children: [
|
||||
...noteRows,
|
||||
CupertinoListSection.insetGrouped(
|
||||
children: [
|
||||
for (final artifact in artifacts)
|
||||
_CupertinoArtifactRow(artifact: artifact, onTap: open),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return ListView(
|
||||
key: const Key('run-visit-body-artifacts'),
|
||||
children: [
|
||||
...noteRows,
|
||||
for (final artifact in artifacts)
|
||||
ListTile(
|
||||
title: Text(artifactDisplayName(artifact)),
|
||||
subtitle: Text(artifactFactsLabel(artifact)),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: open,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CupertinoArtifactRow extends StatelessWidget {
|
||||
const _CupertinoArtifactRow({required this.artifact, required this.onTap});
|
||||
|
||||
final ArtifactRecord artifact;
|
||||
final VoidCallback onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CupertinoListTile(
|
||||
title: Text(artifactDisplayName(artifact)),
|
||||
subtitle: Text(artifactFactsLabel(artifact)),
|
||||
trailing: const Icon(CupertinoIcons.chevron_forward),
|
||||
onTap: onTap,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../graph/widgets/stage_definition_view.dart';
|
||||
import 'run_detail_content.dart';
|
||||
import 'run_detail_visit_facts.dart';
|
||||
|
||||
/// The Definition section: the authored definition this run pinned for the
|
||||
/// visit's stage, rendered by the landed [StageDefinitionView].
|
||||
///
|
||||
/// When the reply's graph does not declare the stage, the pane's exact missing
|
||||
/// sentence is shown instead. Nothing is reconstructed from the current source.
|
||||
class RunVisitDefinition extends StatelessWidget {
|
||||
const RunVisitDefinition({
|
||||
super.key,
|
||||
required this.run,
|
||||
required this.stageKey,
|
||||
});
|
||||
|
||||
final JsonMap run;
|
||||
final String stageKey;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final graph = detailGraph(run);
|
||||
if (!detailVisitHasDefinition(graph, stageKey)) {
|
||||
return ListView(
|
||||
key: const Key('run-visit-body-definition'),
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: const [Text(unknownStageDefinition)],
|
||||
);
|
||||
}
|
||||
final pipelineId = run['pipeline_id'];
|
||||
final version = run['version'];
|
||||
return KeyedSubtree(
|
||||
key: const Key('run-visit-body-definition'),
|
||||
child: StageDefinitionView(
|
||||
graph: graph!,
|
||||
stageKey: stageKey,
|
||||
pipelineId: pipelineId is num ? pipelineId.toInt() : 0,
|
||||
pipelineName: detailPipeline(run),
|
||||
version: version is num ? version.toInt() : 0,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../graph/domain/stage_definition.dart';
|
||||
import '../../pipelines/pipeline_format.dart';
|
||||
import 'run_detail_content.dart';
|
||||
|
||||
/// The exact empty wording for a visit's recorded Input and Output. They are
|
||||
/// the run tabs' own sentences, so a visit never says something different for
|
||||
/// the same absent fact.
|
||||
const String visitEmptyInput = 'No input recorded.';
|
||||
const String visitEmptyOutput = 'No output recorded.';
|
||||
|
||||
/// One always-visible fact of a recorded visit.
|
||||
typedef VisitFact = ({String label, String value});
|
||||
|
||||
/// The detail's own recorded steps as maps, in recorded order.
|
||||
List<JsonMap> detailRunSteps(JsonMap run) {
|
||||
final steps = run['steps'];
|
||||
if (steps is! List) return const <JsonMap>[];
|
||||
return steps.whereType<Map>().map(JsonMap.from).toList();
|
||||
}
|
||||
|
||||
/// The raw step at [index] of the detail's own `steps`, or null when the reply
|
||||
/// has no such recorded visit.
|
||||
///
|
||||
/// The order is the server's recorded order, the same order [detailTimeline]
|
||||
/// uses, so a row and its pane always describe one visit.
|
||||
JsonMap? detailVisitStepAt(JsonMap run, int index) {
|
||||
final steps = detailRunSteps(run);
|
||||
if (index < 0 || index >= steps.length) return null;
|
||||
return steps[index];
|
||||
}
|
||||
|
||||
/// The row index of [stageKey]'s latest recorded visit, or null when the run
|
||||
/// never recorded that stage. It reads the same ordered timeline the rows do,
|
||||
/// so a Graph click opens exactly the row the operator would have selected.
|
||||
int? latestDetailVisitIndex(dynamic steps, String stageKey) {
|
||||
final visits = detailTimeline(steps);
|
||||
int? latest;
|
||||
for (var index = 0; index < visits.length; index += 1) {
|
||||
if (visits[index].stage == stageKey) latest = index;
|
||||
}
|
||||
return latest;
|
||||
}
|
||||
|
||||
/// The visit's recorded facts, in the pane's order. A field the server did not
|
||||
/// record is absent rather than zero, false or a guessed value.
|
||||
List<VisitFact> detailVisitFacts(JsonMap step) {
|
||||
final facts = <VisitFact>[];
|
||||
final status = _text(step['status']);
|
||||
if (status != null) facts.add((label: 'Status', value: status));
|
||||
final outcome = _text(step['outcome']);
|
||||
if (outcome != null) facts.add((label: 'Outcome', value: outcome));
|
||||
final duration = detailVisitDuration(step);
|
||||
if (duration != null) facts.add((label: 'Duration', value: duration));
|
||||
final model = detailVisitProviderModel(step);
|
||||
if (model != null) facts.add((label: 'Provider/model', value: model));
|
||||
final target = _text(step['target']);
|
||||
if (target != null) facts.add((label: 'Target', value: target));
|
||||
return facts;
|
||||
}
|
||||
|
||||
/// The visit's duration, only when the server recorded both timestamps and the
|
||||
/// finish is not before the start. One stamp is not a zero-length visit.
|
||||
String? detailVisitDuration(JsonMap step) {
|
||||
final seconds = durationSeconds(
|
||||
_text(step['started_at']),
|
||||
_text(step['finished_at']),
|
||||
);
|
||||
return seconds == null ? null : formatDuration(seconds);
|
||||
}
|
||||
|
||||
/// The effective provider/model this visit ran with, joined as
|
||||
/// `provider / model` when both were recorded. A visit that recorded neither
|
||||
/// has no row; one recorded part is shown alone, never completed locally.
|
||||
String? detailVisitProviderModel(JsonMap step) {
|
||||
final provider = _text(step['provider']);
|
||||
final model = _text(step['model']);
|
||||
if (provider != null && model != null) return '$provider / $model';
|
||||
return provider ?? model;
|
||||
}
|
||||
|
||||
/// A recorded verdict, or null when the server recorded no option and no
|
||||
/// reason. An empty recorded verdict is not rendered as a decision.
|
||||
({String? option, String? reason})? detailVisitVerdict(JsonMap step) {
|
||||
final verdict = step['verdict'];
|
||||
if (verdict is! Map) return null;
|
||||
final option = _text(verdict['option']);
|
||||
final reason = _text(verdict['reason']);
|
||||
if (option == null && reason == null) return null;
|
||||
return (option: option, reason: reason);
|
||||
}
|
||||
|
||||
/// The visit's diagnostic exactly as recorded, or null when it is blank.
|
||||
String? detailVisitDiagnostic(JsonMap step) => _text(step['diagnostic']);
|
||||
|
||||
/// Whether the reply's pinned graph declares [stageKey], so the Definition
|
||||
/// section shows the authored definition rather than its missing wording.
|
||||
bool detailVisitHasDefinition(JsonMap? graph, String stageKey) =>
|
||||
graph != null && stageDefinitionFor(graph, stageKey) != null;
|
||||
|
||||
String? _text(dynamic value) {
|
||||
if (value == null) return null;
|
||||
final text = '$value'.trim();
|
||||
return text.isEmpty ? null : text;
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import 'run_detail_tab_bodies.dart';
|
||||
import 'run_detail_tab_strip.dart';
|
||||
import 'run_detail_visit_artifacts.dart';
|
||||
import 'run_detail_visit_definition.dart';
|
||||
import 'run_detail_visit_facts.dart';
|
||||
import 'run_detail_visit_session.dart';
|
||||
|
||||
/// The visit pane's recorded sections, in the Android audit order the web
|
||||
/// client follows: the turn's Input and Output, its Artifacts, its Session and
|
||||
/// the authored Definition.
|
||||
enum RunVisitSection {
|
||||
input('Input'),
|
||||
output('Output'),
|
||||
artifacts('Artifacts'),
|
||||
session('Session'),
|
||||
definition('Definition');
|
||||
|
||||
const RunVisitSection(this.label);
|
||||
|
||||
final String label;
|
||||
}
|
||||
|
||||
/// The visit pane's native tab strip: a Material segmented button or a Cupertino
|
||||
/// segmented control. It scrolls instead of squeezing the labels when a narrow
|
||||
/// pane or scaled text cannot fit them.
|
||||
class RunVisitSectionStrip extends StatelessWidget {
|
||||
const RunVisitSectionStrip({
|
||||
super.key,
|
||||
required this.selected,
|
||||
required this.onSelected,
|
||||
});
|
||||
|
||||
final RunVisitSection selected;
|
||||
final ValueChanged<RunVisitSection> onSelected;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final cupertino = usesCupertinoHost(context);
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: ScrollWhenOverflowing(
|
||||
child: KeyedSubtree(
|
||||
key: const Key('run-visit-tabs'),
|
||||
child: cupertino ? _cupertinoControl() : _materialControl(),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _materialControl() => SegmentedButton<RunVisitSection>(
|
||||
segments: [
|
||||
for (final section in RunVisitSection.values)
|
||||
ButtonSegment(value: section, label: _label(section)),
|
||||
],
|
||||
selected: {selected},
|
||||
showSelectedIcon: false,
|
||||
onSelectionChanged: (selection) => onSelected(selection.single),
|
||||
);
|
||||
|
||||
Widget _cupertinoControl() => CupertinoSegmentedControl<RunVisitSection>(
|
||||
groupValue: selected,
|
||||
onValueChanged: onSelected,
|
||||
children: {
|
||||
for (final section in RunVisitSection.values)
|
||||
section: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
child: _label(section),
|
||||
),
|
||||
},
|
||||
);
|
||||
|
||||
Widget _label(RunVisitSection section) => KeyedSubtree(
|
||||
key: ValueKey('run-visit-tab-${section.name}'),
|
||||
child: Text(section.label, maxLines: 1, softWrap: false),
|
||||
);
|
||||
}
|
||||
|
||||
/// The selected section's body for one recorded visit.
|
||||
Widget runVisitSectionBody({
|
||||
required RunVisitSection section,
|
||||
required JsonMap run,
|
||||
required JsonMap step,
|
||||
required int visitIndex,
|
||||
required String stageKey,
|
||||
required List<JsonMap> runSteps,
|
||||
required String configuredEndpoint,
|
||||
required bool cupertino,
|
||||
}) {
|
||||
switch (section) {
|
||||
case RunVisitSection.input:
|
||||
return runDetailFieldTab(
|
||||
tabKey: 'visit-input',
|
||||
value: step['input'],
|
||||
empty: visitEmptyInput,
|
||||
cupertino: cupertino,
|
||||
);
|
||||
case RunVisitSection.output:
|
||||
return runDetailFieldTab(
|
||||
tabKey: 'visit-output',
|
||||
value: step['output'],
|
||||
empty: visitEmptyOutput,
|
||||
cupertino: cupertino,
|
||||
);
|
||||
case RunVisitSection.artifacts:
|
||||
return RunVisitArtifacts(
|
||||
step: step,
|
||||
visitIndex: visitIndex,
|
||||
runSteps: runSteps,
|
||||
configuredEndpoint: configuredEndpoint,
|
||||
);
|
||||
case RunVisitSection.session:
|
||||
return RunVisitSession(
|
||||
step: step,
|
||||
configuredEndpoint: configuredEndpoint,
|
||||
);
|
||||
case RunVisitSection.definition:
|
||||
return RunVisitDefinition(run: run, stageKey: stageKey);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import '../../artifacts/domain/artifact_record.dart';
|
||||
import '../../artifacts/domain/artifact_url.dart';
|
||||
import '../../artifacts/ui/artifact_external_open.dart';
|
||||
import 'run_detail_visit_session_state.dart';
|
||||
|
||||
/// The visit's recorded session pointer and, when the visit exported one, a
|
||||
/// read-only external open of that document.
|
||||
///
|
||||
/// The state comes from [detailVisitSession], so a legacy `session.html`, a
|
||||
/// repair, a still-running session and a failed one each report what the server
|
||||
/// recorded. The open goes through the landed safe-link helper: the recorded url
|
||||
/// is resolved by [resolveArtifactUrl] and passed to [openArtifactExternally]
|
||||
/// without being fetched, rewritten or previewed. A refusal is reported.
|
||||
class RunVisitSession extends StatefulWidget {
|
||||
const RunVisitSession({
|
||||
super.key,
|
||||
required this.step,
|
||||
required this.configuredEndpoint,
|
||||
this.openExternal = openArtifactExternally,
|
||||
});
|
||||
|
||||
final JsonMap step;
|
||||
final String configuredEndpoint;
|
||||
final ArtifactExternalOpen openExternal;
|
||||
|
||||
@override
|
||||
State<RunVisitSession> createState() => _RunVisitSessionState();
|
||||
}
|
||||
|
||||
class _RunVisitSessionState extends State<RunVisitSession> {
|
||||
String? _status;
|
||||
|
||||
Future<void> _open(ResolvedArtifactUrl resolved) async {
|
||||
final opened = await widget.openExternal(resolved.uri);
|
||||
if (!mounted) return;
|
||||
setState(
|
||||
() => _status = opened
|
||||
? 'Link opened externally.'
|
||||
: 'Could not open the link.',
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final session = detailVisitSession(widget.step);
|
||||
final export = session.export;
|
||||
final resolved = export == null
|
||||
? null
|
||||
: resolveArtifactUrl(widget.configuredEndpoint, export.artifact.url);
|
||||
final note = export?.statusNote;
|
||||
final children = <Widget>[
|
||||
if (session.sessionId != null)
|
||||
_SessionFact(label: 'Session', value: session.sessionId!),
|
||||
if (export != null) ...[
|
||||
if (note != null) Text(note),
|
||||
if (resolved == null)
|
||||
const Text(visitSessionEndpointMissing)
|
||||
else
|
||||
_openButton(export.artifact, resolved),
|
||||
] else
|
||||
Text(session.message),
|
||||
if (_status != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Semantics(liveRegion: true, child: Text(_status!)),
|
||||
),
|
||||
];
|
||||
if (usesCupertinoHost(context)) {
|
||||
return ListView(
|
||||
key: const Key('run-visit-body-session'),
|
||||
children: [
|
||||
CupertinoListSection.insetGrouped(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: _spaced(children),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return ListView(
|
||||
key: const Key('run-visit-body-session'),
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: _spaced(children),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _openButton(ArtifactRecord export, ResolvedArtifactUrl resolved) {
|
||||
final label = 'Open ${export.name.isEmpty ? 'session.html' : export.name}';
|
||||
if (usesCupertinoHost(context)) {
|
||||
return CupertinoButton(
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: () => _open(resolved),
|
||||
child: Text(label),
|
||||
);
|
||||
}
|
||||
return Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: TextButton(onPressed: () => _open(resolved), child: Text(label)),
|
||||
);
|
||||
}
|
||||
|
||||
List<Widget> _spaced(List<Widget> children) => [
|
||||
for (var index = 0; index < children.length; index += 1) ...[
|
||||
if (index > 0) const SizedBox(height: 8),
|
||||
children[index],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
class _SessionFact extends StatelessWidget {
|
||||
const _SessionFact({required this.label, required this.value});
|
||||
|
||||
final String label;
|
||||
final String value;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final cupertino = CupertinoTheme.of(context);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
label,
|
||||
style: usesCupertinoHost(context)
|
||||
? cupertino.textTheme.tabLabelTextStyle.copyWith(
|
||||
color: CupertinoColors.secondaryLabel.resolveFrom(context),
|
||||
)
|
||||
: (theme.textTheme.labelMedium ?? const TextStyle()).copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(value),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../artifacts/domain/artifact_record.dart';
|
||||
import '../../artifacts/domain/artifact_selection.dart';
|
||||
|
||||
/// The exact wording for a visit that never started a harness session, in the
|
||||
/// web audit pane's order: a skipped visit, a stopped one, a model visit whose
|
||||
/// session is still being created, a failed one, and a model visit with no
|
||||
/// identity at all. Only a non-model visit with nothing recorded gets the
|
||||
/// generic sentence.
|
||||
const String visitSessionSkipped =
|
||||
'This visit was skipped; no harness session was started.';
|
||||
const String visitSessionStopped =
|
||||
'The stage stopped before a harness session was recorded.';
|
||||
const String visitSessionStarting = 'The stage session is being created.';
|
||||
const String visitSessionFailed = 'The stage did not create a harness session.';
|
||||
const String visitSessionNoIdentity =
|
||||
'Runtime error: this model stage has no recorded session identity.';
|
||||
const String visitSessionNone = 'This visit has no harness session.';
|
||||
|
||||
/// An export that exists but cannot be resolved through the configured server.
|
||||
const String visitSessionEndpointMissing =
|
||||
'Set the server URL in Settings to open the session.';
|
||||
|
||||
/// A recorded session export document and the evidence the server recorded for
|
||||
/// it.
|
||||
class VisitSessionExport {
|
||||
const VisitSessionExport({
|
||||
required this.artifact,
|
||||
this.status,
|
||||
this.diagnostic,
|
||||
this.truncated = false,
|
||||
});
|
||||
|
||||
final ArtifactRecord artifact;
|
||||
final String? status;
|
||||
final String? diagnostic;
|
||||
final bool truncated;
|
||||
|
||||
/// A partial or failed export is still the recorded document; it stays
|
||||
/// openable and the pane says what the evidence reports.
|
||||
bool get isComplete => status == 'complete' && !truncated;
|
||||
|
||||
/// The evidence sentence shown beside a present but incomplete export, or
|
||||
/// null when the export is complete or the visit recorded no evidence.
|
||||
String? get statusNote {
|
||||
if (isComplete) return null;
|
||||
if (status == null && !truncated) return null;
|
||||
return 'This export is ${status ?? 'partial'}; full session evidence is '
|
||||
'not available.';
|
||||
}
|
||||
}
|
||||
|
||||
/// A visit's recorded session: its identity, an openable export document and,
|
||||
/// when neither exists, the one sentence describing the recorded state.
|
||||
class VisitSessionState {
|
||||
const VisitSessionState({this.sessionId, this.export, this.message = ''});
|
||||
|
||||
final String? sessionId;
|
||||
final VisitSessionExport? export;
|
||||
|
||||
/// Empty exactly when [export] is present.
|
||||
final String message;
|
||||
}
|
||||
|
||||
/// Resolves the recorded session state without inventing a session.
|
||||
///
|
||||
/// The export is looked up through the recorded export evidence (including a
|
||||
/// repair that replaced it) and then, for a historical visit that recorded no
|
||||
/// evidence at all, through the `session.html` its inventory carries. When the
|
||||
/// evidence names no file, its own status and diagnostic are reported instead
|
||||
/// of claiming the inventory is empty.
|
||||
VisitSessionState detailVisitSession(JsonMap step) {
|
||||
final sessionId = detailVisitSessionIdentity(step);
|
||||
final export = detailVisitSessionExport(step);
|
||||
if (export != null) {
|
||||
return VisitSessionState(sessionId: sessionId, export: export);
|
||||
}
|
||||
if (sessionId != null) {
|
||||
return VisitSessionState(
|
||||
sessionId: sessionId,
|
||||
message: _missingExportMessage(step, sessionId),
|
||||
);
|
||||
}
|
||||
return VisitSessionState(message: _noSessionMessage(step));
|
||||
}
|
||||
|
||||
/// The recorded harness session identity, from the step or its export evidence.
|
||||
String? detailVisitSessionIdentity(JsonMap step) {
|
||||
final direct = _text(step['session_id']);
|
||||
if (direct != null) return direct;
|
||||
final evidence = _firstEvidence(step);
|
||||
return evidence == null ? null : _text(evidence['session_id']);
|
||||
}
|
||||
|
||||
/// The visit's recorded export document, or null when no recorded export name
|
||||
/// is present in the inventory.
|
||||
///
|
||||
/// The step's own `session_export` is preferred; a repair document is used
|
||||
/// when that is the file the inventory actually carries. A visit with no export
|
||||
/// evidence at all falls back to its `session.html` system artifact, exactly as
|
||||
/// the web audit pane does for runs recorded before the evidence field existed.
|
||||
VisitSessionExport? detailVisitSessionExport(JsonMap step) {
|
||||
final evidence = _exportEvidence(step);
|
||||
for (final entry in evidence) {
|
||||
final artifact = _artifactNamed(step, _text(entry['html']));
|
||||
if (artifact == null) continue;
|
||||
return VisitSessionExport(
|
||||
artifact: artifact,
|
||||
status: _text(entry['status']),
|
||||
diagnostic: _text(entry['diagnostic']),
|
||||
truncated: entry['truncated'] == true,
|
||||
);
|
||||
}
|
||||
if (evidence.isNotEmpty) return null;
|
||||
for (final artifact in systemArtifacts(step)) {
|
||||
if (artifact.name == 'session.html') {
|
||||
return VisitSessionExport(artifact: artifact);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
String _missingExportMessage(JsonMap step, String sessionId) {
|
||||
final evidence = _firstEvidence(step);
|
||||
final recovery = step['session_export_recovery'];
|
||||
final recoveryStatus = recovery is Map ? _text(recovery['status']) : null;
|
||||
final evidenceStatus = evidence == null ? null : _text(evidence['status']);
|
||||
final String status;
|
||||
if (recoveryStatus == 'pending' || recoveryStatus == 'running') {
|
||||
status = 'pending recovery';
|
||||
} else if (evidenceStatus == 'complete') {
|
||||
status = 'not available in the artifact inventory';
|
||||
} else {
|
||||
status = evidenceStatus ?? 'not yet available';
|
||||
}
|
||||
final diagnostic = evidence == null ? null : _text(evidence['diagnostic']);
|
||||
final suffix = diagnostic == null ? '' : ' $diagnostic';
|
||||
return 'Session $sessionId is recorded. Its export is $status.$suffix';
|
||||
}
|
||||
|
||||
String _noSessionMessage(JsonMap step) {
|
||||
final status = _text(step['status']);
|
||||
if (status == 'skipped' || _text(step['outcome']) == 'skipped') {
|
||||
return visitSessionSkipped;
|
||||
}
|
||||
if (status == 'canceled' || status == 'interrupted') {
|
||||
return visitSessionStopped;
|
||||
}
|
||||
final model = _text(step['provider']) != null || _text(step['model']) != null;
|
||||
if (!model) return visitSessionNone;
|
||||
if (status == 'running') return visitSessionStarting;
|
||||
if (status == 'failed') {
|
||||
final diagnostic = _text(step['diagnostic']);
|
||||
return diagnostic == null
|
||||
? visitSessionFailed
|
||||
: '$visitSessionFailed $diagnostic';
|
||||
}
|
||||
return visitSessionNoIdentity;
|
||||
}
|
||||
|
||||
/// The recorded export evidence, most current first: a complete repair, then a
|
||||
/// complete original, then every remaining candidate. A failed later attempt
|
||||
/// never hides an earlier verified document; an older original never hides the
|
||||
/// repair that replaced it.
|
||||
List<Map> _exportEvidence(JsonMap step) {
|
||||
final repairs = <Map>[];
|
||||
final recordedRepairs = step['session_export_repairs'];
|
||||
if (recordedRepairs is List) {
|
||||
for (final entry in recordedRepairs.reversed) {
|
||||
if (entry is Map) repairs.add(entry);
|
||||
}
|
||||
}
|
||||
final original = step['session_export'];
|
||||
final ordered = <Map>[];
|
||||
void add(Map entry) {
|
||||
for (final candidate in ordered) {
|
||||
if (identical(candidate, entry)) return;
|
||||
}
|
||||
ordered.add(entry);
|
||||
}
|
||||
|
||||
for (final repair in repairs) {
|
||||
if (_isComplete(repair)) add(repair);
|
||||
}
|
||||
if (original is Map && _isComplete(original)) add(original);
|
||||
for (final repair in repairs) {
|
||||
add(repair);
|
||||
}
|
||||
if (original is Map) add(original);
|
||||
return ordered;
|
||||
}
|
||||
|
||||
Map? _firstEvidence(JsonMap step) {
|
||||
final original = step['session_export'];
|
||||
if (original is Map) return original;
|
||||
final repairs = step['session_export_repairs'];
|
||||
if (repairs is List) {
|
||||
for (final entry in repairs.reversed) {
|
||||
if (entry is Map) return entry;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
bool _isComplete(Map evidence) =>
|
||||
_text(evidence['status']) == 'complete' &&
|
||||
_positive(evidence['messages']) &&
|
||||
_positive(evidence['html_bytes']) &&
|
||||
evidence['truncated'] != true &&
|
||||
_text(evidence['diagnostic']) == null;
|
||||
|
||||
bool _positive(dynamic value) {
|
||||
if (value is num) return value > 0;
|
||||
if (value is String) return (int.tryParse(value.trim()) ?? 0) > 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
ArtifactRecord? _artifactNamed(JsonMap step, String? name) {
|
||||
if (name == null) return null;
|
||||
for (final artifact in artifactsOf(step)) {
|
||||
if (artifact.name == name) return artifact;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
String? _text(dynamic value) {
|
||||
if (value == null) return null;
|
||||
final text = '$value'.trim();
|
||||
return text.isEmpty ? null : text;
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import 'runs_controller.dart';
|
||||
|
||||
/// The runs list's native sort/schedule/status controls.
|
||||
///
|
||||
/// On Cupertino the controls stay in one horizontally scrollable strip: a phone
|
||||
/// at a doubled text scale cannot stack seven buttons above the list without
|
||||
/// crushing it, and the browser's narrow toolbar is likewise one row. Material
|
||||
/// keeps its native dropdowns and filter chips.
|
||||
class RunsFilters extends StatelessWidget {
|
||||
const RunsFilters({super.key, required this.controller});
|
||||
|
||||
final RunsController controller;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) =>
|
||||
usesCupertinoHost(context) ? _cupertino(context) : _material(context);
|
||||
|
||||
Widget _cupertino(BuildContext context) => SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
|
||||
child: Row(
|
||||
children: [
|
||||
CupertinoButton(
|
||||
onPressed: () => _choose(
|
||||
context,
|
||||
'Sort runs',
|
||||
_sorts,
|
||||
controller.sort,
|
||||
controller.setSort,
|
||||
),
|
||||
child: Text('Sort: ${_sortLabel(controller.sort)}'),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
CupertinoButton(
|
||||
onPressed: () => _choose(
|
||||
context,
|
||||
'Schedule',
|
||||
_schedules,
|
||||
controller.scheduled,
|
||||
controller.setScheduled,
|
||||
),
|
||||
child: Text('Schedule: ${_scheduleLabel(controller.scheduled)}'),
|
||||
),
|
||||
for (final status in _statuses) ...[
|
||||
const SizedBox(width: 8),
|
||||
CupertinoButton(
|
||||
onPressed: () => controller.setStatus(status),
|
||||
child: Text(
|
||||
'${controller.statuses.contains(status) ? '✓ ' : ''}${_title(status)}',
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
Widget _material(BuildContext context) => 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);
|
||||
}
|
||||
}
|
||||
|
||||
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)}';
|
||||
@@ -3,19 +3,35 @@ import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import '../../attention/runtime/attention_store.dart';
|
||||
import '../../attention/ui/needs_you_runs_heading.dart';
|
||||
import '../domain/run_models.dart';
|
||||
import 'runs_controller.dart';
|
||||
import 'runs_filters.dart';
|
||||
|
||||
class RunsList extends StatelessWidget {
|
||||
const RunsList({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.onSelected,
|
||||
this.syncToken = 0,
|
||||
this.attentionStore = const SharedPreferencesAttentionStore(),
|
||||
this.attentionNow,
|
||||
});
|
||||
|
||||
final RunsController controller;
|
||||
final ValueChanged<num> onSelected;
|
||||
|
||||
/// Advances when the shared socket is replaced, so the attention detector
|
||||
/// rebaselines instead of replaying a transition from before the gap.
|
||||
final int syncToken;
|
||||
|
||||
/// Test and fixture seam for the persisted attention dismissals.
|
||||
final AttentionStore attentionStore;
|
||||
|
||||
/// Deterministic local-day clock for the attention window.
|
||||
final DateTime Function()? attentionNow;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (controller.loading && controller.runs.isEmpty) {
|
||||
@@ -31,6 +47,20 @@ class RunsList extends StatelessWidget {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0),
|
||||
child: Align(
|
||||
alignment: AlignmentDirectional.centerEnd,
|
||||
child: NeedsYouRunsHeading(
|
||||
rows: controller.runs,
|
||||
frames: controller.repository.gateway.frames,
|
||||
onOpen: (entry) => onSelected(entry.runId),
|
||||
syncToken: syncToken,
|
||||
store: attentionStore,
|
||||
now: attentionNow,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (controller.usage != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
@@ -52,7 +82,7 @@ class RunsList extends StatelessWidget {
|
||||
onChanged: controller.setQuery,
|
||||
),
|
||||
),
|
||||
_selectors(context),
|
||||
RunsFilters(controller: controller),
|
||||
Expanded(
|
||||
child: controller.visibleRuns.isEmpty
|
||||
? const Center(child: Text('No runs found.'))
|
||||
@@ -101,101 +131,6 @@ class RunsList extends StatelessWidget {
|
||||
),
|
||||
);
|
||||
|
||||
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'];
|
||||
@@ -222,22 +157,3 @@ class RunsList extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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,182 @@
|
||||
# A2 — notification capability behind a platform seam
|
||||
|
||||
The notification capability exists as reusable Dart under
|
||||
`lib/features/attention/notify/`, plus one reusable Settings tile at
|
||||
`lib/features/attention/ui/notification_permission_tile.dart`. Nothing was wired
|
||||
into the shell, `Settings`, the application or the Runs screen; outside those
|
||||
paths only this note, the notify tests and the isolated probe changed.
|
||||
|
||||
## What is there
|
||||
|
||||
| File | Lines | Role |
|
||||
| --- | --- | --- |
|
||||
| `notify/notification_models.dart` | 169 | permission state, environment, copy, permission view, alert title/body, `NotificationMessage` |
|
||||
| `notify/notification_bridge.dart` | 30 | the abstract `NotificationBridge` + the conditional-import factory |
|
||||
| `notify/notification_bridge_web.dart` | 95 | the real `Notification` API via `dart:js_interop` (no `package:web`) |
|
||||
| `notify/notification_bridge_stub.dart` | 27 | non-web stub that reports `unsupported` honestly |
|
||||
| `notify/notification_ledger.dart` | 122 | run+kind identity, the qualifying-key set, ledger with pruning, total JSON codec, `pipelines.next.notify.v1` |
|
||||
| `notify/notification_store.dart` | 83 | injectable store seam; total `shared_preferences` impl + memory impl |
|
||||
| `notify/notification_controller.dart` | 250 | the `ChangeNotifier` capability |
|
||||
| `ui/notification_permission_tile.dart` | 127 | the reusable native tile |
|
||||
| `tool/notification_probe.dart` / `.mjs` | 291 / 314 | isolated real-browser probe |
|
||||
|
||||
## Platform seam
|
||||
|
||||
`NotificationBridge` answers the platform's own facts
|
||||
(`environment()` → `supported`, `secureContext`, raw `permission`),
|
||||
`requestPermission()` (only ever called from an explicit gesture) and
|
||||
`show(message, onTap:)`. The web bridge declares `@JS('Notification')` with
|
||||
`external factory`, `external static permission`, `external static
|
||||
requestPermission` and an `onclick` setter, and reaches the global only after a
|
||||
`globalContext` support check, so an unsupported browser is never touched. The
|
||||
stub returns `supported: false` and `show() == false`.
|
||||
|
||||
`NotificationController.permission` is one of `unsupported`,
|
||||
`needsSecureContext`, `notRequested` (the API's own `default` — `default` is a
|
||||
Dart reserved word, and each state exposes `wireName` = `unsupported` |
|
||||
`insecure` | `default` | `granted` | `denied`), `granted`, `denied`. It is
|
||||
derived only from `notificationStateOf(environment)`; `granted` is never assumed
|
||||
from an unrecognised word. `requestPermission()` asks only while the state is
|
||||
still `notRequested`, issues the platform request before any `await` so it stays
|
||||
inside the gesture, persists `asked` without awaiting, and follows the platform's
|
||||
answer. A denied state is never re-prompted.
|
||||
|
||||
## Notify only on live transitions, dedupe per qualifying state
|
||||
|
||||
The identity is the attention surface's own `{runId}:{Kind}` key, which is also
|
||||
the browser's `alertKey` and therefore the coalescing `tag`:
|
||||
|
||||
- The initial list seed raises no transition, so `publishTransitions` over the
|
||||
attention controller's (empty) transition list posts nothing.
|
||||
- `publishTransitions(transitions, qualifying:, dismissed:)` receives
|
||||
`notificationQualifyingKeys(attention.rows)` — the `{runId}:{Kind}` keys of the
|
||||
runs that are failed or waiting *right now*. A transition whose key is not in
|
||||
that set is stale (the caller's accumulated list still holds it because the run
|
||||
has moved on), so it neither posts nor re-records anything.
|
||||
- At the end of the publish, every recorded identity outside the qualifying set
|
||||
is forgotten ([`NotificationLedger.pruning`]). Publishing the frame that
|
||||
*leaves* the state is what makes the next gate (or a later failure of a new
|
||||
run id) a new announcement.
|
||||
This is the browser's `forget`/`pruneNotified` model.
|
||||
- A waiting run has no `finished_at`, so a timestamp marker cannot separate its
|
||||
first decision gate from a later one. The run+kind identity plus pruning can:
|
||||
`waiting -> running -> waiting` notifies once per gate even though both
|
||||
entries carry identical timestamps. A retry that produces a new failed run id
|
||||
is likewise a new identity; a failed run id never returns to running.
|
||||
- A caller that misses the frame that leaves the state is still handled: the
|
||||
attention detector creates one transition instance per genuine transition, so
|
||||
an identity announced earlier in this session with a different instance is a
|
||||
new occurrence and notifies. Republishing the same instance stays silent.
|
||||
- The same transition can never notify twice across a republish, a reconnect
|
||||
reseed, or a controller rebuilt over the same store while the run still
|
||||
qualifies. The ledger records the identity before the platform is asked to
|
||||
show it and persists it under `pipelines.next.notify.v1` through the injectable
|
||||
`NotificationStore`. A value written by the previous timestamp-identity build
|
||||
stops matching the qualifying set and is dropped on the next publish, so no
|
||||
migration step is needed.
|
||||
- The ledger is bounded by the runs currently qualifying, not by the history of
|
||||
every event the install has ever seen.
|
||||
- Writes are serialized through one queued future, so an older snapshot can
|
||||
never land after a newer one, and a throwing read/write is swallowed: the
|
||||
in-memory ledger still applies for the session.
|
||||
- A dismissed identity is recorded but never shown (the transition detector
|
||||
already suppresses it; the publish guard covers a caller that passes it).
|
||||
- Content is the entry's own words: the kind headline (`A run failed` / `A run
|
||||
needs your decision`) and `label · pipeline`, matching `web/src/notify.js` and
|
||||
`RunAlerts.kt` verbatim. Nothing is invented, and no `stage` field is added
|
||||
because neither reference client's alert body carries one.
|
||||
- A batch posts in order, bounded to `maxNotificationsPerBatch` (5); the rest are
|
||||
posted on the next call because the ones already posted are recorded.
|
||||
- `notified` returns an unmodifiable copy, so a caller cannot mutate the ledger
|
||||
behind the controller's back.
|
||||
|
||||
## Wiring the manager still owes
|
||||
|
||||
```dart
|
||||
final notify = NotificationController(store: const SharedPreferencesNotificationStore());
|
||||
notify.onOpenRun = (runId) { /* open that run — navigation lives here, not in notify */ };
|
||||
await notify.load();
|
||||
// after *every* authoritative read and pushed frame the attention controller handles:
|
||||
notify.publishTransitions(
|
||||
attention.transitions,
|
||||
qualifying: notificationQualifyingKeys(attention.rows),
|
||||
dismissed: attention.dismissed,
|
||||
);
|
||||
```
|
||||
|
||||
Publishing on the frames that leave a state matters as much as publishing the
|
||||
one that entered it: that is when the old identity is forgotten. `load()` once,
|
||||
and `publishTransitions` on every frame/seed, is enough; it is idempotent.
|
||||
`refreshPermission()` re-reads the platform facts after a focus change. The tile
|
||||
is embedded by the Settings screen with the live `state`/`asked` and an
|
||||
`onRequest` that calls `notify.requestPermission()`.
|
||||
|
||||
## Tests and evidence
|
||||
|
||||
- `flutter test test/features/attention` — **147 passed** (12 more than before
|
||||
this change; the notify/tile files hold 55). New coverage in this change: the
|
||||
`waiting -> running -> waiting` second gate with the real waiting shape (empty
|
||||
`finished_at`) notifies again, with and without publishing the leaving frame;
|
||||
a coalesced backlog of two gates notifies once; a stale transition from a run
|
||||
that left is not re-posted; the identity is run+kind so two alerts of one run
|
||||
share the browser tag; pruning drops identities outside the qualifying set;
|
||||
old timestamped identities are dropped; `notificationQualifyingKeys` ignores
|
||||
export waits, malformed ids and duplicates; `notified` is unmodifiable; ledger
|
||||
writes are serialized in call order.
|
||||
- `flutter test` (whole app) — **1058 passed**.
|
||||
- `flutter analyze` — **No issues found** (whole project).
|
||||
- `dart format --output=none --set-exit-if-changed` on every new lib/test file —
|
||||
clean.
|
||||
- `flutter build web` (the real `lib/main.dart`) — **succeeded**. This does *not*
|
||||
compile the notify feature: nothing under `lib/` imports it yet, so the main
|
||||
bundle contains none of its strings. It is a sanity check for the app only.
|
||||
- `flutter build web -t tool/notification_probe.dart -o build/notification_probe_web`
|
||||
— **succeeded**. This is the build that compiles the conditional-import web
|
||||
bridge (`isSecureContext`, the alert copy and the real `Notification` seam are
|
||||
in this bundle).
|
||||
- Real-browser probe (`tool/notification_probe.dart` + `.mjs`, isolated loopback
|
||||
server, `Browser.grantPermissions` / `Browser.setPermission`,
|
||||
`window.Notification` replaced with a recording spy before load):
|
||||
**all 29 checks passed** — seed posted 0; one transition posted exactly 1 with
|
||||
title `A run failed`, body `Nightly audit · nightly` and tag `1:Failed`; a
|
||||
dismissed transition posted 0; a reconnect replay posted 1 in total; a second
|
||||
decision gate posted exactly 2 in total, both tag `7:Decision`, with the
|
||||
waiting frames carrying no `finished_at`; denied and unsupported pages posted 0
|
||||
and read their honest copy; all five tile states read correctly on Material
|
||||
**and** Cupertino at 320 logical px / 2x.
|
||||
- 13 PNG captures regenerated in
|
||||
`/Users/alan/.local/share/pipelines/data/artifacts/100/public/captures/notify/`
|
||||
(`notification-transition-…`, `notification-denied-…`,
|
||||
`notification-unsupported-…`, and
|
||||
`notification-tile-{unsupported,insecure,default,granted,denied}-{material,cupertino}-dark-320-2x.png`).
|
||||
|
||||
One UI defect was found by the first captures and fixed in the previous visit:
|
||||
putting the Enable action in a `ListTile` trailing slot squeezed the section title
|
||||
to one glyph per line at 320 px / 2x, so the action now sits on its own row below
|
||||
the copy (as the browser's settings section does), and the widget test guards it.
|
||||
|
||||
## Deliberate limits
|
||||
|
||||
- `PARITY.md`'s `Notifications` row is **still Missing**: this slice is a
|
||||
capability plus a reusable tile, not a delivered Settings section or shell
|
||||
wiring. The row should move when the manager embeds the tile and wires the
|
||||
controller, with authenticated smoke evidence.
|
||||
- The instance rule is session-local. A controller rebuilt over the same store
|
||||
can only distinguish a later gate if the frame that left the state was
|
||||
published (which prunes the old identity), so the wiring above still publishes
|
||||
every authoritative read and frame rather than only entering transitions.
|
||||
- A browser whose `Notification.requestPermission()` uses the legacy
|
||||
callback-only form (no returned promise) falls back to the honest default
|
||||
wording, as the web client also does.
|
||||
- Mobile (Android/iOS) is unverified: the stub reports `unsupported` and no
|
||||
device or OS notification behaviour was exercised. No `pubspec` change.
|
||||
- The tile is not registered in Settings and background chat-question notices
|
||||
(`web/src/app.js` `notifyChatQuestion`) are not part of this capability.
|
||||
|
||||
## Manager completion after the Code deadline
|
||||
|
||||
The run succeeded at Code, was rejected once at Review, and the retry hit the
|
||||
30-minute deadline. The retained tree is complete: 147 attention tests pass and
|
||||
analysis is clean. Merged directly. Shell wiring (permission tile in Settings and
|
||||
transition delivery from the Runs attention controller) is the manager's next
|
||||
step and is not claimed here.
|
||||
@@ -0,0 +1,54 @@
|
||||
# A3 — artifact files: download and share
|
||||
|
||||
## Scope
|
||||
|
||||
The selected artifact can be saved or shared as a real file. The external
|
||||
`Open` and `Copy link` actions stay unchanged; neither is reused as a stand-in
|
||||
for a file transfer.
|
||||
|
||||
## Implementation
|
||||
|
||||
- `artifact_transfer.dart` is the platform seam with a web implementation and a
|
||||
stub. The web file uses `dart:js_interop`/`dart:js_interop_unsafe` only, so the
|
||||
same source compiles to JavaScript and WebAssembly without `package:web`.
|
||||
- `artifact_transfer_web.dart` builds a `Blob`/`File` from the fetched bytes with
|
||||
the recorded name and MIME type, downloads through an anchor created for that
|
||||
name, and shares through `navigator.share` only when the platform can share
|
||||
files. It never puts the artifact url or a blob page into the user's hands.
|
||||
- `artifact_file_controller.dart` fetches bytes through the same
|
||||
`ArtifactFetch` seam the in-app viewer already uses, so the same-origin
|
||||
credential policy and HTTP status handling apply. One in-flight transfer at a
|
||||
time; a second activation is ignored. Cancel stops the action from continuing
|
||||
and a late result is never reported as a completed transfer.
|
||||
- The selection sheet exposes `Download` and `Share` beside the existing
|
||||
actions, with honest states for unsupported sharing (download still works),
|
||||
missing/malformed name or MIME, fetch failure with its HTTP status, and
|
||||
cancel. Nothing is silently substituted.
|
||||
|
||||
## Evidence
|
||||
|
||||
- Focused suite: 123 artifact tests pass; `flutter analyze` clean.
|
||||
- Browser probe (`tool/artifact_gallery_probe.mjs`, 32 captures, 27 checks) on
|
||||
both hosts, dark at 2x and 320 logical px:
|
||||
- Material and Cupertino `Download` hand the host `report.csv`, `text/csv`,
|
||||
23 exact bytes.
|
||||
- Material and Cupertino `Share` hand the host a `report.csv`, `text/csv`,
|
||||
23-byte `File`.
|
||||
- Existing gallery/viewer checks (recorded rows, duplicate filename, empty vs
|
||||
unavailable, image in-app, HTTP failure, external artifact never fetched,
|
||||
320/2x paging) still pass.
|
||||
|
||||
## Known limits
|
||||
|
||||
- The shared fetch seam has no cancellation token, so Cancel abandons the action
|
||||
without aborting the HTTP request. The UI never claims the transfer finished.
|
||||
- OS share sheets and file downloads are web-verified only. Android/iOS
|
||||
transfer behavior remains unverified until the final build.
|
||||
- No authenticated production artifact was transferred; the probe uses an
|
||||
isolated fixture with fixed bytes.
|
||||
|
||||
## Manager note
|
||||
|
||||
The run reached its Code deadline with this tree complete and verified by the
|
||||
manager: tests, analysis, browser build and the 27-check probe above. Merged
|
||||
directly rather than replayed.
|
||||
@@ -0,0 +1,148 @@
|
||||
# C4-approvals — native permission and question cards
|
||||
|
||||
One checked integration slice: the chat conversation now renders recorded
|
||||
`chat_permission` frames and `form` question frames as native Material/Cupertino
|
||||
cards, answers them through the landed `ChatRepository` request facade, and
|
||||
records the outcome. App-only; no server, `web/`, Android/iOS, shell, route or
|
||||
deployment source was edited.
|
||||
|
||||
## What changed
|
||||
|
||||
| File | Lines | Responsibility |
|
||||
| --- | ---: | --- |
|
||||
| `lib/features/chat/conversation/chat_permission_card_model.dart` | 192 | approval card derivation, risk/resource wording, decision labels, one-shot reply ids |
|
||||
| `lib/features/chat/conversation/chat_permission_card.dart` | 267 | native approval card: kind/headline/status, six-line resources with full-request disclosure, risk panel, once/always/reject |
|
||||
| `lib/features/chat/conversation/chat_question_card_model.dart` | 206 | field visibility/values, web validation messages, visible answers, form folding, answer ids |
|
||||
| `lib/features/chat/conversation/chat_question_card_fields.dart` | 179 | editable field shell, free-text inputs, external-URL text |
|
||||
| `lib/features/chat/conversation/chat_question_option_controls.dart` | 160 | native single/multi select and boolean controls |
|
||||
| `lib/features/chat/conversation/chat_question_recorded_answers.dart` | 99 | read-only recorded answers, including unknown keys |
|
||||
| `lib/features/chat/conversation/chat_question_card.dart` | 275 | pending/answered/expired question card, local answer state, submit/actions |
|
||||
| `lib/features/chat/conversation/chat_transcript_card.dart` | 96 | card-row builder and small permission/question dispatcher |
|
||||
| `lib/features/chat/domain/chat_transcript.dart` | +10/-2 | `transcriptRows(..., trailing:)` keeps cards after the message rows |
|
||||
| `lib/features/chat/conversation/chat_thread_controller.dart` | +140 | folded permission/form frames, answers, errors and one-shot send gates |
|
||||
| `lib/features/chat/conversation/chat_thread_view.dart` | +26/-6 | builds/dispatches card rows inside the existing conversation list |
|
||||
| `app/PARITY.md` | row update | states the native cards as Source, with the real-request smoke still open |
|
||||
| `test/.../chat_permission_card_test.dart` | 300 | model + native behaviour + pushed-frame integration |
|
||||
| `test/.../chat_question_card_test.dart` | 360 | field rules + native behaviour + pushed-frame integration |
|
||||
| `tool/chat_approvals_probe.dart` | 167 | real-widget fixture with a scripted replaying gateway |
|
||||
| `tool/chat_approvals_probe.mjs` | 335 | Chrome CDP interaction, OCR assertions and captures |
|
||||
|
||||
Production files stay under the ~250-line aim except the two 267/275-line card
|
||||
shells; the larger question work is split by responsibility (fields, option
|
||||
controls, recorded answers) rather than arbitrary fragments.
|
||||
|
||||
## Behaviour
|
||||
|
||||
- **Permission card.** Kind line `Permission request · {source.type}` when the
|
||||
server records one, else `Permission request`. Headline `Approve {action}`
|
||||
(`Approve tool call` when blank). Status `Waiting for your response`.
|
||||
Resources are the server's non-blank entries joined by newlines, displayed at
|
||||
most six lines with an ellipsis on the last kept line; when truncated, the
|
||||
native disclosure `Show full request` carries every recorded resource. The risk
|
||||
panel uses the server's `message`, else the web's neutral sentence naming the
|
||||
action, and shows only while pending or after a rejection. Controls use the
|
||||
exact `Allow once` / `always_label or Always allow` / `Reject` labels and only
|
||||
while pending.
|
||||
- **Permission outcome.** Answering settles the card optimistically to the
|
||||
decision label and `Waiting for the agent to continue…`. A server
|
||||
`resolved`/`decision` frame always wins, shows the decision label (or
|
||||
`Already resolved` when the recorded decision is blank) and its `message`/the
|
||||
web's fallback note. A refusal clears the optimistic answer, keeps the card
|
||||
pending, and shows the server reason in a live region.
|
||||
- **Reply wire.** `ChatRepository.replyPermission` sends exactly
|
||||
`{chat_reply:{session_id,request_id,decision,client:'Web'}}`; no extra field is
|
||||
added. Each confirmed action has the stable local id
|
||||
`chat-reply:{requestId}:{decision}` held by a `ChatActionGate`, so a double tap
|
||||
sends once and a refused send reopens only that id for retry.
|
||||
- **Question card.** Shows the recorded title (or `Question`) and
|
||||
`The agent is waiting for your answer.`. Options keep the server's value/label
|
||||
and description exactly; single-select is a radio group under Material and a
|
||||
checkmark row under Cupertino, multi-select is checkboxes/checkmarks, booleans
|
||||
are the explicit Yes/No menu under Material and checkmark rows under Cupertino.
|
||||
Free text appears for `custom` fields or fields with no options, with number,
|
||||
email, URL and date keyboards and secret input where recorded.
|
||||
- **Question rules.** Visibility honours `hidden` and `when` (`eq`/`neq`).
|
||||
Answers preserve `false` and `0`. Required missing answers, invalid
|
||||
number/integer, min/max bounds, boolean type, string length and item counts
|
||||
produce the web's exact messages; invalid input blocks the send and shows the
|
||||
reason. Visible, non-external, answered fields alone travel in `chat_answer`.
|
||||
`accept` is sent when the form lists it; `Decline` / `Cancel question` use the
|
||||
recorded actions and an empty answer map.
|
||||
- **Question outcome.** Submit is one-shot through the stable id
|
||||
`chat-answer:{formId}:{action|answer}`. Success marks the form resolved locally
|
||||
and shows `Answer recorded.`; the server's resolved/cancelled echo replaces it
|
||||
with the recorded answers. `cancelled` shows `This question expired.`.
|
||||
Read-only rendering includes answers for fields no longer present, and says
|
||||
`No answer was recorded.` when the resolved form recorded none. A refusal keeps
|
||||
the card pending with its typed state and shows the server reason.
|
||||
- **Composition.** Cards follow the message rows in server order (permissions
|
||||
then questions), keyed by request/form id so streaming repaints keep an open
|
||||
disclosure or half-typed answer. Unknown message parts still render through the
|
||||
existing plain `Unrecognised part` disclosure; nothing in `ChatMessageView` or
|
||||
the markdown renderer changed.
|
||||
|
||||
## Checks actually run (after the final split)
|
||||
|
||||
- `flutter analyze` — `No issues found!`
|
||||
- `flutter test` — `All tests passed!` (1003 tests, including the 20 new focused
|
||||
card/model/controller cases)
|
||||
- `flutter build web --output build/web-acceptance` — `✓ Built`
|
||||
- `node tool/chat_approvals_probe.mjs` for both hosts — see below.
|
||||
|
||||
## Browser fixture evidence
|
||||
|
||||
The fixture runs the **real** `ChatThreadView`/controller against a scripted
|
||||
gateway that replays one pending `chat_permission` and one `form` question on
|
||||
subscribe, then echoes the reply/answer back as a resolved frame. Chrome CDP at
|
||||
320px logical width, device scale 2, dark appearance, both hosts. Static card
|
||||
text is OCR-verified because Flutter web paints it on the canvas; controls are
|
||||
driven through semantics.
|
||||
|
||||
Captures and evidence (shared run artifacts):
|
||||
|
||||
- `public/chat-approvals-probe/material-cards.png`
|
||||
- `public/chat-approvals-probe/material-approval-answered.png`
|
||||
- `public/chat-approvals-probe/material-question-answered.png`
|
||||
- `public/chat-approvals-probe/material-evidence.json`
|
||||
- `public/chat-approvals-probe/cupertino-cards.png`
|
||||
- `public/chat-approvals-probe/cupertino-approval-answered.png`
|
||||
- `public/chat-approvals-probe/cupertino-question-answered.png`
|
||||
- `public/chat-approvals-probe/cupertino-evidence.json`
|
||||
|
||||
Each run asserted the pending card's recorded action, status, risk, resource
|
||||
lines and all three control labels; that `Allow once` sent the reply (the fixture's
|
||||
server resolution replaced it with `Allowed once` and cleared the controls); and
|
||||
that selecting `Red` + `Send answer` sent the answer and produced the read-only
|
||||
`Answer recorded.` card. Both runs finished with `sendAnswerStillVisible:false`
|
||||
and `allowOnceStillVisible:false`. The Material capture also shows no clipped
|
||||
text at 320/2x; the Cupertino capture uses only Cupertino controls (widget tests
|
||||
assert no `Material` ancestor in that host).
|
||||
|
||||
## Limits, stated plainly
|
||||
|
||||
- **No live server request was answered.** The fixture's gateway is scripted and
|
||||
its reply/answer responses are local; no operator chat, run, approval or real
|
||||
server was mutated.
|
||||
- **No authenticated smoke yet.** The `PARITY.md` row remains Source, not Preview:
|
||||
a real pending approval/question against the authenticated server, and a
|
||||
multi-client server resolution, are still unverified.
|
||||
- **Web only.** Android/iOS builds, ADB, emulators and device/OS behavior were not
|
||||
run (per the app working agreement); source is portable but mobile is
|
||||
unverified.
|
||||
- **External question forms** display only their recorded HTTP(S) URL as
|
||||
selectable text; no URL launcher dependency exists in this app, so they are not
|
||||
opened from the card. Unsupported URLs show the web's alert wording instead.
|
||||
- **Uncommitted.** The pipeline input asked for a candidate commit, but the stage
|
||||
instructions explicitly say not to commit, push or deploy, so the work is left
|
||||
in the working tree (`flutter/chat-approvals`) with no commit or merge.
|
||||
|
||||
## Manager completion after a harness transport failure
|
||||
|
||||
The run ended on a harness transport error (`/api/session/active`) after a full
|
||||
Code visit; the retained tree was complete. Manager verified 173 chat tests,
|
||||
clean analysis, and the both-host browser probe. Two probe expectations were
|
||||
corrected against the web rather than against the app: the approval card's
|
||||
headline is the recorded action (the web has no separate "Permission request"
|
||||
heading), and OCR merges whitespace, so comparisons now ignore it and accept a
|
||||
control that is present in the semantics tree. No app behaviour was changed to
|
||||
make the probe pass.
|
||||
@@ -0,0 +1,144 @@
|
||||
# Graph viewport: pan, zoom, fit and expanded
|
||||
|
||||
The measured definition/run canvases now share one viewport layer. Nothing in
|
||||
the graph's wiring changed: `DefinitionGraphView` and `RunGraphView` keep their
|
||||
existing props and call sites, and the pipeline Graph tab / run detail open the
|
||||
expanded presentation without edits to those tabs.
|
||||
|
||||
## Landed
|
||||
|
||||
- `lib/features/graph/viewport/graph_viewport_math.dart` — the web graph's
|
||||
`fitScale`/`clampOffset` rules (padding 24, min 0.3, max 3, at least 40px of
|
||||
the scaled graph visible) plus the `offset + point * scale` matrix.
|
||||
- `lib/features/graph/viewport/graph_viewport_controller.dart` — owns the
|
||||
`TransformationController`, auto-fits on first layout, re-fits a resize only
|
||||
before the reader interacts, clamps every later transform, and round-trips a
|
||||
`GraphViewportSnapshot`.
|
||||
- `lib/features/graph/viewport/graph_viewport.dart` — the bounded canvas: the
|
||||
host's `InteractiveViewer` gestures (drag, pinch, wheel, trackpad) with an
|
||||
infinite boundary margin so the graph's own fit/bounds win, plus native Fit
|
||||
and Expand controls (`Fit graph to view`, `Expand graph`).
|
||||
- `lib/features/graph/viewport/graph_expanded_view.dart` — a native full-screen
|
||||
presentation (`Scaffold`/`CupertinoPageScaffold`) with one visible `Close`
|
||||
action, `openGraphExpanded()` as the widget/callback seam, and an optional
|
||||
fixed `header` above the canvas. It fits the larger box exactly as the web
|
||||
re-fits when its panel expands, keeps the selected node selected, re-fits a
|
||||
resize until the reader interacts and clamps one afterwards. It owns a
|
||||
separate controller, so closing restores the inline transform exactly.
|
||||
- `DefinitionGraphView`/`RunGraphView` now wrap their measured content in
|
||||
`GraphViewport`; `RunGraphCanvas` is the passive content only (the viewer
|
||||
moved out of it). `DefinitionGraphCanvas` owns the measured definition
|
||||
composition, and `RunGraphHeader` owns the route legend + elapsed line and is
|
||||
carried into the expanded run presentation. Node sizes, routing,
|
||||
executed/unvisited evidence, labels and legend are unchanged.
|
||||
|
||||
## Behavior and bounds
|
||||
|
||||
- The graph is fitted on first layout with 24px padding and never upscaled past
|
||||
1:1, before the first paint: the first layout attaches synchronously, when
|
||||
nothing is listening to the transform yet, rather than flashing an identity
|
||||
transform for a frame.
|
||||
- Scale is clamped to 0.3–3 and a drag can never leave an empty viewport
|
||||
(40px minimum visible per axis).
|
||||
- Pinch/wheel zoom anchors the graph point under the moving focal point; a tap
|
||||
that does not move still reaches the native node under the pointer because
|
||||
hit-testing follows the same transform.
|
||||
- Fit and Expand are stock host buttons with one accessible name and the
|
||||
button's own tap action on both hosts. The icon is the only excluded child
|
||||
and `MergeSemantics` folds the real button action into the labelled node; a
|
||||
hand-written sibling `Semantics` around an `ExcludeSemantics`d button would
|
||||
announce the control with no action at all.
|
||||
- Single taps select nodes; dragging over a node pans instead of selecting.
|
||||
- The canvas consumes gestures only inside its own box. An ancestor scroll view
|
||||
keeps scrolling for gestures outside the canvas, and the canvas never pans
|
||||
from a drag that starts outside it.
|
||||
- Expanded draws the same canvas at its own fit, keeps the legend (run graph),
|
||||
keeps the selection, and leaves the inline canvas untouched.
|
||||
|
||||
## Checks (final tree)
|
||||
|
||||
From `app/` with Flutter 3.44.6 / Dart 3.12.2:
|
||||
|
||||
- `flutter analyze` — **No issues found**.
|
||||
- `flutter test` — **1025 tests pass** (1m 06s in this run).
|
||||
- `flutter test test/features/graph` — **175 pass**.
|
||||
- `flutter test test/features/graph/viewport` — **20 tests pass**
|
||||
(8 math/controller, 9 viewport widget, 3 expanded), covering:
|
||||
- drag pans and pan stays bounded;
|
||||
- pinch clamps at 0.3 and 3;
|
||||
- zoom keeps the graph point under the moving focal point;
|
||||
- the first painted frame is already fitted;
|
||||
- Fit restores the fitted scale/offset;
|
||||
- tap selects the node visually under the pointer after a transform (synthetic
|
||||
targets and real `DefinitionGraphView` nodes);
|
||||
- ancestor scroll is not hijacked outside the canvas;
|
||||
- Fit and Expand are labelled buttons with a tap action on Material and
|
||||
Cupertino, and performing that action runs the real callback;
|
||||
- 320px/2x on Material and dark Cupertino;
|
||||
- expanded fits the larger canvas, preserves selection and returns the inline
|
||||
state exactly;
|
||||
- a rotation re-clamps the expanded transform into the new box.
|
||||
- `flutter build web` — succeeds for the app and the probe target.
|
||||
- Real Chrome probe (`tool/graph_zoom_probe.dart` + `tool/graph_zoom_probe.mjs`,
|
||||
loopback server, OS-assigned port) re-run against this final source, 7 runs:
|
||||
- pipeline graph: Material light 1280x800 1x, Material light 320x700 2x,
|
||||
Cupertino dark 390x844 1x, Cupertino dark 320x700 2x;
|
||||
- run graph: Material light 1280x800 1x, Material dark 320x700 2x,
|
||||
Cupertino dark 390x844 1x.
|
||||
Each asserted a real drag moved a node, wheel zoom grew it, Fit restored it,
|
||||
Expand opened the titled full-screen canvas with the selected node still
|
||||
announced selected, and Close returned to the same inline place and selection.
|
||||
42 captures (initial/panned/zoomed/fitted/expanded/restored per run) were
|
||||
regenerated after the last source edit and are in
|
||||
`/Users/alan/.local/share/pipelines/data/artifacts/101/public/graph-zoom-captures/`.
|
||||
- `dart format --output=none --set-exit-if-changed` on the changed Dart files —
|
||||
0 changed; `git diff --check` — clean.
|
||||
|
||||
## Corrections from actual checks
|
||||
|
||||
- The transform's z axis must be scaled with x/y: `getMaxScaleOnAxis` otherwise
|
||||
reported 1.0 for a 0.8 fit and InteractiveViewer's own pinch math used the
|
||||
wrong scale. Fixed in `graphViewportMatrix`.
|
||||
- Two existing measurement tests compared on-screen rectangles, which now
|
||||
include the fit scale. They divide by the current scale and assert the
|
||||
measured graph-space extent instead; the assertions about wrapping and
|
||||
overlap are unchanged.
|
||||
- Cupertino's full-screen route added its own `Cancel` leading button next to
|
||||
the explicit Close; `automaticallyImplyLeading: false` leaves the one Close
|
||||
action.
|
||||
- `tester.drag` can lose the pre-acceptance movement to the pan slop; gesture
|
||||
tests warm up past the slop and measure from the accepted transform, and the
|
||||
browser probe pans with eight real pointer moves.
|
||||
- The first implementation excluded the whole Cupertino button from semantics
|
||||
and put the label on a sibling node: VoiceOver/TalkBack saw a labelled button
|
||||
with no tap action. The exclusion now covers only the icon and
|
||||
`MergeSemantics` merges the host button's action; the regression test performs
|
||||
the semantics action itself, not a pointer tap.
|
||||
- Material controls previously had only a tooltip as their accessible name. Both
|
||||
hosts now expose one explicit label (`Fit graph to view` / `Expand graph`);
|
||||
Material keeps the tooltip for pointer hover, excluded from semantics so the
|
||||
name is not duplicated.
|
||||
- The inline canvas used to paint one identity-transform frame before the
|
||||
post-frame fit. The first layout now attaches before its child viewer exists,
|
||||
and the regression test pumps exactly once.
|
||||
- Expanded used to keep the small inline scale, unlike the web, which calls
|
||||
`fit()` after growing the panel. It now fits its own canvas and re-clamps (or
|
||||
re-fits) on resize; the inline place/selection still return unchanged on
|
||||
Close.
|
||||
- The expanded run canvas had no route legend; `RunGraphHeader` now travels
|
||||
with it.
|
||||
|
||||
## Limits
|
||||
|
||||
- Inside an ancestor scroll view, a **vertical** drag that starts on the canvas
|
||||
is claimed by the scrollable (Flutter's gesture arena gives the 18px vertical
|
||||
drag the win over the 36px pan slop); horizontal drags and pinch stay with the
|
||||
canvas. The graph is not inside a scrollable in either current tab. Outside
|
||||
the canvas the list scrolls normally, which is the accepted behavior here.
|
||||
- Opening expanded fits the graph rather than keeping the inline place (web
|
||||
behavior); closing still restores the inline transform exactly.
|
||||
- Web only: Android/iOS builds, device gestures and OS behavior are unverified.
|
||||
- `run_graph_view.dart` remains over the 250-line aim (324 lines: measurement,
|
||||
evidence and viewport composition; the legend/header and definition canvas
|
||||
were split out). The new viewport files and viewport test files are all under
|
||||
250 lines.
|
||||
@@ -0,0 +1,190 @@
|
||||
# R4 — recorded-visit pane
|
||||
|
||||
## Delivered
|
||||
|
||||
The Timeline tab now opens a real recorded visit. Selecting a row, or clicking a
|
||||
visited stage in the Graph tab, shows that visit inside the Timeline tab:
|
||||
|
||||
- **Facts** — the row's exact stage/visit title, then only the fields the reply
|
||||
recorded: Status, Outcome, Duration (only when both `started_at` and
|
||||
`finished_at` parse and the finish is not before the start), Provider/model
|
||||
(`provider / model`, or the one part recorded), Target, a recorded Verdict
|
||||
(option and reason) and the visit's Diagnostic. A blank field is absent, never
|
||||
`0`, `false`, `0s` or a guessed value.
|
||||
- **Native sections** — Input, Output, Artifacts, Session, Definition, using the
|
||||
Material segmented button or Cupertino segmented control. The strip scrolls
|
||||
rather than squeezing labels at 320/2x.
|
||||
- Input/Output use the run detail's existing field rendering and the exact
|
||||
empty sentences `No input recorded.` / `No output recorded.`.
|
||||
- Artifacts lists this visit's stage files (`visitArtifacts`, so a shared
|
||||
`public/` file stays with the visit that first recorded it) and opens the
|
||||
existing artifact gallery page for that visit. The page is given the whole
|
||||
run and the focused visit, so it lists exactly the rows the pane lists and
|
||||
keeps the run's own visit group. An empty list uses the landed per-visit
|
||||
capture wording (`Artifacts · capture pending` for a running visit,
|
||||
`Artifacts · capture unavailable` when the field is absent, `Artifacts ·
|
||||
not recorded for this visit` only for an explicitly empty capture) and shows
|
||||
the partial-capture notes when the scan was bounded.
|
||||
- Session shows the recorded session identity and, when the visit exported
|
||||
one, `Open <export name>`. The recorded URL is resolved by the landed
|
||||
`resolveArtifactUrl` and opened through `openArtifactExternally`; a refusal
|
||||
or an unresolved relative URL is reported, never silently swallowed. The
|
||||
state comes from the recorded export evidence (including a repair), falls
|
||||
back to the legacy `session.html` system file web audit uses, and otherwise
|
||||
reports the recorded state in the web client's words: skipped, stopped,
|
||||
session being created, failed with its diagnostic, or the runtime error for
|
||||
a model visit with no identity. An export whose evidence is partial or
|
||||
failed stays openable and says so.
|
||||
- Definition embeds the landed `StageDefinitionView` for the run's own pinned
|
||||
graph and stage, so the authored prompt/output/outcomes/raw source show
|
||||
exactly as landed. When the reply does not declare the stage, the landed
|
||||
exact sentence `This stage is not declared in this pipeline version. No
|
||||
definition has been reconstructed.` is shown instead.
|
||||
- **Back** — `Back to timeline` (native back arrow / Cupertino chevron) closes
|
||||
the pane and restores the rows. The run header, Changes, Artifacts, Rename,
|
||||
Cancel, Retry and Decide actions are untouched and stay outside the tabs.
|
||||
- A different run clears the selection; an unvisited Graph node still opens
|
||||
nothing.
|
||||
|
||||
## Files
|
||||
|
||||
Added:
|
||||
|
||||
- `app/lib/features/runs/ui/run_detail_visit.dart` — pane layout, facts, verdict
|
||||
and diagnostic, Back.
|
||||
- `app/lib/features/runs/ui/run_detail_visit_facts.dart` — pure step lookup,
|
||||
duration/provider/model/verdict/definition facts, exact wording.
|
||||
- `app/lib/features/runs/ui/run_detail_visit_session_state.dart` — recorded
|
||||
session/export state: identity, repair/legacy export resolution and the
|
||||
state-specific wording.
|
||||
- `app/lib/features/runs/ui/run_detail_visit_sections.dart` — section enum,
|
||||
adaptive strip, section body selection.
|
||||
- `app/lib/features/runs/ui/run_detail_visit_artifacts.dart` — visit artifact
|
||||
rows opening the existing gallery entry.
|
||||
- `app/lib/features/runs/ui/run_detail_visit_session.dart` — session pointer and
|
||||
safe-link export open.
|
||||
- `app/lib/features/runs/ui/run_detail_visit_definition.dart` — pinned
|
||||
stage-definition pane or exact missing wording.
|
||||
- `app/test/features/runs/ui/run_detail_visit_support.dart`,
|
||||
`run_detail_visit_test.dart`, `run_detail_visit_sections_test.dart`,
|
||||
`run_detail_visit_session_test.dart`.
|
||||
- `app/tool/run_detail_visit_probe.dart`, `run_detail_visit_probe.mjs`.
|
||||
- `app/notes/R4-visit.md`.
|
||||
|
||||
Changed (minimal wiring):
|
||||
|
||||
- `run_detail_timeline.dart` — rows become selectable and report their index.
|
||||
- `run_detail_tabs.dart` — selected visit index opens the pane; Back closes it;
|
||||
Graph selection uses the latest recorded index.
|
||||
- `run_detail_view.dart`, `run_detail_material.dart`,
|
||||
`run_detail_cupertino.dart` — pass the configured endpoint for the session
|
||||
safe link; the endpoint cast now comes from `configuredGatewayEndpoint` in
|
||||
`core/transport/pipelines_client.dart`.
|
||||
- `run_detail_tab_strip.dart` — `ScrollWhenOverflowing` is public and shared by
|
||||
both tab strips, so the pointer-drag and minimum-width rules live once.
|
||||
- `lib/features/artifacts/domain/artifact_groups.dart` —
|
||||
`visitArtifactGroup` returns the gallery group of exactly one visit from the
|
||||
whole run.
|
||||
- `lib/features/artifacts/ui/artifact_gallery_page.dart`,
|
||||
`artifact_gallery_action.dart` — an optional focused visit limits the page to
|
||||
that visit's attributed group and summary; the run-level gallery is unchanged.
|
||||
- `run_detail_graph_tab_test.dart` — the stage-click expectation now asserts
|
||||
the opened pane and its facts (previous test asserted the row highlight).
|
||||
- `run_detail_graph_support.dart` — optional light/dark theme for 2x checks and
|
||||
an empty-tree reset so one test can pump a second run.
|
||||
- `run_detail_graph_probe.mjs` — the stage-click check now expects the pane and
|
||||
its sections; re-run once to keep the existing probe green.
|
||||
|
||||
The artifact changes are the two focused-visit additions above: the run-level
|
||||
gallery, its viewer and its domain grouping are otherwise untouched. No
|
||||
`graph/`, `pipelines/`, `chat/`, `application/`, `schedules/`, `templates/` or
|
||||
backend file was edited.
|
||||
|
||||
## Checks run
|
||||
|
||||
From `app/` with Flutter 3.44.6:
|
||||
|
||||
- `flutter analyze` — no issues.
|
||||
- `flutter test` — **1014 tests passed** (full suite).
|
||||
- `flutter build web` — built `build/web`.
|
||||
- Probe builds:
|
||||
`flutter build web --target tool/run_detail_visit_probe.dart --output build/probe-run-detail-visit`
|
||||
and the existing `run_detail_graph_probe.dart` build both succeeded.
|
||||
- `node tool/run_detail_visit_probe.mjs` — passed for Material and Cupertino at
|
||||
1280×900/1x dark and 320×568/2x dark: 9/9 checks and 8 captures each.
|
||||
- `node tool/run_detail_graph_probe.mjs` — Material 1280×900/1x dark re-run
|
||||
passed with the pane expectation.
|
||||
|
||||
## Browser evidence
|
||||
|
||||
Probe drives the real `RunDetailView` over a server-shaped fake gateway (plan
|
||||
visit with provider/model, both timestamps, verdict, diagnostic, input/output,
|
||||
artifacts, session id + `session.html` export; a sparse build visit with no
|
||||
timestamps/provider/session). Checks: Graph stage click opens `plan · visit 1`
|
||||
with all five sections; Definition shows the pinned "Draft the plan." source;
|
||||
Session shows `sess-1` and `Open session.html`; Artifacts lists `plan.csv`; the
|
||||
row opens a gallery whose summary says `Artifacts · 1 recorded`, whose only
|
||||
group is `plan · visit 1` and whose only row is `plan.csv` (the `session.html`
|
||||
evidence file is absent); Back restores the rows; the sparse visit has no
|
||||
Duration or Provider/model and its Artifacts tab says
|
||||
`Artifacts · capture unavailable`.
|
||||
|
||||
Under `/Users/alan/.local/share/pipelines/data/artifacts/95/public/r4-visit-fix/`:
|
||||
|
||||
| Host | Viewport | Captures |
|
||||
| --- | --- | --- |
|
||||
| Material | 1280×900, dark, 1x | `run-detail-visit-material-dark-1x-1280x900-{visit-pane,definition,session,artifacts,timeline-rows,sparse-visit,sparse-artifacts,visit-gallery}.png` |
|
||||
| Material | 320×568, dark, 2x | `run-detail-visit-material-dark-2x-320x568-{visit-pane,definition,session,artifacts,timeline-rows,sparse-visit,sparse-artifacts,visit-gallery}.png` |
|
||||
| Cupertino | 1280×900, dark, 1x | `run-detail-visit-cupertino-dark-1x-1280x900-{visit-pane,definition,session,artifacts,timeline-rows,sparse-visit,sparse-artifacts,visit-gallery}.png` |
|
||||
| Cupertino | 320×568, dark, 2x | `run-detail-visit-cupertino-dark-2x-320x568-{visit-pane,definition,session,artifacts,timeline-rows,sparse-visit,sparse-artifacts,visit-gallery}.png` |
|
||||
|
||||
Evidence JSON: `evidence-{material,cupertino}-{1x-1280x900,2x-320x568}.json`;
|
||||
each records 9 checks, all `true`, and the 8 captures above (32 PNGs).
|
||||
|
||||
At 320/2x the run detail keeps its own 240px minimum tab body, so the visit
|
||||
facts area is a short scroll region; all facts remain reachable by scrolling and
|
||||
the section strip/body stay usable. No overflow or exception is reported.
|
||||
|
||||
## Review fixes (visit 2)
|
||||
|
||||
- Artifact empty states now use the landed per-visit capture wording instead of
|
||||
one "nothing recorded" sentence; tests cover absent, explicitly empty and
|
||||
running captures.
|
||||
- The artifact row opens the gallery focused on the same visit with the whole
|
||||
run as context, so a shared `public/` file is not re-attributed. Tests cover
|
||||
two visits of one stage plus a repeated public file, asserting the pane and
|
||||
the opened page both exclude it.
|
||||
- Session resolution handles a repair and the legacy `session.html`, reports the
|
||||
evidence status/diagnostic when the file is missing, and uses the web client's
|
||||
state-specific sentences. Tests cover a legacy export, a running model visit
|
||||
and a failed one.
|
||||
- Advisory cleanups: shared `ScrollWhenOverflowing`, one timeline lookup for the
|
||||
latest visit, one endpoint helper, corrected stale selection comments and the
|
||||
added refusal test.
|
||||
|
||||
## Known gaps
|
||||
|
||||
- The pane title and timeline rows still use the global recorded `sequence`
|
||||
(`plan · visit 5`), while the gallery group uses the per-stage visit number
|
||||
(`plan · visit 2`). This predates this pane; aligning the rows and pane would
|
||||
change the timeline titles and is recorded here rather than done.
|
||||
- At 320/2x the existing 240px minimum tab body leaves the facts area a short
|
||||
scroll region; all facts are reachable by scrolling and no overflow occurs.
|
||||
|
||||
## Not done / unverified
|
||||
|
||||
- No commit, push, merge or deployment (this stage forbids it; the input's
|
||||
“commit the candidate” was not performed).
|
||||
- Web only. Android/iOS builds, layout and device behavior were not run; the
|
||||
source stays portable (Material/Cupertino only, no platform-only imports).
|
||||
- No backend changes. The pane reads only fields the existing `get_run` reply
|
||||
already carries; nothing new was requested from the server.
|
||||
|
||||
## Manager completion after the Code deadline
|
||||
|
||||
The run had succeeded at Code once, been rejected at Review, and its retry hit the
|
||||
30-minute stage deadline. The retained tree is complete: 280 runs/artifacts tests
|
||||
pass and analysis is clean. Merged directly. The only cross-feature edit is an
|
||||
11-line `configuredGatewayEndpoint` helper in the transport so relative recorded
|
||||
artifact/session urls resolve against the configured origin without repeating a
|
||||
cast in the UI.
|
||||
@@ -0,0 +1,84 @@
|
||||
# Runs-list Needs-you bell wiring
|
||||
|
||||
The landed attention model and native bell/sheet are now registered in the real
|
||||
Runs destination. The bell sits in the Runs list heading area and reads the same
|
||||
`list_runs` rows the screen already loaded; it issues no attention request and
|
||||
adds no poll.
|
||||
|
||||
## Code
|
||||
|
||||
- `lib/features/attention/runtime/attention_store.dart` — the injectable
|
||||
`AttentionStore` seam, a `SharedPreferences` implementation under
|
||||
`pipelines.next.attention.v1` (only that key), and an in-memory implementation
|
||||
for tests/fixtures. Reads and writes are total: an unavailable plugin or full
|
||||
store returns null/false instead of throwing.
|
||||
- `lib/features/attention/runtime/attention_controller.dart` — derives today's
|
||||
ordered entries from rows plus the persisted dismissal set, loads asynchronously,
|
||||
and folds pushed `run_event` frames with the runs feature's existing
|
||||
`foldRunEvent`. The attention transition detector is seeded by authoritative
|
||||
list reads, reseeded on reconnect, and keeps emitted keys, so a failure/wait
|
||||
that appears while the screen is open reaches the bell once while a reconnect
|
||||
never replays it. Dismissals update memory and notify before the store write, so
|
||||
a slow or failed write cannot block the sheet. Pushed `title`/`name`/`diagnostic`
|
||||
are retained because the lifecycle fold does not carry the row's attention text.
|
||||
- `lib/features/attention/ui/needs_you_runs_heading.dart` — owns the controller
|
||||
and shared-frame subscription for the destination, passes the dismissed list to
|
||||
the landed `NeedsYouBell`, and opens the existing run through `RunsList`'s
|
||||
`onSelected` (the existing run route).
|
||||
- `lib/features/runs/ui/runs_list.dart` — small heading insert plus injectable
|
||||
store/clock and reconnect token; no other destination is touched.
|
||||
- `lib/features/runs/screen.dart` — forwards the reconnect token and the test
|
||||
seam to the list.
|
||||
- `lib/features/runs/ui/runs_filters.dart` — the existing filter controls moved
|
||||
out of the list file unchanged for Material, with the Cupertino strip made
|
||||
horizontally scrollable. At 320 logical px / 2x the old wrapping strip alone
|
||||
made the Runs `Column` overflow before the attention change; one native row is
|
||||
the same narrow-toolbar shape the browser uses and keeps every control
|
||||
reachable. File split keeps `runs_list.dart` at 159 lines.
|
||||
|
||||
The bell keeps the native `NeedsYouBell` semantics (`Notifications` /
|
||||
`Notifications, N needing attention`), shows no badge when empty, and uses the
|
||||
already-landed Material bottom sheet / Cupertino popup. Failed rows dismiss before
|
||||
opening; Decision rows open without dismissing; Clear all uses the snapshot the
|
||||
sheet captured when it opened. Dismissals survive a screen rebuild through the
|
||||
same store.
|
||||
|
||||
## Verification
|
||||
|
||||
- `flutter test` — 966 tests passed.
|
||||
- Focused `flutter test test/features/attention/runtime` — 20 tests passed:
|
||||
rows -> entries, export waits and yesterday excluded, dismissal persistence
|
||||
across a rebuilt controller, slow write does not block, failed read/write is
|
||||
harmless, clear-all snapshot leaves a later arrival, live failed frame adds an
|
||||
entry, a frame can create a new run summary, reconnect keeps dismissals and
|
||||
emitted keys, empty state keeps the bell and hides its badge, both hosts at
|
||||
320 logical px / 2x with no list/sheet overflow, and the SharedPreferences key
|
||||
ownership test.
|
||||
- `flutter analyze` — no issues.
|
||||
- `flutter build web` — normal `lib/main.dart` built successfully.
|
||||
- Real browser (`tool/attention_wiring_probe.mjs`, isolated `startFixture`, two
|
||||
fresh app boots, one shared socket each): four captures in
|
||||
`public/attention-wiring/` at 320 logical px / 2x:
|
||||
`attention-runs-cupertino-bell-320x2.png`,
|
||||
`attention-runs-cupertino-sheet-320x2.png`,
|
||||
`attention-runs-material-bell-320x2.png`,
|
||||
`attention-runs-material-sheet-320x2.png`.
|
||||
The drive asserted the accessible count `Notifications, 2 needing attention`,
|
||||
both void rows absent, the `Dismiss ...` names and Clear all, and viewed both
|
||||
PNGs. The fixture list held a running row and an `export_pending_sequence`
|
||||
wait that did not enter the sheet; the fixture served one connection and no
|
||||
`get_run`/attention request (`listRuns: 4` across the two boots, the existing
|
||||
screen loads). Both bell and sheet captures were inspected.
|
||||
|
||||
`tool/runs_probe_server.mjs` now accepts an optional `runs` list so this fixture
|
||||
can use current-day timestamps without changing the existing runs probe's
|
||||
default data. No legacy driver was edited.
|
||||
|
||||
## Not done / limits
|
||||
|
||||
- No commit, push, merge, deployment, preview cutover or service restart.
|
||||
- Notification permission/tray delivery remains separate work; the transition
|
||||
ledger is exposed for that wiring but no permission is requested here.
|
||||
- Android/iOS builds and real devices were not run; web only, as required.
|
||||
- The fixture is isolated (loopback, its own browser profile) and does not touch
|
||||
operator runs, chats, storage or production credentials.
|
||||
+1
-1
@@ -374,7 +374,7 @@ packages:
|
||||
source: hosted
|
||||
version: "15.4.0"
|
||||
web:
|
||||
dependency: transitive
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: web
|
||||
sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"
|
||||
|
||||
@@ -38,6 +38,7 @@ dependencies:
|
||||
shared_preferences: ^2.5.6
|
||||
flutter_web_plugins:
|
||||
sdk: flutter
|
||||
web: ^1.1.1
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/artifacts/actions/artifact_file.dart';
|
||||
import 'package:pipelines_app/features/artifacts/actions/artifact_file_actions.dart';
|
||||
import 'package:pipelines_app/features/artifacts/actions/artifact_file_bridge.dart';
|
||||
import 'package:pipelines_app/features/artifacts/actions/artifact_transfer.dart';
|
||||
import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart';
|
||||
import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart';
|
||||
import 'package:pipelines_app/features/artifacts/domain/artifact_url.dart';
|
||||
import 'package:pipelines_app/features/artifacts/ui/artifact_gallery_page.dart';
|
||||
import 'package:pipelines_app/features/artifacts/ui/artifact_visit_list.dart';
|
||||
import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_fetch.dart';
|
||||
import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_page.dart';
|
||||
|
||||
import '../domain/artifact_fixtures.dart';
|
||||
import '../ui/artifact_visit_list_fixture.dart';
|
||||
|
||||
const _endpoint = 'ws://127.0.0.1:8081/connect';
|
||||
final Uint8List _bytes = Uint8List.fromList(<int>[7, 8, 9]);
|
||||
|
||||
final ArtifactRecord _record = ArtifactRecord.fromJson(<String, dynamic>{
|
||||
'name': 'report.csv',
|
||||
'url': '/artifacts/1/1/report.csv',
|
||||
'content_type': 'text/csv',
|
||||
'size_bytes': 3,
|
||||
});
|
||||
|
||||
ArtifactFileBridge _bridge({
|
||||
List<ArtifactFile>? saved,
|
||||
List<ArtifactFile>? shared,
|
||||
bool downloadSupported = true,
|
||||
bool shareSupported = true,
|
||||
}) => ArtifactFileBridge(
|
||||
downloadSupported: downloadSupported,
|
||||
shareSupported: shareSupported,
|
||||
downloadUnsupportedMessage: 'No download on this host.',
|
||||
shareUnsupportedMessage: 'No share on this host.',
|
||||
download: (file) async {
|
||||
saved?.add(file);
|
||||
return ArtifactTransferResult(
|
||||
ArtifactTransferState.saved,
|
||||
'Downloaded ${file.name}.',
|
||||
);
|
||||
},
|
||||
share: (file) async {
|
||||
shared?.add(file);
|
||||
return const ArtifactTransferResult(
|
||||
ArtifactTransferState.shared,
|
||||
'File shared.',
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
Future<ArtifactFetchResult> _fetch(Uri uri) async =>
|
||||
ArtifactFetchResult(status: 200, bytes: _bytes);
|
||||
|
||||
Widget _row({
|
||||
required bool cupertino,
|
||||
ArtifactFileBridge? bridge,
|
||||
ArtifactRecord? artifact,
|
||||
ArtifactFetch? fetch,
|
||||
}) {
|
||||
final actions = ArtifactFileActions(
|
||||
artifact: artifact ?? _record,
|
||||
resolved: resolveArtifactUrl(_endpoint, _record.url)!,
|
||||
fetch: fetch ?? _fetch,
|
||||
bridge: bridge ?? _bridge(),
|
||||
);
|
||||
return cupertino
|
||||
? CupertinoApp(
|
||||
home: CupertinoPageScaffold(
|
||||
child: SafeArea(
|
||||
child: Padding(padding: const EdgeInsets.all(8), child: actions),
|
||||
),
|
||||
),
|
||||
)
|
||||
: MaterialApp(
|
||||
home: Scaffold(
|
||||
body: Padding(padding: const EdgeInsets.all(8), child: actions),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
TextButton _materialButton(WidgetTester tester, String label) =>
|
||||
tester.widget<TextButton>(
|
||||
find
|
||||
.ancestor(of: find.text(label), matching: find.byType(TextButton))
|
||||
.first,
|
||||
);
|
||||
|
||||
CupertinoButton _cupertinoButton(WidgetTester tester, String label) =>
|
||||
tester.widget<CupertinoButton>(
|
||||
find
|
||||
.ancestor(
|
||||
of: find.text(label),
|
||||
matching: find.byType(CupertinoButton),
|
||||
)
|
||||
.first,
|
||||
);
|
||||
|
||||
void main() {
|
||||
testWidgets('Download saves the exact named bytes and reports it', (
|
||||
tester,
|
||||
) async {
|
||||
final saved = <ArtifactFile>[];
|
||||
await tester.pumpWidget(
|
||||
_row(cupertino: false, bridge: _bridge(saved: saved)),
|
||||
);
|
||||
|
||||
await tester.tap(find.text('Download'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(saved, hasLength(1));
|
||||
expect(saved.single.name, 'report.csv');
|
||||
expect(saved.single.mimeType, 'text/csv');
|
||||
expect(saved.single.bytes, _bytes);
|
||||
expect(find.text('Downloaded report.csv.'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('Share starts one file transfer, not a link', (tester) async {
|
||||
final shared = <ArtifactFile>[];
|
||||
await tester.pumpWidget(
|
||||
_row(cupertino: false, bridge: _bridge(shared: shared)),
|
||||
);
|
||||
|
||||
await tester.tap(find.text('Share'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(shared.single.name, 'report.csv');
|
||||
expect(shared.single.byteLength, 3);
|
||||
expect(find.text('File shared.'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('unsupported share is explained but download stays enabled', (
|
||||
tester,
|
||||
) async {
|
||||
final saved = <ArtifactFile>[];
|
||||
await tester.pumpWidget(
|
||||
_row(
|
||||
cupertino: false,
|
||||
bridge: _bridge(saved: saved, shareSupported: false),
|
||||
),
|
||||
);
|
||||
|
||||
expect(find.text('No share on this host.'), findsOneWidget);
|
||||
expect(_materialButton(tester, 'Share').onPressed, isNull);
|
||||
expect(_materialButton(tester, 'Download').onPressed, isNotNull);
|
||||
|
||||
await tester.tap(find.text('Download'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(saved, hasLength(1));
|
||||
});
|
||||
|
||||
testWidgets('a slow fetch shows progress and cancel, then reports cancel', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
_row(
|
||||
cupertino: false,
|
||||
bridge: _bridge(),
|
||||
fetch: (_) => Future<ArtifactFetchResult>.delayed(
|
||||
const Duration(seconds: 30),
|
||||
() => ArtifactFetchResult(status: 200, bytes: _bytes),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
await tester.tap(find.text('Download'));
|
||||
await tester.pump();
|
||||
expect(find.text('Preparing file…'), findsOneWidget);
|
||||
expect(find.byType(CircularProgressIndicator), findsOneWidget);
|
||||
expect(_materialButton(tester, 'Download').onPressed, isNull);
|
||||
expect(find.text('Cancel'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.text('Cancel'));
|
||||
await tester.pump();
|
||||
expect(find.text('Download canceled.'), findsOneWidget);
|
||||
expect(find.text('Cancel'), findsNothing);
|
||||
await tester.pump(const Duration(seconds: 31));
|
||||
});
|
||||
|
||||
testWidgets('both hosts keep the file actions whole at 320/2x dark', (
|
||||
tester,
|
||||
) async {
|
||||
tester.view.physicalSize = const Size(640, 1200);
|
||||
tester.view.devicePixelRatio = 2;
|
||||
tester.platformDispatcher.textScaleFactorTestValue = 2;
|
||||
tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
|
||||
addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue);
|
||||
|
||||
for (final cupertino in <bool>[false, true]) {
|
||||
await tester.pumpWidget(_row(cupertino: cupertino));
|
||||
await tester.pumpAndSettle();
|
||||
expect(tester.takeException(), isNull);
|
||||
expect(find.text('Download'), findsOneWidget);
|
||||
expect(find.text('Share'), findsOneWidget);
|
||||
if (cupertino) {
|
||||
expect(_cupertinoButton(tester, 'Download').onPressed, isNotNull);
|
||||
expect(find.byType(TextButton), findsNothing);
|
||||
} else {
|
||||
expect(_materialButton(tester, 'Download').onPressed, isNotNull);
|
||||
expect(find.byType(CupertinoButton), findsNothing);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
testWidgets('the gallery selection offers both file actions in its dialog', (
|
||||
tester,
|
||||
) async {
|
||||
final saved = <ArtifactFile>[];
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: ArtifactGalleryPage(
|
||||
steps: <JsonMap>[
|
||||
step(
|
||||
stage: 'review',
|
||||
visit: 1,
|
||||
artifacts: <JsonMap>[
|
||||
artifact('report.csv', contentType: 'text/csv', sizeBytes: 3),
|
||||
],
|
||||
),
|
||||
],
|
||||
configuredEndpoint: _endpoint,
|
||||
fetch: _fetch,
|
||||
fileBridge: _bridge(saved: saved),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.text('report.csv'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(AlertDialog), findsOneWidget);
|
||||
expect(find.text('Download'), findsOneWidget);
|
||||
expect(find.text('Share'), findsOneWidget);
|
||||
expect(find.text('Open'), findsOneWidget);
|
||||
expect(find.text('Copy link'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.text('Download'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(saved.single.bytes, _bytes);
|
||||
expect(find.text('Downloaded report.csv.'), findsOneWidget);
|
||||
expect(find.byType(AlertDialog), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('a host without file capabilities explains and disables both', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: ArtifactFileActions(
|
||||
artifact: _record,
|
||||
resolved: resolveArtifactUrl(_endpoint, _record.url)!,
|
||||
fetch: _fetch,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(find.text('Download'), findsOneWidget);
|
||||
expect(find.text('Share'), findsOneWidget);
|
||||
expect(_materialButton(tester, 'Download').onPressed, isNull);
|
||||
expect(_materialButton(tester, 'Share').onPressed, isNull);
|
||||
expect(
|
||||
find.text('Downloading files is not supported on this platform yet.'),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
find.text('File sharing is not supported on this platform yet.'),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('gallery selection keeps both actions at 320/2x dark', (
|
||||
tester,
|
||||
) async {
|
||||
tester.view.physicalSize = const Size(640, 1200);
|
||||
tester.view.devicePixelRatio = 2;
|
||||
tester.platformDispatcher.textScaleFactorTestValue = 2;
|
||||
tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
|
||||
addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue);
|
||||
|
||||
final steps = <JsonMap>[
|
||||
step(
|
||||
stage: 'review',
|
||||
visit: 1,
|
||||
artifacts: <JsonMap>[
|
||||
artifact('report.csv', contentType: 'text/csv', sizeBytes: 3),
|
||||
],
|
||||
),
|
||||
];
|
||||
for (final cupertino in <bool>[false, true]) {
|
||||
await tester.pumpWidget(
|
||||
cupertino
|
||||
? CupertinoApp(
|
||||
theme: const CupertinoThemeData(brightness: Brightness.dark),
|
||||
home: ArtifactGalleryPage(
|
||||
steps: steps,
|
||||
configuredEndpoint: _endpoint,
|
||||
fetch: _fetch,
|
||||
fileBridge: _bridge(),
|
||||
),
|
||||
)
|
||||
: MaterialApp(
|
||||
theme: ThemeData(brightness: Brightness.dark),
|
||||
home: ArtifactGalleryPage(
|
||||
steps: steps,
|
||||
configuredEndpoint: _endpoint,
|
||||
fetch: _fetch,
|
||||
fileBridge: _bridge(),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('report.csv'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(tester.takeException(), isNull);
|
||||
expect(find.text('Download'), findsOneWidget);
|
||||
expect(find.text('Share'), findsOneWidget);
|
||||
expect(
|
||||
cupertino
|
||||
? find.byType(CupertinoAlertDialog)
|
||||
: find.byType(AlertDialog),
|
||||
findsOneWidget,
|
||||
);
|
||||
await tester.tap(find.text('Close'));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'the viewer offers file actions only for a same-origin artifact',
|
||||
(tester) async {
|
||||
final local = recordedArtifact(
|
||||
'clip.mp4',
|
||||
url: '/artifacts/1/1/clip.mp4',
|
||||
contentType: 'video/mp4',
|
||||
);
|
||||
final external = recordedArtifact(
|
||||
'elsewhere.png',
|
||||
url: 'https://elsewhere.test/elsewhere.png',
|
||||
contentType: 'image/png',
|
||||
);
|
||||
final localGroup = visitGroup(artifacts: <ArtifactRecord>[local]);
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: ArtifactViewerPage(
|
||||
key: const ValueKey<String>('local'),
|
||||
groups: <ArtifactGroup>[localGroup],
|
||||
selectedIdentity: artifactVisitIdentity(localGroup, local),
|
||||
configuredEndpoint: _endpoint,
|
||||
fetch: _fetch,
|
||||
fileBridge: _bridge(),
|
||||
openExternal: (_) async => true,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Download'), findsOneWidget);
|
||||
expect(find.text('Share'), findsOneWidget);
|
||||
|
||||
final externalGroup = visitGroup(artifacts: <ArtifactRecord>[external]);
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: ArtifactViewerPage(
|
||||
key: const ValueKey<String>('external'),
|
||||
groups: <ArtifactGroup>[externalGroup],
|
||||
selectedIdentity: artifactVisitIdentity(externalGroup, external),
|
||||
configuredEndpoint: _endpoint,
|
||||
fetch: _fetch,
|
||||
fileBridge: _bridge(),
|
||||
openExternal: (_) async => true,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Download'), findsNothing);
|
||||
expect(find.text('Share'), findsNothing);
|
||||
expect(find.text('Open'), findsOneWidget);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
import 'dart:async';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/artifacts/actions/artifact_file.dart';
|
||||
import 'package:pipelines_app/features/artifacts/actions/artifact_file_bridge.dart';
|
||||
import 'package:pipelines_app/features/artifacts/actions/artifact_file_controller.dart';
|
||||
import 'package:pipelines_app/features/artifacts/actions/artifact_transfer.dart';
|
||||
import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart';
|
||||
import 'package:pipelines_app/features/artifacts/domain/artifact_url.dart';
|
||||
import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_fetch.dart';
|
||||
|
||||
const _url = 'http://127.0.0.1:8081/artifacts/1/1/report.csv';
|
||||
final Uint8List _bytes = Uint8List.fromList(<int>[10, 20, 30, 40]);
|
||||
|
||||
final ArtifactRecord _record = ArtifactRecord.fromJson(<String, dynamic>{
|
||||
'name': 'public/reports/report.csv',
|
||||
'url': '/artifacts/1/1/report.csv',
|
||||
'content_type': 'text/csv; charset=utf-8',
|
||||
'size_bytes': 4,
|
||||
});
|
||||
|
||||
ArtifactFileActionsController _controller({
|
||||
ArtifactFetch? fetch,
|
||||
ArtifactFileBridge bridge = const ArtifactFileBridge(),
|
||||
}) => ArtifactFileActionsController(
|
||||
artifact: _record,
|
||||
resolved: resolveArtifactUrl('ws://127.0.0.1:8081/connect', _record.url)!,
|
||||
fetch: fetch ?? (_) async => ArtifactFetchResult(status: 200, bytes: _bytes),
|
||||
bridge: bridge,
|
||||
);
|
||||
|
||||
ArtifactFileBridge _bridge({
|
||||
List<ArtifactFile>? saved,
|
||||
List<ArtifactFile>? shared,
|
||||
ArtifactTransferResult shareResult = const ArtifactTransferResult(
|
||||
ArtifactTransferState.shared,
|
||||
'File shared.',
|
||||
),
|
||||
bool downloadSupported = true,
|
||||
bool shareSupported = true,
|
||||
}) => ArtifactFileBridge(
|
||||
downloadSupported: downloadSupported,
|
||||
shareSupported: shareSupported,
|
||||
downloadUnsupportedMessage: 'No download here.',
|
||||
shareUnsupportedMessage: 'No share here.',
|
||||
download: (file) async {
|
||||
saved?.add(file);
|
||||
return ArtifactTransferResult(
|
||||
ArtifactTransferState.saved,
|
||||
'Downloaded ${file.name}.',
|
||||
);
|
||||
},
|
||||
share: (file) async {
|
||||
shared?.add(file);
|
||||
return shareResult;
|
||||
},
|
||||
);
|
||||
|
||||
void main() {
|
||||
test('download carries the exact named, typed bytes', () async {
|
||||
final saved = <ArtifactFile>[];
|
||||
final controller = _controller(bridge: _bridge(saved: saved));
|
||||
|
||||
await controller.download();
|
||||
|
||||
expect(saved, hasLength(1));
|
||||
expect(saved.single.name, 'report.csv');
|
||||
expect(saved.single.mimeType, 'text/csv');
|
||||
expect(saved.single.bytes, _bytes);
|
||||
expect(controller.status, 'Downloaded report.csv.');
|
||||
expect(controller.busy, isFalse);
|
||||
});
|
||||
|
||||
test('share uses a file, not a link, and reports when shared', () async {
|
||||
final shared = <ArtifactFile>[];
|
||||
final fetched = <Uri>[];
|
||||
final controller = _controller(
|
||||
bridge: _bridge(shared: shared),
|
||||
fetch: (uri) async {
|
||||
fetched.add(uri);
|
||||
return ArtifactFetchResult(status: 200, bytes: _bytes);
|
||||
},
|
||||
);
|
||||
|
||||
await controller.share();
|
||||
|
||||
expect(fetched, [Uri.parse(_url)]);
|
||||
expect(shared, hasLength(1));
|
||||
expect(shared.single.name, 'report.csv');
|
||||
expect(shared.single.mimeType, 'text/csv');
|
||||
expect(shared.single.bytes, _bytes);
|
||||
expect(controller.canShare, isTrue);
|
||||
expect(controller.status, 'File shared.');
|
||||
});
|
||||
|
||||
test('unsupported sharing leaves download working', () async {
|
||||
final saved = <ArtifactFile>[];
|
||||
final shared = <ArtifactFile>[];
|
||||
var fetches = 0;
|
||||
final controller = _controller(
|
||||
fetch: (_) async {
|
||||
fetches += 1;
|
||||
return ArtifactFetchResult(status: 200, bytes: _bytes);
|
||||
},
|
||||
bridge: _bridge(saved: saved, shared: shared, shareSupported: false),
|
||||
);
|
||||
|
||||
await controller.share();
|
||||
expect(shared, isEmpty);
|
||||
expect(fetches, 0);
|
||||
expect(controller.status, 'No share here.');
|
||||
expect(controller.canDownload, isTrue);
|
||||
|
||||
await controller.download();
|
||||
expect(saved, hasLength(1));
|
||||
expect(controller.status, 'Downloaded report.csv.');
|
||||
});
|
||||
|
||||
test(
|
||||
'an HTTP or network fetch failure is reported, never transferred',
|
||||
() async {
|
||||
final saved = <ArtifactFile>[];
|
||||
final bridge = _bridge(saved: saved);
|
||||
final notFound = _controller(
|
||||
fetch: (_) async =>
|
||||
ArtifactFetchResult(status: 404, bytes: Uint8List(0)),
|
||||
bridge: bridge,
|
||||
);
|
||||
|
||||
await notFound.download();
|
||||
expect(notFound.status, 'Could not fetch the artifact (HTTP 404).');
|
||||
expect(saved, isEmpty);
|
||||
expect(notFound.busy, isFalse);
|
||||
|
||||
final offline = _controller(
|
||||
fetch: (_) async => throw const ArtifactFetchException('network down'),
|
||||
bridge: bridge,
|
||||
);
|
||||
await offline.download();
|
||||
expect(offline.status, contains('network down'));
|
||||
expect(saved, isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'cancel during a slow fetch starts no transfer and ignores the result',
|
||||
() async {
|
||||
final pending = Completer<ArtifactFetchResult>();
|
||||
final saved = <ArtifactFile>[];
|
||||
final controller = _controller(
|
||||
fetch: (_) => pending.future,
|
||||
bridge: _bridge(saved: saved),
|
||||
);
|
||||
|
||||
final action = controller.download();
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
expect(controller.busy, isTrue);
|
||||
expect(controller.canCancel, isTrue);
|
||||
expect(controller.status, 'Preparing file…');
|
||||
|
||||
controller.cancel();
|
||||
expect(controller.busy, isFalse);
|
||||
expect(controller.status, 'Download canceled.');
|
||||
|
||||
pending.complete(ArtifactFetchResult(status: 200, bytes: _bytes));
|
||||
await action;
|
||||
expect(saved, isEmpty);
|
||||
expect(controller.status, 'Download canceled.');
|
||||
},
|
||||
);
|
||||
|
||||
test('one tap starts one transfer even when called twice', () async {
|
||||
var fetches = 0;
|
||||
final pending = Completer<ArtifactFetchResult>();
|
||||
final saved = <ArtifactFile>[];
|
||||
final controller = _controller(
|
||||
fetch: (_) {
|
||||
fetches += 1;
|
||||
return pending.future;
|
||||
},
|
||||
bridge: _bridge(saved: saved),
|
||||
);
|
||||
|
||||
final first = controller.download();
|
||||
final second = controller.download();
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
expect(fetches, 1);
|
||||
|
||||
pending.complete(ArtifactFetchResult(status: 200, bytes: _bytes));
|
||||
await first;
|
||||
await second;
|
||||
expect(saved, hasLength(1));
|
||||
});
|
||||
|
||||
test('a ready share reuses prepared bytes on the fresh tap', () async {
|
||||
var fetches = 0;
|
||||
var shares = 0;
|
||||
final controller = _controller(
|
||||
fetch: (_) async {
|
||||
fetches += 1;
|
||||
return ArtifactFetchResult(status: 200, bytes: _bytes);
|
||||
},
|
||||
bridge: ArtifactFileBridge(
|
||||
shareSupported: true,
|
||||
share: (file) async {
|
||||
shares += 1;
|
||||
return shares == 1
|
||||
? const ArtifactTransferResult(
|
||||
ArtifactTransferState.ready,
|
||||
'File ready. Tap Share again to choose where to send it.',
|
||||
)
|
||||
: const ArtifactTransferResult(
|
||||
ArtifactTransferState.shared,
|
||||
'File shared.',
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
await controller.share();
|
||||
expect(controller.status, contains('Tap Share again'));
|
||||
await controller.share();
|
||||
|
||||
expect(fetches, 1);
|
||||
expect(shares, 2);
|
||||
expect(controller.status, 'File shared.');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/artifacts/actions/artifact_file.dart';
|
||||
import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart';
|
||||
|
||||
ArtifactRecord _record(
|
||||
String name, {
|
||||
String contentType = '',
|
||||
String url = '/artifacts/1/1/report.csv',
|
||||
}) => ArtifactRecord.fromJson(<String, dynamic>{
|
||||
'name': name,
|
||||
'url': url,
|
||||
'content_type': contentType,
|
||||
'size_bytes': 10,
|
||||
});
|
||||
|
||||
void main() {
|
||||
test('a recorded name keeps only its basename', () {
|
||||
final file = artifactFileFor(
|
||||
artifact: _record('public/reports/result.csv', contentType: 'text/csv'),
|
||||
url: Uri.parse('http://127.0.0.1:8081/artifacts/1/1/result.csv'),
|
||||
bytes: Uint8List.fromList(<int>[1, 2, 3]),
|
||||
);
|
||||
|
||||
expect(file.name, 'result.csv');
|
||||
expect(file.mimeType, 'text/csv');
|
||||
expect(file.byteLength, 3);
|
||||
expect(file.bytes, <int>[1, 2, 3]);
|
||||
});
|
||||
|
||||
test(
|
||||
'a recorded name with backslashes and control characters is repaired',
|
||||
() {
|
||||
final name = artifactFileName(
|
||||
_record('C:\\tmp\\odd\u0001name.csv'),
|
||||
Uri.parse('http://127.0.0.1/a.csv'),
|
||||
);
|
||||
|
||||
expect(name, 'odd_name.csv');
|
||||
},
|
||||
);
|
||||
|
||||
test('a missing name falls back to the url basename then artifact', () {
|
||||
expect(
|
||||
artifactFileName(
|
||||
_record(''),
|
||||
Uri.parse('http://127.0.0.1:8081/artifacts/1/1/from-url.csv'),
|
||||
),
|
||||
'from-url.csv',
|
||||
);
|
||||
expect(
|
||||
artifactFileName(_record('public/'), Uri.parse('http://127.0.0.1/')),
|
||||
'artifact',
|
||||
);
|
||||
expect(
|
||||
artifactFileName(_record('..'), Uri.parse('http://127.0.0.1/')),
|
||||
'artifact',
|
||||
);
|
||||
});
|
||||
|
||||
test('the recorded media type loses parameters and is validated', () {
|
||||
expect(
|
||||
artifactFileMimeType(
|
||||
_record('a.txt', contentType: 'Text/Plain; charset=utf-8'),
|
||||
),
|
||||
'text/plain',
|
||||
);
|
||||
expect(
|
||||
artifactFileMimeType(_record('a.bin')),
|
||||
artifactFileFallbackMimeType,
|
||||
);
|
||||
expect(
|
||||
artifactFileMimeType(_record('a.bin', contentType: 'not a mime')),
|
||||
artifactFileFallbackMimeType,
|
||||
);
|
||||
});
|
||||
|
||||
test('a missing name or MIME type gets an explicit fallback notice', () {
|
||||
final url = Uri.parse('http://127.0.0.1/artifacts/1/1/kept.csv');
|
||||
|
||||
expect(
|
||||
artifactFileRecordingNotice(
|
||||
_record('kept.csv', contentType: 'text/csv'),
|
||||
url,
|
||||
),
|
||||
isNull,
|
||||
);
|
||||
expect(
|
||||
artifactFileRecordingNotice(_record('', contentType: 'text/csv'), url),
|
||||
'No usable recorded name; the file is saved as kept.csv.',
|
||||
);
|
||||
expect(
|
||||
artifactFileRecordingNotice(_record('kept.csv'), url),
|
||||
'No usable recorded MIME type; the file is saved as '
|
||||
'application/octet-stream.',
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -266,6 +266,39 @@ void main() {
|
||||
];
|
||||
expect(artifactGroups(steps).single.artifacts.length, 1);
|
||||
});
|
||||
|
||||
test('visitArtifactGroup matches the pane group of a later visit', () {
|
||||
final steps = <Map<String, dynamic>>[
|
||||
step(
|
||||
stage: 'a',
|
||||
sequence: 1,
|
||||
visit: 1,
|
||||
artifacts: <Map<String, dynamic>>[
|
||||
artifact('public/shared.csv'),
|
||||
artifact('a.csv'),
|
||||
],
|
||||
),
|
||||
step(
|
||||
stage: 'a',
|
||||
sequence: 2,
|
||||
visit: 2,
|
||||
artifacts: <Map<String, dynamic>>[
|
||||
artifact('public/shared.csv'),
|
||||
artifact('b.csv'),
|
||||
],
|
||||
),
|
||||
];
|
||||
final group = visitArtifactGroup(steps, 1)!;
|
||||
expect(group.stageKey, 'a');
|
||||
expect(group.visit, 2);
|
||||
expect(group.artifacts.map((record) => record.name), <String>['b.csv']);
|
||||
expect(
|
||||
visitArtifacts(steps[1], steps).map((record) => record.name),
|
||||
<String>['b.csv'],
|
||||
);
|
||||
expect(visitArtifactGroup(steps, 2), isNull);
|
||||
expect(visitArtifactGroup(steps, -1), isNull);
|
||||
});
|
||||
});
|
||||
|
||||
group('unavailable and empty captures', () {
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/attention/notify/notification_controller.dart';
|
||||
import 'package:pipelines_app/features/attention/notify/notification_store.dart';
|
||||
|
||||
import 'notification_test_support.dart';
|
||||
|
||||
void main() {
|
||||
group('the seed never notifies', () {
|
||||
test('an already failed and waiting list is silent', () async {
|
||||
final attention = attentionController();
|
||||
final bridge = FakeNotificationBridge();
|
||||
final notify = NotificationController(
|
||||
store: MemoryNotificationStore(),
|
||||
bridge: bridge,
|
||||
);
|
||||
addTearDown(attention.dispose);
|
||||
addTearDown(notify.dispose);
|
||||
await attention.load();
|
||||
await notify.load();
|
||||
|
||||
attention.seedRows([
|
||||
runSummary(1, 'failed', diagnostic: 'Stage 3 stopped'),
|
||||
runSummary(2, 'waiting'),
|
||||
]);
|
||||
|
||||
expect(attention.transitions, isEmpty);
|
||||
expect(publish(notify, attention), 0);
|
||||
expect(bridge.shown, isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
group('a live transition notifies once', () {
|
||||
test('the frame\'s own words and identity are used', () async {
|
||||
final attention = attentionController();
|
||||
final bridge = FakeNotificationBridge(permission: 'granted');
|
||||
final notify = NotificationController(
|
||||
store: MemoryNotificationStore(),
|
||||
bridge: bridge,
|
||||
);
|
||||
addTearDown(attention.dispose);
|
||||
addTearDown(notify.dispose);
|
||||
await attention.load();
|
||||
await notify.load();
|
||||
expect(notify.canNotify, isTrue);
|
||||
|
||||
attention.seedRows([runSummary(1, 'running', name: 'nightly')]);
|
||||
attention.observeFrame(
|
||||
runFrame(
|
||||
1,
|
||||
'failed',
|
||||
name: 'nightly',
|
||||
title: 'Nightly audit',
|
||||
diagnostic: 'Stage 3 stopped',
|
||||
finishedAt: '2026-10-22T11:00:00Z',
|
||||
),
|
||||
);
|
||||
|
||||
expect(publish(notify, attention), 1);
|
||||
final message = bridge.shown.single;
|
||||
expect(message.title, 'A run failed');
|
||||
expect(message.body, 'Nightly audit \u00b7 nightly');
|
||||
expect(message.tag, '1:Failed');
|
||||
expect(message.runId, 1);
|
||||
});
|
||||
|
||||
test('a duplicate frame and a republished list stay silent', () async {
|
||||
final attention = attentionController();
|
||||
final bridge = FakeNotificationBridge(permission: 'granted');
|
||||
final notify = NotificationController(
|
||||
store: MemoryNotificationStore(),
|
||||
bridge: bridge,
|
||||
);
|
||||
addTearDown(attention.dispose);
|
||||
addTearDown(notify.dispose);
|
||||
await attention.load();
|
||||
await notify.load();
|
||||
|
||||
attention.seedRows([runSummary(1, 'running')]);
|
||||
attention.observeFrame(runFrame(1, 'failed'));
|
||||
expect(publish(notify, attention), 1);
|
||||
|
||||
attention.observeFrame(runFrame(1, 'failed'));
|
||||
expect(attention.transitions, hasLength(1));
|
||||
expect(publish(notify, attention), 0);
|
||||
expect(bridge.shown, hasLength(1));
|
||||
});
|
||||
|
||||
test('a reconnect reseed cannot replay the notification', () async {
|
||||
final attention = attentionController();
|
||||
final bridge = FakeNotificationBridge(permission: 'granted');
|
||||
final notify = NotificationController(
|
||||
store: MemoryNotificationStore(),
|
||||
bridge: bridge,
|
||||
);
|
||||
addTearDown(attention.dispose);
|
||||
addTearDown(notify.dispose);
|
||||
await attention.load();
|
||||
await notify.load();
|
||||
|
||||
attention.seedRows([runSummary(1, 'running')]);
|
||||
attention.observeFrame(runFrame(1, 'failed'));
|
||||
expect(publish(notify, attention), 1);
|
||||
|
||||
attention.resetForReconnect();
|
||||
attention.seedRows([runSummary(1, 'failed')], reconnect: true);
|
||||
expect(publish(notify, attention), 0);
|
||||
attention.observeFrame(runFrame(1, 'failed'));
|
||||
expect(publish(notify, attention), 0);
|
||||
expect(bridge.shown, hasLength(1));
|
||||
});
|
||||
|
||||
test('a rebuilt controller with the same store stays silent', () async {
|
||||
final store = MemoryNotificationStore();
|
||||
final bridge = FakeNotificationBridge(permission: 'granted');
|
||||
final attention = attentionController();
|
||||
final notify = NotificationController(store: store, bridge: bridge);
|
||||
addTearDown(attention.dispose);
|
||||
addTearDown(notify.dispose);
|
||||
await attention.load();
|
||||
await notify.load();
|
||||
|
||||
attention.seedRows([runSummary(1, 'running')]);
|
||||
attention.observeFrame(runFrame(1, 'failed'));
|
||||
expect(publish(notify, attention), 1);
|
||||
await settle();
|
||||
|
||||
final restarted = NotificationController(store: store, bridge: bridge);
|
||||
addTearDown(restarted.dispose);
|
||||
await restarted.load();
|
||||
expect(restarted.notified, contains('1:Failed'));
|
||||
expect(publish(restarted, attention), 0);
|
||||
expect(bridge.shown, hasLength(1));
|
||||
});
|
||||
|
||||
test('a later failure of another run notifies independently', () async {
|
||||
final attention = attentionController();
|
||||
final bridge = FakeNotificationBridge(permission: 'granted');
|
||||
final notify = NotificationController(
|
||||
store: MemoryNotificationStore(),
|
||||
bridge: bridge,
|
||||
);
|
||||
addTearDown(attention.dispose);
|
||||
addTearDown(notify.dispose);
|
||||
await attention.load();
|
||||
await notify.load();
|
||||
|
||||
attention.seedRows([runSummary(1, 'running'), runSummary(2, 'running')]);
|
||||
attention.observeFrame(runFrame(1, 'failed'));
|
||||
expect(publish(notify, attention), 1);
|
||||
|
||||
attention.observeFrame(runFrame(2, 'failed'));
|
||||
expect(publish(notify, attention), 1);
|
||||
expect(bridge.shown, hasLength(2));
|
||||
expect(bridge.shown.map((m) => m.tag), ['1:Failed', '2:Failed']);
|
||||
});
|
||||
|
||||
test('a transition for a run that left is never re-posted', () async {
|
||||
final attention = attentionController();
|
||||
final bridge = FakeNotificationBridge(permission: 'granted');
|
||||
final notify = NotificationController(
|
||||
store: MemoryNotificationStore(),
|
||||
bridge: bridge,
|
||||
);
|
||||
addTearDown(attention.dispose);
|
||||
addTearDown(notify.dispose);
|
||||
await attention.load();
|
||||
await notify.load();
|
||||
|
||||
attention.seedRows([runSummary(1, 'running')]);
|
||||
attention.observeFrame(runFrame(1, 'failed'));
|
||||
expect(publish(notify, attention), 1);
|
||||
|
||||
// Publishing the leaving frame forgets the identity; republishing the
|
||||
// accumulated list afterwards must not resurrect the old alert.
|
||||
attention.observeFrame(runFrame(1, 'running'));
|
||||
expect(publish(notify, attention), 0);
|
||||
expect(publish(notify, attention), 0);
|
||||
expect(bridge.shown, hasLength(1));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/attention/domain/attention_models.dart';
|
||||
import 'package:pipelines_app/features/attention/notify/notification_bridge.dart';
|
||||
import 'package:pipelines_app/features/attention/notify/notification_controller.dart';
|
||||
import 'package:pipelines_app/features/attention/notify/notification_models.dart';
|
||||
import 'package:pipelines_app/features/attention/notify/notification_store.dart';
|
||||
|
||||
import 'notification_test_support.dart';
|
||||
|
||||
void main() {
|
||||
group('a dismissed entry never notifies', () {
|
||||
test('the detector suppresses it and nothing is posted', () async {
|
||||
final attention = attentionController();
|
||||
final bridge = FakeNotificationBridge(permission: 'granted');
|
||||
final notify = NotificationController(
|
||||
store: MemoryNotificationStore(),
|
||||
bridge: bridge,
|
||||
);
|
||||
addTearDown(attention.dispose);
|
||||
addTearDown(notify.dispose);
|
||||
await attention.load();
|
||||
await notify.load();
|
||||
|
||||
attention.seedRows([runSummary(1, 'running')]);
|
||||
await attention.dismiss(attentionEntryFor(runSummary(1, 'failed'))!);
|
||||
attention.observeFrame(runFrame(1, 'failed'));
|
||||
|
||||
expect(attention.transitions, isEmpty);
|
||||
expect(publish(notify, attention), 0);
|
||||
expect(bridge.shown, isEmpty);
|
||||
});
|
||||
|
||||
test(
|
||||
'the publish guard records but does not show a dismissed key',
|
||||
() async {
|
||||
final bridge = FakeNotificationBridge(permission: 'granted');
|
||||
final notify = NotificationController(
|
||||
store: MemoryNotificationStore(),
|
||||
bridge: bridge,
|
||||
);
|
||||
addTearDown(notify.dispose);
|
||||
await notify.load();
|
||||
|
||||
final transition = transitionFor(4);
|
||||
expect(
|
||||
notify.publishTransitions(
|
||||
[transition],
|
||||
qualifying: {transition.key},
|
||||
dismissed: {transition.key},
|
||||
),
|
||||
0,
|
||||
);
|
||||
expect(notify.notified, contains(transition.key));
|
||||
expect(bridge.shown, isEmpty);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
group('batching and the tap seam', () {
|
||||
test('a burst posts a bounded batch in order, then the rest', () async {
|
||||
final bridge = FakeNotificationBridge(permission: 'granted');
|
||||
final notify = NotificationController(
|
||||
store: MemoryNotificationStore(),
|
||||
bridge: bridge,
|
||||
);
|
||||
addTearDown(notify.dispose);
|
||||
await notify.load();
|
||||
|
||||
final transitions = [for (var id = 1; id <= 7; id++) transitionFor(id)];
|
||||
final qualifying = {for (final t in transitions) t.key};
|
||||
expect(notify.publishTransitions(transitions, qualifying: qualifying), 5);
|
||||
expect(bridge.shown.map((m) => m.runId), [1, 2, 3, 4, 5]);
|
||||
expect(notify.publishTransitions(transitions, qualifying: qualifying), 2);
|
||||
expect(bridge.shown.map((m) => m.runId), [1, 2, 3, 4, 5, 6, 7]);
|
||||
});
|
||||
|
||||
test('a tap reports the run and never navigates here', () async {
|
||||
final bridge = FakeNotificationBridge(permission: 'granted');
|
||||
final notify = NotificationController(
|
||||
store: MemoryNotificationStore(),
|
||||
bridge: bridge,
|
||||
);
|
||||
addTearDown(notify.dispose);
|
||||
await notify.load();
|
||||
|
||||
final opened = <int>[];
|
||||
notify.onOpenRun = opened.add;
|
||||
expect(
|
||||
notify.publishTransitions([transitionFor(3)], qualifying: {'3:Failed'}),
|
||||
1,
|
||||
);
|
||||
bridge.taps.single!.call();
|
||||
expect(opened, [3]);
|
||||
});
|
||||
});
|
||||
|
||||
group('the ledger cannot be read into by a caller', () {
|
||||
test('notified is an unmodifiable copy', () async {
|
||||
final bridge = FakeNotificationBridge(permission: 'granted');
|
||||
final notify = NotificationController(
|
||||
store: MemoryNotificationStore(),
|
||||
bridge: bridge,
|
||||
);
|
||||
addTearDown(notify.dispose);
|
||||
await notify.load();
|
||||
|
||||
expect(
|
||||
notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'}),
|
||||
1,
|
||||
);
|
||||
expect(notify.notified, {'1:Failed'});
|
||||
expect(() => notify.notified.add('9:Failed'), throwsUnsupportedError);
|
||||
expect(notify.notified, {'1:Failed'});
|
||||
});
|
||||
});
|
||||
|
||||
group('an unavailable store cannot reach the UI', () {
|
||||
test('a failed read and write still notify and never throw', () async {
|
||||
final store = MemoryNotificationStore()
|
||||
..failReads = true
|
||||
..failWrites = true;
|
||||
final bridge = FakeNotificationBridge(permission: 'granted');
|
||||
final notify = NotificationController(store: store, bridge: bridge);
|
||||
addTearDown(notify.dispose);
|
||||
|
||||
await expectLater(notify.load(), completes);
|
||||
expect(notify.loaded, isTrue);
|
||||
expect(notify.notified, isEmpty);
|
||||
|
||||
expect(
|
||||
notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'}),
|
||||
1,
|
||||
);
|
||||
await settle();
|
||||
expect(bridge.shown, hasLength(1));
|
||||
});
|
||||
|
||||
test('a throwing platform post is reported, not propagated', () async {
|
||||
final bridge = _ThrowingBridge();
|
||||
final notify = NotificationController(
|
||||
store: MemoryNotificationStore(),
|
||||
bridge: bridge,
|
||||
);
|
||||
addTearDown(notify.dispose);
|
||||
await notify.load();
|
||||
|
||||
expect(
|
||||
notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'}),
|
||||
0,
|
||||
);
|
||||
expect(notify.notified, contains('1:Failed'));
|
||||
});
|
||||
|
||||
test('ledger writes land in call order, one at a time', () async {
|
||||
final store = _SlowStore();
|
||||
final bridge = FakeNotificationBridge(permission: 'granted');
|
||||
final notify = NotificationController(store: store, bridge: bridge);
|
||||
addTearDown(notify.dispose);
|
||||
await notify.load();
|
||||
|
||||
notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'});
|
||||
notify.publishTransitions(
|
||||
[transitionFor(2)],
|
||||
qualifying: {'1:Failed', '2:Failed'},
|
||||
);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 40));
|
||||
|
||||
expect(store.maxActive, 1, reason: 'the writes must be serialized');
|
||||
expect(store.stored, contains('"1:Failed"'));
|
||||
expect(store.stored, contains('"2:Failed"'));
|
||||
expect(store.writes.last, store.stored);
|
||||
});
|
||||
});
|
||||
|
||||
group('the platform seam', () {
|
||||
test('the non-web bridge reports unsupported honestly', () async {
|
||||
final bridge = createNotificationBridge();
|
||||
expect(bridge.environment().supported, isFalse);
|
||||
final notify = NotificationController(
|
||||
store: MemoryNotificationStore(),
|
||||
bridge: bridge,
|
||||
);
|
||||
addTearDown(notify.dispose);
|
||||
await notify.load();
|
||||
expect(notify.permission, NotificationPermissionState.unsupported);
|
||||
expect(
|
||||
bridge.show(
|
||||
const NotificationMessage(
|
||||
runId: 1,
|
||||
title: 'A run failed',
|
||||
body: 'release',
|
||||
tag: '1:Failed',
|
||||
),
|
||||
),
|
||||
isFalse,
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// A store whose writes take a tick, so a racing implementation would overlap
|
||||
/// them and the last value to land would be the older snapshot.
|
||||
class _SlowStore implements NotificationStore {
|
||||
String? stored;
|
||||
int active = 0;
|
||||
int maxActive = 0;
|
||||
final List<String> writes = [];
|
||||
|
||||
@override
|
||||
Future<String?> read() async => stored;
|
||||
|
||||
@override
|
||||
Future<bool> write(String value) async {
|
||||
active++;
|
||||
if (active > maxActive) maxActive = active;
|
||||
await Future<void>.delayed(const Duration(milliseconds: 2));
|
||||
stored = value;
|
||||
writes.add(value);
|
||||
active--;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
class _ThrowingBridge implements NotificationBridge {
|
||||
@override
|
||||
NotificationEnvironment environment() => const NotificationEnvironment(
|
||||
supported: true,
|
||||
secureContext: true,
|
||||
permission: 'granted',
|
||||
);
|
||||
|
||||
@override
|
||||
Future<String> requestPermission() async => 'granted';
|
||||
|
||||
@override
|
||||
bool show(NotificationMessage message, {void Function()? onTap}) =>
|
||||
throw StateError('the browser refused to construct a notification');
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/attention/notify/notification_ledger.dart';
|
||||
|
||||
import 'notification_test_support.dart';
|
||||
|
||||
void main() {
|
||||
group('the identity is the run and kind', () {
|
||||
test('two failures of one run are the same announced state', () {
|
||||
final first = transitionFor(7, finishedAt: '2026-10-22T09:10:00Z');
|
||||
final second = transitionFor(7, finishedAt: '2026-10-22T11:30:00Z');
|
||||
expect(notificationIdentity(first), '7:Failed');
|
||||
expect(notificationIdentity(second), '7:Failed');
|
||||
});
|
||||
|
||||
test('a waiting run needs no finish time to have an identity', () {
|
||||
final entry = transitionFor(7, status: 'waiting', finishedAt: '');
|
||||
expect(notificationIdentity(entry), '7:Decision');
|
||||
});
|
||||
|
||||
test('the kind separates a decision from a failure of one run', () {
|
||||
expect(
|
||||
notificationIdentity(transitionFor(7)),
|
||||
isNot(notificationIdentity(transitionFor(7, status: 'waiting'))),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group('the qualifying set is the attention surface\'s own keys', () {
|
||||
test('only failed and human-waiting runs qualify', () {
|
||||
expect(
|
||||
notificationQualifyingKeys([
|
||||
runSummary(1, 'failed'),
|
||||
runSummary(2, 'waiting'),
|
||||
runSummary(3, 'running'),
|
||||
runSummary(4, 'succeeded'),
|
||||
runSummary(5, 'queued'),
|
||||
runSummary(6, 'waiting', exportPending: 2),
|
||||
]),
|
||||
{'1:Failed', '2:Decision'},
|
||||
);
|
||||
});
|
||||
|
||||
test('a duplicate row and a malformed id add nothing', () {
|
||||
expect(
|
||||
notificationQualifyingKeys([
|
||||
runSummary(1, 'failed'),
|
||||
runSummary(1, 'failed'),
|
||||
{'id': 0, 'status': 'failed'},
|
||||
{'id': 'not a run', 'status': 'failed'},
|
||||
]),
|
||||
{'1:Failed'},
|
||||
);
|
||||
expect(notificationQualifyingKeys(null), isEmpty);
|
||||
});
|
||||
|
||||
test('the frame key form is read too', () {
|
||||
expect(notificationQualifyingKeys([runFrame(9, 'failed')]), {'9:Failed'});
|
||||
});
|
||||
});
|
||||
|
||||
group('the ledger records identities', () {
|
||||
test('recording is idempotent and never mutates the original', () {
|
||||
const base = NotificationLedger();
|
||||
final once = base.recording('7:Failed');
|
||||
final twice = once.recording('7:Failed');
|
||||
expect(base.notified, isEmpty);
|
||||
expect(once.hasNotified('7:Failed'), isTrue);
|
||||
expect(twice.notified, {'7:Failed'});
|
||||
});
|
||||
|
||||
test('asked is carried without touching the identities', () {
|
||||
final asked = const NotificationLedger(notified: {'a'}).withAsked(true);
|
||||
expect(asked.asked, isTrue);
|
||||
expect(asked.notified, {'a'});
|
||||
});
|
||||
});
|
||||
|
||||
group('pruning keeps only the current qualifying run', () {
|
||||
test('a run that left the state is forgotten; asked survives', () {
|
||||
final ledger = const NotificationLedger(
|
||||
notified: {'7:Decision', '8:Failed'},
|
||||
).withAsked(true);
|
||||
final pruned = ledger.pruning({'8:Failed'});
|
||||
expect(pruned.notified, {'8:Failed'});
|
||||
expect(pruned.asked, isTrue);
|
||||
});
|
||||
|
||||
test('nothing to drop returns the same ledger', () {
|
||||
const ledger = NotificationLedger(notified: {'7:Failed'});
|
||||
expect(identical(ledger.pruning({'7:Failed'}), ledger), isTrue);
|
||||
});
|
||||
|
||||
test('a timestamped identity from an older build is dropped', () {
|
||||
final old = decodeNotificationLedger(
|
||||
'{"asked":false,"notified":["7:Decision@2026-10-22T11:00:00.000"]}',
|
||||
);
|
||||
expect(old.notified, hasLength(1));
|
||||
expect(old.pruning({'7:Decision'}).notified, isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
group('persistence is total', () {
|
||||
test('a round trip keeps the asked flag and the identities', () {
|
||||
final ledger = const NotificationLedger(
|
||||
notified: {'b', 'a'},
|
||||
).withAsked(true);
|
||||
final decoded = decodeNotificationLedger(
|
||||
encodeNotificationLedger(ledger),
|
||||
);
|
||||
expect(decoded.asked, isTrue);
|
||||
expect(decoded.notified, {'a', 'b'});
|
||||
});
|
||||
|
||||
test('an unchanged ledger always encodes to the same bytes', () {
|
||||
final first = encodeNotificationLedger(
|
||||
const NotificationLedger(notified: {'b', 'a'}),
|
||||
);
|
||||
final second = encodeNotificationLedger(
|
||||
const NotificationLedger(notified: {'a', 'b'}),
|
||||
);
|
||||
expect(first, second);
|
||||
});
|
||||
|
||||
test('blank, malformed and wrong-typed values never throw', () {
|
||||
expect(decodeNotificationLedger(null).notified, isEmpty);
|
||||
expect(decodeNotificationLedger('').asked, isFalse);
|
||||
expect(decodeNotificationLedger('not json').notified, isEmpty);
|
||||
expect(decodeNotificationLedger('[]').notified, isEmpty);
|
||||
expect(decodeNotificationLedger('"text"').notified, isEmpty);
|
||||
expect(
|
||||
decodeNotificationLedger(
|
||||
'{"asked":"yes","notified":[1,null,"a",""]}',
|
||||
).notified,
|
||||
{'a'},
|
||||
);
|
||||
expect(
|
||||
decodeNotificationLedger('{"asked":"yes"}').asked,
|
||||
isFalse,
|
||||
reason: 'only a real true counts as asked',
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/attention/domain/attention_models.dart';
|
||||
import 'package:pipelines_app/features/attention/notify/notification_models.dart';
|
||||
|
||||
NotificationEnvironment _env({
|
||||
bool supported = true,
|
||||
bool secure = true,
|
||||
String permission = 'default',
|
||||
}) => NotificationEnvironment(
|
||||
supported: supported,
|
||||
secureContext: secure,
|
||||
permission: permission,
|
||||
);
|
||||
|
||||
void main() {
|
||||
group('permission state is the platform\'s own answer', () {
|
||||
test('an unsupported API and an insecure page win over the word', () {
|
||||
expect(
|
||||
notificationStateOf(_env(supported: false, permission: 'granted')),
|
||||
NotificationPermissionState.unsupported,
|
||||
);
|
||||
expect(
|
||||
notificationStateOf(_env(secure: false, permission: 'granted')),
|
||||
NotificationPermissionState.needsSecureContext,
|
||||
);
|
||||
});
|
||||
|
||||
test('granted is never assumed from an unrecognised word', () {
|
||||
expect(
|
||||
notificationStateOf(_env(permission: 'prompt')),
|
||||
NotificationPermissionState.notRequested,
|
||||
);
|
||||
expect(
|
||||
notificationStateOf(_env(permission: '')),
|
||||
NotificationPermissionState.notRequested,
|
||||
);
|
||||
expect(
|
||||
notificationStateOf(_env(permission: 'granted')),
|
||||
NotificationPermissionState.granted,
|
||||
);
|
||||
expect(
|
||||
notificationStateOf(_env(permission: 'denied')),
|
||||
NotificationPermissionState.denied,
|
||||
);
|
||||
});
|
||||
|
||||
test('each state carries the browser model\'s own wire word', () {
|
||||
expect(NotificationPermissionState.unsupported.wireName, 'unsupported');
|
||||
expect(
|
||||
NotificationPermissionState.needsSecureContext.wireName,
|
||||
'insecure',
|
||||
);
|
||||
expect(NotificationPermissionState.notRequested.wireName, 'default');
|
||||
expect(NotificationPermissionState.granted.wireName, 'granted');
|
||||
expect(NotificationPermissionState.denied.wireName, 'denied');
|
||||
});
|
||||
});
|
||||
|
||||
group('the permission view', () {
|
||||
test('only a still-undecided page can request', () {
|
||||
final view = notificationPermissionView(
|
||||
NotificationPermissionState.notRequested,
|
||||
);
|
||||
expect(view.canRequest, isTrue);
|
||||
expect(view.actionLabel, notificationRequestLabel);
|
||||
expect(view.body, notificationDefaultCopy);
|
||||
|
||||
for (final state in [
|
||||
NotificationPermissionState.unsupported,
|
||||
NotificationPermissionState.needsSecureContext,
|
||||
NotificationPermissionState.granted,
|
||||
NotificationPermissionState.denied,
|
||||
]) {
|
||||
final other = notificationPermissionView(state);
|
||||
expect(other.canRequest, isFalse, reason: '$state');
|
||||
expect(other.actionLabel, isNull, reason: '$state');
|
||||
}
|
||||
});
|
||||
|
||||
test('asked only changes the undecided wording', () {
|
||||
expect(
|
||||
notificationPermissionView(
|
||||
NotificationPermissionState.notRequested,
|
||||
asked: true,
|
||||
).body,
|
||||
notificationDefaultAskedCopy,
|
||||
);
|
||||
expect(
|
||||
notificationPermissionView(
|
||||
NotificationPermissionState.denied,
|
||||
asked: true,
|
||||
).body,
|
||||
notificationDeniedCopy,
|
||||
);
|
||||
});
|
||||
|
||||
test('every unavailable state names the in-app channel', () {
|
||||
for (final state in [
|
||||
NotificationPermissionState.unsupported,
|
||||
NotificationPermissionState.needsSecureContext,
|
||||
NotificationPermissionState.denied,
|
||||
]) {
|
||||
expect(
|
||||
notificationPermissionView(state).body,
|
||||
contains('in-app Needs you surface'),
|
||||
reason: '$state',
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
group('notification content is the entry\'s own words', () {
|
||||
test('the headline is the kind, nothing invented', () {
|
||||
expect(
|
||||
notificationAlertTitle(AttentionKind.decision),
|
||||
'A run needs your decision',
|
||||
);
|
||||
expect(notificationAlertTitle(AttentionKind.failed), 'A run failed');
|
||||
});
|
||||
|
||||
test('the body is the run label then its pipeline', () {
|
||||
final entry = attentionEntryFor({
|
||||
'id': 7,
|
||||
'name': 'nightly-audit',
|
||||
'title': 'Nightly audit',
|
||||
'status': 'failed',
|
||||
'diagnostic': 'Stage 3 stopped',
|
||||
'created_at': '2026-10-22T09:00:00Z',
|
||||
'finished_at': '2026-10-22T09:10:00Z',
|
||||
})!;
|
||||
expect(
|
||||
notificationAlertBody(entry),
|
||||
'Nightly audit \u00b7 nightly-audit',
|
||||
);
|
||||
});
|
||||
|
||||
test('a blank or equal pipeline is never repeated', () {
|
||||
final untitled = attentionEntryFor({
|
||||
'id': 7,
|
||||
'name': 'release',
|
||||
'status': 'failed',
|
||||
'created_at': '2026-10-22T09:00:00Z',
|
||||
'finished_at': '2026-10-22T09:10:00Z',
|
||||
})!;
|
||||
expect(notificationAlertBody(untitled), 'release');
|
||||
|
||||
final nameless = attentionEntryFor({
|
||||
'id': 8,
|
||||
'name': '',
|
||||
'title': 'A title',
|
||||
'status': 'failed',
|
||||
'created_at': '2026-10-22T09:00:00Z',
|
||||
'finished_at': '2026-10-22T09:10:00Z',
|
||||
})!;
|
||||
expect(notificationAlertBody(nameless), 'A title');
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/attention/notify/notification_controller.dart';
|
||||
import 'package:pipelines_app/features/attention/notify/notification_models.dart';
|
||||
import 'package:pipelines_app/features/attention/notify/notification_store.dart';
|
||||
|
||||
import 'notification_test_support.dart';
|
||||
|
||||
void main() {
|
||||
group('permission is only ever the platform\'s answer', () {
|
||||
test('an unsupported platform is never asked and never posts', () async {
|
||||
final bridge = FakeNotificationBridge(supported: false);
|
||||
final notify = NotificationController(
|
||||
store: MemoryNotificationStore(),
|
||||
bridge: bridge,
|
||||
);
|
||||
addTearDown(notify.dispose);
|
||||
await notify.load();
|
||||
expect(notify.permission, NotificationPermissionState.unsupported);
|
||||
|
||||
expect(
|
||||
await notify.requestPermission(),
|
||||
NotificationPermissionState.unsupported,
|
||||
);
|
||||
expect(bridge.requests, 0);
|
||||
expect(
|
||||
notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'}),
|
||||
0,
|
||||
);
|
||||
expect(bridge.shown, isEmpty);
|
||||
});
|
||||
|
||||
test('an insecure page reports needsSecureContext', () async {
|
||||
final bridge = FakeNotificationBridge(secureContext: false);
|
||||
final notify = NotificationController(
|
||||
store: MemoryNotificationStore(),
|
||||
bridge: bridge,
|
||||
);
|
||||
addTearDown(notify.dispose);
|
||||
await notify.load();
|
||||
expect(notify.permission, NotificationPermissionState.needsSecureContext);
|
||||
await notify.requestPermission();
|
||||
expect(bridge.requests, 0);
|
||||
});
|
||||
|
||||
test('a default page is asked once and follows the real answer', () async {
|
||||
final store = MemoryNotificationStore();
|
||||
final bridge = FakeNotificationBridge(answer: 'granted');
|
||||
final notify = NotificationController(store: store, bridge: bridge);
|
||||
addTearDown(notify.dispose);
|
||||
await notify.load();
|
||||
expect(notify.permission, NotificationPermissionState.notRequested);
|
||||
expect(notify.canNotify, isFalse);
|
||||
|
||||
final state = await notify.requestPermission();
|
||||
expect(bridge.requests, 1);
|
||||
expect(state, NotificationPermissionState.granted);
|
||||
expect(notify.canNotify, isTrue);
|
||||
expect(notify.asked, isTrue);
|
||||
await settle();
|
||||
expect(store.stored, contains('"asked":true'));
|
||||
});
|
||||
|
||||
test('a denied answer is never re-prompted', () async {
|
||||
final bridge = FakeNotificationBridge(permission: 'denied');
|
||||
final notify = NotificationController(
|
||||
store: MemoryNotificationStore(),
|
||||
bridge: bridge,
|
||||
);
|
||||
addTearDown(notify.dispose);
|
||||
await notify.load();
|
||||
expect(notify.permission, NotificationPermissionState.denied);
|
||||
|
||||
expect(
|
||||
await notify.requestPermission(),
|
||||
NotificationPermissionState.denied,
|
||||
);
|
||||
expect(bridge.requests, 0);
|
||||
expect(
|
||||
notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'}),
|
||||
0,
|
||||
);
|
||||
expect(bridge.shown, isEmpty);
|
||||
});
|
||||
|
||||
test(
|
||||
'a prompt that grants nothing keeps the honest default wording',
|
||||
() async {
|
||||
final bridge = FakeNotificationBridge(answer: 'default');
|
||||
final notify = NotificationController(
|
||||
store: MemoryNotificationStore(),
|
||||
bridge: bridge,
|
||||
);
|
||||
addTearDown(notify.dispose);
|
||||
await notify.load();
|
||||
|
||||
final state = await notify.requestPermission();
|
||||
expect(state, NotificationPermissionState.notRequested);
|
||||
expect(notify.asked, isTrue);
|
||||
expect(notify.canNotify, isFalse);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/attention/notify/notification_controller.dart';
|
||||
import 'package:pipelines_app/features/attention/notify/notification_store.dart';
|
||||
|
||||
import 'notification_test_support.dart';
|
||||
|
||||
/// A run that leaves a qualifying state and enters it again is a new event.
|
||||
///
|
||||
/// A waiting run has no `finished_at`, and its creation time never changes, so
|
||||
/// both gates of one run carry exactly the same timestamps. These tests pin the
|
||||
/// behaviour that was silently dropped when the identity included that marker.
|
||||
void main() {
|
||||
test('a second decision gate of the same run notifies again', () async {
|
||||
final attention = attentionController();
|
||||
final bridge = FakeNotificationBridge(permission: 'granted');
|
||||
final notify = NotificationController(
|
||||
store: MemoryNotificationStore(),
|
||||
bridge: bridge,
|
||||
);
|
||||
addTearDown(attention.dispose);
|
||||
addTearDown(notify.dispose);
|
||||
await attention.load();
|
||||
await notify.load();
|
||||
|
||||
attention.seedRows([runSummary(7, 'running')]);
|
||||
attention.observeFrame(runFrame(7, 'waiting', finishedAt: ''));
|
||||
expect(publish(notify, attention), 1);
|
||||
expect(bridge.shown.single.tag, '7:Decision');
|
||||
|
||||
attention.observeFrame(runFrame(7, 'running'));
|
||||
expect(publish(notify, attention), 0);
|
||||
|
||||
attention.observeFrame(runFrame(7, 'waiting', finishedAt: ''));
|
||||
expect(attention.transitions, hasLength(2));
|
||||
expect(publish(notify, attention), 1);
|
||||
expect(bridge.shown, hasLength(2));
|
||||
// The browser coalesces by run+kind, so both alerts share one tag.
|
||||
expect(bridge.shown.map((m) => m.tag).toSet(), {'7:Decision'});
|
||||
});
|
||||
|
||||
test(
|
||||
'a second decision gate notifies even without the leaving publish',
|
||||
() async {
|
||||
final attention = attentionController();
|
||||
final bridge = FakeNotificationBridge(permission: 'granted');
|
||||
final notify = NotificationController(
|
||||
store: MemoryNotificationStore(),
|
||||
bridge: bridge,
|
||||
);
|
||||
addTearDown(attention.dispose);
|
||||
addTearDown(notify.dispose);
|
||||
await attention.load();
|
||||
await notify.load();
|
||||
|
||||
attention.seedRows([runSummary(7, 'running')]);
|
||||
attention.observeFrame(runFrame(7, 'waiting', finishedAt: ''));
|
||||
expect(publish(notify, attention), 1);
|
||||
|
||||
// The caller misses the frame that leaves the state; the detector still
|
||||
// creates a new instance for the next gate, so it must notify again.
|
||||
attention.observeFrame(runFrame(7, 'running'));
|
||||
attention.observeFrame(runFrame(7, 'waiting', finishedAt: ''));
|
||||
expect(publish(notify, attention), 1);
|
||||
expect(bridge.shown, hasLength(2));
|
||||
expect(bridge.shown.map((m) => m.tag).toSet(), {'7:Decision'});
|
||||
},
|
||||
);
|
||||
|
||||
test('a coalesced backlog of two gates notifies once', () async {
|
||||
final attention = attentionController();
|
||||
final bridge = FakeNotificationBridge(permission: 'granted');
|
||||
final notify = NotificationController(
|
||||
store: MemoryNotificationStore(),
|
||||
bridge: bridge,
|
||||
);
|
||||
addTearDown(attention.dispose);
|
||||
addTearDown(notify.dispose);
|
||||
await attention.load();
|
||||
await notify.load();
|
||||
|
||||
attention.seedRows([runSummary(7, 'running')]);
|
||||
attention.observeFrame(runFrame(7, 'waiting', finishedAt: ''));
|
||||
attention.observeFrame(runFrame(7, 'running'));
|
||||
attention.observeFrame(runFrame(7, 'waiting', finishedAt: ''));
|
||||
expect(attention.transitions, hasLength(2));
|
||||
|
||||
// Both gates were folded before the caller published; the current state is
|
||||
// what the operator should be told about, once.
|
||||
expect(publish(notify, attention), 1);
|
||||
expect(bridge.shown, hasLength(1));
|
||||
expect(bridge.shown.single.tag, '7:Decision');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import 'package:pipelines_app/features/attention/domain/attention_models.dart';
|
||||
import 'package:pipelines_app/features/attention/domain/attention_transitions.dart';
|
||||
import 'package:pipelines_app/features/attention/notify/notification_bridge.dart';
|
||||
import 'package:pipelines_app/features/attention/notify/notification_controller.dart';
|
||||
import 'package:pipelines_app/features/attention/notify/notification_ledger.dart';
|
||||
import 'package:pipelines_app/features/attention/notify/notification_models.dart';
|
||||
import 'package:pipelines_app/features/attention/runtime/attention_controller.dart';
|
||||
import 'package:pipelines_app/features/attention/runtime/attention_store.dart';
|
||||
|
||||
/// The fixed local time the attention tests order and window by.
|
||||
final attentionNow = DateTime(2026, 10, 22, 12);
|
||||
|
||||
String at(Duration before) => attentionNow.subtract(before).toIso8601String();
|
||||
|
||||
/// One run summary, built exactly as the runs list holds it.
|
||||
Map<String, dynamic> runSummary(
|
||||
int id,
|
||||
String status, {
|
||||
String name = 'release',
|
||||
String? title,
|
||||
Duration age = const Duration(hours: 1),
|
||||
String diagnostic = '',
|
||||
Object? exportPending,
|
||||
Map<String, dynamic> extra = const {},
|
||||
}) => {
|
||||
'id': id,
|
||||
'name': name,
|
||||
'title': title ?? 'Run $id',
|
||||
'status': status,
|
||||
'diagnostic': diagnostic,
|
||||
'created_at': at(age),
|
||||
// The server leaves finished_at empty for a waiting run (and for one still in
|
||||
// flight); only a settled run carries a finish time.
|
||||
'finished_at': status == 'waiting' || status == 'running'
|
||||
? ''
|
||||
: at(age - const Duration(minutes: 5)),
|
||||
'export_pending_sequence': ?exportPending,
|
||||
...extra,
|
||||
};
|
||||
|
||||
/// One qualifying pushed frame for a run, as `run_event` carries it.
|
||||
///
|
||||
/// A waiting or running frame has no `finished_at`, matching the server; pass
|
||||
/// [finishedAt] only to describe a settled run.
|
||||
Map<String, dynamic> runFrame(
|
||||
int id,
|
||||
String status, {
|
||||
String name = 'release',
|
||||
String? title,
|
||||
String diagnostic = '',
|
||||
String? finishedAt,
|
||||
}) => {
|
||||
'type': 'run_event',
|
||||
'run_id': id,
|
||||
'name': name,
|
||||
'title': title ?? 'Run $id',
|
||||
'status': status,
|
||||
'diagnostic': diagnostic,
|
||||
'created_at': at(const Duration(hours: 1)),
|
||||
'finished_at':
|
||||
finishedAt ??
|
||||
(status == 'waiting' || status == 'running'
|
||||
? ''
|
||||
: at(const Duration(minutes: 1))),
|
||||
};
|
||||
|
||||
/// One transition for a run that just entered [status], for batch tests.
|
||||
AttentionTransition transitionFor(
|
||||
int id, {
|
||||
String status = 'failed',
|
||||
String name = 'release',
|
||||
String? title,
|
||||
String? finishedAt,
|
||||
}) => AttentionTransition(
|
||||
attentionEntryFor(
|
||||
runFrame(id, status, name: name, title: title, finishedAt: finishedAt),
|
||||
)!,
|
||||
);
|
||||
|
||||
/// Let the controller's fire-and-forget ledger write land.
|
||||
Future<void> settle() => Future<void>.delayed(Duration.zero);
|
||||
|
||||
/// Publish exactly the way the manager wires it: the accumulated transitions,
|
||||
/// the current rows and the dismissed set from the same attention snapshot.
|
||||
int publish(NotificationController notify, AttentionController attention) =>
|
||||
notify.publishTransitions(
|
||||
attention.transitions,
|
||||
qualifying: notificationQualifyingKeys(attention.rows),
|
||||
dismissed: attention.dismissed,
|
||||
);
|
||||
|
||||
AttentionController attentionController() =>
|
||||
AttentionController(store: MemoryAttentionStore(), now: () => attentionNow);
|
||||
|
||||
/// A bridge whose answers are set explicitly, so every permission path is
|
||||
/// exercised without a browser. It records what the controller asked for.
|
||||
class FakeNotificationBridge implements NotificationBridge {
|
||||
FakeNotificationBridge({
|
||||
this.supported = true,
|
||||
this.secureContext = true,
|
||||
this.permission = 'default',
|
||||
this.answer = 'granted',
|
||||
this.accepts = true,
|
||||
});
|
||||
|
||||
bool supported;
|
||||
bool secureContext;
|
||||
String permission;
|
||||
String answer;
|
||||
bool accepts;
|
||||
|
||||
int requests = 0;
|
||||
final List<NotificationMessage> shown = [];
|
||||
final List<void Function()?> taps = [];
|
||||
|
||||
@override
|
||||
NotificationEnvironment environment() => NotificationEnvironment(
|
||||
supported: supported,
|
||||
secureContext: secureContext,
|
||||
permission: permission,
|
||||
);
|
||||
|
||||
@override
|
||||
Future<String> requestPermission() async {
|
||||
requests++;
|
||||
permission = answer;
|
||||
return answer;
|
||||
}
|
||||
|
||||
@override
|
||||
bool show(NotificationMessage message, {void Function()? onTap}) {
|
||||
shown.add(message);
|
||||
taps.add(onTap);
|
||||
return accepts;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/attention/domain/attention_models.dart';
|
||||
import 'package:pipelines_app/features/attention/runtime/attention_controller.dart';
|
||||
import 'package:pipelines_app/features/attention/runtime/attention_store.dart';
|
||||
|
||||
final _now = DateTime(2026, 10, 22, 12);
|
||||
|
||||
String _at(Duration before) => _now.subtract(before).toIso8601String();
|
||||
|
||||
Map<String, dynamic> _run(
|
||||
int id,
|
||||
String status, {
|
||||
String name = 'release',
|
||||
String? title,
|
||||
Duration age = const Duration(hours: 1),
|
||||
String diagnostic = '',
|
||||
Object? exportPending,
|
||||
Map<String, dynamic> extra = const {},
|
||||
}) => {
|
||||
'id': id,
|
||||
'name': name,
|
||||
'title': title ?? 'Run $id',
|
||||
'status': status,
|
||||
'diagnostic': diagnostic,
|
||||
'created_at': _at(age),
|
||||
'finished_at': _at(age - const Duration(minutes: 5)),
|
||||
'export_pending_sequence': ?exportPending,
|
||||
...extra,
|
||||
};
|
||||
|
||||
AttentionController _controller(AttentionStore store) =>
|
||||
AttentionController(store: store, now: () => _now);
|
||||
|
||||
class _SlowStore extends MemoryAttentionStore {
|
||||
final gate = Completer<bool>();
|
||||
|
||||
@override
|
||||
Future<bool> write(String value) {
|
||||
writes++;
|
||||
stored = value;
|
||||
return gate.future;
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
group('entries from the rows the Runs destination already holds', () {
|
||||
test('only failed and human waiting rows become entries', () async {
|
||||
final controller = _controller(MemoryAttentionStore());
|
||||
addTearDown(controller.dispose);
|
||||
await controller.load();
|
||||
controller.seedRows([
|
||||
_run(1, 'running'),
|
||||
_run(2, 'succeeded'),
|
||||
_run(3, 'queued'),
|
||||
_run(4, 'canceled'),
|
||||
_run(5, 'failed', diagnostic: 'Stage 2 failed'),
|
||||
_run(6, 'waiting', title: 'Approve the release'),
|
||||
]);
|
||||
|
||||
expect(controller.entries.map((entry) => entry.key), [
|
||||
'6:Decision',
|
||||
'5:Failed',
|
||||
]);
|
||||
expect(controller.entries.last.detail, 'Stage 2 failed');
|
||||
});
|
||||
|
||||
test('export handoffs and yesterday do not ask the operator', () async {
|
||||
final controller = _controller(MemoryAttentionStore());
|
||||
addTearDown(controller.dispose);
|
||||
await controller.load();
|
||||
controller.seedRows([
|
||||
_run(1, 'waiting', exportPending: 4),
|
||||
_run(2, 'waiting', exportPending: ' 2 '),
|
||||
_run(3, 'waiting', exportPending: 0),
|
||||
_run(4, 'failed', age: const Duration(days: 1, hours: 2)),
|
||||
_run(5, 'waiting', age: const Duration(days: 1)),
|
||||
]);
|
||||
|
||||
expect(controller.entries.map((entry) => entry.runId), [3]);
|
||||
});
|
||||
});
|
||||
|
||||
group('dismissal persistence', () {
|
||||
test('a dismissed identity survives a rebuilt controller', () async {
|
||||
final store = MemoryAttentionStore();
|
||||
final first = _controller(store);
|
||||
await first.load();
|
||||
first.seedRows([_run(7, 'failed')]);
|
||||
final entry = first.entries.single;
|
||||
|
||||
expect(await first.dismiss(entry), isTrue);
|
||||
expect(first.entries, isEmpty);
|
||||
expect(store.stored, encodeAttentionDismissals({'7:Failed'}));
|
||||
first.dispose();
|
||||
|
||||
final rebuilt = _controller(store);
|
||||
addTearDown(rebuilt.dispose);
|
||||
await rebuilt.load();
|
||||
rebuilt.seedRows([_run(7, 'failed')]);
|
||||
expect(rebuilt.dismissed, {'7:Failed'});
|
||||
expect(rebuilt.entries, isEmpty);
|
||||
});
|
||||
|
||||
test('Clear all applies only the snapshot, leaving later arrivals', () async {
|
||||
final controller = _controller(MemoryAttentionStore());
|
||||
addTearDown(controller.dispose);
|
||||
await controller.load();
|
||||
controller.seedRows([_run(1, 'failed'), _run(2, 'waiting')]);
|
||||
final snapshot = attentionDismissalSnapshot(controller.entries);
|
||||
|
||||
// A third run arrives while the sheet is open. Clear all must not know it.
|
||||
controller.seedRows([
|
||||
_run(1, 'failed'),
|
||||
_run(2, 'waiting'),
|
||||
_run(3, 'failed'),
|
||||
]);
|
||||
expect(await controller.clearAll(snapshot), isTrue);
|
||||
|
||||
expect(controller.dismissed, {'1:Failed', '2:Decision'});
|
||||
expect(controller.entries.map((entry) => entry.key), ['3:Failed']);
|
||||
});
|
||||
|
||||
test('a slow write never holds the bell or entries back', () async {
|
||||
final store = _SlowStore();
|
||||
final controller = _controller(store);
|
||||
addTearDown(controller.dispose);
|
||||
await controller.load();
|
||||
controller.seedRows([_run(4, 'failed')]);
|
||||
final entry = controller.entries.single;
|
||||
|
||||
final pending = controller.dismiss(entry);
|
||||
expect(controller.entries, isEmpty, reason: 'memory applies first');
|
||||
expect(store.stored, encodeAttentionDismissals({'4:Failed'}));
|
||||
store.gate.complete(true);
|
||||
expect(await pending, isTrue);
|
||||
});
|
||||
|
||||
test('failed reads and writes are total and keep this session', () async {
|
||||
final store = MemoryAttentionStore()
|
||||
..failReads = true
|
||||
..failWrites = true;
|
||||
final controller = _controller(store);
|
||||
addTearDown(controller.dispose);
|
||||
|
||||
await expectLater(controller.load(), completes);
|
||||
expect(controller.loaded, isTrue);
|
||||
expect(controller.dismissed, isEmpty);
|
||||
|
||||
controller.seedRows([_run(8, 'failed')]);
|
||||
final entry = controller.entries.single;
|
||||
expect(await controller.dismiss(entry), isFalse);
|
||||
expect(controller.dismissed, {'8:Failed'});
|
||||
expect(controller.entries, isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
group('pushed frames and reconnect', () {
|
||||
test('a live frame that becomes failed appears without a reload', () async {
|
||||
final controller = _controller(MemoryAttentionStore());
|
||||
addTearDown(controller.dispose);
|
||||
await controller.load();
|
||||
controller.seedRows([_run(1, 'running')]);
|
||||
expect(controller.entries, isEmpty);
|
||||
|
||||
controller.observeFrame({
|
||||
'type': 'run_event',
|
||||
'run_id': 1,
|
||||
'status': 'failed',
|
||||
'diagnostic': 'Stage 4 failed',
|
||||
'finished_at': _at(const Duration(minutes: 1)),
|
||||
});
|
||||
|
||||
expect(controller.entries.map((entry) => entry.key), ['1:Failed']);
|
||||
expect(controller.entries.single.detail, 'Stage 4 failed');
|
||||
expect(controller.transitions.map((item) => item.key), ['1:Failed']);
|
||||
|
||||
// The same state again is not a new transition.
|
||||
controller.observeFrame({
|
||||
'type': 'run_event',
|
||||
'run_id': 1,
|
||||
'status': 'failed',
|
||||
'diagnostic': 'Stage 4 failed',
|
||||
});
|
||||
expect(controller.entries, hasLength(1));
|
||||
expect(controller.transitions, hasLength(1));
|
||||
});
|
||||
|
||||
test('a live frame for a new run can create its own summary', () async {
|
||||
final controller = _controller(MemoryAttentionStore());
|
||||
addTearDown(controller.dispose);
|
||||
await controller.load();
|
||||
controller.seedRows(const []);
|
||||
|
||||
controller.observeFrame({
|
||||
'type': 'run_event',
|
||||
'run_id': 9,
|
||||
'pipeline_id': 10,
|
||||
'name': 'nightly',
|
||||
'title': 'Nightly audit',
|
||||
'status': 'waiting',
|
||||
'created_at': _at(const Duration(minutes: 3)),
|
||||
});
|
||||
|
||||
expect(controller.entries.single.runId, 9);
|
||||
expect(controller.entries.single.kind, AttentionKind.decision);
|
||||
});
|
||||
|
||||
test(
|
||||
'a reconnect reseed keeps dismissals and does not re-notify',
|
||||
() async {
|
||||
final controller = _controller(MemoryAttentionStore());
|
||||
addTearDown(controller.dispose);
|
||||
await controller.load();
|
||||
controller.seedRows([_run(1, 'running'), _run(2, 'failed')]);
|
||||
final failed = controller.entries.single;
|
||||
expect(await controller.dismiss(failed), isTrue);
|
||||
|
||||
controller.observeFrame({
|
||||
'type': 'run_event',
|
||||
'run_id': 1,
|
||||
'status': 'failed',
|
||||
});
|
||||
expect(controller.transitions, hasLength(1));
|
||||
|
||||
controller.resetForReconnect();
|
||||
controller.seedRows([
|
||||
_run(1, 'failed'),
|
||||
_run(2, 'failed'),
|
||||
], reconnect: true);
|
||||
|
||||
expect(controller.dismissed, {'2:Failed'});
|
||||
expect(controller.entries.map((entry) => entry.key), ['1:Failed']);
|
||||
expect(
|
||||
controller.transitions,
|
||||
hasLength(1),
|
||||
reason: 'the reconnect baseline is already failed for run 1',
|
||||
);
|
||||
|
||||
controller.observeFrame({
|
||||
'type': 'run_event',
|
||||
'run_id': 1,
|
||||
'status': 'failed',
|
||||
});
|
||||
expect(controller.transitions, hasLength(1));
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/attention/runtime/attention_store.dart';
|
||||
import 'package:pipelines_app/features/attention/ui/needs_you_keys.dart';
|
||||
|
||||
import 'attention_runs_test_support.dart';
|
||||
|
||||
/// The hardest real-app case: a narrow phone at a doubled text scale. Both the
|
||||
/// Runs list chrome and the native sheet must keep the bell and every action
|
||||
/// inside the viewport.
|
||||
void main() {
|
||||
testWidgets('both hosts fit the bell and sheet at 320 logical px and 2x', (
|
||||
tester,
|
||||
) async {
|
||||
tester.view.devicePixelRatio = 2;
|
||||
tester.view.physicalSize = const Size(640, 1280);
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
final gateway = AttentionRunsGateway();
|
||||
addTearDown(gateway.framesController.close);
|
||||
|
||||
for (final native in [false, true]) {
|
||||
await mountAttentionRuns(
|
||||
tester,
|
||||
gateway,
|
||||
cupertino: native,
|
||||
store: MemoryAttentionStore(),
|
||||
runs: [
|
||||
attentionRun(
|
||||
1,
|
||||
'waiting',
|
||||
title: 'Approve a release candidate at 320 px',
|
||||
),
|
||||
attentionRun(
|
||||
2,
|
||||
'failed',
|
||||
title: 'A failed run with a label long enough to wrap',
|
||||
diagnostic: 'Stage 3 stopped because the credential is missing.',
|
||||
),
|
||||
],
|
||||
request: native ? 1 : 0,
|
||||
textScale: 2,
|
||||
key: ValueKey(native),
|
||||
);
|
||||
expect(find.byKey(attentionBellKey), findsOneWidget);
|
||||
final listError = tester.takeException();
|
||||
expect(
|
||||
listError,
|
||||
isNull,
|
||||
reason: listError is FlutterError
|
||||
? '${native ? 'Cupertino' : 'Material'} list: ${listError.toStringDeep()}'
|
||||
: '${native ? 'Cupertino' : 'Material'} list: $listError',
|
||||
);
|
||||
await openAttentionSheet(tester);
|
||||
final sheetError = tester.takeException();
|
||||
expect(
|
||||
sheetError,
|
||||
isNull,
|
||||
reason: sheetError is FlutterError
|
||||
? '${native ? 'Cupertino' : 'Material'} sheet: ${sheetError.toStringDeep()}'
|
||||
: '${native ? 'Cupertino' : 'Material'} sheet: $sheetError',
|
||||
);
|
||||
final sheet = tester.getRect(find.byKey(attentionSheetKey));
|
||||
expect(sheet.left, greaterThanOrEqualTo(0));
|
||||
expect(sheet.right, lessThanOrEqualTo(320));
|
||||
expect(sheet.top, greaterThanOrEqualTo(0));
|
||||
expect(sheet.bottom, lessThanOrEqualTo(640));
|
||||
await tester.binding.handlePopRoute();
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/attention/runtime/attention_store.dart';
|
||||
import 'package:pipelines_app/features/attention/ui/needs_you_keys.dart';
|
||||
import 'package:pipelines_app/features/runs/screen.dart';
|
||||
|
||||
/// A fixed local noon so the attention local-day window is deterministic.
|
||||
final attentionTestNow = DateTime(2026, 10, 22, 12);
|
||||
|
||||
Map<String, dynamic> attentionRun(
|
||||
int id,
|
||||
String status, {
|
||||
required String title,
|
||||
String name = 'release',
|
||||
String diagnostic = '',
|
||||
}) => {
|
||||
'id': id,
|
||||
'name': name,
|
||||
'title': title,
|
||||
'status': status,
|
||||
'diagnostic': diagnostic,
|
||||
'created_at': attentionTestNow
|
||||
.subtract(const Duration(hours: 1))
|
||||
.toIso8601String(),
|
||||
'finished_at': attentionTestNow
|
||||
.subtract(const Duration(minutes: 30))
|
||||
.toIso8601String(),
|
||||
};
|
||||
|
||||
/// The two requests the Runs destination makes; no attention request exists.
|
||||
class AttentionRunsGateway implements ApiGateway {
|
||||
final framesController = StreamController<JsonMap>.broadcast();
|
||||
final listRequests = <Completer<JsonMap>>[];
|
||||
final detailRequests = <num, List<Completer<JsonMap>>>{};
|
||||
|
||||
@override
|
||||
Stream<JsonMap> get frames => framesController.stream;
|
||||
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
|
||||
final request = Completer<JsonMap>();
|
||||
if (type == 'list_runs') {
|
||||
listRequests.add(request);
|
||||
} else if (type == 'get_run') {
|
||||
final id = fields['run_id'] as num;
|
||||
detailRequests.putIfAbsent(id, () => []).add(request);
|
||||
} else {
|
||||
request.completeError(UnsupportedError(type));
|
||||
}
|
||||
return request.future;
|
||||
}
|
||||
|
||||
void replyList(int index, List<JsonMap> runs) =>
|
||||
listRequests[index].complete({'runs': runs});
|
||||
|
||||
void replyDetail(num id, JsonMap detail) =>
|
||||
detailRequests[id]!.first.complete({'run_detail': detail});
|
||||
}
|
||||
|
||||
Widget attentionRunsApp(
|
||||
AttentionRunsGateway gateway, {
|
||||
required bool cupertino,
|
||||
required AttentionStore store,
|
||||
double textScale = 1,
|
||||
Key? key,
|
||||
}) {
|
||||
Widget scaled(BuildContext context, Widget? child) => MediaQuery(
|
||||
data: MediaQuery.of(
|
||||
context,
|
||||
).copyWith(textScaler: TextScaler.linear(textScale)),
|
||||
child: child!,
|
||||
);
|
||||
final screen = RunsScreen(
|
||||
key: key,
|
||||
gateway: gateway,
|
||||
attentionStore: store,
|
||||
attentionNow: () => attentionTestNow,
|
||||
);
|
||||
if (cupertino) {
|
||||
return CupertinoApp(
|
||||
theme: const CupertinoThemeData(brightness: Brightness.dark),
|
||||
builder: scaled,
|
||||
home: CupertinoPageScaffold(child: screen),
|
||||
);
|
||||
}
|
||||
return MaterialApp(
|
||||
theme: ThemeData(platform: TargetPlatform.android),
|
||||
builder: scaled,
|
||||
home: Scaffold(body: screen),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> mountAttentionRuns(
|
||||
WidgetTester tester,
|
||||
AttentionRunsGateway gateway, {
|
||||
required bool cupertino,
|
||||
required AttentionStore store,
|
||||
required List<JsonMap> runs,
|
||||
int request = 0,
|
||||
double textScale = 1,
|
||||
Key? key,
|
||||
}) async {
|
||||
await tester.pumpWidget(
|
||||
attentionRunsApp(
|
||||
gateway,
|
||||
cupertino: cupertino,
|
||||
store: store,
|
||||
textScale: textScale,
|
||||
key: key,
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
gateway.replyList(request, runs);
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
Future<void> openAttentionSheet(WidgetTester tester) async {
|
||||
await tester.tap(find.byKey(attentionBellKey));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/attention/domain/attention_models.dart';
|
||||
import 'package:pipelines_app/features/attention/runtime/attention_store.dart';
|
||||
import 'package:pipelines_app/features/attention/ui/needs_you_keys.dart';
|
||||
|
||||
import 'attention_runs_test_support.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
late AttentionRunsGateway gateway;
|
||||
|
||||
setUp(() => gateway = AttentionRunsGateway());
|
||||
tearDown(() => gateway.framesController.close());
|
||||
|
||||
for (final native in [false, true]) {
|
||||
final host = native ? 'Cupertino' : 'Material';
|
||||
|
||||
testWidgets(
|
||||
'$host Runs list bell opens the native sheet and dismisses one',
|
||||
(tester) async {
|
||||
final semantics = tester.ensureSemantics();
|
||||
final store = MemoryAttentionStore();
|
||||
await mountAttentionRuns(
|
||||
tester,
|
||||
gateway,
|
||||
cupertino: native,
|
||||
store: store,
|
||||
runs: [
|
||||
attentionRun(1, 'waiting', title: 'Approve the release'),
|
||||
attentionRun(
|
||||
2,
|
||||
'failed',
|
||||
title: 'Ship the release',
|
||||
diagnostic: 'Stage 2',
|
||||
),
|
||||
attentionRun(3, 'waiting', title: 'Machine export')
|
||||
..['export_pending_sequence'] = 2,
|
||||
attentionRun(4, 'running', title: 'Still running'),
|
||||
],
|
||||
);
|
||||
|
||||
expect(
|
||||
find.bySemanticsLabel('Notifications, 2 needing attention'),
|
||||
findsOneWidget,
|
||||
);
|
||||
await openAttentionSheet(tester);
|
||||
expect(find.byKey(attentionSheetKey), findsOneWidget);
|
||||
expect(find.byKey(attentionRowKey('3:Decision')), findsNothing);
|
||||
expect(find.byKey(attentionRowKey('4:Failed')), findsNothing);
|
||||
expect(find.byKey(attentionRowKey('2:Failed')), findsOneWidget);
|
||||
|
||||
await tester.tap(find.byKey(attentionDismissKey('2:Failed')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(attentionSheetKey), findsOneWidget);
|
||||
expect(find.byKey(attentionRowKey('2:Failed')), findsNothing);
|
||||
expect(store.stored, encodeAttentionDismissals({'2:Failed'}));
|
||||
|
||||
// Closing and rebuilding from the same store keeps the dismissal.
|
||||
await tester.binding.handlePopRoute();
|
||||
await tester.pumpAndSettle();
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await mountAttentionRuns(
|
||||
tester,
|
||||
gateway,
|
||||
cupertino: native,
|
||||
store: store,
|
||||
runs: [
|
||||
attentionRun(1, 'waiting', title: 'Approve the release'),
|
||||
attentionRun(
|
||||
2,
|
||||
'failed',
|
||||
title: 'Ship the release',
|
||||
diagnostic: 'Stage 2',
|
||||
),
|
||||
],
|
||||
request: 1,
|
||||
key: const ValueKey('rebuilt'),
|
||||
);
|
||||
expect(
|
||||
find.bySemanticsLabel('Notifications, 1 needing attention'),
|
||||
findsOneWidget,
|
||||
);
|
||||
semantics.dispose();
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('$host rows follow the browser open/dismiss rules', (
|
||||
tester,
|
||||
) async {
|
||||
final store = MemoryAttentionStore();
|
||||
await mountAttentionRuns(
|
||||
tester,
|
||||
gateway,
|
||||
cupertino: native,
|
||||
store: store,
|
||||
runs: [
|
||||
attentionRun(1, 'waiting', title: 'Approve the release'),
|
||||
attentionRun(2, 'failed', title: 'Ship the release'),
|
||||
],
|
||||
);
|
||||
|
||||
await openAttentionSheet(tester);
|
||||
await tester.tap(find.byKey(attentionRowKey('1:Decision')));
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 400));
|
||||
expect(gateway.detailRequests[1], hasLength(1));
|
||||
expect(
|
||||
store.stored,
|
||||
isNull,
|
||||
reason: 'a Decision opens without dismissing',
|
||||
);
|
||||
gateway.replyDetail(1, {'id': 1, 'title': 'Approve the release'});
|
||||
await tester.pump();
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.text(native ? 'Back' : 'Back to list'));
|
||||
await tester.pump();
|
||||
await openAttentionSheet(tester);
|
||||
await tester.tap(find.byKey(attentionRowKey('2:Failed')));
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 400));
|
||||
expect(gateway.detailRequests[2], hasLength(1));
|
||||
expect(store.stored, encodeAttentionDismissals({'2:Failed'}));
|
||||
gateway.replyDetail(2, {'id': 2, 'title': 'Ship the release'});
|
||||
await tester.pump();
|
||||
});
|
||||
|
||||
testWidgets('$host live frame and Clear-all snapshot reach the bell', (
|
||||
tester,
|
||||
) async {
|
||||
final semantics = tester.ensureSemantics();
|
||||
final store = MemoryAttentionStore();
|
||||
await mountAttentionRuns(
|
||||
tester,
|
||||
gateway,
|
||||
cupertino: native,
|
||||
store: store,
|
||||
runs: [attentionRun(1, 'failed', title: 'First failure')],
|
||||
);
|
||||
expect(
|
||||
find.bySemanticsLabel('Notifications, 1 needing attention'),
|
||||
findsOneWidget,
|
||||
);
|
||||
|
||||
await openAttentionSheet(tester);
|
||||
gateway.framesController.add({
|
||||
'type': 'run_event',
|
||||
'run_id': 9,
|
||||
'pipeline_id': 4,
|
||||
'name': 'nightly',
|
||||
'title': 'Arrived while open',
|
||||
'status': 'waiting',
|
||||
'created_at': attentionTestNow
|
||||
.subtract(const Duration(minutes: 5))
|
||||
.toIso8601String(),
|
||||
});
|
||||
await tester.pump();
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(attentionRowKey('9:Decision')), findsOneWidget);
|
||||
|
||||
await tester.tap(find.byKey(attentionClearAllKey));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(attentionRowKey('1:Failed')), findsNothing);
|
||||
expect(
|
||||
find.byKey(attentionRowKey('9:Decision')),
|
||||
findsOneWidget,
|
||||
reason: 'Clear all acts on the snapshot it opened with',
|
||||
);
|
||||
expect(store.stored, encodeAttentionDismissals({'1:Failed'}));
|
||||
semantics.dispose();
|
||||
});
|
||||
|
||||
testWidgets('$host empty runs hide the badge but keep the bell', (
|
||||
tester,
|
||||
) async {
|
||||
final semantics = tester.ensureSemantics();
|
||||
await mountAttentionRuns(
|
||||
tester,
|
||||
gateway,
|
||||
cupertino: native,
|
||||
store: MemoryAttentionStore(),
|
||||
runs: const [],
|
||||
);
|
||||
|
||||
expect(find.byKey(attentionBellKey), findsOneWidget);
|
||||
expect(find.byKey(attentionBadgeKey), findsNothing);
|
||||
expect(find.bySemanticsLabel('Notifications'), findsOneWidget);
|
||||
await openAttentionSheet(tester);
|
||||
expect(find.text('Nothing needs you right now.'), findsOneWidget);
|
||||
expect(find.byKey(attentionClearAllKey), findsNothing);
|
||||
semantics.dispose();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/attention/domain/attention_models.dart';
|
||||
import 'package:pipelines_app/features/attention/runtime/attention_store.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
test('reads and writes only the attention model key', () async {
|
||||
SharedPreferences.setMockInitialValues(<String, Object>{
|
||||
attentionStorageKey: '["7:Failed"]',
|
||||
'pipelines.next.workspace.v1': '/srv/keep',
|
||||
});
|
||||
const store = SharedPreferencesAttentionStore();
|
||||
|
||||
expect(await store.read(), '["7:Failed"]');
|
||||
expect(await store.write('["8:Decision"]'), isTrue);
|
||||
|
||||
final preferences = await SharedPreferences.getInstance();
|
||||
expect(preferences.getString(attentionStorageKey), '["8:Decision"]');
|
||||
expect(
|
||||
preferences.getString('pipelines.next.workspace.v1'),
|
||||
'/srv/keep',
|
||||
reason: 'another owned preference must not be rewritten',
|
||||
);
|
||||
});
|
||||
|
||||
test('an empty store reads as null and the key stays namespaced', () async {
|
||||
SharedPreferences.setMockInitialValues(<String, Object>{});
|
||||
const store = SharedPreferencesAttentionStore();
|
||||
|
||||
expect(await store.read(), isNull);
|
||||
expect(attentionStorageKey, 'pipelines.next.attention.v1');
|
||||
expect(await store.write('[]'), isTrue);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/attention/notify/notification_models.dart';
|
||||
import 'package:pipelines_app/features/attention/ui/notification_permission_tile.dart';
|
||||
|
||||
import 'needs_you_test_support.dart';
|
||||
|
||||
/// The tile inside a normal page, so both native hosts can draw it. The page
|
||||
/// scrolls like the Settings list does, so the tile is never given a fixed
|
||||
/// height to overflow.
|
||||
Widget _page({
|
||||
required NotificationPermissionState state,
|
||||
bool cupertino = false,
|
||||
bool asked = false,
|
||||
VoidCallback? onRequest,
|
||||
}) => attentionApp(
|
||||
Scaffold(
|
||||
body: SingleChildScrollView(
|
||||
child: NotificationPermissionTile(
|
||||
state: state,
|
||||
asked: asked,
|
||||
onRequest: onRequest,
|
||||
),
|
||||
),
|
||||
),
|
||||
cupertino: cupertino,
|
||||
);
|
||||
|
||||
void _noop() {}
|
||||
|
||||
void main() {
|
||||
for (final native in [false, true]) {
|
||||
final host = native ? 'Cupertino' : 'Material';
|
||||
|
||||
testWidgets('$host shows the state\'s own honest copy', (tester) async {
|
||||
final cases = <NotificationPermissionState, String>{
|
||||
NotificationPermissionState.unsupported: notificationUnsupportedCopy,
|
||||
NotificationPermissionState.needsSecureContext:
|
||||
notificationInsecureCopy,
|
||||
NotificationPermissionState.granted: notificationGrantedCopy,
|
||||
NotificationPermissionState.denied: notificationDeniedCopy,
|
||||
NotificationPermissionState.notRequested: notificationDefaultCopy,
|
||||
};
|
||||
for (final entry in cases.entries) {
|
||||
await tester.pumpWidget(
|
||||
_page(state: entry.key, cupertino: native, onRequest: _noop),
|
||||
);
|
||||
expect(find.text(notificationSectionTitle), findsOneWidget);
|
||||
expect(find.text(notificationRationale), findsOneWidget);
|
||||
expect(find.text(entry.value), findsOneWidget, reason: '${entry.key}');
|
||||
expect(
|
||||
find.byKey(notificationEnableKey),
|
||||
entry.key == NotificationPermissionState.notRequested
|
||||
? findsOneWidget
|
||||
: findsNothing,
|
||||
reason: '${entry.key}',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
testWidgets('$host shows the asked wording without an action', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
_page(
|
||||
state: NotificationPermissionState.notRequested,
|
||||
asked: true,
|
||||
cupertino: native,
|
||||
),
|
||||
);
|
||||
expect(find.text(notificationDefaultAskedCopy), findsOneWidget);
|
||||
expect(find.text(notificationDefaultCopy), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('$host Enable runs the explicit request', (tester) async {
|
||||
var requested = 0;
|
||||
await tester.pumpWidget(
|
||||
_page(
|
||||
state: NotificationPermissionState.notRequested,
|
||||
cupertino: native,
|
||||
onRequest: () => requested++,
|
||||
),
|
||||
);
|
||||
await tester.tap(find.byKey(notificationEnableKey));
|
||||
await tester.pump();
|
||||
expect(requested, 1);
|
||||
});
|
||||
|
||||
testWidgets('$host tile wraps at 320 logical px and 2x in dark', (
|
||||
tester,
|
||||
) async {
|
||||
tester.view.devicePixelRatio = 2;
|
||||
tester.view.physicalSize = const Size(640, 1280);
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
|
||||
// The undecided state is the hardest: it carries the Enable action as well
|
||||
// as the longest copy, so the section title must still have room to read.
|
||||
await tester.pumpWidget(
|
||||
attentionApp(
|
||||
Scaffold(
|
||||
body: SingleChildScrollView(
|
||||
child: NotificationPermissionTile(
|
||||
state: NotificationPermissionState.notRequested,
|
||||
onRequest: _noop,
|
||||
),
|
||||
),
|
||||
),
|
||||
cupertino: native,
|
||||
dark: true,
|
||||
textScale: 2,
|
||||
),
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
|
||||
final title = tester.renderObject<RenderParagraph>(
|
||||
find.text(notificationSectionTitle),
|
||||
);
|
||||
// Cupertino's list tile deliberately caps its title at one line; the
|
||||
// defect this guards is the title being squeezed to a single glyph by the
|
||||
// action sharing the row, so its width is the meaningful check.
|
||||
expect(
|
||||
title.size.width,
|
||||
greaterThan(100),
|
||||
reason: 'the action must not squeeze the section title to one glyph',
|
||||
);
|
||||
final body = tester.renderObject<RenderParagraph>(
|
||||
find.text(notificationDefaultCopy),
|
||||
);
|
||||
expect(body.didExceedMaxLines, isFalse);
|
||||
expect(find.byKey(notificationEnableKey), findsOneWidget);
|
||||
|
||||
final rect = tester.getRect(find.byKey(notificationStateKey));
|
||||
expect(rect.left, greaterThanOrEqualTo(0));
|
||||
expect(rect.right, lessThanOrEqualTo(320));
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,415 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_permission_card.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_permission_card_model.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
|
||||
|
||||
import 'chat_thread_fixtures.dart';
|
||||
|
||||
Widget materialHost(Widget child) => MaterialApp(
|
||||
theme: ThemeData(platform: TargetPlatform.android),
|
||||
home: Scaffold(body: child),
|
||||
);
|
||||
|
||||
Widget scrollHost(Widget child) =>
|
||||
materialHost(SingleChildScrollView(child: child));
|
||||
|
||||
Widget cupertinoHost(Widget child) => CupertinoApp(
|
||||
theme: const CupertinoThemeData(brightness: Brightness.dark),
|
||||
home: CupertinoPageScaffold(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: child,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
JsonMap permission({
|
||||
String id = 'req-1',
|
||||
String action = 'bash',
|
||||
List<String> resources = const [
|
||||
'command: rm -rf build',
|
||||
'cwd: /workspace/demo',
|
||||
],
|
||||
String message = 'This deletes the build output.',
|
||||
bool resolved = false,
|
||||
String decision = '',
|
||||
}) => {
|
||||
'session_id': 's',
|
||||
'request_id': id,
|
||||
'action': action,
|
||||
'resources': resources,
|
||||
'message': message,
|
||||
'source': {'type': 'tool'},
|
||||
'resolved': resolved,
|
||||
if (decision.isNotEmpty) 'decision': decision,
|
||||
};
|
||||
|
||||
void main() {
|
||||
test('recorded action, risk and options survive the card model', () {
|
||||
final card = chatPermissionCard(permission(), '')!;
|
||||
expect(card.headline, 'Approve bash');
|
||||
expect(card.statusLine, chatApprovalStatusPending);
|
||||
expect(card.risk, 'This deletes the build output.');
|
||||
expect(card.resources, ['command: rm -rf build', 'cwd: /workspace/demo']);
|
||||
expect(card.alwaysLabel, 'Always allow');
|
||||
expect(card.actionable, isTrue);
|
||||
expect(card.showRisk, isTrue);
|
||||
});
|
||||
|
||||
test('resources keep their recorded indentation and order', () {
|
||||
final card = chatPermissionCard(
|
||||
permission(
|
||||
resources: const [
|
||||
' cd /workspace/demo',
|
||||
'command: |\n echo hello',
|
||||
' ',
|
||||
],
|
||||
),
|
||||
'',
|
||||
)!;
|
||||
expect(card.resources, [
|
||||
' cd /workspace/demo',
|
||||
'command: |\n echo hello',
|
||||
]);
|
||||
expect(
|
||||
card.resourceText,
|
||||
' cd /workspace/demo\ncommand: |\n echo hello',
|
||||
);
|
||||
});
|
||||
|
||||
test('risk falls back to the action and resources cap at six lines', () {
|
||||
final card = chatPermissionCard(
|
||||
permission(
|
||||
message: '',
|
||||
resources: const [
|
||||
'one',
|
||||
'two\nthree',
|
||||
'four',
|
||||
'five',
|
||||
'six',
|
||||
'seven',
|
||||
'eight',
|
||||
],
|
||||
),
|
||||
'',
|
||||
)!;
|
||||
expect(
|
||||
card.risk,
|
||||
'The agent is asking to run bash; review the request before allowing.',
|
||||
);
|
||||
expect(card.resourceText.split('\n'), hasLength(6));
|
||||
expect(card.resourceText.endsWith('…'), isTrue);
|
||||
expect(card.resources, hasLength(7));
|
||||
});
|
||||
|
||||
test('a server resolution outranks a local answer and a blank decision is '
|
||||
'stale', () {
|
||||
final resolved = chatPermissionCard(
|
||||
permission(
|
||||
resolved: true,
|
||||
decision: 'always',
|
||||
message: 'Another client already allowed this.',
|
||||
),
|
||||
'once',
|
||||
)!;
|
||||
expect(resolved.state, ChatPermissionState.resolved);
|
||||
expect(resolved.headline, 'Always allowed');
|
||||
expect(resolved.statusLine, 'Another client already allowed this.');
|
||||
expect(resolved.actionable, isFalse);
|
||||
expect(resolved.showRisk, isFalse);
|
||||
|
||||
final stale = chatPermissionCard(
|
||||
permission(resolved: true, message: ''),
|
||||
'',
|
||||
)!;
|
||||
expect(stale.state, ChatPermissionState.stale);
|
||||
expect(stale.headline, 'Already resolved');
|
||||
expect(stale.statusLine, chatApprovalStatusResolved);
|
||||
expect(stale.actionable, isFalse);
|
||||
});
|
||||
|
||||
test('a rejection keeps the risk panel while answered', () {
|
||||
final rejected = chatPermissionCard(permission(), 'reject')!;
|
||||
expect(rejected.state, ChatPermissionState.answered);
|
||||
expect(rejected.headline, 'Rejected');
|
||||
expect(rejected.statusLine, chatApprovalStatusAnswered);
|
||||
expect(rejected.showRisk, isTrue);
|
||||
expect(rejected.actionable, isFalse);
|
||||
});
|
||||
|
||||
test('one stable reply id per confirmed action', () {
|
||||
expect(
|
||||
chatPermissionReplyId('req-1', 'once'),
|
||||
chatPermissionReplyId('req-1', 'once'),
|
||||
);
|
||||
expect(
|
||||
chatPermissionReplyId('req-1', 'once'),
|
||||
isNot(chatPermissionReplyId('req-1', 'always')),
|
||||
);
|
||||
final gate = ChatActionGate();
|
||||
final id = chatPermissionReplyId('req-1', 'once');
|
||||
expect(gate.start(id), isTrue);
|
||||
expect(gate.start(id), isFalse);
|
||||
gate.release(id);
|
||||
expect(gate.start(id), isTrue);
|
||||
});
|
||||
|
||||
testWidgets('a pending approval renders native Material controls', (
|
||||
tester,
|
||||
) async {
|
||||
final decisions = <String>[];
|
||||
final card = chatPermissionCard(permission(), '')!;
|
||||
await tester.pumpWidget(
|
||||
scrollHost(
|
||||
ChatPermissionCard(
|
||||
card: card,
|
||||
onDecision: (value) async {
|
||||
decisions.add(value);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(find.text('Approve bash'), findsOneWidget);
|
||||
expect(find.text('Waiting for your response'), findsOneWidget);
|
||||
expect(find.text('RISK REVIEW'), findsOneWidget);
|
||||
expect(find.text('This deletes the build output.'), findsOneWidget);
|
||||
expect(find.text('Allow once'), findsOneWidget);
|
||||
expect(find.text('Always allow'), findsOneWidget);
|
||||
expect(find.text('Reject'), findsOneWidget);
|
||||
expect(find.text('Permission request · tool'), findsNothing);
|
||||
|
||||
await tester.tap(find.text('Allow once'));
|
||||
await tester.pump();
|
||||
expect(decisions, ['once']);
|
||||
});
|
||||
|
||||
testWidgets('Show full request expands to every recorded resource line', (
|
||||
tester,
|
||||
) async {
|
||||
final card = chatPermissionCard(
|
||||
permission(
|
||||
resources: const [
|
||||
' one',
|
||||
'two',
|
||||
'three',
|
||||
'four',
|
||||
'five',
|
||||
'six',
|
||||
'seven',
|
||||
],
|
||||
),
|
||||
'',
|
||||
)!;
|
||||
await tester.pumpWidget(
|
||||
scrollHost(ChatPermissionCard(card: card, onDecision: (_) async {})),
|
||||
);
|
||||
expect(find.text(' one'), findsNothing);
|
||||
await tester.tap(find.text('Show full request'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text(card.resources.join('\n')), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('320px at 2x in dark Cupertino keeps the card native and '
|
||||
'readable', (tester) async {
|
||||
tester.view.physicalSize = const Size(640, 1400);
|
||||
tester.view.devicePixelRatio = 2;
|
||||
tester.platformDispatcher.textScaleFactorTestValue = 2;
|
||||
tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
|
||||
addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue);
|
||||
|
||||
final card = chatPermissionCard(
|
||||
permission(
|
||||
action: 'a very long tool name that has to wrap at twice the text size',
|
||||
resources: const [
|
||||
'a long resource line that wraps instead of clipping any words at all',
|
||||
],
|
||||
),
|
||||
'',
|
||||
)!;
|
||||
await tester.pumpWidget(
|
||||
cupertinoHost(ChatPermissionCard(card: card, onDecision: (_) async {})),
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
expect(find.text('Allow once'), findsOneWidget);
|
||||
expect(find.byType(Material), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('a pushed chat_permission renders, sends the recorded reply, '
|
||||
'and a second tap sends once', (tester) async {
|
||||
final gateway = FakeChatGateway();
|
||||
addTearDown(gateway.close);
|
||||
gateway.history = (_) async => chatPage(const []);
|
||||
final held = Completer<JsonMap>();
|
||||
gateway.reply = (_) => held.future;
|
||||
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
gateway.emitRaw({
|
||||
'type': 'chat_permission',
|
||||
'chat_permission': permission(),
|
||||
});
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Approve bash'), findsOneWidget);
|
||||
await tester.tap(find.text('Allow once'));
|
||||
await tester.tap(find.text('Allow once'));
|
||||
await tester.pump();
|
||||
|
||||
final replies = gateway.calls.where((call) => call.type == 'chat_reply');
|
||||
expect(replies, hasLength(1));
|
||||
expect(replies.single.fields, {
|
||||
'chat_reply': {
|
||||
'session_id': 's',
|
||||
'request_id': 'req-1',
|
||||
'decision': 'once',
|
||||
'client': 'Web',
|
||||
},
|
||||
});
|
||||
expect(find.text('Allowed once'), findsOneWidget);
|
||||
expect(find.text('Waiting for the agent to continue…'), findsOneWidget);
|
||||
held.complete(const {});
|
||||
await tester.pumpAndSettle();
|
||||
});
|
||||
|
||||
testWidgets('a refused reply keeps the card pending and shows the server '
|
||||
'reason', (tester) async {
|
||||
final gateway = FakeChatGateway();
|
||||
addTearDown(gateway.close);
|
||||
gateway.history = (_) async => chatPage(const []);
|
||||
gateway.reply = (_) async => throw StateError('request expired');
|
||||
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
gateway.emitRaw({
|
||||
'type': 'chat_permission',
|
||||
'chat_permission': permission(),
|
||||
});
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.text('Reject'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.textContaining('request expired'), findsOneWidget);
|
||||
expect(find.text('Approve bash'), findsOneWidget);
|
||||
expect(find.text('Allow once'), findsOneWidget);
|
||||
expect(find.text('Reject'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('a server resolution clears the controls and shows the recorded '
|
||||
'decision', (tester) async {
|
||||
final gateway = FakeChatGateway();
|
||||
addTearDown(gateway.close);
|
||||
gateway.history = (_) async => chatPage(const []);
|
||||
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
gateway.emitRaw({
|
||||
'type': 'chat_permission',
|
||||
'chat_permission': permission(),
|
||||
});
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Allow once'), findsOneWidget);
|
||||
|
||||
gateway.emitRaw({
|
||||
'type': 'chat_permission',
|
||||
'chat_permission': permission(
|
||||
resolved: true,
|
||||
decision: 'once',
|
||||
message: 'Another device allowed once.',
|
||||
),
|
||||
});
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Allowed once'), findsOneWidget);
|
||||
expect(find.text('Another device allowed once.'), findsOneWidget);
|
||||
expect(find.text('Allow once'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('a turn waiting on a pending card hides the running indicator '
|
||||
'but keeps Stop', (tester) async {
|
||||
final gateway = FakeChatGateway();
|
||||
addTearDown(gateway.close);
|
||||
gateway.history = (_) async => chatPage(const []);
|
||||
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
gateway.emitRaw({
|
||||
'type': 'chat_permission',
|
||||
'chat_permission': permission(),
|
||||
});
|
||||
gateway.emitEvent(chatStepFrame('running'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Approve bash'), findsOneWidget);
|
||||
expect(find.text('Assistant is responding…'), findsNothing);
|
||||
expect(find.text('Stop'), findsOneWidget);
|
||||
|
||||
gateway.emitRaw({
|
||||
'type': 'chat_permission',
|
||||
'chat_permission': permission(resolved: true, decision: 'once'),
|
||||
});
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Assistant is responding…'), findsOneWidget);
|
||||
expect(find.text('Stop'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('consecutive Material cards stay separate surfaces', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = FakeChatGateway();
|
||||
addTearDown(gateway.close);
|
||||
gateway.history = (_) async => chatPage(const []);
|
||||
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
gateway.emitRaw({
|
||||
'type': 'chat_permission',
|
||||
'chat_permission': permission(id: 'req-1'),
|
||||
});
|
||||
gateway.emitRaw({
|
||||
'type': 'chat_permission',
|
||||
'chat_permission': permission(id: 'req-2', action: 'python'),
|
||||
});
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final first = tester.getRect(
|
||||
find
|
||||
.descendant(of: find.byType(Card).at(0), matching: find.byType(Material))
|
||||
.first,
|
||||
);
|
||||
final second = tester.getRect(
|
||||
find
|
||||
.descendant(of: find.byType(Card).at(1), matching: find.byType(Material))
|
||||
.first,
|
||||
);
|
||||
expect(second.top - first.bottom, greaterThanOrEqualTo(12));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_question_card_model.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_question_validation.dart';
|
||||
|
||||
void main() {
|
||||
test('field visibility keeps false and zero as answers', () {
|
||||
final fields = [
|
||||
{'key': 'enabled', 'type': 'boolean'},
|
||||
{
|
||||
'key': 'count',
|
||||
'type': 'integer',
|
||||
'when': [
|
||||
{'key': 'enabled', 'op': 'eq', 'value': true},
|
||||
],
|
||||
},
|
||||
];
|
||||
final hidden = {'enabled': false, 'count': 0};
|
||||
expect(chatFormFieldVisible(fields[1], hidden), isFalse);
|
||||
expect(chatFormAnswerError(fields, hidden), '');
|
||||
expect(chatVisibleFormAnswers(fields, hidden), {'enabled': false});
|
||||
});
|
||||
|
||||
test('required free text and numeric bounds use the web wording', () {
|
||||
final fields = [
|
||||
{'key': 'note', 'title': 'Notes', 'type': 'string', 'required': true},
|
||||
{'key': 'count', 'type': 'integer', 'minimum': 1, 'maximum': 5},
|
||||
];
|
||||
expect(
|
||||
chatFormAnswerError(fields, {'count': 2}),
|
||||
'Answer Notes before sending.',
|
||||
);
|
||||
expect(
|
||||
chatFormAnswerError(fields, {'note': 'ok', 'count': 1.5}),
|
||||
'count needs a valid integer.',
|
||||
);
|
||||
expect(
|
||||
chatFormAnswerError(fields, {'note': 'ok', 'count': 6}),
|
||||
'count must be at most 5.',
|
||||
);
|
||||
expect(
|
||||
chatFormAnswerError(fields, {'note': 'ok', 'count': 0}),
|
||||
'count must be at least 1.',
|
||||
);
|
||||
expect(chatFormAnswerError(fields, {'note': 'ok', 'count': 5}), '');
|
||||
});
|
||||
|
||||
test('integer input becomes an int, including decimal and exponent forms', () {
|
||||
final field = <String, dynamic>{'key': 'count', 'type': 'integer'};
|
||||
expect(chatFormFieldValue(field, '1.0'), isA<int>());
|
||||
expect(chatFormFieldValue(field, '1.0'), 1);
|
||||
expect(chatFormFieldValue(field, '1e3'), 1000);
|
||||
expect(chatFormFieldValue(field, '1.5'), 1.5);
|
||||
expect((chatFormFieldValue(field, 'nope')! as num).isNaN, isTrue);
|
||||
expect(chatFormFieldValue({'type': 'number'}, '1e3'), 1000.0);
|
||||
|
||||
final fields = [field];
|
||||
expect(
|
||||
chatVisibleFormAnswers(
|
||||
fields,
|
||||
{'count': chatFormFieldValue(field, '1.0')},
|
||||
),
|
||||
{'count': 1},
|
||||
);
|
||||
expect(
|
||||
chatFormAnswerError(fields, {'count': chatFormFieldValue(field, '1.0')}),
|
||||
'',
|
||||
);
|
||||
});
|
||||
|
||||
test('a malformed pattern is reported with the documented wording', () {
|
||||
final fields = [
|
||||
{
|
||||
'key': 'code',
|
||||
'title': 'Code',
|
||||
'type': 'string',
|
||||
'pattern': r'^[a-z]+$',
|
||||
},
|
||||
];
|
||||
expect(chatFormAnswerError(fields, {'code': 'abc'}), '');
|
||||
expect(
|
||||
chatFormAnswerError(fields, {'code': 'ABC'}),
|
||||
'Code does not match the required format.',
|
||||
);
|
||||
// An unparseable server pattern constrains nothing, like a browser ignoring
|
||||
// an invalid `pattern` attribute.
|
||||
expect(
|
||||
chatFormAnswerError([
|
||||
{'key': 'code', 'type': 'string', 'pattern': '('},
|
||||
], {'code': 'anything'}),
|
||||
'',
|
||||
);
|
||||
});
|
||||
|
||||
test('email, URL and date formats are checked like native inputs', () {
|
||||
final fields = [
|
||||
{'key': 'mail', 'title': 'Email', 'type': 'string', 'format': 'email'},
|
||||
{'key': 'site', 'title': 'Site', 'type': 'string', 'format': 'uri'},
|
||||
{'key': 'day', 'title': 'Day', 'type': 'string', 'format': 'date'},
|
||||
];
|
||||
expect(chatFormAnswerError(fields, {'mail': 'a@b.co'}), '');
|
||||
expect(
|
||||
chatFormAnswerError(fields, {
|
||||
'mail': 'not-a-mail',
|
||||
'site': 'https://example.com',
|
||||
'day': '2026-10-22',
|
||||
}),
|
||||
'Email is not a valid email address.',
|
||||
);
|
||||
expect(
|
||||
chatFormAnswerError(fields, {
|
||||
'mail': 'a@b.co',
|
||||
'site': 'exa mple',
|
||||
'day': '2026-10-22',
|
||||
}),
|
||||
'Site is not a valid URL.',
|
||||
);
|
||||
expect(
|
||||
chatFormAnswerError(fields, {
|
||||
'mail': 'a@b.co',
|
||||
'site': 'https://example.com',
|
||||
'day': '2026-02-31',
|
||||
}),
|
||||
'Day is not a valid date.',
|
||||
);
|
||||
expect(
|
||||
chatFormAnswerError(fields, {
|
||||
'mail': 'a@b.co',
|
||||
'site': 'https://example.com',
|
||||
'day': '2026-10-22',
|
||||
}),
|
||||
'',
|
||||
);
|
||||
});
|
||||
|
||||
test('options with an empty recorded value are skipped', () {
|
||||
final field = <String, dynamic>{
|
||||
'key': 'choice',
|
||||
'options': [
|
||||
{'value': '', 'label': 'Blank'},
|
||||
{'value': 'red', 'label': 'Red'},
|
||||
{'label': 'Blue'},
|
||||
],
|
||||
};
|
||||
expect(chatQuestionOptions(field).map(chatQuestionOptionValue), [
|
||||
'red',
|
||||
'Blue',
|
||||
]);
|
||||
expect(chatQuestionFieldOptionValues(field), ['red', 'Blue']);
|
||||
});
|
||||
|
||||
test('external URLs require an absolute HTTP(S) URL with a host', () {
|
||||
expect(chatExternalUrlIsSafe('https://example.com/form'), isTrue);
|
||||
expect(chatExternalUrlIsSafe('http://example.com'), isTrue);
|
||||
expect(chatExternalUrlIsSafe('http://'), isFalse);
|
||||
expect(chatExternalUrlIsSafe('http://exa mple.com'), isFalse);
|
||||
expect(chatExternalUrlIsSafe('ftp://example.com'), isFalse);
|
||||
expect(chatExternalUrlIsSafe('not a url'), isFalse);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,545 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_question_card.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_question_card_model.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_question_validation.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
|
||||
|
||||
import 'chat_thread_fixtures.dart';
|
||||
|
||||
Widget materialHost(Widget child) => MaterialApp(
|
||||
theme: ThemeData(platform: TargetPlatform.android),
|
||||
home: Scaffold(body: child),
|
||||
);
|
||||
|
||||
Widget scrollHost(Widget child) =>
|
||||
materialHost(SingleChildScrollView(child: child));
|
||||
|
||||
Widget cupertinoHost(Widget child) => CupertinoApp(
|
||||
theme: const CupertinoThemeData(brightness: Brightness.dark),
|
||||
home: CupertinoPageScaffold(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: child,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
List<JsonMap> fields() => [
|
||||
{
|
||||
'key': 'colour',
|
||||
'title': 'Colour',
|
||||
'type': 'string',
|
||||
'required': true,
|
||||
'options': [
|
||||
{'value': 'red', 'label': 'Red'},
|
||||
{'value': 'blue', 'label': 'Blue'},
|
||||
],
|
||||
},
|
||||
{
|
||||
'key': 'extras',
|
||||
'title': 'Extras',
|
||||
'type': 'multiselect',
|
||||
'options': [
|
||||
{'value': 'extra-a', 'label': 'Extra A'},
|
||||
{'value': 'extra-b', 'label': 'Extra B'},
|
||||
],
|
||||
},
|
||||
{
|
||||
'key': 'note',
|
||||
'title': 'Notes',
|
||||
'type': 'string',
|
||||
'required': true,
|
||||
'min_length': 3,
|
||||
},
|
||||
];
|
||||
|
||||
JsonMap question({
|
||||
bool resolved = false,
|
||||
bool cancelled = false,
|
||||
Map<String, dynamic>? answers,
|
||||
}) => {
|
||||
'id': 'form-1',
|
||||
'session_id': 's',
|
||||
'kind': 'question',
|
||||
'title': 'A demo question',
|
||||
'fields': fields(),
|
||||
'actions': ['accept', 'decline', 'cancel'],
|
||||
if (resolved) 'resolved': true,
|
||||
if (cancelled) 'cancelled': true,
|
||||
'answers': ?answers,
|
||||
};
|
||||
|
||||
void main() {
|
||||
test('field visibility keeps false and zero as answers', () {
|
||||
final fields = [
|
||||
{'key': 'enabled', 'type': 'boolean'},
|
||||
{
|
||||
'key': 'count',
|
||||
'type': 'integer',
|
||||
'when': [
|
||||
{'key': 'enabled', 'op': 'eq', 'value': true},
|
||||
],
|
||||
},
|
||||
];
|
||||
final hidden = {'enabled': false, 'count': 0};
|
||||
expect(chatFormFieldVisible(fields[1], hidden), isFalse);
|
||||
expect(chatFormAnswerError(fields, hidden), '');
|
||||
expect(chatVisibleFormAnswers(fields, hidden), {'enabled': false});
|
||||
});
|
||||
|
||||
test('required free text and numeric bounds use the web wording', () {
|
||||
final fields = [
|
||||
{'key': 'note', 'title': 'Notes', 'type': 'string', 'required': true},
|
||||
{'key': 'count', 'type': 'integer', 'minimum': 1, 'maximum': 5},
|
||||
];
|
||||
expect(
|
||||
chatFormAnswerError(fields, {'count': 2}),
|
||||
'Answer Notes before sending.',
|
||||
);
|
||||
expect(
|
||||
chatFormAnswerError(fields, {'note': 'ok', 'count': 1.5}),
|
||||
'count needs a valid integer.',
|
||||
);
|
||||
expect(
|
||||
chatFormAnswerError(fields, {'note': 'ok', 'count': 6}),
|
||||
'count must be at most 5.',
|
||||
);
|
||||
expect(
|
||||
chatFormAnswerError(fields, {'note': 'ok', 'count': 0}),
|
||||
'count must be at least 1.',
|
||||
);
|
||||
expect(chatFormAnswerError(fields, {'note': 'ok', 'count': 5}), '');
|
||||
});
|
||||
|
||||
testWidgets('a pending question answers single, multi and required free text '
|
||||
'exactly as recorded', (tester) async {
|
||||
tester.view.physicalSize = const Size(800, 1200);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
Map<String, dynamic>? sent;
|
||||
await tester.pumpWidget(
|
||||
scrollHost(
|
||||
ChatQuestionCard(
|
||||
form: question(),
|
||||
onSubmit: (answers, action) async {
|
||||
sent = answers;
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(find.text('A demo question'), findsOneWidget);
|
||||
expect(find.text(chatQuestionWaiting), findsOneWidget);
|
||||
|
||||
await tester.tap(find.text('Red'));
|
||||
await tester.pump();
|
||||
await tester.tap(find.text('Extra A'));
|
||||
await tester.pump();
|
||||
await tester.tap(find.text('Send answer'));
|
||||
await tester.pump();
|
||||
expect(find.text('Answer Notes before sending.'), findsOneWidget);
|
||||
expect(sent, isNull);
|
||||
|
||||
await tester.enterText(
|
||||
find.byKey(const ValueKey<String>('chat-question-input-note')),
|
||||
' ready ',
|
||||
);
|
||||
await tester.pump();
|
||||
await tester.tap(find.text('Send answer'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(sent, {
|
||||
'colour': 'red',
|
||||
'extras': ['extra-a'],
|
||||
'note': ' ready ',
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('a single-select option replaces the previous choice and a '
|
||||
'multi-select toggles', (tester) async {
|
||||
Map<String, dynamic>? sent;
|
||||
await tester.pumpWidget(
|
||||
scrollHost(
|
||||
ChatQuestionCard(
|
||||
form: question(),
|
||||
onSubmit: (answers, action) async {
|
||||
sent = answers;
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.tap(find.text('Red'));
|
||||
await tester.pump();
|
||||
await tester.tap(find.text('Blue'));
|
||||
await tester.pump();
|
||||
await tester.tap(find.text('Extra A'));
|
||||
await tester.pump();
|
||||
await tester.tap(find.text('Extra B'));
|
||||
await tester.pump();
|
||||
await tester.tap(find.text('Extra A'));
|
||||
await tester.pump();
|
||||
await tester.enterText(
|
||||
find.byKey(const ValueKey<String>('chat-question-input-note')),
|
||||
'done',
|
||||
);
|
||||
await tester.tap(find.text('Send answer'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(sent, {
|
||||
'colour': 'blue',
|
||||
'extras': ['extra-b'],
|
||||
'note': 'done',
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('answered questions show the recorded answer read-only', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
scrollHost(
|
||||
ChatQuestionCard(
|
||||
form: question(
|
||||
resolved: true,
|
||||
answers: {
|
||||
'colour': 'red',
|
||||
'extras': ['extra-b'],
|
||||
'note': 'Recorded note',
|
||||
},
|
||||
),
|
||||
onSubmit: (_, _) async {},
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(find.text(chatQuestionAnswered), findsOneWidget);
|
||||
expect(find.text('Red'), findsOneWidget);
|
||||
expect(find.text('Extra B'), findsOneWidget);
|
||||
expect(find.text('Recorded note'), findsOneWidget);
|
||||
expect(find.text('Send answer'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('an expired question keeps recorded answers and offers no '
|
||||
'controls', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
scrollHost(
|
||||
ChatQuestionCard(
|
||||
form: question(cancelled: true, answers: {'colour': 'red'}),
|
||||
onSubmit: (_, _) async {},
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(find.text(chatQuestionExpired), findsOneWidget);
|
||||
expect(find.text('Red'), findsOneWidget);
|
||||
expect(find.text('Send answer'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('Cupertino field labels stay subordinate to the card title', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
cupertinoHost(
|
||||
ChatQuestionCard(form: question(), onSubmit: (_, _) async {}),
|
||||
),
|
||||
);
|
||||
final title = tester.widget<Text>(find.text('A demo question'));
|
||||
final label = tester.widget<Text>(find.text('Colour'));
|
||||
expect(label.style!.fontSize, lessThan(title.style!.fontSize!));
|
||||
});
|
||||
|
||||
testWidgets('a free-text input carries its visual label in semantics', (
|
||||
tester,
|
||||
) async {
|
||||
final semantics = tester.ensureSemantics();
|
||||
await tester.pumpWidget(
|
||||
scrollHost(
|
||||
ChatQuestionCard(form: question(), onSubmit: (_, _) async {}),
|
||||
),
|
||||
);
|
||||
final node = tester.getSemantics(
|
||||
find.byKey(const ValueKey<String>('chat-question-input-note')),
|
||||
);
|
||||
expect(node.label, contains('Notes'));
|
||||
semantics.dispose();
|
||||
});
|
||||
|
||||
testWidgets('integer input sends an int, never a decimal double', (
|
||||
tester,
|
||||
) async {
|
||||
Map<String, dynamic>? sent;
|
||||
await tester.pumpWidget(
|
||||
scrollHost(
|
||||
ChatQuestionCard(
|
||||
form: {
|
||||
'id': 'form-int',
|
||||
'title': 'How many?',
|
||||
'actions': ['accept'],
|
||||
'fields': [
|
||||
{'key': 'count', 'title': 'Count', 'type': 'integer'},
|
||||
],
|
||||
},
|
||||
onSubmit: (answers, action) async {
|
||||
sent = answers;
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.enterText(
|
||||
find.byKey(const ValueKey<String>('chat-question-input-count')),
|
||||
'1.0',
|
||||
);
|
||||
await tester.pump();
|
||||
await tester.tap(find.text('Send answer'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(sent, {'count': 1});
|
||||
expect(sent!['count'], isA<int>());
|
||||
});
|
||||
|
||||
testWidgets('decline and cancel send their recorded actions with no answers', (
|
||||
tester,
|
||||
) async {
|
||||
final actions = <String>[];
|
||||
final answers = <Map<String, dynamic>>[];
|
||||
await tester.pumpWidget(
|
||||
scrollHost(
|
||||
ChatQuestionCard(
|
||||
form: question(),
|
||||
onSubmit: (sent, action) async {
|
||||
actions.add(action);
|
||||
answers.add(sent);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.tap(find.text('Decline'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Cancel question'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(actions, ['decline', 'cancel']);
|
||||
expect(answers, [<String, dynamic>{}, <String, dynamic>{}]);
|
||||
});
|
||||
|
||||
testWidgets('an all-external form confirms completion without field answers', (
|
||||
tester,
|
||||
) async {
|
||||
Map<String, dynamic>? sent;
|
||||
String? action;
|
||||
await tester.pumpWidget(
|
||||
scrollHost(
|
||||
ChatQuestionCard(
|
||||
form: {
|
||||
'id': 'form-external',
|
||||
'title': 'Open the form',
|
||||
'actions': ['accept'],
|
||||
'fields': [
|
||||
{
|
||||
'key': 'form',
|
||||
'title': 'External form',
|
||||
'type': 'external',
|
||||
'url': 'https://example.com/complete',
|
||||
},
|
||||
],
|
||||
},
|
||||
onSubmit: (answers, next) async {
|
||||
sent = answers;
|
||||
action = next;
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(find.text('Confirm completion'), findsOneWidget);
|
||||
expect(find.text('https://example.com/complete'), findsOneWidget);
|
||||
await tester.tap(find.text('Confirm completion'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(sent, isEmpty);
|
||||
expect(action, 'accept');
|
||||
});
|
||||
|
||||
testWidgets('an unsupported external URL shows the web alert wording', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
scrollHost(
|
||||
ChatQuestionCard(
|
||||
form: {
|
||||
'id': 'form-external',
|
||||
'title': 'Open the form',
|
||||
'actions': ['accept'],
|
||||
'fields': [
|
||||
{'key': 'form', 'type': 'external', 'url': 'http://'},
|
||||
],
|
||||
},
|
||||
onSubmit: (_, _) async {},
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(
|
||||
find.text('This form has an unsupported external URL.'),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('a resolved question without answers says none was recorded', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
scrollHost(
|
||||
ChatQuestionCard(
|
||||
form: question(resolved: true, answers: const {}),
|
||||
onSubmit: (_, _) async {},
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(find.text('No answer was recorded.'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('recorded booleans use Yes/No and blank titles fall back to the '
|
||||
'key', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
scrollHost(
|
||||
ChatQuestionCard(
|
||||
form: {
|
||||
'id': 'form-recorded',
|
||||
'title': 'Recorded',
|
||||
'resolved': true,
|
||||
'answers': {'enabled': true, 'extra': 'kept'},
|
||||
'fields': [
|
||||
{'key': 'enabled', 'title': '', 'description': '', 'type': 'boolean'},
|
||||
],
|
||||
},
|
||||
onSubmit: (_, _) async {},
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(find.text('enabled'), findsOneWidget);
|
||||
expect(find.text('Yes'), findsOneWidget);
|
||||
expect(find.text('true'), findsNothing);
|
||||
expect(find.text('extra'), findsOneWidget);
|
||||
expect(find.text('kept'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('320px at 2x in dark Cupertino keeps native controls', (
|
||||
tester,
|
||||
) async {
|
||||
tester.view.physicalSize = const Size(640, 1600);
|
||||
tester.view.devicePixelRatio = 2;
|
||||
tester.platformDispatcher.textScaleFactorTestValue = 2;
|
||||
tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
|
||||
addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue);
|
||||
|
||||
await tester.pumpWidget(
|
||||
cupertinoHost(
|
||||
ChatQuestionCard(form: question(), onSubmit: (_, _) async {}),
|
||||
),
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
expect(find.text('A demo question'), findsOneWidget);
|
||||
expect(find.text('Send answer'), findsOneWidget);
|
||||
expect(find.byType(Material), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('a pushed form renders and sends one exact chat_answer', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = FakeChatGateway();
|
||||
addTearDown(gateway.close);
|
||||
gateway.history = (_) async => chatPage(const []);
|
||||
final held = Completer<JsonMap>();
|
||||
gateway.answer = (_) => held.future;
|
||||
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
gateway.emitEvent({'session_id': 's', 'kind': 'form', 'form': question()});
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('A demo question'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.text('Red'));
|
||||
await tester.pump();
|
||||
await tester.enterText(
|
||||
find.byKey(const ValueKey<String>('chat-question-input-note')),
|
||||
'sent once',
|
||||
);
|
||||
await tester.tap(find.text('Send answer'));
|
||||
await tester.tap(find.text('Send answer'));
|
||||
await tester.pump();
|
||||
|
||||
final answers = gateway.calls.where((call) => call.type == 'chat_answer');
|
||||
expect(answers, hasLength(1));
|
||||
expect(answers.single.fields, {
|
||||
'chat_answer': {
|
||||
'session_id': 's',
|
||||
'form_id': 'form-1',
|
||||
'answers': {'colour': 'red', 'note': 'sent once'},
|
||||
'action': 'accept',
|
||||
},
|
||||
});
|
||||
held.complete(const {});
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text(chatQuestionAnswered), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('a refused question keeps the card open with the server reason', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = FakeChatGateway();
|
||||
addTearDown(gateway.close);
|
||||
gateway.history = (_) async => chatPage(const []);
|
||||
gateway.answer = (_) async => throw StateError('form already closed');
|
||||
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
gateway.emitEvent({'session_id': 's', 'kind': 'form', 'form': question()});
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Red'));
|
||||
await tester.pump();
|
||||
await tester.enterText(
|
||||
find.byKey(const ValueKey<String>('chat-question-input-note')),
|
||||
'retry me',
|
||||
);
|
||||
await tester.tap(find.text('Send answer'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.textContaining('form already closed'), findsOneWidget);
|
||||
expect(find.text('Send answer'), findsOneWidget);
|
||||
expect(find.text(chatQuestionWaiting), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('unknown transcript parts remain available beside cards', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = FakeChatGateway();
|
||||
addTearDown(gateway.close);
|
||||
gateway.history = (_) async => chatPage([
|
||||
chatMessage(
|
||||
'a1',
|
||||
'assistant',
|
||||
parts: [
|
||||
{'type': 'text', 'text': 'Recorded answer with a fallback part.'},
|
||||
{'type': 'future-content', 'future_value': 'still preserved'},
|
||||
],
|
||||
),
|
||||
]);
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Recorded answer with a fallback part.'), findsOneWidget);
|
||||
await tester.tap(find.text('Unrecognised part: future-content'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.textContaining('still preserved'), findsOneWidget);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_thread_controller.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_thread_cards.dart';
|
||||
|
||||
import 'chat_thread_fixtures.dart';
|
||||
|
||||
JsonMap permission(String id, {bool resolved = false}) => {
|
||||
'session_id': 's',
|
||||
'request_id': id,
|
||||
'action': 'bash',
|
||||
'resources': const ['command: ls'],
|
||||
'message': '',
|
||||
'resolved': resolved,
|
||||
if (resolved) 'decision': 'once',
|
||||
};
|
||||
|
||||
JsonMap form(String id, {bool resolved = false}) => {
|
||||
'id': id,
|
||||
'session_id': 's',
|
||||
'title': 'Question',
|
||||
'fields': const [],
|
||||
'actions': const ['accept'],
|
||||
'resolved': resolved,
|
||||
if (resolved) 'answers': const {'note': 'recorded'},
|
||||
};
|
||||
|
||||
void main() {
|
||||
test('settled approvals are bounded while the pending one is kept', () async {
|
||||
final gateway = FakeChatGateway();
|
||||
addTearDown(gateway.close);
|
||||
final controller = ChatThreadController(gateway, 's');
|
||||
addTearDown(controller.dispose);
|
||||
|
||||
for (var index = 0; index < ChatThreadCards.settledLimit + 5; index++) {
|
||||
gateway.emitRaw({
|
||||
'type': 'chat_permission',
|
||||
'chat_permission': permission('req-$index', resolved: true),
|
||||
});
|
||||
}
|
||||
gateway.emitRaw({
|
||||
'type': 'chat_permission',
|
||||
'chat_permission': permission('req-pending'),
|
||||
});
|
||||
await pumpEventQueue();
|
||||
|
||||
expect(controller.permissionFrames, hasLength(ChatThreadCards.settledLimit + 1));
|
||||
expect(
|
||||
controller.permissionFrames.first['request_id'],
|
||||
'req-5',
|
||||
);
|
||||
expect(
|
||||
controller.permissionFrames.last['request_id'],
|
||||
'req-pending',
|
||||
);
|
||||
});
|
||||
|
||||
test('settled forms are bounded while the pending one is kept', () async {
|
||||
final gateway = FakeChatGateway();
|
||||
addTearDown(gateway.close);
|
||||
final controller = ChatThreadController(gateway, 's');
|
||||
addTearDown(controller.dispose);
|
||||
|
||||
for (var index = 0; index < ChatThreadCards.settledLimit + 5; index++) {
|
||||
gateway.emitEvent({
|
||||
'session_id': 's',
|
||||
'kind': 'form',
|
||||
'form': form('form-$index', resolved: true),
|
||||
});
|
||||
}
|
||||
gateway.emitEvent({
|
||||
'session_id': 's',
|
||||
'kind': 'form',
|
||||
'form': form('form-pending'),
|
||||
});
|
||||
await pumpEventQueue();
|
||||
|
||||
expect(controller.questionForms, hasLength(ChatThreadCards.settledLimit + 1));
|
||||
expect(controller.questionForms.first['id'], 'form-5');
|
||||
expect(controller.questionForms.last['id'], 'form-pending');
|
||||
});
|
||||
}
|
||||
@@ -9,6 +9,8 @@ class FakeChatGateway implements ApiGateway {
|
||||
final _frames = StreamController<JsonMap>.broadcast();
|
||||
Future<JsonMap> Function(JsonMap fields)? history;
|
||||
Future<JsonMap> Function()? subscribe;
|
||||
Future<JsonMap> Function(JsonMap fields)? reply;
|
||||
Future<JsonMap> Function(JsonMap fields)? answer;
|
||||
void Function()? onSubscribe;
|
||||
|
||||
@override
|
||||
@@ -23,6 +25,12 @@ class FakeChatGateway implements ApiGateway {
|
||||
historyRequests.add(completer);
|
||||
if (history != null) return history!(fields);
|
||||
return completer.future;
|
||||
case 'chat_reply':
|
||||
if (reply != null) return reply!(fields);
|
||||
return <String, dynamic>{};
|
||||
case 'chat_answer':
|
||||
if (answer != null) return answer!(fields);
|
||||
return <String, dynamic>{};
|
||||
}
|
||||
return <String, dynamic>{};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/graph/viewport/graph_expanded_view.dart';
|
||||
import 'package:pipelines_app/features/graph/viewport/graph_viewport_math.dart';
|
||||
import 'package:pipelines_app/features/graph/widgets/definition_graph_view.dart';
|
||||
import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart';
|
||||
|
||||
import '../domain/graph_fixtures.dart';
|
||||
|
||||
Widget _materialHost({
|
||||
required JsonMap graph,
|
||||
required String? selected,
|
||||
required ValueChanged<String> onSelected,
|
||||
}) => MaterialApp(
|
||||
home: Scaffold(
|
||||
body: DefinitionGraphView(
|
||||
graph: graph,
|
||||
selectedStage: selected,
|
||||
onSelected: onSelected,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
Finder _node(String key) => find.byWidgetPredicate(
|
||||
(widget) => widget is GraphStageNode && widget.node.key == key,
|
||||
);
|
||||
|
||||
Finder _inExpanded(Finder finder) =>
|
||||
find.descendant(of: find.byType(GraphExpandedView), matching: finder);
|
||||
|
||||
Future<void> _settle(WidgetTester tester) async {
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
TransformationController _inlineTransform(WidgetTester tester) => tester
|
||||
.widget<InteractiveViewer>(find.byType(InteractiveViewer))
|
||||
.transformationController!;
|
||||
|
||||
void main() {
|
||||
testWidgets(
|
||||
'expanded fits the larger canvas and returns to the inline state',
|
||||
(tester) async {
|
||||
tester.view.physicalSize = const Size(900, 700);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
final picked = <String>[];
|
||||
await tester.pumpWidget(
|
||||
_materialHost(
|
||||
graph: linearGraph(),
|
||||
selected: 'build',
|
||||
onSelected: picked.add,
|
||||
),
|
||||
);
|
||||
await _settle(tester);
|
||||
|
||||
final inline = _inlineTransform(tester);
|
||||
final inlineMatrix = Matrix4.copy(inline.value);
|
||||
final inlineRect = tester.getRect(_node('build'));
|
||||
|
||||
await tester.tap(find.byKey(const Key('graph-expand')));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.byType(GraphExpandedView), findsOneWidget);
|
||||
expect(find.text(definitionGraphExpandedTitle), findsOneWidget);
|
||||
final expanded = _inExpanded(find.byType(InteractiveViewer));
|
||||
expect(expanded, findsOneWidget);
|
||||
final expandedController = tester
|
||||
.widget<InteractiveViewer>(expanded)
|
||||
.transformationController!;
|
||||
final expandedView = tester.widget<GraphExpandedView>(
|
||||
find.byType(GraphExpandedView),
|
||||
);
|
||||
final canvas = tester.getRect(
|
||||
_inExpanded(find.byKey(const Key('graph-viewport'))),
|
||||
);
|
||||
// The web re-fits when its panel expands: the larger canvas fits the
|
||||
// whole graph instead of keeping the small inline scale.
|
||||
expect(
|
||||
expandedController.value.getMaxScaleOnAxis(),
|
||||
closeTo(graphFitScale(canvas.size, expandedView.contentSize), 1e-9),
|
||||
);
|
||||
expect(
|
||||
canvas.contains(tester.getCenter(_inExpanded(_node('build')))),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
tester.widget<GraphStageNode>(_inExpanded(_node('build'))).selected,
|
||||
isTrue,
|
||||
);
|
||||
|
||||
// A tap in the larger canvas follows the same transform and updates the
|
||||
// presentation's own selection.
|
||||
await tester.tap(_inExpanded(_node('plan')));
|
||||
await tester.pump();
|
||||
expect(picked, ['plan']);
|
||||
expect(
|
||||
tester.widget<GraphStageNode>(_inExpanded(_node('plan'))).selected,
|
||||
isTrue,
|
||||
);
|
||||
|
||||
await tester.tap(find.byKey(const Key('graph-expanded-close')));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.byType(GraphExpandedView), findsNothing);
|
||||
// The inline canvas was never changed: same selection, same place.
|
||||
expect(tester.widget<GraphStageNode>(_node('build')).selected, isTrue);
|
||||
expect(tester.getRect(_node('build')), inlineRect);
|
||||
expect(inline.value.storage, orderedEquals(inlineMatrix.storage));
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('a rotation re-clamps the expanded transform into the new box', (
|
||||
tester,
|
||||
) async {
|
||||
tester.view.physicalSize = const Size(900, 700);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
await tester.pumpWidget(
|
||||
_materialHost(
|
||||
graph: linearGraph(),
|
||||
selected: 'build',
|
||||
onSelected: (_) {},
|
||||
),
|
||||
);
|
||||
await _settle(tester);
|
||||
await tester.tap(find.byKey(const Key('graph-expand')));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final expanded = _inExpanded(find.byType(InteractiveViewer));
|
||||
final controller = tester
|
||||
.widget<InteractiveViewer>(expanded)
|
||||
.transformationController!;
|
||||
final canvas = find.descendant(
|
||||
of: find.byType(GraphExpandedView),
|
||||
matching: find.byKey(const Key('graph-viewport')),
|
||||
);
|
||||
// Pan far enough that the wide canvas' clamp is the only limit.
|
||||
await tester.drag(canvas, const Offset(500, 0));
|
||||
await tester.pumpAndSettle();
|
||||
final wide = tester.getRect(canvas);
|
||||
final panned = controller.value.getTranslation().x;
|
||||
expect(panned, lessThanOrEqualTo(wide.width - graphMinVisible + 0.5));
|
||||
|
||||
// Rotating to a narrow box must keep the graph inside it, not leave the
|
||||
// reader's old place hanging outside until Fit is pressed.
|
||||
tester.view.physicalSize = const Size(320, 700);
|
||||
await tester.pumpAndSettle();
|
||||
await _settle(tester);
|
||||
final narrow = tester.getRect(canvas);
|
||||
expect(narrow.width, lessThan(wide.width));
|
||||
final clamped = controller.value.getTranslation().x;
|
||||
expect(
|
||||
clamped,
|
||||
lessThanOrEqualTo(narrow.width - graphMinVisible + 0.5),
|
||||
reason: 'a resize must re-clamp the existing transform',
|
||||
);
|
||||
expect(clamped, lessThan(panned));
|
||||
});
|
||||
|
||||
testWidgets('320px at 2x opens and closes on the dark Cupertino host', (
|
||||
tester,
|
||||
) async {
|
||||
tester.view.physicalSize = const Size(320, 700);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
final picked = <String>[];
|
||||
await tester.pumpWidget(
|
||||
CupertinoApp(
|
||||
theme: const CupertinoThemeData(brightness: Brightness.dark),
|
||||
home: CupertinoPageScaffold(
|
||||
child: Builder(
|
||||
builder: (context) => MediaQuery(
|
||||
data: MediaQuery.of(
|
||||
context,
|
||||
).copyWith(textScaler: const TextScaler.linear(2)),
|
||||
child: DefinitionGraphView(
|
||||
graph: linearGraph(),
|
||||
selectedStage: 'build',
|
||||
onSelected: picked.add,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await _settle(tester);
|
||||
final inline = _inlineTransform(tester);
|
||||
final inlineMatrix = Matrix4.copy(inline.value);
|
||||
|
||||
await tester.tap(find.byKey(const Key('graph-expand')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(GraphExpandedView), findsOneWidget);
|
||||
expect(_inExpanded(find.text(graphExpandedClose)), findsOneWidget);
|
||||
expect(
|
||||
tester.widget<GraphStageNode>(_inExpanded(_node('build'))).selected,
|
||||
isTrue,
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
|
||||
await tester.tap(find.byKey(const Key('graph-expanded-close')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(GraphExpandedView), findsNothing);
|
||||
expect(tester.widget<GraphStageNode>(_node('build')).selected, isTrue);
|
||||
expect(inline.value.storage, orderedEquals(inlineMatrix.storage));
|
||||
expect(picked, isEmpty);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'package:pipelines_app/features/graph/viewport/graph_viewport_controller.dart';
|
||||
|
||||
import 'graph_viewport_fixtures.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('Fit and Expand stay labelled, activatable buttons on both hosts', (
|
||||
tester,
|
||||
) async {
|
||||
for (final cupertino in [false, true]) {
|
||||
final host = cupertino ? 'cupertino' : 'material';
|
||||
final controller = GraphViewportController();
|
||||
addTearDown(controller.dispose);
|
||||
var expands = 0;
|
||||
await tester.pumpWidget(
|
||||
viewportHost(
|
||||
controller: controller,
|
||||
child: viewportTargets([]),
|
||||
cupertino: cupertino,
|
||||
onExpand: () => expands += 1,
|
||||
),
|
||||
);
|
||||
await settleViewport(tester);
|
||||
final fitted = controller.snapshot;
|
||||
|
||||
for (final control in viewportControls().entries) {
|
||||
final node = tester.getSemantics(find.byKey(control.key));
|
||||
final data = node.getSemanticsData();
|
||||
expect(
|
||||
data.label,
|
||||
control.value,
|
||||
reason: '$host ${control.key} must have the web name',
|
||||
);
|
||||
expect(
|
||||
data.flagsCollection.isButton,
|
||||
isTrue,
|
||||
reason: '$host ${control.key} must be announced as a button',
|
||||
);
|
||||
// A labelled button with no action is unusable with VoiceOver/TalkBack;
|
||||
// this is the regression the excluded-button wrapper introduced.
|
||||
expect(
|
||||
data.hasAction(SemanticsAction.tap),
|
||||
isTrue,
|
||||
reason: '$host ${control.key} must expose a tap action',
|
||||
);
|
||||
}
|
||||
|
||||
// The exposed action must run the real callback, not just be announced.
|
||||
await pinchViewport(tester, const Offset(200, 150), 2);
|
||||
await tester.pumpAndSettle();
|
||||
expect(controller.snapshot, isNot(fitted));
|
||||
performViewportTap(tester, find.byKey(const Key('graph-fit')));
|
||||
await tester.pump();
|
||||
expect(controller.scale, closeTo(fitted.scale, 1e-9));
|
||||
|
||||
performViewportTap(tester, find.byKey(const Key('graph-expand')));
|
||||
await tester.pump();
|
||||
expect(expands, 1, reason: '$host Expand must activate');
|
||||
}
|
||||
});
|
||||
|
||||
testWidgets('320px at 2x keeps native controls and gestures on both hosts', (
|
||||
tester,
|
||||
) async {
|
||||
for (final cupertino in [false, true]) {
|
||||
final controller = GraphViewportController();
|
||||
addTearDown(controller.dispose);
|
||||
await tester.pumpWidget(
|
||||
viewportHost(
|
||||
controller: controller,
|
||||
child: viewportTargets([]),
|
||||
cupertino: cupertino,
|
||||
dark: cupertino,
|
||||
textScale: 2,
|
||||
viewport: const Size(320, 300),
|
||||
onExpand: () {},
|
||||
),
|
||||
);
|
||||
await settleViewport(tester);
|
||||
expect(find.byKey(const Key('graph-fit')), findsOneWidget);
|
||||
expect(find.byKey(const Key('graph-expand')), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
|
||||
final before = controller.offset;
|
||||
await dragViewport(
|
||||
tester,
|
||||
find.byKey(const Key('graph-viewport')),
|
||||
const Offset(-30, -10),
|
||||
);
|
||||
expect(controller.offset, isNot(before));
|
||||
await pinchViewport(tester, const Offset(160, 150), 2);
|
||||
await tester.pumpAndSettle();
|
||||
expect(controller.scale, greaterThan(0.3));
|
||||
expect(tester.takeException(), isNull);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'package:pipelines_app/features/graph/viewport/graph_viewport.dart';
|
||||
import 'package:pipelines_app/features/graph/viewport/graph_viewport_controller.dart';
|
||||
|
||||
/// Shared fixture for the graph viewport widget tests.
|
||||
///
|
||||
/// One 1200x900 graph in a 400x300 box unless a test asks for another size.
|
||||
const Size viewportContent = Size(1200, 900);
|
||||
const Size defaultViewportSize = Size(400, 300);
|
||||
|
||||
/// Two native tap targets at known graph coordinates; a tap reports its key so
|
||||
/// hit-testing can be checked against the visible transform.
|
||||
Widget viewportTargets(List<String> picked) => Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
Positioned(
|
||||
left: 60,
|
||||
top: 60,
|
||||
width: 120,
|
||||
height: 60,
|
||||
child: GestureDetector(
|
||||
key: const Key('target-a'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: () => picked.add('a'),
|
||||
child: const ColoredBox(color: Color(0xFF3366CC)),
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
left: 900,
|
||||
top: 700,
|
||||
width: 160,
|
||||
height: 80,
|
||||
child: GestureDetector(
|
||||
key: const Key('target-b'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: () => picked.add('b'),
|
||||
child: const ColoredBox(color: Color(0xFFCC6633)),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
Widget viewportHost({
|
||||
required GraphViewportController controller,
|
||||
required Widget child,
|
||||
VoidCallback? onExpand,
|
||||
bool cupertino = false,
|
||||
bool dark = false,
|
||||
double textScale = 1,
|
||||
Size viewport = defaultViewportSize,
|
||||
}) {
|
||||
final graph = MediaQuery(
|
||||
data: MediaQueryData(textScaler: TextScaler.linear(textScale)),
|
||||
child: SizedBox.fromSize(
|
||||
size: viewport,
|
||||
child: GraphViewport(
|
||||
controller: controller,
|
||||
contentSize: viewportContent,
|
||||
onExpand: onExpand,
|
||||
child: child,
|
||||
),
|
||||
),
|
||||
);
|
||||
if (cupertino) {
|
||||
return CupertinoApp(
|
||||
theme: CupertinoThemeData(
|
||||
brightness: dark ? Brightness.dark : Brightness.light,
|
||||
),
|
||||
home: CupertinoPageScaffold(child: Center(child: graph)),
|
||||
);
|
||||
}
|
||||
return MaterialApp(
|
||||
theme: dark ? ThemeData.dark() : ThemeData.light(),
|
||||
home: Scaffold(body: Center(child: graph)),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> settleViewport(WidgetTester tester) async {
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
/// Two-pointer pinch around [center]; [factor] > 1 zooms in.
|
||||
Future<void> pinchViewport(
|
||||
WidgetTester tester,
|
||||
Offset center,
|
||||
double factor, {
|
||||
double half = 20,
|
||||
}) async {
|
||||
final origin = viewportGlobal(tester, center);
|
||||
final left = await tester.startGesture(origin - Offset(half, 0));
|
||||
final right = await tester.startGesture(origin + Offset(half, 0));
|
||||
await tester.pump();
|
||||
const steps = 8;
|
||||
final end = half * factor;
|
||||
for (var step = 1; step <= steps; step += 1) {
|
||||
final spread = half + (end - half) * step / steps;
|
||||
await left.moveTo(origin - Offset(spread, 0));
|
||||
await right.moveTo(origin + Offset(spread, 0));
|
||||
await tester.pump();
|
||||
}
|
||||
await left.up();
|
||||
await right.up();
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
Offset viewportScreenOf(
|
||||
GraphViewportController controller,
|
||||
Offset graphPoint,
|
||||
) => MatrixUtils.transformPoint(controller.transformation.value, graphPoint);
|
||||
|
||||
/// Viewport-local coordinates to the test screen, where gestures are dispatched.
|
||||
Offset viewportGlobal(WidgetTester tester, Offset local) =>
|
||||
tester.getTopLeft(find.byKey(const Key('graph-viewport'))) + local;
|
||||
|
||||
/// Starts a drag and moves past the pan slop, so the canvas owns the gesture.
|
||||
///
|
||||
/// The viewer only pans movement after it accepts the gesture, so tests record
|
||||
/// their reference offset after this warm-up rather than at pointer down.
|
||||
Future<TestGesture> startViewportDrag(
|
||||
WidgetTester tester,
|
||||
Finder finder, {
|
||||
Offset warmUp = const Offset(-10, -10),
|
||||
}) async {
|
||||
final gesture = await tester.startGesture(tester.getCenter(finder));
|
||||
for (var step = 0; step < 4; step += 1) {
|
||||
await gesture.moveBy(warmUp);
|
||||
await tester.pump();
|
||||
}
|
||||
return gesture;
|
||||
}
|
||||
|
||||
Future<void> dragViewport(
|
||||
WidgetTester tester,
|
||||
Finder finder,
|
||||
Offset delta, {
|
||||
Offset warmUp = const Offset(-10, -10),
|
||||
}) async {
|
||||
final gesture = await startViewportDrag(tester, finder, warmUp: warmUp);
|
||||
for (var step = 0; step < 4; step += 1) {
|
||||
await gesture.moveBy(delta / 4);
|
||||
await tester.pump();
|
||||
}
|
||||
await gesture.up();
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
/// Activates a control the way a screen reader does: through its semantics
|
||||
/// action, not pointer input.
|
||||
void performViewportTap(WidgetTester tester, Finder finder) {
|
||||
final node = tester.getSemantics(finder);
|
||||
tester.binding.renderViews.first.owner!.semanticsOwner!.performAction(
|
||||
node.id,
|
||||
SemanticsAction.tap,
|
||||
);
|
||||
}
|
||||
|
||||
/// The controls' accessible names, in the order they are shown.
|
||||
Map<Key, String> viewportControls() => <Key, String>{
|
||||
const Key('graph-fit'): graphFitLabel,
|
||||
const Key('graph-expand'): graphExpandLabel,
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user