diff --git a/app/PARITY.md b/app/PARITY.md index e27822da..4c1a0543 100644 --- a/app/PARITY.md +++ b/app/PARITY.md @@ -31,20 +31,20 @@ or scratch servers only, never real operator sessions/runs/workflows. | Run detail/input/output/copy/metrics | Preview | latest summary tabs/fields and exact empty/unknown states | | Rename run | Preview | verified exact accepted title fold; no live production mutation tested | | Cancel run | Preview | exact confirm/server-accepted detail+list fold; production cancellation not tested | -| Retry/restart | Source actions/dialogs | actual detail controls, accepted new-run navigation, stale/refusal handling | +| Retry/restart | Preview controls in the run detail | accepted new-run navigation, stale/refusal handling verified in the app | | Human decisions | Preview waiting card/native prompt/exact accepted reply | attention/action URL entry; no production decision answered during tests | -| Run graph | Source projection/visits; definition canvas landed | executed/unvisited routes, live activity, graph clicks open latest RECORDED visit, no definition by default | -| Timeline/recorded visit pane | Preview text rows only; authored pane77 | visit selection, status/outcome/duration/model/target/verdict, artifacts/session/input/output/definition tabs | -| Changes/diffs | Preview via run detail | settled-run aggregate gate rechecked in shell; per-visit capture entry still separate | -| Artifact groups | Source model/list | actual visit/run gallery integration and truthful unavailable capture facts | -| Artifact preview | Missing | image-primary in-app viewer, video/doc/text/markdown, paging, focus/back, authenticated fetch errors | +| Run graph | Source projection/visits; definition canvas and stage pane landed | executed/unvisited routes, live activity, graph clicks open latest RECORDED visit, no definition by default | +| Timeline/recorded visit pane | Preview text rows only; authored definition pane landed | visit selection, status/outcome/duration/model/target/verdict, artifacts/session/input/output/definition tabs | +| 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 + text in-app, markdown seam, paging, honest unsupported/external/HTTP states | wire the chat markdown renderer into the viewer; 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 | | Session audit/export repair facts | Missing UI | session.html read-only open, partial/missing/skipped/repair choices without fabricating complete evidence | -| Chat session management | Source | normal Chat destination, directory groups/history/search, shared rename/star/close/reopen/create, local hide/undo/seen state | -| Chat history/live transport | Source controller72; active live screen79 | authoritative reconnect/paging/live-failure status and stable session navigation in the shell | +| 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 | | Chat message surfaces | Source native body70; integrating in79 | markdown (safe links/headings/lists/tables/fences), exact attachments and unknown-part retention | | 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 | Source controller75 | native composer UI, Enter newline/Ctrl-Cmd+Enter send, Send beside Stop, optimistic identity display | +| Chat composer | Source controller75 | native composer UI in the thread, Enter newline/Ctrl-Cmd+Enter send, Send beside Stop, optimistic identity display | | 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 model/Info/background tasks | Source request facade | current-model selection, numeric Info modal (unknown !=0), bounded running shell pages | @@ -52,7 +52,7 @@ or scratch servers only, never real operator sessions/runs/workflows. | 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 | | Search | Source screen | shell entry, close/focus/selection retention, exact pipeline/version/run/field/visit/artifact target routing | -| Needs you | Missing | derived failed/waiting counts, native list/sheet, open/dismiss/clear snapshot, persisted identities | +| Needs you | Source model82; active sheet84 | runs-list bell/count wiring, open/dismiss/clear persistence, notification transitions | | 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 | diff --git a/app/WORK.md b/app/WORK.md index ef928a2d..66c667d1 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -45,8 +45,19 @@ All work under app/. Existing applications remain running and unchanged. | C3-state | Chat draft/send/stop controller | run75 /565cdaa |10min MET target; manager reviewed per-chat persistence, stable intent id, refusal restore, queued flag | merged main; ancestry verified | composer UI next | | C3-form | Native composer control | run? pending | drafts/send/stop UI atop75 | queued | pending | | Chat screen | Live Chat destination + read-only history | run79 /flutter/chat-live-screen | list/detail routing, paging, live one-thread, reconnect | running | pending | -| Templates gallery | Native template gallery/detail | run76 /flutter/templates-gallery | actual catalogue/source + create prompt forwarding | running | pending | -| Stage definition | Native authored stage pane | run77 /flutter/stage-definition | pinned definition identity, outcomes/tools/raw unknown | running | pending | +| Templates gallery | run76 /c56b5d45 | manager re-ran38 templates tests, rebuilt fixture;7 probe checks/7 captures incl inspected detail | merged main; ancestry verified | entry/route registration pending | +| 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 /flutter/pipeline-graph-wire | pinned definition graph, measured canvas, selection to definition | running | pending | +| Needs you UI | Bell + native sheet | run84 /flutter/attention-ui | snapshot clear/dismiss, both hosts | running | pending | +| 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 | +| Chat markdown | Safe native chat markdown | run83 /flutter/chat-markdown | parser/widget subset, unsafe links inert | running | transcript integration next | +| Artifact viewer | In-app preview + paging | run86 retained/151bd1c | harness deadline recovery;99 artifacts tests + probe(7 viewer states,320/2x,Cupertino); gallery opens viewer for previewable types | merged main; ancestry verified | published8096 | +| Composer UI | Composer strip in the thread | run87 /flutter/chat-composer-ui | drafts/send/stop atop75 | running | pending | +| Search entry | Register Search in the shell | run88 /flutter/search-entry | route + focus + prior-state restore | running | pending | +| Run graph | Run-mode executed-route canvas | run89 /flutter/run-graph | recorded visits only, legend, click→visit key | running | run detail Graph tab next | | Schedule form | Native schedule draft editor | run78 /flutter/schedule-form | binds74, no save engine | running | pending | ## Next ready work @@ -96,6 +107,58 @@ override, server edit or shell-write bypass was used by the manager. Allowed pipeline models: Luna or DeepSeek V4.1 Flash; current runs use Luna. ## Latest integration check +The artifact viewer landed after its Code visit ended on a harness transport +deadline; the retained edits were verified rather than retried. Previewable +records open in-app (image bytes or selectable text, markdown via an injected +builder), external-origin urls are marked and never fetched, paging clamps, and +unsupported types keep the facts dialog. Published; rollback +build/web-before-viewer-1792621280, JS SHA256 +053c61f3de1cd4abfb49eb6f77717912454066ab57a84e23045688394bcf92ac. + +Two more slices needed direct recovery. Chat 79 hit its Code deadline while active; +its edits were retained, and the manager verified the focused application/chat +suites (110 tests), then drove the Material and Cupertino fixture probes and +inspected the Cupertino live thread. Retry 80 landed normally. + +The real-app browser probe now drives three destinations end to end on top of the +existing run coverage: Pipeline graph-era detail remains, Changes and Artifacts +open from a run, Settings shares the one socket, and Chat lists a session, opens +`/chat/ses_probechat`, shows the stored turn (asserted by OCR, since Flutter paints +selectable text on the canvas) and returns to `/chat`. It passes with 34 captures. + +Integrated main after Chat, retry, artifacts and attention:831 tests pass; +analysis clean; normal web build passed. Published: rollback +build/web-before-chat-1792620525, JS SHA256 +17dfb800fcd3617deef93bf9a1287f002d7cc9cd957817576fd38c7c52b68043; unauthenticated +asset access still 401. + +The active set is now markdown rendering, the Needs-you sheet, pipeline graph +wiring and the artifact viewer; composer UI, schedule save wiring, search entry, +run graph and notifications follow. +Templates gallery76 landed after inspection: 38 template tests pass, and the +in-process fixture probe passed 7 checks with 7 captures; the selected-template +capture shows metadata, verbatim source and the native create action under one +bar. Schedule form78 and its lossless draft are also in main; the form probe passed +every step with 7 captures and both the Cupertino dark and 320px/2x Material +captures were inspected. Two native-default violations were then removed from the +schedule surfaces: secondary metadata used a hard-coded 14px Cupertino size, and +row titles/statuses forced weights the host already defines. They now use the +host's own text roles. + +The real-app browser probe was extended to exercise the newly wired Changes action +end to end: run detail → recorded file → rendered diff with the exact added/removed +lines → close → back to the same detail. It passes with 30 captures; the diff +capture was inspected. Earlier assertions that indexed captures numerically were +replaced with named capture variables so inserted evidence cannot silently shift +an OCR check. + +Integrated main after these landings:718 tests pass; analysis clean; normal web +build passed; full normal-app probe 30 captures. Published that verified bundle +(rollback build/web-before-full-1792617308). The JS hash is unchanged from the +previous publication because Templates, schedules and their probes are not yet +reachable from shell routes and are tree-shaken; that is expected, not evidence of +a missing build. + The user directs continued work until the whole client is ported, not just components. app/PARITY.md now enumerates the entire remaining behavior inventory against latest web behavior, distinguishing preview/source/active/missing. diff --git a/app/lib/application/app_route.dart b/app/lib/application/app_route.dart index 889f04f5..34ce499a 100644 --- a/app/lib/application/app_route.dart +++ b/app/lib/application/app_route.dart @@ -10,7 +10,7 @@ enum AppRouteKind { pipelines, runs, chat, settings } /// malformed path resolves to the default Pipelines list instead of throwing. /// The serialiser is its inverse for every route the app can produce. class AppRoute { - const AppRoute(this.kind, {this.runId}); + const AppRoute(this.kind, {this.runId, this.chatSessionId}); static const pipelines = AppRoute(AppRouteKind.pipelines); static const runs = AppRoute(AppRouteKind.runs); @@ -19,16 +19,27 @@ class AppRoute { static const run = _RunRouteFactory(); + /// One chat session, or the chat list when [id] is not a session id. + static AppRoute chatSession(String id) => isChatSessionId(id) + ? AppRoute(AppRouteKind.chat, chatSessionId: id) + : chat; + final AppRouteKind kind; /// The run shown by the Runs destination, or null for the list. final int? runId; + /// The chat session shown by the Chat destination, or null for the list. + final String? chatSessionId; + /// The path the app writes into history for this route. String get path => switch (kind) { AppRouteKind.pipelines => '/pipelines', AppRouteKind.runs => runId == null ? '/runs' : '/runs/$runId', - AppRouteKind.chat => '/chat', + AppRouteKind.chat => + chatSessionId == null || !isChatSessionId(chatSessionId!) + ? '/chat' + : '/chat/${Uri.encodeComponent(chatSessionId!)}', AppRouteKind.settings => '/settings', }; @@ -65,6 +76,7 @@ class AppRoute { 'runs' when segments.length == 1 => runs, 'runs' when segments.length == 2 => _runRoute(segments[1]), 'chat' when segments.length == 1 => chat, + 'chat' when segments.length == 2 => _chatRoute(segments[1]), 'settings' when segments.length == 1 => settings, _ => pipelines, }; @@ -77,12 +89,26 @@ class AppRoute { return AppRoute(AppRouteKind.runs, runId: id); } - @override - bool operator ==(Object other) => - other is AppRoute && other.kind == kind && other.runId == runId; + /// A chat session id is nonempty, bounded and URL-safe, matching the web + /// parser. Anything else is malformed rather than a stale session the + /// destination has to guess about. + static bool isChatSessionId(String value) => + value.isNotEmpty && + value.length <= 200 && + RegExp(r'^[A-Za-z0-9_-]+$').hasMatch(value); + + static AppRoute _chatRoute(String value) => + isChatSessionId(value) ? chatSession(value) : pipelines; @override - int get hashCode => Object.hash(kind, runId); + bool operator ==(Object other) => + other is AppRoute && + other.kind == kind && + other.runId == runId && + other.chatSessionId == chatSessionId; + + @override + int get hashCode => Object.hash(kind, runId, chatSessionId); @override String toString() => path; diff --git a/app/lib/application/app_router.dart b/app/lib/application/app_router.dart index 44c87efb..80010651 100644 --- a/app/lib/application/app_router.dart +++ b/app/lib/application/app_router.dart @@ -27,6 +27,7 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { AppRouterDelegate({ required this.builder, required this.onPopToRuns, + required this.onPopToChat, required this.cupertino, AppRoute initial = AppRoute.pipelines, }) : _route = initial; @@ -36,6 +37,9 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { /// Called when a system Back belongs to the Runs detail, not the app stack. final VoidCallback onPopToRuns; + /// Called when a system Back belongs to one chat session. + final VoidCallback onPopToChat; + final bool cupertino; final _navigatorKey = GlobalKey(); @@ -81,9 +85,15 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { @override Future popRoute() async { - if (_route.runId == null) return false; - onPopToRuns(); - return true; + if (_route.runId != null) { + onPopToRuns(); + return true; + } + if (_route.chatSessionId != null) { + onPopToChat(); + return true; + } + return false; } /// Records a user move; the Router turns the new configuration into a diff --git a/app/lib/application/chat_destination.dart b/app/lib/application/chat_destination.dart new file mode 100644 index 00000000..15b2a56d --- /dev/null +++ b/app/lib/application/chat_destination.dart @@ -0,0 +1,69 @@ +import 'package:flutter/material.dart'; + +import '../features/chat/screen.dart'; +import '../ui/adaptive/host.dart'; +import 'app_session.dart'; +import 'connection_status.dart'; +import 'server_endpoint.dart'; + +/// The Chat destination: the shared session list and one read-only thread. +/// +/// Before the shared socket accepts its first connection nothing is requested, +/// so an offline launch cannot look like an empty chat list. After that the +/// screen stays mounted through drops; a reconnect advances [syncToken] so the +/// open conversation re-subscribes and re-reads without losing its selection. +class ChatDestination extends StatelessWidget { + const ChatDestination({ + super.key, + required this.session, + required this.server, + this.initialSessionId, + this.onSessionSelected, + this.onBack, + }); + + final AppSession session; + final ServerEndpoint server; + final String? initialSessionId; + final ValueChanged? onSessionSelected; + final VoidCallback? onBack; + + @override + Widget build(BuildContext context) => AnimatedBuilder( + animation: session, + builder: (context, _) { + final cupertino = usesCupertinoHost(context); + if ((server.requiresConfiguration || server.error != null) && + session.endpoint == null) { + return ConnectionGate( + session: session, + server: server, + cupertino: cupertino, + ); + } + if (!session.everConnected) { + if (session.connected) return _chatScreen(); + return ConnectionGate( + session: session, + server: server, + cupertino: cupertino, + ); + } + return Column( + children: [ + if (!session.connected) + ConnectionBanner(session: session, cupertino: cupertino), + Expanded(child: _chatScreen()), + ], + ); + }, + ); + + Widget _chatScreen() => ChatScreen( + gateway: session.gateway, + initialSessionId: initialSessionId, + syncToken: session.connectionEpoch, + onSessionSelected: onSessionSelected, + onBack: onBack, + ); +} diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index e5de270d..ac66045a 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -11,6 +11,7 @@ import 'app.dart'; import 'app_route.dart'; import 'app_router.dart'; import 'app_session.dart'; +import 'chat_destination.dart'; import 'pipelines_destination.dart'; import 'runs_destination.dart'; import 'server_endpoint.dart'; @@ -71,6 +72,7 @@ class _PipelinesAppState extends State { initial: initial, cupertino: _cupertino, onPopToRuns: () => _delegate.goTo(AppRoute.runs), + onPopToChat: () => _delegate.goTo(AppRoute.chat), builder: _buildShell, ); _config = RouterConfig( @@ -110,6 +112,13 @@ class _PipelinesAppState extends State { onRunSelected: (id) => _delegate.goTo(AppRoute.run(id)), onBack: () => _delegate.goTo(AppRoute.runs), ), + AppDestination.chat: (_) => ChatDestination( + session: _session, + server: widget.server, + initialSessionId: route.chatSessionId, + onSessionSelected: (id) => _delegate.goTo(AppRoute.chatSession(id)), + onBack: () => _delegate.goTo(AppRoute.chat), + ), AppDestination.settings: (_) => SettingsScreen( client: _session.client, initialEndpoint: _session.endpoint, diff --git a/app/lib/features/artifacts/domain/artifact_kind.dart b/app/lib/features/artifacts/domain/artifact_kind.dart index 7bac7708..3cf24f0c 100644 --- a/app/lib/features/artifacts/domain/artifact_kind.dart +++ b/app/lib/features/artifacts/domain/artifact_kind.dart @@ -196,13 +196,17 @@ bool isMarkdownArtifact(String contentType, String name) { return _markdownExtensions.contains(_extensionOf(name)); } -/// Whether an artifact opens inside the full-screen viewer: images, videos, and -/// markdown/text documents. A `text/plain` log, source file or spreadsheet stays -/// an external file because those are evidence, not prose. +/// Whether an artifact opens inside the viewer: images, videos, markdown/text +/// documents and any recorded `text/plain` file. The viewer draws text/plain as +/// selectable text; a CSV, source file or spreadsheet with its own type stays an +/// external file because it is evidence, not prose. Videos are pageable but the +/// viewer reports that it cannot draw them rather than faking a player. bool isViewerArtifact(String contentType, String name) { if (isImageContentType(contentType) || isVideoContentType(contentType)) { return true; } + final mime = contentType.split(';').first.trim().toLowerCase(); + if (mime == 'text/plain') return true; return artifactKind(contentType, name) == ArtifactKind.document && isMarkdownArtifact(contentType, name); } diff --git a/app/lib/features/artifacts/domain/artifact_preview.dart b/app/lib/features/artifacts/domain/artifact_preview.dart new file mode 100644 index 00000000..f60b39ae --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_preview.dart @@ -0,0 +1,118 @@ +import 'artifact_kind.dart'; +import 'artifact_record.dart'; +import 'artifact_url.dart'; + +/// What the in-app viewer can do with one recorded artifact. +enum ArtifactPreviewKind { + image, + text, + markdown, + + /// A recorded file the viewer cannot draw (video, CSV, archives, ...). + unsupported, + + /// No safe same-origin url to fetch: absent, unsafe or another origin. + unavailable, +} + +/// One artifact's preview decision: the safe resolved url, the content kind and +/// the exact wording for a state that cannot be previewed. +/// +/// An external url is deliberately [ArtifactPreviewKind.unavailable]: the viewer +/// never fetches another origin, so a recorded url on a different host is marked +/// instead of being requested with the app's credentials. [canFetch] is the one +/// gate the viewer's fetch consults. +class ArtifactPreviewPlan { + const ArtifactPreviewPlan({ + required this.kind, + required this.resolved, + required this.message, + }); + + final ArtifactPreviewKind kind; + final ResolvedArtifactUrl? resolved; + + /// The explicit reason a non-previewable artifact is not drawn; empty for an + /// image, text or markdown document that may be fetched. + final String message; + + bool get canFetch => + resolved != null && + resolved!.external == false && + (kind == ArtifactPreviewKind.image || + kind == ArtifactPreviewKind.text || + kind == ArtifactPreviewKind.markdown); +} + +const String artifactPreviewNoUrl = 'No artifact URL recorded.'; +const String artifactPreviewUnsafeUrl = + 'The recorded artifact URL cannot be opened safely.'; +const String artifactPreviewExternalUrl = + 'This artifact is hosted on another origin and is not previewed here.'; + +/// Classifies [artifact] against the configured server origin. +/// +/// Images are drawn from the resolved bytes; `text/plain` is selectable text; a +/// `.md`/`.markdown` name or `text/markdown` is handed to the injected markdown +/// builder. Everything else is explicitly unsupported rather than faked. +ArtifactPreviewPlan planArtifactPreview({ + required ArtifactRecord artifact, + required String configuredEndpoint, +}) { + if (!artifact.hasUrl) { + return const ArtifactPreviewPlan( + kind: ArtifactPreviewKind.unavailable, + resolved: null, + message: artifactPreviewNoUrl, + ); + } + final resolved = resolveArtifactUrl(configuredEndpoint, artifact.url); + if (resolved == null) { + return const ArtifactPreviewPlan( + kind: ArtifactPreviewKind.unavailable, + resolved: null, + message: artifactPreviewUnsafeUrl, + ); + } + if (resolved.external) { + return ArtifactPreviewPlan( + kind: ArtifactPreviewKind.unavailable, + resolved: resolved, + message: artifactPreviewExternalUrl, + ); + } + final mime = artifact.contentType.split(';').first.trim().toLowerCase(); + if (isImageContentType(mime)) { + return ArtifactPreviewPlan( + kind: ArtifactPreviewKind.image, + resolved: resolved, + message: '', + ); + } + if (mime == 'text/markdown' || _isMarkdownName(artifact.name)) { + return ArtifactPreviewPlan( + kind: ArtifactPreviewKind.markdown, + resolved: resolved, + message: '', + ); + } + if (mime == 'text/plain') { + return ArtifactPreviewPlan( + kind: ArtifactPreviewKind.text, + resolved: resolved, + message: '', + ); + } + return ArtifactPreviewPlan( + kind: ArtifactPreviewKind.unsupported, + resolved: resolved, + message: 'This file type cannot be previewed here.', + ); +} + +bool _isMarkdownName(String name) { + final dot = name.lastIndexOf('.'); + if (dot == -1) return false; + final extension = name.substring(dot + 1).toLowerCase(); + return extension == 'md' || extension == 'markdown'; +} diff --git a/app/lib/features/artifacts/domain/gallery_navigation.dart b/app/lib/features/artifacts/domain/gallery_navigation.dart index ca115a73..a5d519a9 100644 --- a/app/lib/features/artifacts/domain/gallery_navigation.dart +++ b/app/lib/features/artifacts/domain/gallery_navigation.dart @@ -7,24 +7,34 @@ import 'artifact_record.dart'; /// a visit-scoped key so two url-less records never collapse into one page. class PagedArtifact { const PagedArtifact({ - required this.stageKey, - required this.visit, + required this.group, required this.artifact, required this.pageIndex, }); - final String stageKey; - final int visit; + final ArtifactGroup group; final ArtifactRecord artifact; /// Position in the filtered page list. final int pageIndex; + String get stageKey => group.stageKey; + int get visit => group.visit; + String get identity => artifact.hasUrl ? artifact.url : '$stageKey\u0000$visit\u0000$pageIndex\u0000${artifact.name}'; } +/// The gallery row identity of [artifact] inside [group], shared by the row +/// list and the viewer so selecting a row opens exactly that page. The recorded +/// visit is part of the key, so two visits that recorded the same name stay +/// distinct even when their recorded urls match. +String artifactVisitIdentityOf(ArtifactGroup group, ArtifactRecord artifact) { + final recorded = artifact.hasUrl ? artifact.url : artifact.name; + return '${group.stageKey}\u0000${group.visit}\u0000$recorded'; +} + /// The artifacts the viewer can page through, in gallery order: group by group, /// each group's images, videos and markdown/text documents in recorded order. /// Other artifacts open externally and are not part of this list. Pure: it only @@ -36,8 +46,7 @@ List pagedArtifacts(List groups) { if (!isViewerArtifact(artifact.contentType, artifact.name)) continue; pages.add( PagedArtifact( - stageKey: group.stageKey, - visit: group.visit, + group: group, artifact: artifact, pageIndex: pages.length, ), diff --git a/app/lib/features/artifacts/ui/artifact_external_open.dart b/app/lib/features/artifacts/ui/artifact_external_open.dart new file mode 100644 index 00000000..15ae4180 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_external_open.dart @@ -0,0 +1,14 @@ +import '../domain/artifact_url.dart'; +import 'artifact_external_open_stub.dart' + if (dart.library.js_interop) 'artifact_external_open_web.dart' + as impl; + +/// Opens an already validated artifact url with the host's external handler. +/// +/// The url must come from [resolveArtifactUrl]; this capability never resolves, +/// rewrites, fetches or previews it. Returns whether the host accepted the +/// request, so a refusal is reported instead of being silently swallowed. +typedef ArtifactExternalOpen = Future Function(Uri uri); + +Future openArtifactExternally(Uri uri) => + impl.openArtifactExternally(uri); diff --git a/app/lib/features/artifacts/ui/artifact_external_open_stub.dart b/app/lib/features/artifacts/ui/artifact_external_open_stub.dart new file mode 100644 index 00000000..95708cb5 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_external_open_stub.dart @@ -0,0 +1,6 @@ +/// Non-web fallback for external artifact urls. +/// +/// A native launcher needs a platform plugin that this slice does not depend +/// on, so a non-web host reports the refusal instead of pretending to open the +/// link. The page surfaces that message to the operator. +Future openArtifactExternally(Uri uri) async => false; diff --git a/app/lib/features/artifacts/ui/artifact_external_open_web.dart b/app/lib/features/artifacts/ui/artifact_external_open_web.dart new file mode 100644 index 00000000..f57fc411 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_external_open_web.dart @@ -0,0 +1,20 @@ +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +/// Web external open: a new browser tab. The url is already validated by +/// [resolveArtifactUrl]; it is passed through unchanged and never fetched. +/// +/// `window.open` is reached through `js_interop` rather than `dart:html`, so the +/// same source compiles for both the JavaScript and WebAssembly web targets. +Future openArtifactExternally(Uri uri) async { + try { + final opened = globalContext.callMethod( + 'open'.toJS, + uri.toString().toJS, + '_blank'.toJS, + ); + return opened.isDefinedAndNotNull; + } catch (_) { + return false; + } +} diff --git a/app/lib/features/artifacts/ui/artifact_gallery_action.dart b/app/lib/features/artifacts/ui/artifact_gallery_action.dart new file mode 100644 index 00000000..7cffb7c8 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_gallery_action.dart @@ -0,0 +1,104 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../core/transport/pipelines_client.dart'; +import '../../../ui/adaptive/host.dart'; +import 'artifact_external_open.dart'; +import 'artifact_gallery_page.dart'; + +/// The run detail's action label key, so a host can find the one action. +const ValueKey runArtifactsButtonKey = ValueKey( + 'run-detail-artifacts', +); + +const Set _executingStatuses = {'queued', 'running', 'waiting'}; + +/// The detail's `steps` exactly as returned by the server. The pushed page +/// snapshots the returned list once, so it never re-derives on each rebuild. +List runDetailArtifactSteps(JsonMap run) { + final steps = run['steps']; + if (steps is List) return steps; + if (steps is List) return steps.cast(); + return const []; +} + +/// Whether the run detail offers the gallery action at all: only once the +/// loaded detail actually carries steps. A run with no steps has nothing to +/// list, so the action is absent rather than opening a page that says so. +bool showRunArtifactsAction(JsonMap run) => + runDetailArtifactSteps(run).isNotEmpty; + +/// Whether the run is still executing, so the page can say capture pending +/// instead of claiming nothing was recorded. +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 { + const RunArtifactsButton({ + super.key, + required this.run, + required this.gateway, + }); + + final JsonMap run; + final ApiGateway gateway; + + @override + Widget build(BuildContext context) { + final steps = runDetailArtifactSteps(run); + void open() => showArtifactGallery( + context, + steps: steps, + executing: _runExecuting(run), + configuredEndpoint: _gatewayEndpoint(gateway), + ); + if (usesCupertinoHost(context)) { + return CupertinoButton.tinted( + key: runArtifactsButtonKey, + onPressed: open, + child: const Text(artifactGalleryTitle), + ); + } + return FilledButton.tonalIcon( + key: runArtifactsButtonKey, + onPressed: open, + icon: const Icon(Icons.inventory_2_outlined), + label: const Text(artifactGalleryTitle), + ); + } +} + +/// Opens the recorded artifact groups on a native page. The steps are +/// snapshotted once; the page never re-fetches or re-derives them. +Future showArtifactGallery( + BuildContext context, { + required List steps, + bool executing = false, + String configuredEndpoint = '', + ArtifactExternalOpen openExternal = openArtifactExternally, +}) { + final page = ArtifactGalleryPage( + steps: List.unmodifiable(steps), + executing: executing, + configuredEndpoint: configuredEndpoint, + openExternal: openExternal, + ); + return Navigator.of(context).push( + usesCupertinoHost(context) + ? CupertinoPageRoute(builder: (_) => page) + : MaterialPageRoute(builder: (_) => page), + ); +} diff --git a/app/lib/features/artifacts/ui/artifact_gallery_page.dart b/app/lib/features/artifacts/ui/artifact_gallery_page.dart new file mode 100644 index 00000000..12c5617a --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_gallery_page.dart @@ -0,0 +1,246 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../ui/adaptive/host.dart'; +import '../domain/artifact_groups.dart'; +import '../domain/artifact_kind.dart'; +import '../domain/artifact_record.dart'; +import '../domain/artifact_summary.dart'; +import '../domain/artifact_url.dart'; +import 'artifact_external_open.dart'; +import 'artifact_selection_facts.dart'; +import 'artifact_viewer_content.dart'; +import 'artifact_viewer_fetch.dart'; +import 'artifact_viewer_page.dart'; +import 'artifact_visit_list.dart'; + +/// The gallery page title. +const String artifactGalleryTitle = 'Artifacts'; + +/// A read-only page of recorded stage/visit artifact groups. +/// +/// Selection uses [artifactVisitIdentity], so the same filename in two visits +/// stays two distinct selections. Selecting a viewer artifact with a resolved +/// url opens the native [ArtifactViewerPage] (an external origin is marked and +/// 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. It never downloads, shares or filters. +class ArtifactGalleryPage extends StatefulWidget { + const ArtifactGalleryPage({ + super.key, + required this.steps, + this.executing = false, + this.configuredEndpoint = '', + this.openExternal = openArtifactExternally, + this.fetch = fetchArtifact, + this.markdownBuilder = defaultArtifactMarkdown, + }); + + final List steps; + final bool executing; + final String configuredEndpoint; + final ArtifactExternalOpen openExternal; + final ArtifactFetch fetch; + final ArtifactMarkdownBuilder markdownBuilder; + + @override + State createState() => _ArtifactGalleryPageState(); +} + +class _ArtifactGalleryPageState extends State { + late final Map _stepsByGroup = recordedStepsByGroup( + widget.steps, + ); + late final List _groups = artifactGroups(widget.steps); + String? _selectedIdentity; + String? _status; + + Future _select(ArtifactGroup group, ArtifactRecord artifact) async { + final identity = artifactVisitIdentity(group, artifact); + final resolved = artifact.hasUrl + ? resolveArtifactUrl(widget.configuredEndpoint, artifact.url) + : null; + setState(() { + _selectedIdentity = identity; + _status = null; + }); + if (resolved != null && + isViewerArtifact(artifact.contentType, artifact.name)) { + await _openViewer(identity); + return; + } + await _showSelected(group, artifact, resolved); + } + + Future _openViewer(String identity) async { + final previousFocus = FocusManager.instance.primaryFocus; + await Navigator.of(context).push( + usesCupertinoHost(context) + ? CupertinoPageRoute( + builder: (_) => ArtifactViewerPage( + groups: _groups, + selectedIdentity: identity, + configuredEndpoint: widget.configuredEndpoint, + openExternal: widget.openExternal, + fetch: widget.fetch, + markdownBuilder: widget.markdownBuilder, + ), + ) + : MaterialPageRoute( + builder: (_) => ArtifactViewerPage( + groups: _groups, + selectedIdentity: identity, + configuredEndpoint: widget.configuredEndpoint, + openExternal: widget.openExternal, + fetch: widget.fetch, + markdownBuilder: widget.markdownBuilder, + ), + ), + ); + if (!mounted) return; + if (previousFocus != null && previousFocus.canRequestFocus) { + previousFocus.requestFocus(); + } + } + + Future _showSelected( + ArtifactGroup group, + ArtifactRecord artifact, + ResolvedArtifactUrl? resolved, + ) { + final step = _stepsByGroup[artifactGroupKey(group.stageKey, group.visit)]; + final facts = ArtifactSelectionFacts( + group: group, + artifact: artifact, + step: step, + resolved: resolved, + ); + if (usesCupertinoHost(context)) { + return showCupertinoDialog( + context: context, + builder: (dialogContext) => CupertinoAlertDialog( + title: Text(artifactDisplayName(artifact)), + content: facts, + actions: [ + if (resolved != null) + CupertinoDialogAction( + isDefaultAction: true, + onPressed: () => _open(resolved, dialogContext), + child: const Text('Open'), + ), + if (resolved != null) + CupertinoDialogAction( + onPressed: () => _copyLink(resolved, dialogContext), + child: const Text('Copy link'), + ), + CupertinoDialogAction( + onPressed: () => Navigator.of(dialogContext).pop(), + child: const Text('Close'), + ), + ], + ), + ); + } + return showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: Text(artifactDisplayName(artifact)), + content: SingleChildScrollView(child: facts), + actions: [ + if (resolved != null) + TextButton( + onPressed: () => _copyLink(resolved, dialogContext), + child: const Text('Copy link'), + ), + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: const Text('Close'), + ), + if (resolved != null) + TextButton( + onPressed: () => _open(resolved, dialogContext), + child: const Text('Open'), + ), + ], + ), + ); + } + + Future _open( + ResolvedArtifactUrl resolved, + BuildContext dialogContext, + ) async { + Navigator.of(dialogContext).pop(); + final opened = await widget.openExternal(resolved.uri); + if (!mounted) return; + setState( + () => _status = opened + ? 'Link opened externally.' + : 'Could not open the link.', + ); + } + + Future _copyLink( + ResolvedArtifactUrl resolved, + BuildContext dialogContext, + ) async { + Navigator.of(dialogContext).pop(); + String message; + try { + await Clipboard.setData(ClipboardData(text: resolved.url)); + message = 'Link copied.'; + } catch (_) { + message = 'Could not copy link.'; + } + if (!mounted) return; + setState(() => _status = message); + } + + @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 body = Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 4), + child: Text(summary), + ), + if (_status != null) + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 4), + child: Semantics(liveRegion: true, child: Text(_status!)), + ), + if (groups.isNotEmpty) + Expanded( + child: ArtifactVisitList( + groups: groups, + selectedIdentity: _selectedIdentity, + onSelected: _select, + ), + ), + ], + ); + if (usesCupertinoHost(context)) { + return CupertinoPageScaffold( + // Sections paint the grouped background; the page must match it or a + // white seam shows below the last section in light mode. + backgroundColor: CupertinoColors.systemGroupedBackground, + navigationBar: const CupertinoNavigationBar( + middle: Text(artifactGalleryTitle), + ), + child: SafeArea(child: body), + ); + } + return Scaffold( + appBar: AppBar(title: const Text(artifactGalleryTitle)), + body: SafeArea(top: false, child: body), + ); + } +} diff --git a/app/lib/features/artifacts/ui/artifact_selection_facts.dart b/app/lib/features/artifacts/ui/artifact_selection_facts.dart new file mode 100644 index 00000000..083a322e --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_selection_facts.dart @@ -0,0 +1,71 @@ +import 'package:flutter/widgets.dart'; + +import '../../../core/api_gateway.dart'; +import '../../graph/domain/stage_visits.dart'; +import '../domain/artifact_groups.dart'; +import '../domain/artifact_record.dart'; +import '../domain/artifact_summary.dart'; +import '../domain/artifact_url.dart'; +import 'artifact_visit_list.dart'; + +/// The key one recorded group maps to, used only to find its step. +String artifactGroupKey(String stageKey, int visit) => '$stageKey\u0000$visit'; + +/// Each recorded group's step, keyed by stage and display visit, so a selected +/// row can show its own visit's capture facts. Derives the same grouping the +/// gallery uses; an absent key yields null rather than a fabricated capture. +Map recordedStepsByGroup(List steps) { + final result = {}; + for (final entry in visitsByStage(steps).entries) { + for (var index = 0; index < entry.value.length; index += 1) { + final step = entry.value[index]; + result[artifactGroupKey(entry.key, displayVisit(step, index))] = step; + } + } + return result; +} + +/// The recorded facts of one selected artifact: name, MIME/size, its visit's +/// capture summary and notes, and the url state. Nothing is inferred. +class ArtifactSelectionFacts extends StatelessWidget { + const ArtifactSelectionFacts({ + super.key, + required this.group, + required this.artifact, + required this.step, + required this.resolved, + }); + + final ArtifactGroup group; + final ArtifactRecord artifact; + final JsonMap? step; + final ResolvedArtifactUrl? resolved; + + @override + Widget build(BuildContext context) { + final recordedStep = step; + final url = resolved; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text(artifactFactsLabel(artifact)), + const SizedBox(height: 8), + Text(artifactGroupLabel(group)), + if (recordedStep != null) ...[ + const SizedBox(height: 8), + Text(artifactsSummary(recordedStep, count: group.artifacts.length)), + for (final note in artifactCaptureNotes(recordedStep)) + Padding(padding: const EdgeInsets.only(top: 4), child: Text(note)), + ], + if (!artifact.hasUrl) ...[ + const SizedBox(height: 8), + const Text('No artifact URL recorded.'), + ] else if (url == null) ...[ + const SizedBox(height: 8), + const Text('The recorded artifact URL cannot be opened safely.'), + ], + ], + ); + } +} diff --git a/app/lib/features/artifacts/ui/artifact_viewer_body.dart b/app/lib/features/artifacts/ui/artifact_viewer_body.dart new file mode 100644 index 00000000..e5ffdf1d --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_viewer_body.dart @@ -0,0 +1,210 @@ +import 'dart:typed_data'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.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'; + +/// One viewer page: the recorded facts, position, live status, preview surface, +/// 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. +class ArtifactViewerBody extends StatelessWidget { + const ArtifactViewerBody({ + super.key, + required this.page, + required this.plan, + required this.index, + required this.count, + required this.loading, + required this.markdownBuilder, + required this.onPrevious, + required this.onNext, + required this.onOpen, + required this.onCopy, + this.text, + this.bytes, + this.error, + this.status, + }); + + final PagedArtifact page; + final ArtifactPreviewPlan plan; + final int index; + final int count; + final bool loading; + final ArtifactMarkdownBuilder markdownBuilder; + final VoidCallback onPrevious; + final VoidCallback onNext; + final VoidCallback onOpen; + final VoidCallback onCopy; + final String? text; + final Uint8List? bytes; + final String? error; + final String? status; + + @override + Widget build(BuildContext context) { + 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, + ), + ), + ), + 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, + onPrevious: onPrevious, + onNext: onNext, + ), + ], + ); + } +} + +class _Actions extends StatelessWidget { + const _Actions({ + required this.resolved, + required this.onOpen, + required this.onCopy, + }); + + final ResolvedArtifactUrl resolved; + final VoidCallback onOpen; + final VoidCallback onCopy; + + @override + Widget build(BuildContext context) { + if (usesCupertinoHost(context)) { + return SafeArea( + top: false, + child: Wrap( + alignment: WrapAlignment.center, + spacing: 8, + children: [ + CupertinoButton(onPressed: onOpen, child: const Text('Open')), + CupertinoButton(onPressed: onCopy, child: const Text('Copy link')), + ], + ), + ); + } + return SafeArea( + top: false, + child: Wrap( + alignment: WrapAlignment.center, + spacing: 8, + children: [ + TextButton.icon( + onPressed: onOpen, + icon: const Icon(Icons.open_in_new), + label: const Text('Open'), + ), + TextButton.icon( + onPressed: onCopy, + icon: const Icon(Icons.content_copy), + label: const Text('Copy link'), + ), + ], + ), + ); + } +} + +class _Pager extends StatelessWidget { + const _Pager({ + required this.index, + required this.count, + required this.onPrevious, + required this.onNext, + }); + + final int index; + final int count; + final VoidCallback onPrevious; + final VoidCallback onNext; + + @override + Widget build(BuildContext context) { + if (count <= 1) return const SizedBox.shrink(); + final hasPrevious = pagedIndex(index, -1, count) != index; + final hasNext = pagedIndex(index, 1, count) != index; + if (usesCupertinoHost(context)) { + return SafeArea( + top: false, + child: Wrap( + alignment: WrapAlignment.spaceBetween, + children: [ + CupertinoButton( + onPressed: hasPrevious ? onPrevious : null, + child: const Text('Previous artifact'), + ), + CupertinoButton( + onPressed: hasNext ? onNext : null, + child: const Text('Next artifact'), + ), + ], + ), + ); + } + return SafeArea( + top: false, + child: Padding( + padding: const EdgeInsetsDirectional.fromSTEB(8, 0, 8, 4), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + TextButton.icon( + onPressed: hasPrevious ? onPrevious : null, + icon: const Icon(Icons.arrow_back), + label: const Text('Previous artifact'), + ), + TextButton.icon( + onPressed: hasNext ? onNext : null, + icon: const Icon(Icons.arrow_forward), + label: const Text('Next artifact'), + ), + ], + ), + ), + ); + } +} diff --git a/app/lib/features/artifacts/ui/artifact_viewer_content.dart b/app/lib/features/artifacts/ui/artifact_viewer_content.dart new file mode 100644 index 00000000..a191b8fb --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_viewer_content.dart @@ -0,0 +1,122 @@ +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; + +import '../domain/artifact_preview.dart'; + +/// Renders fetched markdown text for the viewer. The gallery's default builder +/// returns plain selectable text, so the viewer is honest before the markdown +/// lane supplies a real renderer. +typedef ArtifactMarkdownBuilder = Widget Function(String text); + +Widget defaultArtifactMarkdown(String text) => SelectableText(text); + +/// The viewer's preview surface for one page. +/// +/// It draws only what was actually fetched: image bytes as an [Image], text as +/// selectable text, markdown through [markdownBuilder], and an explicit message +/// for unsupported/unavailable pages. It never substitutes a placeholder that +/// looks like a preview. +class ArtifactPreviewBody extends StatelessWidget { + const ArtifactPreviewBody({ + super.key, + required this.plan, + required this.loading, + required this.markdownBuilder, + this.text, + this.bytes, + this.error, + }); + + final ArtifactPreviewPlan plan; + final bool loading; + final ArtifactMarkdownBuilder markdownBuilder; + final String? text; + final Uint8List? bytes; + final String? error; + + @override + Widget build(BuildContext context) { + if (plan.kind == ArtifactPreviewKind.unavailable || + plan.kind == ArtifactPreviewKind.unsupported) { + return _Message(plan.message); + } + if (loading) { + return const _Loading(); + } + if (error != null) { + return _Message(error!); + } + switch (plan.kind) { + case ArtifactPreviewKind.image: + final data = bytes; + if (data == null) return const _Message('The image is empty.'); + return Center( + child: Image.memory( + data, + fit: BoxFit.contain, + errorBuilder: (_, _, _) => + const _Message('The image could not be decoded.'), + ), + ); + case ArtifactPreviewKind.text: + return _ScrollingText(child: SelectableText(text ?? '')); + case ArtifactPreviewKind.markdown: + return _ScrollingText(child: markdownBuilder(text ?? '')); + case ArtifactPreviewKind.unsupported: + case ArtifactPreviewKind.unavailable: + return const SizedBox.shrink(); + } + } +} + +class _Loading extends StatelessWidget { + const _Loading(); + + @override + Widget build(BuildContext context) { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const CircularProgressIndicator(), + const SizedBox(height: 12), + Text( + 'Loading preview…', + style: Theme.of(context).textTheme.bodyMedium, + ), + ], + ), + ); + } +} + +class _ScrollingText extends StatelessWidget { + const _ScrollingText({required this.child}); + + final Widget child; + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 16), + child: child, + ); + } +} + +class _Message extends StatelessWidget { + const _Message(this.message); + + final String message; + + @override + Widget build(BuildContext context) { + return Center( + child: Padding( + padding: const EdgeInsets.all(16), + child: Text(message, textAlign: TextAlign.center), + ), + ); + } +} diff --git a/app/lib/features/artifacts/ui/artifact_viewer_fetch.dart b/app/lib/features/artifacts/ui/artifact_viewer_fetch.dart new file mode 100644 index 00000000..d757af45 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_viewer_fetch.dart @@ -0,0 +1,35 @@ +import 'dart:typed_data'; + +import 'artifact_viewer_fetch_stub.dart' + if (dart.library.js_interop) 'artifact_viewer_fetch_web.dart' + as impl; + +/// One artifact fetch result: the status the server answered and the bytes. +class ArtifactFetchResult { + const ArtifactFetchResult({required this.status, required this.bytes}); + + final int status; + final Uint8List bytes; + + bool get ok => status >= 200 && status < 300; +} + +/// A fetch that did not reach an HTTP response (network, TLS, blocked, ...). +class ArtifactFetchException implements Exception { + const ArtifactFetchException(this.message); + + final String message; + + @override + String toString() => message; +} + +/// Fetches an already resolved same-origin artifact. +/// +/// The viewer only calls this for [planArtifactPreview]'s safe local urls; the +/// platform implementation sends no credentials to a different origin. +typedef ArtifactFetch = Future Function(Uri uri); + +/// The host fetch used when a caller does not inject one. Web uses `fetch` with +/// same-origin credentials; native uses an HttpClient with no stored cookies. +Future fetchArtifact(Uri uri) => impl.fetchArtifact(uri); diff --git a/app/lib/features/artifacts/ui/artifact_viewer_fetch_stub.dart b/app/lib/features/artifacts/ui/artifact_viewer_fetch_stub.dart new file mode 100644 index 00000000..8c1bb237 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_viewer_fetch_stub.dart @@ -0,0 +1,29 @@ +import 'dart:io'; +import 'dart:typed_data'; + +import 'artifact_viewer_fetch.dart'; + +/// Native fetch for an already resolved same-origin artifact. +/// +/// No cookie jar, authorization header or userinfo is attached, redirects are +/// not followed across origins, and the caller only passes safe local urls. +Future fetchArtifact(Uri uri) async { + final client = HttpClient()..connectionTimeout = const Duration(seconds: 15); + try { + final request = await client.getUrl(uri); + request.followRedirects = false; + final response = await request.close(); + final bytes = BytesBuilder(copy: false); + await for (final chunk in response) { + bytes.add(chunk); + } + return ArtifactFetchResult( + status: response.statusCode, + bytes: bytes.takeBytes(), + ); + } on IOException catch (error) { + throw ArtifactFetchException('$error'); + } finally { + client.close(force: true); + } +} diff --git a/app/lib/features/artifacts/ui/artifact_viewer_fetch_web.dart b/app/lib/features/artifacts/ui/artifact_viewer_fetch_web.dart new file mode 100644 index 00000000..5cb2fb04 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_viewer_fetch_web.dart @@ -0,0 +1,37 @@ +import 'dart:js_interop'; + +import 'artifact_viewer_fetch.dart'; + +@JS('fetch') +external JSPromise<_FetchResponse> _fetch(JSString input, _FetchInit init); + +extension type _FetchInit._(JSObject _) implements JSObject { + external factory _FetchInit({JSString credentials}); +} + +extension type _FetchResponse._(JSObject _) implements JSObject { + external int get status; + + external JSPromise arrayBuffer(); +} + +/// Web fetch for an already resolved same-origin artifact. +/// +/// `credentials: 'same-origin'` attaches the browser's credentials only to this +/// server's origin; the viewer never asks for another origin. The status is +/// returned verbatim so a failed preview can report the HTTP failure. +Future fetchArtifact(Uri uri) async { + try { + final response = await _fetch( + uri.toString().toJS, + _FetchInit(credentials: 'same-origin'.toJS), + ).toDart; + final buffer = await response.arrayBuffer().toDart; + return ArtifactFetchResult( + status: response.status, + bytes: buffer.toDart.asUint8List(), + ); + } catch (error) { + throw ArtifactFetchException('$error'); + } +} diff --git a/app/lib/features/artifacts/ui/artifact_viewer_page.dart b/app/lib/features/artifacts/ui/artifact_viewer_page.dart new file mode 100644 index 00000000..5673986f --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_viewer_page.dart @@ -0,0 +1,250 @@ +import 'dart:convert'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../../../ui/adaptive/host.dart'; +import '../domain/artifact_groups.dart'; +import '../domain/artifact_preview.dart'; +import '../domain/artifact_url.dart'; +import '../domain/gallery_navigation.dart'; +import 'artifact_external_open.dart'; +import 'artifact_viewer_body.dart'; +import 'artifact_viewer_content.dart'; +import 'artifact_viewer_fetch.dart'; +import 'artifact_visit_list.dart'; + +/// The full-screen viewer's title, matching the web client's wording. +const String artifactViewerTitle = 'Artifact viewer'; + +/// One artifact of a recorded visit, previewed in-app. +/// +/// Images are drawn from bytes fetched from the already-resolved safe url, a +/// `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. +/// +/// Nothing is ever drawn for an external, unsafe or unsupported url: the viewer +/// reports the exact state instead. External urls are never fetched. +class ArtifactViewerPage extends StatefulWidget { + const ArtifactViewerPage({ + super.key, + required this.groups, + required this.selectedIdentity, + this.configuredEndpoint = '', + this.fetch = fetchArtifact, + this.markdownBuilder = defaultArtifactMarkdown, + this.openExternal = openArtifactExternally, + }); + + final List groups; + + /// [artifactVisitIdentityOf] of the row the operator selected. + final String selectedIdentity; + + final String configuredEndpoint; + final ArtifactFetch fetch; + final ArtifactMarkdownBuilder markdownBuilder; + final ArtifactExternalOpen openExternal; + + @override + State createState() => _ArtifactViewerPageState(); +} + +class _FetchedPreview { + const _FetchedPreview({this.text, this.bytes}); + + final String? text; + final Uint8List? bytes; +} + +class _ArtifactViewerPageState extends State { + late final List _pages = pagedArtifacts(widget.groups); + final Map _cache = {}; + late int _index = _initialIndex(); + int _generation = 0; + bool _loading = false; + String? _error; + _FetchedPreview? _fetched; + String? _status; + + int _initialIndex() { + final found = _pages.indexWhere( + (page) => + artifactVisitIdentityOf(page.group, page.artifact) == + widget.selectedIdentity, + ); + return found < 0 ? 0 : found; + } + + PagedArtifact? get _page => _index < _pages.length ? _pages[_index] : null; + + ArtifactPreviewPlan? get _plan { + final page = _page; + if (page == null) return null; + return planArtifactPreview( + artifact: page.artifact, + configuredEndpoint: widget.configuredEndpoint, + ); + } + + @override + void initState() { + super.initState(); + _beginLoad(initial: true); + } + + void _beginLoad({bool initial = false}) { + final generation = ++_generation; + final plan = _plan; + if (plan == null || !plan.canFetch) { + void clear() { + _loading = false; + _error = null; + _fetched = null; + } + + if (initial) { + clear(); + } else { + setState(clear); + } + return; + } + final key = plan.resolved!.url; + final cached = _cache[key]; + if (cached != null) { + void apply() { + _loading = false; + _error = null; + _fetched = cached; + } + + if (initial) { + apply(); + } else { + setState(apply); + } + return; + } + void start() { + _loading = true; + _error = null; + _fetched = null; + } + + if (initial) { + start(); + } else { + setState(start); + } + widget + .fetch(plan.resolved!.uri) + .then( + (result) { + if (!mounted || generation != _generation) return; + if (!result.ok) { + setState(() { + _loading = false; + _error = 'The server answered ${result.status}.'; + }); + return; + } + final fetched = _decode(plan.kind, result.bytes); + _cache[key] = fetched; + setState(() { + _loading = false; + _fetched = fetched; + }); + }, + onError: (Object error) { + if (!mounted || generation != _generation) return; + setState(() { + _loading = false; + _error = 'Could not load preview: $error'; + }); + }, + ); + } + + static _FetchedPreview _decode(ArtifactPreviewKind kind, Uint8List bytes) { + if (kind == ArtifactPreviewKind.image) { + return _FetchedPreview(bytes: bytes); + } + return _FetchedPreview(text: utf8.decode(bytes, allowMalformed: true)); + } + + void _step(int delta) { + final next = pagedIndex(_index, delta, _pages.length); + if (next == _index) return; + setState(() { + _index = next; + _status = null; + }); + _beginLoad(); + } + + Future _open(ResolvedArtifactUrl resolved) async { + final opened = await widget.openExternal(resolved.uri); + if (!mounted) return; + setState( + () => + _status = opened ? 'Link opened externally.' : 'Could not open link.', + ); + } + + Future _copy(ResolvedArtifactUrl resolved) async { + String message; + try { + await Clipboard.setData(ClipboardData(text: resolved.url)); + message = 'Link copied.'; + } catch (_) { + message = 'Could not copy link.'; + } + if (!mounted) return; + setState(() => _status = message); + } + + @override + Widget build(BuildContext context) { + final page = _page; + final plan = _plan; + final title = page == null + ? artifactViewerTitle + : artifactDisplayName(page.artifact); + final body = page == null || plan == null + ? const Center(child: Text('No previewable artifacts recorded.')) + : ArtifactViewerBody( + page: page, + plan: plan, + index: _index, + count: _pages.length, + loading: _loading, + markdownBuilder: widget.markdownBuilder, + text: _fetched?.text, + bytes: _fetched?.bytes, + error: _error, + status: _status, + onPrevious: () => _step(-1), + onNext: () => _step(1), + onOpen: plan.resolved == null ? () {} : () => _open(plan.resolved!), + onCopy: plan.resolved == null ? () {} : () => _copy(plan.resolved!), + ); + if (usesCupertinoHost(context)) { + return CupertinoPageScaffold( + backgroundColor: CupertinoColors.systemGroupedBackground, + navigationBar: CupertinoNavigationBar( + middle: Text(title, overflow: TextOverflow.ellipsis), + ), + child: SafeArea(child: body), + ); + } + return Scaffold( + appBar: AppBar(title: Text(title, overflow: TextOverflow.ellipsis)), + body: SafeArea(top: false, child: body), + ); + } +} diff --git a/app/lib/features/artifacts/ui/artifact_visit_list.dart b/app/lib/features/artifacts/ui/artifact_visit_list.dart index 82cf0aa8..a134d250 100644 --- a/app/lib/features/artifacts/ui/artifact_visit_list.dart +++ b/app/lib/features/artifacts/ui/artifact_visit_list.dart @@ -5,6 +5,7 @@ import '../../../ui/adaptive/host.dart'; import '../domain/artifact_groups.dart'; import '../domain/artifact_kind.dart'; import '../domain/artifact_record.dart'; +import '../domain/gallery_navigation.dart'; /// A selection callback carrying the recorded group and the exact record the /// operator chose, so the visit is never lost when two groups share a name. @@ -17,9 +18,26 @@ typedef ArtifactSelected = /// The recorded stage visit is part of the key, so two visits that both /// recorded `result.csv` stay distinct even when their urls are identical. /// A filename alone is never an identity. -String artifactVisitIdentity(ArtifactGroup group, ArtifactRecord artifact) { - final recorded = artifact.hasUrl ? artifact.url : artifact.name; - return '${group.stageKey}\u0000${group.visit}\u0000$recorded'; +String artifactVisitIdentity(ArtifactGroup group, ArtifactRecord artifact) => + artifactVisitIdentityOf(group, artifact); + +/// The recorded group heading, matching the web client's group vocabulary. +String artifactGroupLabel(ArtifactGroup group) => + '${group.stageKey} · visit ${group.visit}'; + +/// The displayed artifact name: a missing server name stays explicit. +String artifactDisplayName(ArtifactRecord artifact) => + artifact.name.isEmpty ? '(unnamed artifact)' : artifact.name; + +/// The recorded MIME and byte size, never inferred from the name. +/// +/// The value and its unit are joined by a non-breaking space so a narrow row +/// never wraps `120.6` away from `KiB`. +String artifactFactsLabel(ArtifactRecord artifact) { + final type = artifact.contentType.split(';').first.trim(); + final mime = type.isEmpty ? 'type not recorded' : type; + final size = humanBytes(artifact.sizeBytes).replaceFirst(' ', '\u00a0'); + return '$mime · $size'; } /// A read-only, selectable list of recorded artifact groups. @@ -60,7 +78,7 @@ class ArtifactVisitList extends StatelessWidget { header: Semantics( container: true, header: true, - child: Text(_groupLabel(group)), + child: Text(artifactGroupLabel(group)), ), hasLeading: false, children: [ @@ -85,7 +103,7 @@ class ArtifactVisitList extends StatelessWidget { child: Semantics( container: true, header: true, - child: Text(_groupLabel(group)), + child: Text(artifactGroupLabel(group)), ), ), for (var index = 0; index < group.artifacts.length; index += 1) @@ -108,25 +126,6 @@ class ArtifactVisitList extends StatelessWidget { ValueKey('${artifactVisitIdentity(group, artifact)}\u0000$index'); } -/// The recorded group heading, matching the web client's group vocabulary. -String _groupLabel(ArtifactGroup group) => - '${group.stageKey} · visit ${group.visit}'; - -/// The displayed artifact name: a missing server name stays explicit. -String _displayName(ArtifactRecord artifact) => - artifact.name.isEmpty ? '(unnamed artifact)' : artifact.name; - -/// The recorded MIME and byte size, never inferred from the name. -/// -/// The value and its unit are joined by a non-breaking space so a narrow row -/// never wraps `120.6` away from `KiB`. -String _facts(ArtifactRecord artifact) { - final type = artifact.contentType.split(';').first.trim(); - final mime = type.isEmpty ? 'type not recorded' : type; - final size = humanBytes(artifact.sizeBytes).replaceFirst(' ', '\u00a0'); - return '$mime · $size'; -} - class _MaterialRow extends StatelessWidget { const _MaterialRow({ super.key, @@ -145,8 +144,8 @@ class _MaterialRow extends StatelessWidget { Widget build(BuildContext context) { return ListTile( selected: selected, - title: Text(_displayName(artifact)), - subtitle: Text(_facts(artifact)), + title: Text(artifactDisplayName(artifact)), + subtitle: Text(artifactFactsLabel(artifact)), trailing: selected ? const Icon(Icons.check) : null, onTap: onSelected == null ? null : () => onSelected!(group, artifact), ); @@ -181,8 +180,8 @@ class _CupertinoRow extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(_displayName(artifact)), - Text(_facts(artifact), style: factsStyle), + Text(artifactDisplayName(artifact)), + Text(artifactFactsLabel(artifact), style: factsStyle), ], ), ), diff --git a/app/lib/features/attention/domain/attention_models.dart b/app/lib/features/attention/domain/attention_models.dart new file mode 100644 index 00000000..6381b86d --- /dev/null +++ b/app/lib/features/attention/domain/attention_models.dart @@ -0,0 +1,246 @@ +import 'dart:convert'; + +import '../../../core/api_gateway.dart'; + +/// The two things the attention surface ranks, most important first. The rank +/// orders the list; the wire name is what a dismissal identity is keyed by. +/// +/// This mirrors the browser's pure `web/src/attention.js` model: only a run +/// parked on a person ([AttentionKind.decision]) and a failed run +/// ([AttentionKind.failed]) need the operator. A waiting run that is really an +/// audit/export handoff asks nobody, so it is excluded by [attentionKindForRun]. +enum AttentionKind { + decision(0, 'Decision'), + failed(1, 'Failed'); + + const AttentionKind(this.rank, this.wireName); + + final int rank; + + /// The spelling used in a persisted `{runId}:{kind}` identity. + final String wireName; +} + +/// This client's own storage key, namespaced like the rest of the app +/// (`pipelines.next.*`). The identity format matches the browser's, but a +/// dismissal set is deliberately not shared with the legacy web app: the two +/// clients must never rewrite each other's local state on a shared origin. +const attentionStorageKey = 'pipelines.next.attention.v1'; + +/// The run id a summary or pushed frame carries, or null when it is malformed. +/// The server ids are positive integers; anything else cannot identify an entry. +int? attentionRunId(dynamic value) { + final id = value is num + ? (value.isFinite ? value.toInt() : null) + : int.tryParse('${value ?? ''}'.trim()); + return id != null && id > 0 ? id : null; +} + +/// The attention kind a server status word maps to. Only the server's own +/// `waiting` and `failed` words qualify; queued, running, succeeded, canceled, +/// interrupted and unknown words ask nobody. A waiting run's *reason* is +/// checked by [attentionKindForRun], because the status word alone cannot tell a +/// human decision from an export handoff. +AttentionKind? attentionKindOf(dynamic status) { + switch (_word(status)) { + case 'waiting': + return AttentionKind.decision; + case 'failed': + return AttentionKind.failed; + default: + return null; + } +} + +/// The attention kind a complete run summary maps to, or null when it asks +/// nobody. +/// +/// A `waiting` run is listed only when it is actually waiting on a person. It is +/// not a Decision when the server recorded a session audit/export handoff +/// (`export_pending_sequence > 0`), so a machine export wait never reaches the +/// operator's "Needs you" list. +/// +/// `resource_wait` is deliberately not consulted, matching `web/src/attention.js` +/// and the Android client: it was retired server-side, and a stale value carried +/// onto a waiting run must not hide a genuine human decision. +AttentionKind? attentionKindForRun(JsonMap run) { + final kind = attentionKindOf(run['status']); + if (kind != AttentionKind.decision) return kind; + if (_positive(run['export_pending_sequence'])) return null; + return kind; +} + +/// The identity of one run+kind entry; the unit an explicit dismissal removes. +String attentionKey(int runId, AttentionKind kind) => '$runId:${kind.wireName}'; + +/// What one entry asks of the operator, in the operator's words. A failed run +/// shows the server's own diagnostic when it recorded one. +String attentionDetail(AttentionKind kind, JsonMap run) { + if (kind == AttentionKind.decision) return 'Waiting for your decision'; + final diagnostic = '${run['diagnostic'] ?? ''}'.trim(); + return diagnostic.isNotEmpty ? diagnostic : 'Run failed'; +} + +/// The one-line secondary text for a row: `{pipeline} · {detail}`. +String attentionRowDescription(AttentionEntry entry) => + '${entry.pipeline} · ${entry.detail}'; + +/// The bell action's accessible name: the bare `Notifications` when nothing +/// needs the operator, else the count. +String attentionBadgeLabel(int count) => + count > 0 ? 'Notifications, $count needing attention' : 'Notifications'; + +/// One run that needs the operator. +/// +/// The original summary map is kept whole, so fields this model does not read — +/// or fields a newer server adds — remain available to the caller unchanged. +/// Only [attentionEntryFor] constructs an entry, so [runId] is always a validated +/// positive server id rather than a getter that could throw. +class AttentionEntry { + const AttentionEntry._({ + required this.run, + required this.kind, + required this.runId, + }); + + final JsonMap run; + final AttentionKind kind; + final int runId; + + String get pipeline => '${run['name'] ?? ''}'; + String get detail => attentionDetail(kind, run); + String get key => attentionKey(runId, kind); + + /// The trimmed title else the pipeline label. + String get label { + final title = '${run['title'] ?? ''}'.trim(); + return title.isNotEmpty ? title : pipeline; + } + + /// The run's own recency, used only for ordering equal kinds newest-first. + /// A finished run is ordered by `finished_at`; a still-waiting one by its + /// creation time. + String get recency { + final finished = '${run['finished_at'] ?? ''}'; + return finished.trim().isNotEmpty ? finished : '${run['created_at'] ?? ''}'; + } +} + +/// The entry for one qualifying run, or null when it asks nobody. +AttentionEntry? attentionEntryFor(JsonMap run) { + final runId = attentionRunId(run['run_id']) ?? attentionRunId(run['id']); + final kind = attentionKindForRun(run); + if (runId == null || kind == null) return null; + return AttentionEntry._(run: run, kind: kind, runId: runId); +} + +/// The start of the operator's local day. "Needs you" is a to-do list for what +/// changed now, so callers pass this as [attentionEntries]' `since`; yesterday's +/// failures are history, not a badge that follows every device for ever. Inject +/// [now] for a deterministic test; production callers pass nothing. +DateTime startOfLocalDay({DateTime? now}) { + final local = (now ?? DateTime.now()).toLocal(); + return DateTime(local.year, local.month, local.day); +} + +/// The ordered attention list: one entry per qualifying run, minus any identity +/// the operator explicitly dismissed and minus work older than [since]. +/// +/// Order matches the browser: kind rank (Decision before Failed), then recency +/// descending (the server's timestamp text, `finished_at` else `created_at`), +/// then run id descending so equal rows never reshuffle between reads. +/// +/// [since] is the local-day cutoff ([startOfLocalDay]) the bell, the sheet and +/// Clear all pass. As in `web/src/attention.js`, the cutoff applies only when the +/// entry's recency parses as a timestamp; a blank or unreadable recency is kept. +/// A null or epoch-zero cutoff shows everything. +List attentionEntries( + Iterable? runs, { + Set dismissed = const {}, + DateTime? since, +}) { + final entries = []; + for (final run in runs ?? const []) { + final entry = attentionEntryFor(run); + if (entry == null || dismissed.contains(entry.key)) continue; + if (since != null && + since.millisecondsSinceEpoch > 0 && + _before(entry.recency, since)) { + continue; + } + entries.add(entry); + } + entries.sort((a, b) { + final rank = a.kind.rank.compareTo(b.kind.rank); + if (rank != 0) return rank; + final recency = b.recency.compareTo(a.recency); + return recency != 0 ? recency : b.runId.compareTo(a.runId); + }); + return entries; +} + +/// Captures what the surface showed when it opened. Clear all acts on this +/// snapshot, so an entry that arrives later is not silently removed. +List attentionDismissalSnapshot( + Iterable entries, +) => List.unmodifiable(entries); + +/// Adds one identity, ignoring a blank or already-present key. +Set attentionDismiss(Set dismissed, String key) { + final next = {...dismissed}; + if (key.trim().isNotEmpty) next.add(key); + return next; +} + +/// Unions exactly the snapshot's identities. Entries that arrived after the +/// snapshot was taken are left alone. +Set attentionDismissAll( + Set dismissed, + Iterable snapshot, +) { + final next = {...dismissed}; + for (final entry in snapshot) { + next.add(entry.key); + } + return next; +} + +/// The one-line JSON a dismissed set is stored as: a sorted array of strings, so +/// an unchanged set always encodes to the same bytes. +String encodeAttentionDismissals(Set dismissed) { + final keys = dismissed.where((key) => key.isNotEmpty).toList()..sort(); + return jsonEncode(keys); +} + +/// Decodes a stored value into a dismissed set. Total: blank text, unreadable +/// JSON, a non-array value and non-string members all decode to the members we +/// can read, and a malformed value never throws. +Set decodeAttentionDismissals(String? stored) { + final text = (stored ?? '').trim(); + if (text.isEmpty) return {}; + dynamic parsed; + try { + parsed = jsonDecode(text); + } catch (_) { + return {}; + } + if (parsed is! List) return {}; + return { + for (final value in parsed) + if (value is String && value.isNotEmpty) value, + }; +} + +String _word(dynamic value) => '${value ?? ''}'.trim().toLowerCase(); + +bool _positive(dynamic value) { + final number = value is num ? value : num.tryParse('${value ?? ''}'.trim()); + return (number ?? 0) > 0; +} + +/// True only when [recency] is a readable timestamp before [cutoff]. An +/// unparseable or blank timestamp is not filtered out, matching the browser. +bool _before(String recency, DateTime cutoff) { + final at = DateTime.tryParse(recency.trim()); + return at != null && at.isBefore(cutoff); +} diff --git a/app/lib/features/attention/domain/attention_transitions.dart b/app/lib/features/attention/domain/attention_transitions.dart new file mode 100644 index 00000000..8876ef40 --- /dev/null +++ b/app/lib/features/attention/domain/attention_transitions.dart @@ -0,0 +1,136 @@ +import '../../../core/api_gateway.dart'; +import 'attention_models.dart'; + +/// One newly-entered attention state: a run that has just become failed or has +/// just become a human decision. The entry carries the whole current summary, so +/// its wording and unknown fields match what the surface would show. +class AttentionTransition { + const AttentionTransition(this.entry); + + final AttentionEntry entry; + + int get runId => entry.runId; + AttentionKind get kind => entry.kind; + String get key => entry.key; + JsonMap get run => entry.run; +} + +/// Tracks the last status seen for each run and emits only a genuine transition +/// *into* a qualifying state. +/// +/// - [seed] records the authoritative list (the initial `list_runs` read or a +/// `subscribe` snapshot) without emitting anything, so a run that was already +/// failed/waiting before this client looked never announces itself. +/// - [beginSeed]/[endSeed] bracket a reconnect's pushed snapshot: frames seen +/// while seeding update the baseline but raise nothing, so a gap can never +/// manufacture a transition. +/// - [observe] emits only when a known run's status changes into `failed` or a +/// human `waiting`. A duplicate frame, an unchanged qualifying state, an +/// unknown/nonqualifying status and a first-seen run all return null. +/// - A run+kind key is forgotten when the run leaves that qualifying state (or +/// enters the other kind), so a genuinely new transition can fire once more; +/// the same transition can never repeat. +/// - [resetForReconnect] drops the status baseline but keeps the emitted keys. +/// The following [reseed] establishes the new baseline without emitting, so a +/// disconnect cannot produce a delayed notification for a state the operator +/// already saw. +class AttentionTransitionDetector { + final Map _lastStatus = {}; + final Set _emitted = {}; + bool _seeding = false; + + /// Records [runs] as the baseline without emitting. Keys that still qualify + /// are kept so a reconnect cannot repeat them; keys whose run disappeared from + /// the read are kept too, because an absent run tells us nothing. + void seed(Iterable? runs) { + final statuses = {}; + final kinds = {}; + for (final run in runs ?? const []) { + final runId = attentionRunId(run['run_id']) ?? attentionRunId(run['id']); + if (runId == null) continue; + statuses[runId] = _word(run['status']); + kinds[runId] = attentionKindForRun(run); + } + _lastStatus + ..clear() + ..addAll(statuses); + for (final key in [..._emitted]) { + final split = key.lastIndexOf(':'); + if (split <= 0) continue; + final runId = attentionRunId(key.substring(0, split)); + if (runId == null || !statuses.containsKey(runId)) continue; + final kind = kinds[runId]; + if (kind == null || key != attentionKey(runId, kind)) { + _emitted.remove(key); + } + } + } + + /// Replaces the baseline for a reconnect. Emitted keys survive: a transition + /// swallowed by the gap is not replayed after the socket returns. + void reseed(Iterable? runs) { + _lastStatus.clear(); + _seeding = false; + seed(runs); + } + + /// Drops the status baseline but keeps this session's emitted keys. Call + /// before the next [seed] when the connection is lost. + void resetForReconnect() { + _lastStatus.clear(); + _seeding = false; + } + + void beginSeed() => _seeding = true; + + void endSeed() => _seeding = false; + + /// Observes one pushed `run_event` summary/frame. Returns the transition only + /// when this run enters a qualifying state; [dismissed] identities are marked + /// seen but do not emit. + AttentionTransition? observe( + JsonMap frame, { + Set dismissed = const {}, + }) { + final runId = + attentionRunId(frame['run_id']) ?? attentionRunId(frame['id']); + final status = _word(frame['status']); + if (runId == null || status.isEmpty) return null; + + final previous = _lastStatus[runId]; + _lastStatus[runId] = status; + + final kind = attentionKindForRun(frame); + if (kind == null) { + _forget(runId); + return null; + } + for (final other in AttentionKind.values) { + if (other != kind) _emitted.remove(attentionKey(runId, other)); + } + if (_seeding) return null; + + final key = attentionKey(runId, kind); + if (previous == null || previous == status) return null; + + final entry = attentionEntryFor(frame); + if (entry == null) return null; + _emitted.add(key); + if (dismissed.contains(key)) return null; + return AttentionTransition(entry); + } + + /// A copy of the run+kind identities raised in this session. + Set get emittedKeys => {..._emitted}; + + /// The last status recorded for [runId], or null for a run never seen. + String? statusOf(int runId) => _lastStatus[runId]; + + void _forget(int runId) { + for (final kind in AttentionKind.values) { + _emitted.remove(attentionKey(runId, kind)); + } + } +} + +String _word(dynamic value) => '${value ?? ''}'.trim().toLowerCase(); diff --git a/app/lib/features/chat/conversation/chat_row_keys.dart b/app/lib/features/chat/conversation/chat_row_keys.dart new file mode 100644 index 00000000..f677ac09 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_row_keys.dart @@ -0,0 +1,73 @@ +import '../../../core/api_gateway.dart'; + +/// Stable widget-key strings for transcript rows while history grows at both +/// ends. +/// +/// A folded assistant turn has no stable message boundary: `Load older` can +/// prepend messages into the turn (changing its first id) and a live frame can +/// append a message (changing its last id). Deriving the row key from either +/// boundary remounts the row and resets every native disclosure in it, which +/// moved an open reasoning block to another answer or closed it. +/// +/// So the first sighting of a turn assigns a synthetic key, and later calls +/// carry that key forward while the turn still contains any message it held +/// before. Rows without a message id fall back to their position: they have no +/// identity that survives a prepend. +class ChatRowKeys { + final Map _byMessageId = {}; + int _serial = 0; + + /// One key per row, in row order. Call once per build. + List forRows(List rows) { + final nextByMessageId = {}; + final used = {}; + final keys = []; + for (var index = 0; index < rows.length; index++) { + final row = rows[index]; + final kind = '${row['kind'] ?? ''}'; + final ids = _messageIds(row); + String? key; + for (final id in ids) { + final held = _byMessageId[id]; + if (held != null) { + key = held; + break; + } + } + if (key == null) { + // A row with no id has no identity that survives a prepend, so it + // follows its position, as a plain indexed list would. Every other new + // row gets a key no older row can generate. + key = ids.isEmpty + ? 'chat-row-$kind-index-$index' + : 'chat-row-$kind-${_serial++}'; + used.add(key); + } else if (!used.add(key)) { + // Defensive: a held key is only reused once even if input unexpectedly + // splits one turn into two rows; duplicate widget keys would throw. + key = 'chat-row-$kind-${_serial++}'; + used.add(key); + } + keys.add(key); + for (final id in ids) { + nextByMessageId[id] = key; + } + } + _byMessageId + ..clear() + ..addAll(nextByMessageId); + return keys; + } + + static List _messageIds(JsonMap row) { + final listed = row['messageIds']; + if (listed is List) { + return listed + .map((id) => '$id'.trim()) + .where((id) => id.isNotEmpty) + .toList(); + } + final key = '${row['key'] ?? ''}'.trim(); + return key.isEmpty ? const [] : [key]; + } +} diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart new file mode 100644 index 00000000..b5257ab9 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -0,0 +1,195 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../domain/chat_transcript.dart'; +import '../ui/sessions/chat_adaptive.dart'; +import '../ui/transcript/chat_message_view.dart'; +import 'chat_row_keys.dart'; +import 'chat_thread_controller.dart'; + +/// One read-only conversation: the controller's transcript in the order the +/// server reports it, rendered by the existing [ChatMessageView]. +/// +/// History and live-subscription failures are separate notices: readable stored +/// history must never hide a refused live watch. The shell owns the navigation +/// bar, so this view adds only its own Back control and content. +class ChatThreadView extends StatefulWidget { + const ChatThreadView({ + super.key, + required this.gateway, + required this.sessionId, + required this.onBack, + this.title = '', + this.syncToken = 0, + }); + + final ApiGateway gateway; + final String sessionId; + final VoidCallback onBack; + + /// The list row's title when this visit knows it; a deep link may not. + final String title; + + /// Advances when the shared socket is replaced, keeping this selection. + final int syncToken; + + @override + State createState() => _ChatThreadViewState(); +} + +class _ChatThreadViewState extends State { + late ChatThreadController _controller = _attach(); + late ChatRowKeys _rowKeys = ChatRowKeys(); + + ChatThreadController _attach() => + ChatThreadController(widget.gateway, widget.sessionId)..load(); + + @override + void didUpdateWidget(covariant ChatThreadView oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.gateway != widget.gateway || + oldWidget.sessionId != widget.sessionId) { + _controller.dispose(); + _controller = _attach(); + _rowKeys = ChatRowKeys(); + } else if (oldWidget.syncToken != widget.syncToken) { + unawaited(_controller.resync()); + } + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => AnimatedBuilder( + animation: _controller, + builder: (context, _) { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final rows = transcriptRows(_controller.messages); + // 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 + // its previous messages, keeping the element (and its open disclosures) + // across paging and streaming. + final keys = _rowKeys.forRows(rows); + final initialLoad = !_controller.loaded && _controller.loading; + return ListView( + key: ValueKey('chat-thread-${widget.sessionId}'), + padding: const EdgeInsets.symmetric(vertical: 8), + children: [ + Padding( + key: const Key('chat-thread-header'), + padding: const EdgeInsetsDirectional.fromSTEB(8, 0, 16, 4), + child: Wrap( + spacing: 8, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + _backButton(cupertino), + if (widget.title.trim().isNotEmpty) + Text( + widget.title.trim(), + style: cupertino + ? CupertinoTheme.of(context).textTheme.navTitleTextStyle + : Theme.of(context).textTheme.titleLarge, + ), + ], + ), + ), + if (initialLoad) + Padding( + key: const Key('chat-thread-loading'), + padding: const EdgeInsets.all(16), + child: Center( + child: cupertino + ? const CupertinoActivityIndicator() + : const CircularProgressIndicator(), + ), + ), + if (_controller.hasMore) + Padding( + key: const Key('chat-load-older'), + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Align( + alignment: AlignmentDirectional.centerStart, + child: cupertino + ? CupertinoButton( + padding: EdgeInsets.zero, + onPressed: _controller.loading + ? null + : _controller.loadOlder, + child: const Text('Load older'), + ) + : TextButton( + onPressed: _controller.loading + ? null + : _controller.loadOlder, + child: const Text('Load older'), + ), + ), + ), + if (_controller.error != null) + ChatErrorNotice( + key: const Key('chat-history-error'), + message: 'Chat history unavailable\n${_controller.error}', + onRetry: _controller.load, + ), + if (_controller.subscriptionError != null) + ChatErrorNotice( + key: const Key('chat-live-error'), + message: + 'Live updates unavailable\n${_controller.subscriptionError}', + onRetry: _controller.resync, + ), + if (_controller.loaded && rows.isEmpty && _controller.error == null) + const Padding( + key: Key('chat-thread-empty'), + padding: EdgeInsets.all(16), + child: Text('No messages in this chat yet.'), + ), + for (var index = 0; index < rows.length; index++) + Padding( + key: ValueKey(keys[index]), + padding: const EdgeInsets.symmetric(horizontal: 16), + child: ChatMessageView(row: rows[index]), + ), + if (_controller.running) + Padding( + key: const Key('chat-running'), + padding: const EdgeInsets.all(16), + child: Semantics( + liveRegion: true, + child: const Text('Assistant is responding…'), + ), + ), + ], + ); + }, + ); + + Widget _backButton(bool cupertino) => cupertino + ? CupertinoButton( + padding: const EdgeInsetsDirectional.fromSTEB(8, 0, 8, 0), + onPressed: widget.onBack, + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(CupertinoIcons.back), + SizedBox(width: 4), + Text('Back'), + ], + ), + ) + : TextButton.icon( + onPressed: widget.onBack, + icon: const Icon(Icons.arrow_back), + label: const Text('Back to chats'), + ); +} diff --git a/app/lib/features/chat/domain/chat_transcript.dart b/app/lib/features/chat/domain/chat_transcript.dart index b766f15e..b9f54459 100644 --- a/app/lib/features/chat/domain/chat_transcript.dart +++ b/app/lib/features/chat/domain/chat_transcript.dart @@ -34,25 +34,36 @@ JsonMap mergeChatHistory(JsonMap previous, JsonMap page, {bool older = false}) { /// Consecutive assistant messages form one answer turn. All part fields (also /// future/unknown protocol types) are preserved in original order. +/// +/// `key` is the turn's first assistant message id, which is only a display +/// anchor: paging an older assistant message into the turn changes it, so widget +/// 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 transcriptRows(List messages) { final rows = []; String? key; + final ids = []; final parts = []; void flush() { if (key != null && parts.isNotEmpty) { rows.add({ 'kind': 'assistant', 'key': key, + 'messageIds': List.of(ids), 'parts': List.of(parts), }); } key = null; + ids.clear(); parts.clear(); } for (final message in messages) { if (message['role'] == 'assistant') { - key ??= '${message['id'] ?? ''}'; + final id = '${message['id'] ?? ''}'.trim(); + key ??= id; + if (id.isNotEmpty) ids.add(id); for (final part in (message['parts'] as List? ?? const [])) { if (part is Map) parts.add(Map.from(part)); } diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart new file mode 100644 index 00000000..f2859581 --- /dev/null +++ b/app/lib/features/chat/screen.dart @@ -0,0 +1,99 @@ +import 'package:flutter/material.dart'; + +import '../../core/api_gateway.dart'; +import 'conversation/chat_thread_view.dart'; +import 'ui/sessions/chat_sessions_screen.dart'; + +/// The Chat destination's list/detail switch. +/// +/// The route names the open session, so a row tap, a deep link and Back all +/// navigate through the same value. The session list stays mounted (offstage) +/// while a conversation is open, so returning to it keeps its rows and query. +/// The shell owns the app bar; this screen adds no second one. +class ChatScreen extends StatefulWidget { + const ChatScreen({ + super.key, + required this.gateway, + this.initialSessionId, + this.syncToken = 0, + this.onSessionSelected, + this.onBack, + }); + + final ApiGateway gateway; + + /// The chat session the current route names, or null for the list. + final String? initialSessionId; + + /// Advances when the shared socket is replaced. The open conversation + /// re-subscribes and re-reads in place, so its selection survives. + final int syncToken; + + final ValueChanged? onSessionSelected; + final VoidCallback? onBack; + + @override + State createState() => _ChatScreenState(); +} + +class _ChatScreenState extends State { + /// Rows opened in this visit, used only for the native title. A deep link has + /// no title until the list loads, and this screen waits for no list request. + final Map _titles = {}; + String? _standaloneSelection; + + String? get _selected { + final routed = widget.initialSessionId; + if (routed != null && routed.isNotEmpty) return routed; + return _standaloneSelection; + } + + void _open(JsonMap session) { + final id = '${session['id'] ?? ''}'; + if (id.isEmpty) return; + final title = '${session['title'] ?? ''}'.trim(); + if (title.isNotEmpty) _titles[id] = title; + final select = widget.onSessionSelected; + if (select != null) { + select(id); + } else { + setState(() => _standaloneSelection = id); + } + } + + void _back() { + final back = widget.onBack; + if (back != null) { + back(); + } else { + setState(() => _standaloneSelection = null); + } + } + + @override + Widget build(BuildContext context) { + final selected = _selected; + return Stack( + children: [ + Offstage( + offstage: selected != null, + child: ChatSessionsScreen( + gateway: widget.gateway, + embedded: true, + syncToken: widget.syncToken, + onOpen: _open, + ), + ), + if (selected != null) + ChatThreadView( + key: ValueKey('chat-session-$selected'), + gateway: widget.gateway, + sessionId: selected, + title: _titles[selected] ?? '', + syncToken: widget.syncToken, + onBack: _back, + ), + ], + ); + } +} diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart index ff345739..f15311f1 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; @@ -16,10 +18,19 @@ class ChatSessionsScreen extends StatefulWidget { super.key, required this.gateway, required this.onOpen, + this.embedded = false, + this.syncToken = 0, }); final ApiGateway gateway; final void Function(JsonMap session) onOpen; + /// True under the application shell, which owns the single navigation bar. + final bool embedded; + + /// Advances when the shared socket is replaced; sessions created, renamed or + /// closed elsewhere during the gap must not stay invisible until Refresh. + final int syncToken; + @override State createState() => _ChatSessionsScreenState(); } @@ -35,6 +46,8 @@ class _ChatSessionsScreenState extends State { super.didUpdateWidget(oldWidget); if (oldWidget.gateway != widget.gateway) { _controller.replaceRepository(ChatRepository(widget.gateway)); + } else if (oldWidget.syncToken != widget.syncToken) { + unawaited(_controller.refresh()); } } @@ -115,53 +128,38 @@ class _ChatSessionsScreenState extends State { ], ); + if (widget.embedded) { + return Column( + children: [ + Align( + alignment: AlignmentDirectional.centerEnd, + child: Padding( + padding: const EdgeInsetsDirectional.only(end: 8), + child: Row( + mainAxisSize: MainAxisSize.min, + children: _actions(), + ), + ), + ), + Expanded(child: body), + ], + ); + } + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { return CupertinoPageScaffold( navigationBar: CupertinoNavigationBar( middle: const Text('Chats'), trailing: Row( mainAxisSize: MainAxisSize.min, - children: [ - ChatBarAction( - key: const Key('chat-new-chat'), - label: 'New chat', - onPressed: _newChat, - materialIcon: Icons.add, - cupertinoIcon: CupertinoIcons.add, - ), - ChatBarAction( - key: const Key('chat-refresh'), - label: 'Refresh', - onPressed: _controller.refresh, - materialIcon: Icons.refresh, - cupertinoIcon: CupertinoIcons.refresh, - ), - ], + children: _actions(), ), ), child: SafeArea(child: body), ); } return Scaffold( - appBar: AppBar( - title: const Text('Chats'), - actions: [ - ChatBarAction( - key: const Key('chat-new-chat'), - label: 'New chat', - onPressed: _newChat, - materialIcon: Icons.add, - cupertinoIcon: CupertinoIcons.add, - ), - ChatBarAction( - key: const Key('chat-refresh'), - label: 'Refresh', - onPressed: _controller.refresh, - materialIcon: Icons.refresh, - cupertinoIcon: CupertinoIcons.refresh, - ), - ], - ), + appBar: AppBar(title: const Text('Chats'), actions: _actions()), body: body, floatingActionButton: FloatingActionButton.extended( key: const Key('chat-new-chat-fab'), @@ -173,4 +171,21 @@ class _ChatSessionsScreenState extends State { }, ); } + + List _actions() => [ + ChatBarAction( + key: const Key('chat-new-chat'), + label: 'New chat', + onPressed: _newChat, + materialIcon: Icons.add, + cupertinoIcon: CupertinoIcons.add, + ), + ChatBarAction( + key: const Key('chat-refresh'), + label: 'Refresh', + onPressed: _controller.refresh, + materialIcon: Icons.refresh, + cupertinoIcon: CupertinoIcons.refresh, + ), + ]; } diff --git a/app/lib/features/chat/ui/transcript/chat_message_view.dart b/app/lib/features/chat/ui/transcript/chat_message_view.dart index 953da8b4..3cb022d3 100644 --- a/app/lib/features/chat/ui/transcript/chat_message_view.dart +++ b/app/lib/features/chat/ui/transcript/chat_message_view.dart @@ -92,13 +92,34 @@ class ChatMessageView extends StatelessWidget { List _agentParts(BuildContext context) { final widgets = []; - for (final part in _partsOf(row)) { + final parts = _partsOf(row); + final seen = {}; + for (var index = 0; index < parts.length; index++) { + final part = parts[index]; final widget = _agentPart(context, part); - if (widget != null) widgets.add(widget); + if (widget == null) continue; + // Part identity, not position, so an older assistant message that folds + // into the same turn can prepend its parts without moving an open + // disclosure. The enclosing row's identity is carried by ChatRowKeys; a + // part with no server id still falls back to its position. + widgets.add( + KeyedSubtree(key: _partKey(part, index, seen), child: widget), + ); } return widgets; } + /// The server's part id when there is one, else this part's position. A + /// repeated identity gets an ordinal so two sibling keys never collide. + Key _partKey(JsonMap part, int index, Map seen) { + final type = '${part['type'] ?? ''}'; + final id = '${part['id'] ?? ''}'.trim(); + final base = id.isEmpty ? 'index-$index' : '$type:$id'; + final ordinal = (seen[base] ?? 0) + 1; + seen[base] = ordinal; + return ValueKey('chat-part-$base-$ordinal'); + } + /// One agent part, or null when a known part has nothing to draw. The web's /// `partRendering` hides blank text/reasoning too, so a blank known part must /// not fall through to the unknown-part disclosure. diff --git a/app/lib/features/graph/domain/stage_definition.dart b/app/lib/features/graph/domain/stage_definition.dart new file mode 100644 index 00000000..08680773 --- /dev/null +++ b/app/lib/features/graph/domain/stage_definition.dart @@ -0,0 +1,212 @@ +import 'graph_definition.dart'; +import 'graph_protocol.dart'; + +/// The read-only definition of one declared stage, as field rows. +/// +/// Mirrors `stageDefinitionFields`/`terminalFields` from `web/src/graph.js`: +/// the same labels, the same order, and the same rule that blank fields are +/// omitted rather than shown as an empty row. Pure data only: nothing here +/// reads run visits, so a definition can be inspected without claiming that a +/// stage executed. +class StageDefinitionField { + const StageDefinitionField(this.label, this.value, {this.block = false}); + + final String label; + final String value; + + /// Multi-line content (prompt, output, outcomes, tools, memory, routes). + final bool block; +} + +/// The one stage declaration [key] names, or null when this version does not +/// declare it. +/// +/// The last declaration wins, matching the web pane's `new Map(stages)`. +Map? stageDefinitionFor(dynamic graph, String key) { + final stages = graph is Map ? graph['stages'] : null; + if (stages is! List) return null; + Map? found; + for (final stage in stages) { + if (stage is Map && _text(stage['key']) == key) { + found = Map.from(stage); + } + } + return found; +} + +/// A stage's effective type: a blank/absent type reads `model`, exactly as +/// `effectiveStageType` in `web/src/templates.js`. +String effectiveStageType(dynamic type) { + final text = _text(type); + return text.trim().isEmpty ? 'model' : text; +} + +/// A config key's display label (`configLabel` in `web/src/graph.js`). +String stageConfigLabel(String key) { + switch (key) { + case 'provider': + return 'Provider'; + case 'model': + return 'Model'; + case 'retries': + return 'Retries'; + case 'timeout': + return 'Timeout'; + case 'budget_usd': + return 'Budget (USD)'; + case 'budget_tokens': + return 'Budget (tokens)'; + case 'harness': + return 'Harness'; + default: + return key; + } +} + +/// The definition fields of one stage declaration, in the web pane's order. +/// +/// Only non-blank fields are emitted. Unknown keys are deliberately not +/// interpreted here; the pane keeps the stage's raw JSON so they stay visible. +List stageDefinitionFields(dynamic stage) { + if (stage is! Map) return const []; + final fields = [ + StageDefinitionField('Type', effectiveStageType(stage['type'])), + ]; + + final prompt = _text(stage['prompt']); + if (prompt.trim().isNotEmpty) { + fields.add(StageDefinitionField('Prompt', prompt, block: true)); + } + final output = _text(stage['output']); + if (output.trim().isNotEmpty) { + fields.add(StageDefinitionField('Output', output, block: true)); + } + + final edges = stage['edges']; + final outcomes = []; + for (final outcome in stageOutcomes(stage)) { + final raw = edges is Map ? edges[outcome] : null; + final target = resolveTarget(outcome, raw == null ? '' : _text(raw)) ?? ''; + final suffix = isTerminalTarget(target) ? ' (terminal)' : ''; + outcomes.add('$outcome \u2192 ${nodeLabel(target)}$suffix'); + } + if (outcomes.isNotEmpty) { + fields.add( + StageDefinitionField('Outcomes', outcomes.join('\n'), block: true), + ); + } + + final configs = stage['configs']; + if (configs is Map) { + final entries = configs.entries.toList() + ..sort((a, b) => _text(a.key).compareTo(_text(b.key))); + for (final entry in entries) { + final value = _text(entry.value); + if (entry.value == null || value.trim().isEmpty) continue; + fields.add( + StageDefinitionField(stageConfigLabel(_text(entry.key)), value), + ); + } + } + + final blocks = stage['blocks']; + if (blocks is Map) { + final tools = blocks['tools']; + final text = _text(tools); + if (tools != null && text.trim().isNotEmpty) { + fields.add(StageDefinitionField('Tools', text, block: true)); + } + } + + final limits = stage['limits']; + if (limits is Map) { + final maxVisits = limits['max_visits']; + final visits = maxVisits is num + ? maxVisits + : num.tryParse(_text(maxVisits)); + if (visits != null && visits > 0) { + fields.add(StageDefinitionField('Max visits', _text(maxVisits))); + } + final on = _items(limits['on']); + if (on.isNotEmpty) { + fields.add(StageDefinitionField('Limit on', on.join(', '))); + } + } + + final memory = stage['memory']; + if (memory is Map && memory.isNotEmpty) { + fields.add( + StageDefinitionField( + 'Memory', + [ + for (final entry in memory.entries) + '${_text(entry.key)}: ${_text(entry.value)}', + ].join('\n'), + block: true, + ), + ); + } + + final notify = stage['notify']; + if (notify is Map) { + final on = _items(notify['on']); + if (on.isNotEmpty) { + fields.add(StageDefinitionField('Notify on', on.join(', '))); + } + final destination = _text(notify['destination']); + if (destination.trim().isNotEmpty) { + fields.add(StageDefinitionField('Notify destination', destination)); + } + final artifacts = _items(notify['artifacts']); + if (artifacts.isNotEmpty) { + fields.add( + StageDefinitionField('Notify artifacts', artifacts.join(', ')), + ); + } + } + + return fields; +} + +/// A terminal pane's fields: the declared routes into that target. +/// +/// A terminal is part of the definition, not evidence that a run reached it. +List terminalDefinitionFields(dynamic graph, String key) { + final lines = [ + for (final edge in graphEdges(graph)) + if (edge.target == key) + '${edge.source} \u00b7 ${edge.label} \u2192 ${nodeLabel(key)}', + ]; + return lines.isEmpty + ? const [] + : [ + StageDefinitionField( + 'Incoming routes', + lines.join('\n'), + block: true, + ), + ]; +} + +List _items(dynamic value) { + if (value is! List) return const []; + return [for (final item in value) _text(item)]; +} + +/// Web `String(value)` for the values the definition fields carry. Numbers +/// that are integral render without a trailing `.0`, as JavaScript does; a +/// complex value stays visible but its exact shape is preserved by the raw +/// JSON section instead. +String _text(dynamic value) { + if (value == null) return ''; + if (value is String) return value; + if (value is num) { + if (value.isFinite && + value == value.roundToDouble() && + value.abs() < 1e21) { + return value.toInt().toString(); + } + return value.toString(); + } + return value.toString(); +} diff --git a/app/lib/features/graph/widgets/stage_definition_view.dart b/app/lib/features/graph/widgets/stage_definition_view.dart new file mode 100644 index 00000000..e86a31a1 --- /dev/null +++ b/app/lib/features/graph/widgets/stage_definition_view.dart @@ -0,0 +1,241 @@ +import 'dart:convert'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../ui/adaptive/host.dart'; +import '../domain/graph_protocol.dart'; +import '../domain/stage_definition.dart'; + +/// Wording for a stage that this pinned definition does not declare. +const String unknownStageDefinition = + 'This stage is not declared in this pipeline version. ' + 'No definition has been reconstructed.'; + +/// The web pane's message when a node has no recorded stage or incoming routes. +const String noStageDefinitionDetails = 'No details recorded for this node.'; + +/// Terminals are definition targets; this pane never presents one as evidence. +const String terminalDefinitionNote = + 'Success and Failure are definition targets, not recorded visits. ' + 'This pane shows where the definition routes.'; + +/// The raw section's heading: unknown stage fields stay visible and selectable. +const String rawStageDefinitionTitle = 'Raw stage definition'; + +/// A read-only native view of one stage's declared definition. +/// +/// [graph] is the graph pinned for exactly [pipelineId]/[version] and +/// [stageKey] is a node key (a stage or `#success`/`#failure`). Nothing is +/// fetched and no run visit is read, so the pane cannot imply that the stage +/// executed. Unknown stage declarations get an explicit missing state; every +/// declared stage also keeps its exact JSON below the structured fields. +class StageDefinitionView extends StatelessWidget { + const StageDefinitionView({ + super.key, + required this.graph, + required this.stageKey, + required this.pipelineId, + required this.pipelineName, + required this.version, + }); + + final JsonMap graph; + final String stageKey; + final int pipelineId; + final String pipelineName; + final int version; + + String get _identity => + '${pipelineName.isEmpty ? 'Pipeline' : pipelineName} \u00b7 v$version'; + + @override + Widget build(BuildContext context) { + final style = _StageDefinitionStyle.of(context); + final stage = stageDefinitionFor(graph, stageKey); + final terminal = isTerminalTarget(stageKey); + final fields = stage != null + ? stageDefinitionFields(stage) + : terminal + ? terminalDefinitionFields(graph, stageKey) + : const []; + + return ListView( + padding: const EdgeInsets.all(16), + children: [ + Text(_identity, style: style.muted), + const SizedBox(height: 16), + if (stage == null && !terminal) + Text(unknownStageDefinition, style: style.value) + else ...[ + if (terminal) ...[ + Text(terminalDefinitionNote, style: style.muted), + const SizedBox(height: 16), + ], + for (final field in fields) + _StageDefinitionFieldView(field: field, style: style), + if (terminal && fields.isEmpty) + Text(noStageDefinitionDetails, style: style.muted), + if (stage != null) ...[ + const SizedBox(height: 8), + Text(rawStageDefinitionTitle, style: style.heading), + const SizedBox(height: 8), + _SelectableDefinitionText( + value: const JsonEncoder.withIndent(' ').convert(stage), + style: style.value, + ), + ], + ], + ], + ); + } +} + +/// Opens the platform's native full-screen stage-definition page. +/// +/// The page owns the single navigation bar and its standard back control; the +/// caller only supplies the pinned graph and identity. This is the hook the +/// pipeline graph uses when a node is selected. +Future openStageDefinition( + BuildContext context, { + required JsonMap graph, + required String stageKey, + required int pipelineId, + required String pipelineName, + required int version, +}) { + final view = StageDefinitionView( + graph: graph, + stageKey: stageKey, + pipelineId: pipelineId, + pipelineName: pipelineName, + version: version, + ); + final settings = RouteSettings( + name: 'stage-definition/$pipelineId/$version/$stageKey', + ); + // A terminal is a definition target, not its protocol key: the web pane + // titles it with `nodeDisplayLabel` (`Failure`/`Success`). + final title = '${nodeDisplayLabel(stageKey)} definition'; + final route = usesCupertinoHost(context) + ? CupertinoPageRoute( + settings: settings, + builder: (_) => CupertinoPageScaffold( + navigationBar: CupertinoNavigationBar(middle: Text(title)), + child: SafeArea(child: view), + ), + ) + : MaterialPageRoute( + settings: settings, + builder: (_) => Scaffold( + appBar: AppBar(title: Text(title)), + body: SafeArea(child: view), + ), + ); + return Navigator.of(context).push(route); +} + +/// One labelled field: a compact row for scalars, a selectable block when the +/// value is multi-line authored text. +class _StageDefinitionFieldView extends StatelessWidget { + const _StageDefinitionFieldView({required this.field, required this.style}); + + final StageDefinitionField field; + final _StageDefinitionStyle style; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.only(bottom: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(field.label, style: style.label), + const SizedBox(height: 4), + if (field.block) + _SelectableDefinitionText(value: field.value, style: style.value) + else + Text(field.value, style: style.value), + ], + ), + ); + } +} + +/// Authored definition text in the host's selectable body. +/// +/// The semantic leaf carries the exact value: Flutter web maps a +/// [SelectableText] to an empty read-only field, so without this a screen +/// reader (and a browser check) sees only its label. The child keeps native +/// pointer selection and the host's system typography. +/// +/// The strut is derived from that same host style and forced, so a glyph the +/// host font lacks (the outcomes arrow `→` is one example) cannot pull in a +/// fallback font with taller metrics and double-space only that block. It is +/// the host's own line metrics, not a font override or a fixed height. +class _SelectableDefinitionText extends StatelessWidget { + const _SelectableDefinitionText({required this.value, required this.style}); + + final String value; + final TextStyle style; + + @override + Widget build(BuildContext context) { + return Semantics( + label: value, + child: ExcludeSemantics( + child: SelectableText( + value, + style: style, + strutStyle: StrutStyle.fromTextStyle(style, forceStrutHeight: true), + ), + ), + ); + } +} + +/// Host text roles only: no palette, font family or explicit size. +class _StageDefinitionStyle { + const _StageDefinitionStyle({ + required this.label, + required this.value, + required this.muted, + required this.heading, + }); + + factory _StageDefinitionStyle.of(BuildContext context) { + if (usesCupertinoHost(context)) { + final theme = CupertinoTheme.of(context); + final secondary = CupertinoColors.secondaryLabel.resolveFrom(context); + return _StageDefinitionStyle( + label: theme.textTheme.tabLabelTextStyle.copyWith(color: secondary), + // SelectableText needs a style it can merge into the default text + // style; Cupertino's textStyle is a complete style with `inherit: false` + // and no baseline. + value: theme.textTheme.textStyle.copyWith(inherit: true), + muted: theme.textTheme.textStyle.copyWith( + inherit: true, + color: secondary, + ), + heading: theme.textTheme.navTitleTextStyle, + ); + } + final theme = Theme.of(context); + return _StageDefinitionStyle( + label: (theme.textTheme.labelMedium ?? const TextStyle()).copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + 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 label; + final TextStyle value; + final TextStyle muted; + final TextStyle heading; +} diff --git a/app/lib/features/runs/actions/retry_action.dart b/app/lib/features/runs/actions/retry_action.dart index 28cda388..b7f593a2 100644 --- a/app/lib/features/runs/actions/retry_action.dart +++ b/app/lib/features/runs/actions/retry_action.dart @@ -22,12 +22,20 @@ class RetryRunAction extends StatefulWidget { required this.run, required this.gateway, required this.onRunChanged, + this.onRunOpened, }); final JsonMap run; final ApiGateway gateway; final ValueChanged onRunChanged; + /// Receives the id the accepted server reply names for the new retry run. + /// + /// The reply is first delivered through [onRunChanged] like every other + /// accepted detail. This callback then opens that run; it is never called + /// with a guessed id, and a reply without a usable id changes no selection. + final ValueChanged? onRunOpened; + @override State createState() => _RetryRunActionState(); } @@ -70,7 +78,11 @@ class _RetryRunActionState extends State { mode: intent.mode.wireMode, ); if (!mounted) return null; - if (_owns(id)) widget.onRunChanged(run); + if (_owns(id)) { + widget.onRunChanged(run); + final opened = retryRunId(run); + if (opened != null && opened != id) widget.onRunOpened?.call(opened); + } return null; } catch (error) { return ActionRefusal( diff --git a/app/lib/features/runs/actions/retry_intent.dart b/app/lib/features/runs/actions/retry_intent.dart index 17140a70..4b97bb0e 100644 --- a/app/lib/features/runs/actions/retry_intent.dart +++ b/app/lib/features/runs/actions/retry_intent.dart @@ -20,10 +20,16 @@ class RetryIntent { final String requestKey; } +/// The entropy bound for a fresh key. +/// +/// Written as a literal: on the web a bitwise `1 << 32` wraps to 0, which makes +/// `Random.nextInt` reject every retry with a `RangeError`. +const _entropyBound = 0x100000000; + /// A fresh `request_key` for one retry intent. The server requires one and caps /// it at 128 characters; this stays well inside that bound and unique per call. String newRetryRequestKey(num runId, {DateTime? now, int? random}) { final stamp = (now ?? DateTime.now()).microsecondsSinceEpoch; - final entropy = random ?? Random().nextInt(1 << 32); + final entropy = random ?? Random().nextInt(_entropyBound); return 'app-retry-$runId-$stamp-${entropy.toRadixString(36)}'; } diff --git a/app/lib/features/runs/screen.dart b/app/lib/features/runs/screen.dart index fbc4e66d..42126b44 100644 --- a/app/lib/features/runs/screen.dart +++ b/app/lib/features/runs/screen.dart @@ -111,6 +111,7 @@ class _RunsScreenState extends State { controller: controller, gateway: widget.gateway, onBack: _back, + onRunOpened: _select, ), ], ); diff --git a/app/lib/features/runs/ui/run_detail_actions.dart b/app/lib/features/runs/ui/run_detail_actions.dart index 699f734c..9a961e0b 100644 --- a/app/lib/features/runs/ui/run_detail_actions.dart +++ b/app/lib/features/runs/ui/run_detail_actions.dart @@ -1,7 +1,11 @@ import 'package:flutter/widgets.dart'; import '../../../core/api_gateway.dart'; +import '../../artifacts/ui/artifact_gallery_action.dart'; +import '../actions/cancel_eligibility.dart'; import '../actions/cancel_run_action.dart'; +import '../actions/retry_action.dart'; +import '../actions/retry_eligibility.dart'; import '../actions/title_action.dart'; import 'run_decision_notice.dart'; @@ -13,29 +17,50 @@ class RunDetailActions extends StatelessWidget { required this.run, required this.gateway, required this.onRunChanged, + this.onRunOpened, }); final JsonMap run; final ApiGateway gateway; final ValueChanged onRunChanged; + /// Opens the new run named by an accepted retry reply; see [RetryRunAction]. + final ValueChanged? onRunOpened; + @override Widget build(BuildContext context) => Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ + // Standard native spacing keeps adjacent outlines and fills distinct. + // Only actions that render are included: a hidden zero-size child still + // consumes Wrap spacing and would double the visible gap. Wrap( + spacing: 8, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, children: [ - RunTitleAction( - run: run, - gateway: gateway, - onRunChanged: onRunChanged, - ), - CancelRunAction( - run: run, - gateway: gateway, - onRunChanged: onRunChanged, - ), + if (runTitleId(run) != null) + RunTitleAction( + run: run, + gateway: gateway, + onRunChanged: onRunChanged, + ), + if (retryRunId(run) != null && canRetryRun(run)) + RetryRunAction( + run: run, + gateway: gateway, + onRunChanged: onRunChanged, + onRunOpened: onRunOpened, + ), + if (cancelRunId(run) != null && canCancelRun(run)) + CancelRunAction( + run: run, + gateway: gateway, + onRunChanged: onRunChanged, + ), + if (showRunArtifactsAction(run)) + RunArtifactsButton(run: run, gateway: gateway), ], ), RunDecisionNotice(run: run, gateway: gateway, onRunChanged: onRunChanged), diff --git a/app/lib/features/runs/ui/run_detail_view.dart b/app/lib/features/runs/ui/run_detail_view.dart index f6982913..3e510b62 100644 --- a/app/lib/features/runs/ui/run_detail_view.dart +++ b/app/lib/features/runs/ui/run_detail_view.dart @@ -16,6 +16,7 @@ class RunDetailView extends StatefulWidget { required this.controller, required this.gateway, required this.onBack, + this.onRunOpened, }); final RunsController controller; @@ -24,6 +25,10 @@ class RunDetailView extends StatefulWidget { final ApiGateway gateway; final VoidCallback onBack; + /// Opens the run named by an accepted retry reply, so the host route follows + /// the server-identified new run. Null keeps the detail on the retried run. + final ValueChanged? onRunOpened; + @override State createState() => _RunDetailViewState(); } @@ -44,6 +49,7 @@ class _RunDetailViewState extends State { run: run, gateway: widget.gateway, onRunChanged: widget.controller.acceptRunDetail, + onRunOpened: widget.onRunOpened, ); return cupertino ? buildCupertinoRunDetail( diff --git a/app/lib/features/schedules/ui/editor/schedule_editor_fields.dart b/app/lib/features/schedules/ui/editor/schedule_editor_fields.dart index 044a98e3..f33476b7 100644 --- a/app/lib/features/schedules/ui/editor/schedule_editor_fields.dart +++ b/app/lib/features/schedules/ui/editor/schedule_editor_fields.dart @@ -6,8 +6,8 @@ import '../../../../ui/adaptive/host.dart'; /// Secondary text under a field, using the host's own colours and text theme. TextStyle scheduleEditorSecondaryStyle(BuildContext context) { if (usesCupertinoHost(context)) { - return CupertinoTheme.of(context).textTheme.textStyle.copyWith( - fontSize: 14, + // The host's own secondary-label style; no invented point size. + return CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith( color: CupertinoColors.secondaryLabel.resolveFrom(context), ); } diff --git a/app/lib/features/schedules/ui/list/schedule_list_row.dart b/app/lib/features/schedules/ui/list/schedule_list_row.dart index 010bf53b..110fb2f9 100644 --- a/app/lib/features/schedules/ui/list/schedule_list_row.dart +++ b/app/lib/features/schedules/ui/list/schedule_list_row.dart @@ -80,28 +80,22 @@ class ScheduleListRow extends StatelessWidget { Text(value, style: _metaStyle(context)); TextStyle? _titleStyle(BuildContext context) => cupertino - ? CupertinoTheme.of( - context, - ).textTheme.textStyle.copyWith(fontWeight: FontWeight.w600) - : Theme.of( - context, - ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w600); + ? CupertinoTheme.of(context).textTheme.navTitleTextStyle + : Theme.of(context).textTheme.titleMedium; TextStyle? _bodyStyle(BuildContext context) => cupertino ? CupertinoTheme.of(context).textTheme.textStyle : null; TextStyle? _metaStyle(BuildContext context) => cupertino - ? CupertinoTheme.of(context).textTheme.textStyle.copyWith( - fontSize: 14, - color: _secondaryColor(context), - ) + ? CupertinoTheme.of( + context, + ).textTheme.tabLabelTextStyle.copyWith(color: _secondaryColor(context)) : Theme.of( context, ).textTheme.bodySmall?.copyWith(color: _secondaryColor(context)); - TextStyle? _statusStyle(BuildContext context) => _metaStyle( - context, - )?.copyWith(color: _statusColor(context), fontWeight: FontWeight.w600); + TextStyle? _statusStyle(BuildContext context) => + _metaStyle(context)?.copyWith(color: _statusColor(context)); Color _secondaryColor(BuildContext context) => cupertino ? CupertinoColors.secondaryLabel.resolveFrom(context) diff --git a/app/lib/features/schedules/ui/list/schedule_list_toolbar.dart b/app/lib/features/schedules/ui/list/schedule_list_toolbar.dart index 374c7424..4e01c4fb 100644 --- a/app/lib/features/schedules/ui/list/schedule_list_toolbar.dart +++ b/app/lib/features/schedules/ui/list/schedule_list_toolbar.dart @@ -169,8 +169,7 @@ class ScheduleListToolbar extends StatelessWidget { } TextStyle? _metaStyle(BuildContext context) => cupertino - ? CupertinoTheme.of(context).textTheme.textStyle.copyWith( - fontSize: 14, + ? CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith( color: CupertinoColors.secondaryLabel.resolveFrom(context), ) : Theme.of(context).textTheme.bodySmall?.copyWith( diff --git a/app/lib/features/search/search_screen.dart b/app/lib/features/search/search_screen.dart index 3c2e80ce..adaae3e7 100644 --- a/app/lib/features/search/search_screen.dart +++ b/app/lib/features/search/search_screen.dart @@ -2,6 +2,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../core/api_gateway.dart'; +import '../../ui/adaptive/host.dart'; import 'data/search_repository.dart'; import 'domain/search_controller.dart'; import 'domain/search_models.dart'; @@ -100,12 +101,14 @@ class _SearchScreenState extends State { @override Widget build(BuildContext context) { + // Follow the actual host app class first: a CupertinoApp supplies no + // Material theme, so reading only the platform would pick Material controls + // inside a Cupertino host on macOS/iOS. final cupertino = widget.cupertino ?? - switch (Theme.of(context).platform) { - TargetPlatform.iOS || TargetPlatform.macOS => true, - _ => false, - }; + (usesCupertinoHost(context) || + Theme.of(context).platform == TargetPlatform.iOS || + Theme.of(context).platform == TargetPlatform.macOS); return cupertino ? _cupertinoScreen() : _materialScreen(); } diff --git a/app/lib/features/templates/screen.dart b/app/lib/features/templates/screen.dart new file mode 100644 index 00000000..20bc130d --- /dev/null +++ b/app/lib/features/templates/screen.dart @@ -0,0 +1,208 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; + +import '../../core/api_gateway.dart'; +import '../../ui/adaptive/host.dart'; +import 'data/template_repository.dart'; +import 'domain/template_entry.dart'; +import 'ui/template_create_dialog.dart'; +import 'ui/template_detail.dart'; +import 'ui/template_gallery.dart'; +import 'ui/templates_failure.dart'; +import 'ui/templates_frame.dart'; + +export 'ui/template_detail.dart' + show + templateCreateActionKey, + templateDetailKey, + templateSourceKey, + templateSourceLabel; +export 'ui/template_gallery.dart' + show + templateRowKey, + templatesEmptyKey, + templatesGalleryKey, + templatesLoadingKey; +export 'ui/templates_failure.dart' + show + templatesBannerRetryKey, + templatesErrorBannerKey, + templatesErrorKey, + templatesRetryKey; +export 'ui/templates_frame.dart' show templatesBackKey, templatesRefreshKey; + +/// The reusable Templates gallery: the server's actual catalogue, one selected +/// template's metadata and verbatim selectable source, and the existing native +/// create-only prompt. +/// +/// Loading and selecting only read. The single create action calls +/// [showTemplateCreateDialog] unchanged, so validate-then-submit semantics stay +/// there; an accepted `detail` is forwarded once through [onCreated]. Nothing +/// here publishes, runs, schedules or overwrites a pipeline. +/// +/// Standalone use keeps this screen's own native app bar with Back and Refresh. +/// A shell that already owns navigation passes [embedded], which drops the bar +/// and keeps Back inside the detail and Refresh at the top of the body. +class TemplatesScreen extends StatefulWidget { + const TemplatesScreen({ + super.key, + required this.gateway, + this.embedded = false, + this.onCreated, + }); + + final ApiGateway gateway; + final bool embedded; + final ValueChanged? onCreated; + + @override + State createState() => _TemplatesScreenState(); +} + +class _TemplatesScreenState extends State { + late TemplateRepository _repository = TemplateRepository(widget.gateway); + List _templates = const []; + bool _loading = true; + bool _loaded = false; + String? _error; + String? _selectedKey; + int _generation = 0; + + @override + void initState() { + super.initState(); + unawaited(_load()); + } + + @override + void didUpdateWidget(TemplatesScreen oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.gateway == widget.gateway) return; + // A different gateway is a different server: never keep this one's rows or + // selection while the replacement is read. + _repository = TemplateRepository(widget.gateway); + _templates = const []; + _loaded = false; + _selectedKey = null; + unawaited(_load()); + } + + bool _owns(int generation) => mounted && generation == _generation; + + Future _load() async { + final generation = ++_generation; + setState(() { + _loading = true; + _error = null; + }); + try { + final templates = await _repository.listTemplates(); + if (!_owns(generation)) return; + setState(() { + _templates = templates; + _loaded = true; + _loading = false; + final selected = _selectedKey; + if (selected != null && + !templates.any((entry) => entry.key == selected)) { + _selectedKey = null; + } + }); + } catch (error) { + if (!_owns(generation)) return; + setState(() { + _loading = false; + _error = _describe(error); + }); + } + } + + String _describe(Object error) { + final text = error is TemplateRepositoryException + ? error.message + : '$error'; + final message = text.trim(); + if (message.isEmpty) return 'The templates could not be loaded.'; + return message.startsWith('Exception: ') ? message.substring(11) : message; + } + + TemplateEntry? get _selected { + for (final entry in _templates) { + if (entry.key == _selectedKey) return entry; + } + return null; + } + + void _open(String key) => setState(() => _selectedKey = key); + + void _back() => setState(() => _selectedKey = null); + + void _openCreate(TemplateEntry template) { + unawaited( + showTemplateCreateDialog( + context: context, + template: template, + repository: _repository, + cupertino: usesCupertinoHost(context), + onCreated: (detail) => widget.onCreated?.call(detail), + ), + ); + } + + @override + Widget build(BuildContext context) { + final selected = _selected; + final body = selected == null + ? TemplateGallery( + templates: _templates, + loaded: _loaded, + loading: _loading, + error: _error, + onRetry: () => unawaited(_load()), + onOpen: _open, + ) + : TemplateDetail( + entry: selected, + showBack: widget.embedded, + onBack: _back, + onCreate: () => _openCreate(selected), + ); + final framed = TemplatesFrame( + body: _withFailure(context, body), + embedded: widget.embedded, + canGoBack: selected != null, + refreshing: _loading, + onBack: _back, + onRefresh: () => unawaited(_load()), + ); + if (widget.embedded) return framed; + // A selected template is this screen's own page: native back returns to + // the gallery instead of leaving the destination. + return PopScope( + canPop: selected == null, + onPopInvokedWithResult: (didPop, _) { + if (!didPop && _selectedKey != null) _back(); + }, + child: framed, + ); + } + + /// A refused refresh stays visible above whichever body is current, so an + /// open template never hides a failed read. The rows and selection are kept. + Widget _withFailure(BuildContext context, Widget body) { + final error = _error; + if (error == null || !_loaded) return body; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + TemplatesFailureBanner( + message: error, + retrying: _loading, + onRetry: () => unawaited(_load()), + ), + Expanded(child: body), + ], + ); + } +} diff --git a/app/lib/features/templates/ui/template_detail.dart b/app/lib/features/templates/ui/template_detail.dart new file mode 100644 index 00000000..97c4b204 --- /dev/null +++ b/app/lib/features/templates/ui/template_detail.dart @@ -0,0 +1,168 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; +import '../domain/template_entry.dart'; + +/// Browser wording for the gallery and the selected template, kept verbatim. +const templateSourceLabel = 'Definition source'; +const templateIncludesScheduleLabel = 'Includes a schedule'; +const templateCreateActionLabel = 'Create pipeline from this template'; + +const templateDetailKey = ValueKey('template-detail'); +const templateSourceKey = ValueKey('template-source'); +const templateCreateActionKey = ValueKey('template-create-action'); +const templateDetailBackKey = ValueKey('template-detail-back'); + +/// A gallery card's name: a blank name is the explicit unnamed placeholder. +String templateGalleryName(TemplateEntry entry) { + final name = entry.name.trim(); + return name.isEmpty ? '(unnamed template)' : entry.name; +} + +/// A detail's heading: a blank name falls back to the template's key. +String templateDetailName(TemplateEntry entry) { + final name = entry.name.trim(); + return name.isEmpty ? entry.key : entry.name; +} + +/// One template's metadata and its complete, selectable definition source. +/// +/// Selecting and reading a template sends nothing. The one action opens the +/// existing create-only prompt through [onCreate]; this view never submits, +/// runs or schedules anything itself. +class TemplateDetail extends StatelessWidget { + const TemplateDetail({ + super.key, + required this.entry, + required this.showBack, + required this.onBack, + required this.onCreate, + }); + + final TemplateEntry entry; + + /// True under a shell/app bar that does not own a back control for this page. + final bool showBack; + final VoidCallback onBack; + final VoidCallback onCreate; + + @override + Widget build(BuildContext context) { + final cupertino = usesCupertinoHost(context); + return ListView( + key: templateDetailKey, + padding: const EdgeInsets.only(bottom: 24), + children: [ + if (showBack) _backRow(context, cupertino), + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _createButton(context, cupertino), + const SizedBox(height: 12), + Text( + templateDetailName(entry), + style: templateTitleStyle(context), + ), + if (entry.description.trim().isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(entry.description), + ), + const SizedBox(height: 16), + Text('Key', style: templateMutedStyle(context)), + SelectableText(entry.key, style: templateBodyStyle(context)), + if (entry.scheduled) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(templateIncludesScheduleLabel), + ), + const SizedBox(height: 20), + Text(templateSourceLabel, style: templateSectionStyle(context)), + const SizedBox(height: 8), + // The server's source, byte-for-byte: no trim, re-indent or + // re-encoding, so selecting it copies exactly what was received. + SelectableText( + entry.source, + key: templateSourceKey, + style: templateBodyStyle(context), + ), + ], + ), + ), + ], + ); + } + + Widget _createButton(BuildContext context, bool cupertino) { + if (cupertino) { + return CupertinoButton.filled( + key: templateCreateActionKey, + onPressed: onCreate, + child: const Text(templateCreateActionLabel), + ); + } + return FilledButton( + key: templateCreateActionKey, + onPressed: onCreate, + child: const Text(templateCreateActionLabel), + ); + } + + Widget _backRow(BuildContext context, bool cupertino) { + final back = cupertino + ? CupertinoButton( + key: templateDetailBackKey, + padding: EdgeInsets.zero, + onPressed: onBack, + child: const Icon(CupertinoIcons.back, semanticLabel: 'Back'), + ) + : BackButton(key: templateDetailBackKey, onPressed: onBack); + return Padding( + padding: const EdgeInsets.fromLTRB(4, 4, 16, 0), + child: Row( + children: [ + back, + const SizedBox(width: 4), + Expanded( + child: Text('Templates', style: templateSectionStyle(context)), + ), + ], + ), + ); + } +} + +TextStyle? templateTitleStyle(BuildContext context) => + usesCupertinoHost(context) + ? CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle + : Theme.of(context).textTheme.headlineSmall; + +TextStyle? templateSectionStyle(BuildContext context) => + usesCupertinoHost(context) + ? CupertinoTheme.of(context).textTheme.navTitleTextStyle + : Theme.of(context).textTheme.titleMedium; + +TextStyle? templateBodyStyle(BuildContext context) { + if (usesCupertinoHost(context)) { + // SelectableText needs an explicit baseline when it inherits no style. + return CupertinoTheme.of( + context, + ).textTheme.textStyle.copyWith(inherit: true); + } + return Theme.of(context).textTheme.bodyMedium; +} + +TextStyle? templateMutedStyle(BuildContext context) { + if (usesCupertinoHost(context)) { + return CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith( + color: CupertinoColors.secondaryLabel.resolveFrom(context), + ); + } + final theme = Theme.of(context); + return theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ); +} diff --git a/app/lib/features/templates/ui/template_gallery.dart b/app/lib/features/templates/ui/template_gallery.dart new file mode 100644 index 00000000..809b0496 --- /dev/null +++ b/app/lib/features/templates/ui/template_gallery.dart @@ -0,0 +1,138 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; +import '../domain/template_entry.dart'; +import 'template_detail.dart'; +import 'templates_failure.dart'; + +const templatesGalleryKey = ValueKey('template-gallery'); +const templatesLoadingKey = ValueKey('templates-loading'); +const templatesEmptyKey = ValueKey('templates-empty'); + +const _loadingLabel = 'Loading templates'; +const _loadingMessage = 'Loading templates…'; +const _emptyMessage = 'No templates are available on this server.'; + +Key templateRowKey(String key) => ValueKey('template-row-$key'); + +/// The gallery's truthful states and native catalogue rows. +/// +/// It owns no requests: loading, failure and the actual rows all come from the +/// screen, so opening a row only selects an already-read template. +class TemplateGallery extends StatelessWidget { + const TemplateGallery({ + super.key, + required this.templates, + required this.loaded, + required this.loading, + required this.error, + required this.onRetry, + required this.onOpen, + }); + + final List templates; + final bool loaded; + final bool loading; + final String? error; + final VoidCallback onRetry; + final ValueChanged onOpen; + + @override + Widget build(BuildContext context) => _body(context); + + Widget _body(BuildContext context) { + if (!loaded) { + if (error != null) { + return TemplatesFailureState( + message: error!, + retrying: loading, + onRetry: onRetry, + ); + } + return _loadingState(context); + } + if (templates.isEmpty) return _emptyState(context); + return usesCupertinoHost(context) + ? _cupertinoList(context) + : _materialList(context); + } + + Widget _loadingState(BuildContext context) { + return Center( + key: templatesLoadingKey, + child: Semantics( + liveRegion: true, + label: _loadingLabel, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + usesCupertinoHost(context) + ? const CupertinoActivityIndicator() + : const CircularProgressIndicator(), + const SizedBox(height: 12), + const Text(_loadingMessage), + ], + ), + ), + ); + } + + Widget _emptyState(BuildContext context) { + return Center( + key: templatesEmptyKey, + child: Padding( + padding: const EdgeInsets.all(24), + child: Text(_emptyMessage, style: templateMutedStyle(context)), + ), + ); + } + + Widget _materialList(BuildContext context) { + return ListView.separated( + key: templatesGalleryKey, + itemCount: templates.length, + separatorBuilder: (_, _) => const Divider(height: 1), + itemBuilder: (context, index) { + final entry = templates[index]; + return ListTile( + key: templateRowKey(entry.key), + title: Text(templateGalleryName(entry)), + subtitle: entry.description.trim().isEmpty + ? null + : Text(entry.description), + trailing: const Icon(Icons.chevron_right), + onTap: () => onOpen(entry.key), + ); + }, + ); + } + + Widget _cupertinoList(BuildContext context) { + return ListView( + key: templatesGalleryKey, + children: [ + CupertinoListSection.insetGrouped( + children: [ + for (final entry in templates) + CupertinoListTile( + key: templateRowKey(entry.key), + title: _cupertinoText(templateGalleryName(entry)), + subtitle: entry.description.trim().isEmpty + ? null + : _cupertinoText(entry.description), + trailing: const CupertinoListTileChevron(), + onTap: () => onOpen(entry.key), + ), + ], + ), + ], + ); + } + + /// The native tile is single-line by default. Let its content wrap at larger + /// text sizes instead of ellipsizing a template's own name; the row grows + /// with the content and nothing else about the tile is restyled. + Widget _cupertinoText(String text) => + DefaultTextStyle.merge(maxLines: 3, child: Text(text)); +} diff --git a/app/lib/features/templates/ui/templates_failure.dart b/app/lib/features/templates/ui/templates_failure.dart new file mode 100644 index 00000000..5eab12d8 --- /dev/null +++ b/app/lib/features/templates/ui/templates_failure.dart @@ -0,0 +1,118 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; + +const templatesErrorKey = ValueKey('templates-error'); +const templatesRetryKey = ValueKey('templates-retry'); +const templatesErrorBannerKey = ValueKey('templates-error-banner'); +const templatesBannerRetryKey = ValueKey('templates-banner-retry'); + +/// A refusal for a catalogue that never loaded: the whole body is the failure. +class TemplatesFailureState extends StatelessWidget { + const TemplatesFailureState({ + super.key, + required this.message, + required this.retrying, + required this.onRetry, + }); + + final String message; + final bool retrying; + final VoidCallback onRetry; + + @override + Widget build(BuildContext context) { + return Center( + key: templatesErrorKey, + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Semantics( + liveRegion: true, + child: Text(message, textAlign: TextAlign.center), + ), + const SizedBox(height: 8), + _retryButton( + context, + buttonKey: templatesRetryKey, + retrying: retrying, + onRetry: onRetry, + ), + ], + ), + ), + ); + } +} + +/// A refused refresh, shown above whichever body stays visible. +/// +/// The screen renders this above both the catalogue and an open template, so a +/// failed refresh can never be silent while a template is selected. +class TemplatesFailureBanner extends StatelessWidget { + const TemplatesFailureBanner({ + super.key, + required this.message, + required this.retrying, + required this.onRetry, + }); + + final String message; + final bool retrying; + final VoidCallback onRetry; + + @override + Widget build(BuildContext context) { + return Padding( + key: templatesErrorBannerKey, + padding: const EdgeInsets.fromLTRB(16, 8, 16, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Semantics( + liveRegion: true, + child: Text( + message, + style: TextStyle( + color: usesCupertinoHost(context) + ? CupertinoColors.systemRed.resolveFrom(context) + : Theme.of(context).colorScheme.error, + ), + ), + ), + _retryButton( + context, + buttonKey: templatesBannerRetryKey, + retrying: retrying, + onRetry: onRetry, + ), + ], + ), + ); + } +} + +Widget _retryButton( + BuildContext context, { + required Key buttonKey, + required bool retrying, + required VoidCallback onRetry, +}) { + final onPressed = retrying ? null : onRetry; + if (usesCupertinoHost(context)) { + return CupertinoButton( + key: buttonKey, + padding: EdgeInsets.zero, + onPressed: onPressed, + child: const Text('Retry'), + ); + } + return TextButton( + key: buttonKey, + onPressed: onPressed, + child: const Text('Retry'), + ); +} diff --git a/app/lib/features/templates/ui/templates_frame.dart b/app/lib/features/templates/ui/templates_frame.dart new file mode 100644 index 00000000..5abd42e2 --- /dev/null +++ b/app/lib/features/templates/ui/templates_frame.dart @@ -0,0 +1,104 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; + +const templatesRefreshKey = ValueKey('templates-refresh'); +const templatesBackKey = ValueKey('templates-back'); + +/// The screen's native chrome. +/// +/// Standalone use keeps the host's own app bar with Back and Refresh. A shell +/// that already owns navigation passes [embedded], which drops the bar and +/// keeps Refresh at the top of the body. +class TemplatesFrame extends StatelessWidget { + const TemplatesFrame({ + super.key, + required this.body, + required this.embedded, + required this.canGoBack, + required this.refreshing, + required this.onBack, + required this.onRefresh, + }); + + final Widget body; + final bool embedded; + final bool canGoBack; + final bool refreshing; + final VoidCallback onBack; + final VoidCallback onRefresh; + + @override + Widget build(BuildContext context) { + if (embedded) return _embedded(context); + return usesCupertinoHost(context) + ? _cupertino(context) + : _material(context); + } + + Widget _embedded(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Align( + alignment: AlignmentDirectional.centerEnd, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: _refreshButton(context), + ), + ), + Expanded(child: body), + ], + ); + } + + Widget _cupertino(BuildContext context) { + return CupertinoPageScaffold( + navigationBar: CupertinoNavigationBar( + leading: canGoBack + ? CupertinoButton( + key: templatesBackKey, + padding: EdgeInsets.zero, + onPressed: onBack, + child: const Icon(CupertinoIcons.back, semanticLabel: 'Back'), + ) + : null, + middle: const Text('Templates'), + trailing: _refreshButton(context), + ), + child: SafeArea(child: body), + ); + } + + Widget _material(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Templates'), + leading: canGoBack + ? BackButton(key: templatesBackKey, onPressed: onBack) + : null, + actions: [_refreshButton(context)], + ), + body: SafeArea(child: body), + ); + } + + Widget _refreshButton(BuildContext context) { + final onPressed = refreshing ? null : onRefresh; + if (usesCupertinoHost(context)) { + return CupertinoButton( + key: templatesRefreshKey, + padding: EdgeInsets.zero, + onPressed: onPressed, + child: const Icon(CupertinoIcons.refresh, semanticLabel: 'Refresh'), + ); + } + return IconButton( + key: templatesRefreshKey, + tooltip: 'Refresh', + onPressed: onPressed, + icon: const Icon(Icons.refresh), + ); + } +} diff --git a/app/notes/A1-viewer.md b/app/notes/A1-viewer.md new file mode 100644 index 00000000..668a1be9 --- /dev/null +++ b/app/notes/A1-viewer.md @@ -0,0 +1,87 @@ +# A1-viewer — native in-app artifact viewer + +## What changed + +The recorded-artifact gallery now opens a reusable native viewer for a viewer +artifact with a resolved url. Images are drawn in-app from fetched bytes, +`text/plain` is selectable fetched text, `.md`/`.markdown` or `text/markdown` +uses an injected markdown builder (default: plain selectable text), and every +other type shows an explicit cannot-preview state with the existing Open/Copy +link actions. An external origin is opened in the viewer as a marked, +unfetched page; unsafe and absent urls stay in the facts dialog. + +| File | Responsibility | +| --- | --- | +| `lib/features/artifacts/domain/artifact_preview.dart` | Safe-url preview classification and exact unavailable/unsupported wording | +| `lib/features/artifacts/ui/artifact_viewer_page.dart` | Page, paging state, fetch generations, cache, Open/Copy | +| `lib/features/artifacts/ui/artifact_viewer_body.dart` | Facts, position, live status, preview surface, actions, Previous/Next | +| `lib/features/artifacts/ui/artifact_viewer_content.dart` | Image/text/markdown/loading/error/unsupported surface and markdown seam | +| `lib/features/artifacts/ui/artifact_viewer_fetch.dart` | `ArtifactFetch` seam, status/bytes result, network failure | +| `lib/features/artifacts/ui/artifact_viewer_fetch_web.dart` | Web `fetch` with `credentials: 'same-origin'` | +| `lib/features/artifacts/ui/artifact_viewer_fetch_stub.dart` | Native `HttpClient`, no cookies, no redirects | +| `lib/features/artifacts/ui/artifact_gallery_page.dart` | Opens the viewer for previewable same-origin rows; optional fetch/builder seams | +| `lib/features/artifacts/domain/artifact_kind.dart` | `text/plain` joins the viewer list; video stays pageable but unpresentable | +| `lib/features/artifacts/domain/gallery_navigation.dart` | One visit identity helper shared by rows and viewer | +| `tool/artifact_gallery_probe.dart` / `.mjs` | Gallery + viewer fixture, both hosts, 320/2x, real PNG, 404 and external states | +| `test/features/artifacts/domain/artifact_preview_test.dart` | Same-origin, external, unsafe, absent and unsupported plans | +| `test/features/artifacts/ui/artifact_viewer_page_test.dart` | Image no-tab, text content, markdown seam, external refusal, unsupported, paging/clamp, loading/404/network, Cupertino | + +## Behaviour + +- The gallery row identity is the recorded stage/visit plus recorded url (or + name), so paging starts on exactly the selected row. +- Preview pages are `pagedArtifacts(groups)` in gallery order. Previous/Next use + `pagedIndex` and are disabled at both ends; a one-page viewer has no pager. +- The viewer keeps the recorded MIME/size and `stage · visit N` facts visible on + every page, along with the position label (`3 of 4 · image/png`). +- Open/Copy link are the existing external actions and operate on the resolved + url. They are not previews. +- Fetch failures report `The server answered .`; network failures report + `Could not load preview: …`; loading says `Loading preview…`. An image that + cannot decode says so. +- Native `Back`/AppBar/CupertinoNavigationBar close returns to the gallery row + list and restores the row focus captured before the push. + +## Checks actually run + +``` +flutter analyze # No issues found! (1.2s) +flutter test test/features/artifacts \ + test/features/runs/ui/run_artifacts_action_test.dart # 104 passed +flutter build web # ✓ Built build/web +flutter build web -t tool/artifact_gallery_probe.dart # ✓ Built build/probe-gallery +node tool/artifact_gallery_probe.mjs --root build/probe-gallery --out … # 21 checks, 23 captures +``` + +Browser captures: shared +`artifact-viewer-captures/` (material/cupertino image, text, unsupported, +HTTP 404, external marked page, 320/2x both hosts, plus the retained gallery +states). The viewer text assertion for fetched content relies on the rendered +capture; Flutter web did not expose `SelectableText` content in the extracted +DOM text. The widget test asserts the fetched value directly. + +## Honest limits + +- No HTML embed, video player, download or file-share action was added. +- Only web was built and captured. Android/iOS were not built, installed or + device-tested. +- The default markdown seam is plain selectable text; the markdown lane can + inject a real renderer through `ArtifactMarkdownBuilder`. +- The fixture and browser evidence use loopback files only; no server, real run + or operator session was touched. + +## Manager completion after a harness transport deadline + +The Code visit ended with `HARNESS TRANSPORT: context deadline exceeded`; the +session was no longer active and every edit was retained. No retry was started. +The manager ran the full artifacts suite (99 tests pass) and analysis, rebuilt the +gallery/viewer fixture, and ran the probe: it passes and writes the viewer states +(text, image, unsupported, external-origin marked, HTTP error, plus 320/2x and +Cupertino variants). The Material text viewer and the Cupertino 320/2x image +viewer were inspected: recorded facts, page position, in-app image, paging at both +ends and Open/Copy link. + +Deliberate limits: markdown is rendered through an injected builder that defaults +to selectable plain text (the markdown lane supplies the real renderer later), +external-origin urls are never fetched, and video/CSV/archives are explicitly +unsupported rather than faked. Share/download/file-upload remain open items. diff --git a/app/notes/A1-wire.md b/app/notes/A1-wire.md new file mode 100644 index 00000000..94949244 --- /dev/null +++ b/app/notes/A1-wire.md @@ -0,0 +1,150 @@ +# A1-wire — native Artifacts action and recorded-group gallery + +## What changed + +The run detail now offers a standard native **Artifacts** action whenever the +loaded detail carries steps. It pushes a native page that lists the recorded +stage/visit groups from the landed `artifactGroups`/`ArtifactVisitList`. +Selecting a row opens the host's native dialog with the recorded name, MIME and +size, the visit's own capture facts, and — only when the recorded url resolves +through the existing `resolveArtifactUrl` rules — native **Open** and a separate +**Copy link**. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/artifacts/ui/artifact_gallery_action.dart` | 104 | Action gate, steps snapshot, native button, page push | +| `lib/features/artifacts/ui/artifact_gallery_page.dart` | 194 | The page: summary/empty state, list, selection, Open/Copy link | +| `lib/features/artifacts/ui/artifact_selection_facts.dart` | 71 | Group→step map and the recorded-facts widget | +| `lib/features/artifacts/ui/artifact_external_open.dart` | 14 | `ArtifactExternalOpen` capability + default | +| `lib/features/artifacts/ui/artifact_external_open_web.dart` | 20 | `window.open` through `js_interop` (JS and wasm) | +| `lib/features/artifacts/ui/artifact_external_open_stub.dart` | 6 | Non-web refusal (no launcher dependency in this slice) | +| `lib/features/artifacts/ui/artifact_visit_list.dart` | +28/-25 | Exposes the landed label helpers the page reuses | +| `lib/features/runs/ui/run_detail_actions.dart` | +3 | Composes the action beside Rename/Cancel | +| `test/features/artifacts/ui/artifact_gallery_page_test.dart` | 321 | Page, identity, capture facts, url rules, copy | +| `test/features/runs/ui/run_artifacts_action_test.dart` | 161 | Action gate and wiring on both hosts | +| `tool/artifact_gallery_probe.dart` | 232 | Isolated fixture entry (real `RunDetailView`) | +| `tool/artifact_gallery_probe.mjs` | 421 | Loopback server + headless Chrome driver | + +No shell/main, pubspec, `web/`, Go server, `android/` or other feature was +edited. No dependency was added. + +## Behaviour + +- **Gate.** `showRunArtifactsAction` is true exactly when the loaded detail has + at least one step. A detail with no steps shows no action; the page also has + an explicit `No steps recorded for this run.` state if ever reached. +- **Truthful empty/unavailable.** The page header is the landed + `artifactsHeader`: `Artifacts · N recorded` (`· partial capture` when a visit + excluded/omitted files), `Artifacts · capture pending` while executing, + `No artifacts recorded for this run.` only for a recorded empty capture, and + `Artifacts · capture unavailable` when the field was absent. An unavailable + capture never says nothing was recorded. +- **Selection identity.** `ArtifactVisitList` selection uses + `artifactVisitIdentity`; two visits that both recorded `result.csv` stay two + distinct rows and selections (unit + browser evidence). +- **Facts.** The dialog shows the recorded filename (or `(unnamed artifact)`), + the recorded MIME/size (`type not recorded` when empty), the group's + `stage · visit N`, the visit's `artifactsSummary` and its + `artifactCaptureNotes`. Nothing is inferred from a name. +- **Url rules.** Open/Copy link appear only when `resolveArtifactUrl` returns a + value: absolute http(s) or a server-relative path resolved against the + configured endpoint. Protocol-relative, credentialed, malformed and + non-http(s) urls are rejected and the dialog says + `The recorded artifact URL cannot be opened safely.` A record with no url says + `No artifact URL recorded.` and offers no action. The endpoint comes from the + app's shared `PipelinesClient` when the gateway exposes it; a fixture gateway + leaves it blank, which only disables relative resolution. +- **Open vs copy.** Open calls the injected `ArtifactExternalOpen` with the + resolved `Uri` (web: a new tab via `window.open` reached through + `js_interop`, so it compiles for JS and wasm). Copy link is a separate action + that writes the resolved url to the clipboard. Each reports + `Link opened externally.` / `Could not open the link.` and `Link copied.` / + `Could not copy link.` as an inline live region. +- **Controls.** Material uses `FilledButton.tonalIcon` + `AlertDialog`; Cupertino + uses `CupertinoButton.tinted` + `CupertinoAlertDialog` and the grouped page + background. No fixed row/button sizes, custom font or palette. The Cupertino + action is text-only: the icon variant overflowed by 11 px at 2x text on 390 px + (caught by the existing `run_detail_widget_test`), and dropping the icon keeps + the label whole without clipping. +- **Out of scope, labelled next:** in-app preview/viewer, download, share files, + gallery filters and any network artifact fetch were not written. + +## Checks actually run + +``` +flutter analyze # No issues found +dart format --output=none --set-exit-if-changed ... # 0 changed +flutter test test/features/artifacts test/features/runs # 203 passed +flutter test # 712 passed (whole app) +flutter build web # ✓ Built build/web +flutter build web -t tool/artifact_gallery_probe.dart # ✓ Built build/probe-gallery +node --check tool/artifact_gallery_probe.mjs # ok +node tool/artifact_gallery_probe.mjs ... # 13/13 checks, 16 captures +``` + +`git status --short --untracked-files=all` lists only the files above; +`pubspec.yaml`/`pubspec.lock` are unchanged. No commit, push or deploy. + +## Real browser evidence + +`tool/artifact_gallery_probe.dart` renders the real `RunDetailView` over a fake +`get_run` gateway; `tool/artifact_gallery_probe.mjs` serves the build on an +OS-assigned loopback port and drives headless Chrome. Recorded urls point at the +probe's own loopback origin (plus unsafe/no-url/empty/unavailable states). No +server or operator run was touched. + +13/13 checks passed; 16 captures in +`/Users/alan/.local/share/pipelines/data/artifacts/81/public/a1-wire/` +(`evidence.json` holds the machine-readable result): + +- The run detail offers the native Artifacts action; the page lists the actual + recorded rows (`build.log`, `shot.png`, two `result.csv` visits, group + headings, MIME/size), not nav labels. +- Selecting the lower duplicate `result.csv` selected `reviewer · visit 2` with + its own `Artifacts · 1 recorded · partial capture` and + `2 files excluded from artifact capture.` +- The safe selection offers native **Open** and a separate **Copy link**; a + protocol-relative url offers neither and shows the unsafe wording; a url-less + record shows `No artifact URL recorded.` and no action. +- A recorded empty capture says `No artifacts recorded for this run.`; an + unavailable capture says `Artifacts · capture unavailable` and never the empty + wording. +- Cupertino lists the same rows with its native dialog and actions; dark + Cupertino dialog text samples light (max luminance 1.0). +- Both hosts at 320 px / 2x text keep the recorded rows, facts and actions + whole. + +Captures: `a1w-material-{detail,gallery,selected,open,unsafe,nourl,empty, +unavailable}.png`, `a1w-cupertino-{gallery,selected,dark-gallery, +dark-selected}.png`, `a1w-{material,cupertino}-2x-320-{gallery,selected}.png`. + +## Not verified / limits + +- The actual new-tab open could not be driven in headless Chrome: a synthetic + semantics activation carries no user gesture, so the app reports its honest + `Could not open the link.` refusal path. The browser proves the action is + offered only for a safe resolved url; the widget test proves the exact + `http://127.0.0.1:8081/artifacts/1/1/result.csv` uri handed to the opener and + the clipboard write. A genuine user tap was not captured. +- Non-web external open returns false (no launcher dependency is in scope); the + page reports that refusal. Mobile targets were not built or run, so **mobile + remains unverified**. +- All data is fixture data; no live server or operator run was used. +- Page/viewer/share/download/filters are not part of this slice and are labelled + as next work. + +## Manager completion after the Code deadline + +The Code visit hit its 30-minute deadline while still active; its session settled +and all edits were retained. No retry was started. The manager confirmed the dirty +paths were exactly this slice, then ran the focused artifacts/UI tests (29 pass), +analysis, and the fixture probe. The probe covers both hosts plus 320px/2x and +produced 16 captures (detail, gallery, selected facts, Open, unsafe url, no url, +empty, unavailable capture). The Cupertino dark selected dialog and the Material +320px/2x selected dialog were inspected: recorded name/MIME/size, the visit's own +capture facts, excluded-file note, and distinct Open / Copy link / Close where a +safe url exists. + +Deliberate scope: this slice links to a validated url externally and copies that +link. It performs no in-app preview, download or file sharing, so the artifact +viewer/Share rows in app/PARITY.md remain open. diff --git a/app/notes/C2-wire.md b/app/notes/C2-wire.md new file mode 100644 index 00000000..c45fb1e4 --- /dev/null +++ b/app/notes/C2-wire.md @@ -0,0 +1,139 @@ +# C2-wire — Chat session list to read-only conversation + +The Chat tab is now the real session browser plus a selected read-only thread. +The shell registers a normal Chat destination, `/chat/:id` is a real history +entry, and the existing `ChatThreadController`/`ChatMessageView` render the +stored transcript. No composer, markdown, forms, metrics, attachments, new +socket, server or platform change is included. + +## Behavior + +- The destination renders the list at `/chat`; tapping a row records + `/chat/`, and Back (the in-page control, browser Back, or system + back through `AppRouterDelegate.popRoute`) returns to `/chat`. The list stays + mounted offstage, so its rows, grouping, search text and actions survive the + round trip. +- `/chat/:id` opens the exact session. Parsing is total and matches the web + parser: a nonempty, bounded, URL-safe id is accepted after percent-decoding; + malformed escapes, extra segments and invalid ids resolve to the default + Pipelines route rather than throwing. The route serialises through + `Uri.encodeComponent`. +- Before the shared socket has ever connected, the destination shows the normal + connection screen and sends no chat request. It never opens its own socket or + subscribes outside the shared `AppSession`. +- The selected thread subscribes that one session, reads the newest history + page (`limit: 200`, empty cursor), renders `transcriptRows` with + `ChatMessageView`, and folds pushed `chat_event` frames for that session only. + Live text/reasoning/tool parts use the landed native surfaces; reasoning and + tools stay collapsed until opened. +- `Load older` is shown only while the server says `has_more`; the server's + `next_cursor` is passed back verbatim and is never parsed. Paging prepends + messages, and a page boundary can fall inside one folded assistant turn (the + repository's paged history fixture pages consecutive assistant messages). A + turn's first message id is therefore not widget identity: `ChatRowKeys` + carries each turn's key forward while it still holds a message it had before, + and each agent part carries its server id. An open reasoning/tool disclosure + stays on the answer the operator opened, whether the older page extends a turn + at its head or the `Load older` control disappears. A part without a server id + still falls back to its position; server history parts carry ids. +- `ChatThreadController.subscriptionError` and history `error` render as two + separate notices with separate Retry actions. Readable stored history can + therefore never hide a refused live watch. Initial loading, a running turn + and an honest empty transcript each have their own state. +- On reconnect, `connectionEpoch` advances the thread's `syncToken`; the + mounted view re-subscribes and replaces the transcript in place, keeping the + selected session id and route. A session change mounts a keyed view, so a + superseded read from the previous session cannot land in the new thread. The + offstage session list also re-reads on the same token, so a session created, + renamed or closed on another device during the socket gap appears without + pressing Refresh. +- The shell owns the only navigation bar. `ChatSessionsScreen` gained a small + `embedded` flag: under the shell it renders a compact action row for New chat + and Refresh instead of a second `AppBar`/`CupertinoNavigationBar`. Standalone + use keeps its previous native scaffolding. +- Deep links only carry the session id, so a directly opened thread may show no + title until it is opened from a list row. The transcript itself is complete + and honest; this is not treated as chat parity. + +## Files + +| Path | Lines | Role | +| --- | ---: | --- | +| `lib/features/chat/screen.dart` | 99 | List/thread switch, selection, in-page Back, reconnect token | +| `lib/features/chat/conversation/chat_thread_view.dart` | 195 | Keyed read-only transcript, paging, live/history notices | +| `lib/features/chat/conversation/chat_row_keys.dart` | 63 | Stable row identity while a folded turn grows at either end | +| `lib/features/chat/domain/chat_transcript.dart` | 246 | History merge, turn folding, live frame fold | +| `lib/features/chat/ui/transcript/chat_message_view.dart` | 218 | Agent parts keyed by part identity (disclosure state) | +| `lib/application/chat_destination.dart` | 69 | Connection gate/banner and shared session wiring | +| `lib/features/chat/ui/sessions/chat_sessions_screen.dart` | 191 | Embedded layout flag, actions, reconnect re-read | +| `lib/application/app_route.dart` | +30/−4 | `/chat/:id` parse, serialise, equality | +| `lib/application/app_router.dart` | +13/−3 | System Back callback for a chat session | +| `lib/application/pipelines_app.dart` | +9 | Destination registration and `/chat` route mapping | + +Focused tests: `test/application/chat_registration_test.dart`, +`test/application/chat_destination_test.dart`, `test/application/app_router_test.dart`, +`test/application/app_route_test.dart`, +`test/features/chat/conversation/chat_thread_view_test.dart`, +`test/features/chat/conversation/chat_row_keys_test.dart`. +The thread tests cover both paging variants (the older page keeps `has_more`, and +the older page ends history) in Material and Cupertino, for alternating pages and +for the assistant-only fixture shape. In every case the newest `Reasoning` stays +open and the older blocks stay collapsed. `chat_row_keys_test.dart` covers a +prepended assistant page, an appended live assistant message and distinct turns. +Probe: `tool/chat_wire_probe.dart` and `tool/chat_wire_probe.mjs` include both +alternating variants plus two assistant-fold sessions (`has_more` kept and ended). + +## Checks (actual) + +- `flutter test test/features/chat test/application` — **110 tests passed**. +- `flutter test` (full suite) — **696 tests passed**. +- `flutter analyze` — **No issues found**. +- `dart format --output=none --set-exit-if-changed` on the changed Dart files — + exit 0. +- `flutter build web` — built successfully. +- `flutter build web -t tool/chat_wire_probe.dart` for the Material and Cupertino + dark fixtures — both built successfully. +- `node tool/chat_wire_probe.mjs` against real headless Chrome for both hosts — + exit 0. Each run checked, with the semantics tree and OCR of the rendered + canvas: + - embedded list shows server rows and keeps New chat/Refresh; + - the thread shows the exact stored user body, assistant body, `Reasoning` and + `shell` disclosures while collapsed bodies stay hidden; + - `Load older` renders the opaque-cursor page; + - a pushed `chat_event` delta appends to the open thread; + - after expanding the newest `Reasoning`, paging with `has_more` still true and + paging that removes `Load older` both keep the newest body open and the older + body collapsed (`newestKept: true`, `olderLeaked: false` in both hosts); + - the assistant-fold sessions repeat that check with pages of consecutive + assistant messages, for both `has_more` outcomes. +- Captures and evidence JSON: `/Users/alan/.local/share/pipelines/data/artifacts/79/public/chat-fold-paging/` + (`{material,cupertino}-{list,thread,expanded,older,live,more-expanded,more-older,fold-expanded,fold-older,fold-end-expanded,fold-end-older}.png` + and `*-evidence.json`). These come from the standalone `ChatScreen` fixture. +- Normal-app rendered check: `/Users/alan/.local/share/pipelines/data/artifacts/79/public/chat-fold-app/` + has `{material,cupertino}-{fold,fold-end}-{collapsed,expanded,older}.png` and + `fold-app-evidence.json`, driven through the real `build/web` composition and + the real router at `/chat/`. Material is a Linux UA in light mode, + Cupertino the macOS host in dark mode. Both hosts and both `has_more` outcomes + report `newestKept: true`, `olderLeaked: false`, and the expected `Load older` + presence; no page exceptions. + +Not done: composer, markdown rendering, attachments, forms, permissions, model +selection, metrics, shells, and the initial newest-message placement / live +follow scroll behaviour remain the tracked next chat items. The transcript is +still an eager, keyed `ListView` so an open disclosure also survives while its +row is offscreen; moving to a lazy builder would need that expansion state to +live above the rows. Mobile builds/devices were not used or verified. Nothing +was committed, pushed, merged or deployed. + +## Manager completion after the Code deadline + +The final Code visit reached its 30-minute deadline while active; the session then +settled and all edits were retained. No retry was started. The manager ran the +focused application/chat suites (110 tests pass) and drove the fixture probes for +both hosts. Material and Cupertino each passed and wrote captures; the Cupertino +live capture was inspected and shows the read-only conversation with the exact +user text, the stored assistant reply, collapsed Reasoning/tool disclosures, the +live delta and the responding line, all under the shell's single bar. + +Scope stays read-only: no composer, markdown rendering, forms, approvals, metrics +or attachments are claimed by this item. diff --git a/app/notes/P2-stage.md b/app/notes/P2-stage.md new file mode 100644 index 00000000..36b7b411 --- /dev/null +++ b/app/notes/P2-stage.md @@ -0,0 +1,103 @@ +# P2 stage: read-only definition pane + +The definition graph can now open one stage's authored definition without +reading a run. `StageDefinitionView` receives the graph JsonMap pinned for a +pipeline/version, a stage key and that identity; it performs no request and +shows no visit, status or session data. `openStageDefinition` pushes the +platform's normal page with one navigation bar and its standard back control, +for the manager's graph hook. + +## Behaviour + +- Fields match `stageDefinitionFields`/`terminalFields` in `web/src/graph.js`: + Type, Prompt, Output, Outcomes (ordered, targets resolved, terminals marked), + configs in sorted order with the web labels, Tools, Max visits, Limit on, + Memory, Notify on/destination/artifacts. Only non-blank fields are emitted. +- `effectiveStageType` keeps the web rule that a blank/absent type reads + `model`; no other default is invented. +- A terminal (`#success`/`#failure`) lists its incoming definition routes and + says explicitly that these are definition targets, not recorded visits. Its + page is titled with the web's display label (`Failure definition` / + `Success definition`, via `nodeDisplayLabel`), never the raw `#failure` key. +- A stage key this version does not declare gets an explicit missing state. No + fields, terminal note or raw JSON are fabricated. +- Every declared stage also shows its exact pretty-printed stage JSON in a + selectable raw section, so unknown/future fields stay available. The raw + value is the only source for those keys; the structured rows only interpret + documented ones. +- Host text roles only: Material `Theme`/`ColorScheme`, Cupertino + `CupertinoTheme`/`CupertinoColors`, system fonts, light/dark and text scale + follow the host. No palette, font family, fixed component size or custom + control clone. +- Selectable body blocks force a strut derived from that same host style. + Without it, a glyph the host font lacks (the outcomes arrow `→`) pulls in a + fallback font with taller metrics and doubles only that block's leading. The + strut is the host's own family/size, not a font override or fixed height, and + selection stays native. + +## UI review fixes + +- Cupertino `Outcomes` leading: the block's rendered line pitch matched a + fallback font (34 px between outcome lines against 19 px for `Tools` at 1×, + 68 px against 30 px at 2×). With the forced host strut the line pitch is + 19 px for both blocks at 1× and 37/39 px at 2×, and the semantics block + heights are equal (72/72 at 1×, 123/123 at 2×). The 390×844 / 2× wrap of + `(terminal)` now sits on the same rhythm as the line above it. +- Terminal titles: `#failure definition`/`#success definition` became + `Failure definition`/`Success definition`. The Cupertino widget test now + asserts `Success definition` and the absence of the raw key; a Material + test covers `Failure definition`; the browser probe fails if `#failure` + reappears in the terminal page or if the outcomes/Tools block heights + diverge. + +## Integration dependency + +`PipelineDetail` still has no `graph` field, so the manager's graph hook must +supply the pinned JsonMap it already draws. This item deliberately does not +change the pipeline repository/model. There is no run-mode latest-visit pane +here; recorded visits remain the separate run-graph/audit work. + +## Checks run + +- `flutter test test/features/graph` - 140 tests passed (138 before; two new + regression tests for the terminal title and the forced host strut). +- `flutter analyze` - no issues. +- `dart format --set-exit-if-changed` on the five Dart files - 0 changed. +- `flutter build web` (normal app) - succeeded. +- `flutter build web -t tool/stage_definition_probe.dart` - succeeded. +- `node --check tool/stage_definition_probe.mjs`. +- Real Chrome probe, 1280x900: material dark/light 1x, Cupertino dark/light 1x + and Cupertino dark/light 2x. Each case passed 9 checks and produced 5 + captures. The probe now compares the `Outcomes` and `Tools` semantics block + heights (equal in every case), fails on any raw `#failure` in the terminal + page, asserts `Failure definition`, and scrolls to the pane bottom so the + raw capture really shows `future_field.kept` and `fallback_error`. +- Real Chrome probe, 390x844: Cupertino dark 2x and Material light 1x. Each + passed 8 checks and produced 5 captures, including the `(terminal)` wrap and + the raw JSON at the narrow width. The accent-free rhythm check is skipped at + this width because the outcomes value wraps to three lines. +- Pixel measurement of the final captures: Cupertino 1x outcomes 19 px vs + Tools 19 px (was 34 vs 19); Cupertino 2x outcomes 37 px vs Tools 39 px (was + 68 vs 30); Material 1x outcomes 19 px vs Tools 20 px. + +Captures (under the run's shared artifact folder +`public/stage-definition/`): `--x-{declared,raw,terminal,unknown,closed}.png` +for the six 1280x900 cases, and the same names prefixed with `stage-definition-` +under `narrow-390x844/` for the two 390x844 cases. The raw capture is the real +bottom-scrolled state and its sha1 differs from the declared capture in every +case. + +Mobile (Android/iOS) remains unverified; only web was run. + +## Manager completion after result-validation failure + +Run 77's final Review visit returned no parseable outcome, so the runner retained +its edits and failed the stage without undoing them. No retry was started. The +manager verified the dirty files were the reviewed slice only, ran the focused +domain/view tests (10 pass), and drove the real-browser probe on both hosts: +Material light 1x desktop and Cupertino dark 2x 390x844. Each run passed and +produced five captures (declared, raw, terminal, unknown, closed) under approved +temp/stage-def-browser. The Cupertino dark 2x declared pane was inspected: pinned +identity, wrapping outcome line, native type roles, readable secondary labels. +This remains a definition pane only; run visits and the pipeline graph hook are +separate work. diff --git a/app/notes/R2c-wire.md b/app/notes/R2c-wire.md new file mode 100644 index 00000000..060ebd1c --- /dev/null +++ b/app/notes/R2c-wire.md @@ -0,0 +1,158 @@ +# R2c-wire — Retry/restart in the real run detail + +## Result + +The already-landed `RetryRunAction` now renders in the real run detail action +row under both native hosts, beside Rename and Cancel/decision wiring. Only a +loaded, stopped `failed` run offers it. Resume sends exactly `run_id` and +`request_key`; restart additionally sends `retry_mode: "restart"`. `Keep` sends +nothing. The accepted reply is delivered through +`RunsController.acceptRunDetail` like cancel/title, and the new run is opened +only when the reply itself carries a numeric, different run id. A reply without +an id, a reply naming the source run, a late reply, or a reply after leaving +never guesses a run or moves the route. + +The action row now uses the detail's native 8 dp / 4 dp `Wrap` spacing. It +previously used the default zero spacing, so the outlined Rename border met the +filled Retry button at 320 px (browser-measured gap 0.008 CSS px). Only actions +that render are included in the `Wrap`: a hidden action still consumed spacing +and would have doubled the visible gap. + +The browser probe found one real web-only defect in the landed key generator: +dart2js evaluates `1 << 32` as `0`, so `Random.nextInt` raised every retry +before the request left the app. The bound is now a literal `0x100000000`; a +browser-compiled test and the web probe both exercise the real generator. + +## Files + +| File | Change | +| --- | --- | +| `lib/features/runs/ui/run_detail_actions.dart` | Renders `RetryRunAction` in the action row, forwards the reply-id callback, uses 8/4 dp spacing, includes only eligible actions | +| `lib/features/runs/ui/run_detail_view.dart` | Passes an optional server-identified run opener through to the actions | +| `lib/features/runs/screen.dart` | Opens the reply-named run through the existing `_select` path (controller selection + route) | +| `lib/features/runs/actions/retry_action.dart` | After the accepted detail callback, opens only a different numeric reply id | +| `lib/features/runs/actions/retry_intent.dart` | Web-safe 2^32 entropy literal instead of `1 << 32` | +| `test/features/runs/ui/run_retry_wiring_support.dart` | New: fixture gateway and both-host detail mount | +| `test/features/runs/ui/run_retry_wiring_test.dart` | New: real screen wiring, exact resume/restart payloads, server-named navigation | +| `test/features/runs/ui/run_retry_guard_test.dart` | New: no-id/same-id/refusal/late reply and eligibility gates | +| `test/features/runs/ui/run_retry_layout_test.dart` | New: action-row spacing at 320 px and 2x, no doubled gap from a hidden action | +| `test/features/runs/actions/retry_action_test.dart` | Full-width entropy regression for the request key | +| `test/features/runs/actions/retry_intent_web_test.dart` | New browser-only (`@TestOn('browser')`) regression for the dart2js entropy defect | +| `tool/retry_wiring_probe.dart`, `tool/retry_wiring_probe.mjs` | Normal-app browser probe; `CHROME_PATH`/`TESSERACT`/`PROBE_THEME` envs; measures the 8 dp action gap | + +No dialog, repository protocol, server, web, shell, main, pubspec, Android or +iOS file changed. No new server command or API. + +## Behaviour + +- Action order in the detail `Wrap` is Rename, Retry, Cancel; Retry renders + nothing unless `canRetryRun(run)` holds (`!executing && status == "failed"`). + Both Material (`FilledButton`) and Cupertino (`CupertinoButton.filled`) use + their native controls and host typography. The row uses `spacing: 8` and + `runSpacing: 4`, matching the detail's other action rows. +- Opening the prompt and choosing `Keep` send nothing. Resume sends exactly + `{run_id, request_key}`; restart sends + `{run_id, request_key, retry_mode: "restart"}`. The key is + `app-retry--…`, bounded at 128 characters, fresh per deliberate + intent, and retained across an uncertain resend by the landed dialog. +- The accepted `run_detail` goes through `onRunChanged`, i.e. + `controller.acceptRunDetail`: it folds an existing list row and replaces the + open detail only when its id still matches. A refusal stays in the prompt + with the server words and a bounded `get_run` recheck, as landed. +- The new run is opened only when `retryRunId(reply)` is numeric and differs + from the source id. `RunsScreen._select` then uses the existing controller + `select` generation guard and reports the route change, so the URL becomes + `/runs/`. No id or same id, no navigation; a later reply after + leaving is ignored by the action's ownership check and never reaches the + controller. The accepted reply for the source run is still folded normally. +- The reply is not used to invent a title, status or id. The opened detail is + the server's `get_run` for the id the retry reply named. + +## Checks actually run + +``` +dart format lib/features/runs test/features/runs tool/retry_wiring_probe.dart + # Formatted 61 files (0 changed) +flutter analyze # No issues found! +flutter test test/features/runs/ui/run_retry_guard_test.dart \ + test/features/runs/ui/run_retry_layout_test.dart \ + test/features/runs/ui/run_retry_wiring_test.dart # 13 passed +flutter test test/features/runs test/application/runs_destination_test.dart + # 134 passed +flutter test # 708 passed +flutter test --platform chrome \ + test/features/runs/actions/retry_intent_web_test.dart + # 1 passed (dart2js) +flutter build web # Built build/web +flutter build web --target=tool/retry_wiring_probe.dart -o build/retry_probe_web_code + # Built +OPENCODE_ARTIFACT_DIR=.../public/r2c-retry-wire-code-fix \ + node tool/retry_wiring_probe.mjs build/retry_probe_web_code + # ok: true, 9 checks, 10 captures +OPENCODE_ARTIFACT_DIR=.../public/r2c-retry-wire-code-fix PROBE_THEME=light \ + node tool/retry_wiring_probe.mjs build/retry_probe_web_code + # ok: true, 9 checks, 10 captures +``` + +Regression guards were mutation-checked: with `spacing: 0` the 320 px spacing +test fails, and with `Random().nextInt(1 << 32)` the browser test fails with the +dart2js `RangeError`; both were restored. + +Real-browser probe (normal app composition, isolated loopback websocket, +320×480 CSS at DPR 2, both themes and hosts): + +- The action row measures **8.016 CSS px** (Cupertino) and **8.008 CSS px** + (Material) between Rename and Retry in both themes, versus 0.008–0.016 px + before the fix. Failed and running rows are visually separated in dark and + light. +- Cupertino: failed run shows Rename and Retry; `Keep` recorded zero retry + requests; restart sent + `{run_id: 7, request_key: "app-retry-7-…", retry_mode: "restart"}` and opened + only `/runs/8`, the reply's run. Resume from the still-failed source sent + only `{run_id: 7, request_key: "app-retry-7-…"}`, omitted `retry_mode`, and + opened only `/runs/9`. +- Material: the same failed run and action row; `Keep` sent nothing; resume + sent the same two-field payload and opened only `/runs/10`. +- All retry request keys started with `app-retry-7-`, fit 128 characters, and + no navigation occurred before a reply. Back listed the source and retried + runs. +- Twenty PNGs in + `/Users/alan/.local/share/pipelines/data/artifacts/80/public/r2c-retry-wire-code-fix/` + cover both themes and both hosts (failed, prompt, kept, restart prompt, + restart run, list, resume run; seven Cupertino and three Material each). + OCR asserted the source/new-run titles; the + failed captures were inspected for the restored native gap and readable + 320 px layout. + +Before the key fix, the same probe failed with +`ZONE ERROR: RangeError: max must be in range 0 < max ≤ 2^32, was 0` and +recorded zero retry requests. + +## Honest limits + +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used; + sources stay portable Material/Cupertino. +- No production server, operator run or real retry was touched. The probe used + an isolated fixture with no credentials or shared data. +- Browser text scaling cannot be driven from CDP; 2x text at 320 px is covered + by the widget tests, while the browser probe covers 320 CSS px at DPR 2 in + dark and light. +- The browser entropy test is not part of the default `flutter test` VM run; it + needs `flutter test --platform chrome` and a Chrome install. No CI wiring + exists in this repository to add it to. +- The app opens the reply-named new run, while `web/src/views/dialogs.js` + silently re-selects the source run. The reply is genuinely the new run, so + this remains an intended improvement rather than pure parity; the product + decision is unchanged in this turn. +- The accepted reply's own detail is discarded when navigating and one + `get_run` follows, briefly showing the loading placeholder. Correct, one + extra round trip; not changed in this focused fix. +- `tool/retry_wiring_probe.mjs` remains long and requires Chrome; it now + honours `CHROME_PATH`, `TESSERACT` and `PROBE_THEME`, but is not otherwise + split. +- The post-Keep Cupertino capture is identical to the failed state; the + "sent nothing" claim rests on the probe's zero-request fixture state. +- A pre-existing Cupertino detail-header defect was observed at 320 px/2x: the + landed Changes button's internal `Row` overflows by 14 px. It reproduces with + Retry absent and belongs to the Changes lane, so it was not edited here. +- Nothing was committed, pushed, merged to main or deployed. diff --git a/app/notes/R4-attention.md b/app/notes/R4-attention.md new file mode 100644 index 00000000..873c95d6 --- /dev/null +++ b/app/notes/R4-attention.md @@ -0,0 +1,62 @@ +# Attention model (pure domain) + +The `Needs you` model exists as reusable, widget-free Dart under +`lib/features/attention/domain/`. The list, identity, wording and local-day +window mirror the browser's `src/attention.js`; no UI, storage plugin, +notification permission or API request is added here. + +`attention_transitions.dart` is an attention transition ledger, not a port of +`src/notify.js`: notification permission, tray alerts, `notify_mode` suppression +and success alerts are deliberately outside this slice. + +- `attention_models.dart` owns the two kinds (`Decision` rank 0, `Failed` rank 1), + qualification, ordered entries, labels/detail wording, `{runId}:{kind}` + identities, dismissal/snapshot bookkeeping and the JSON string-array + serialisation under this app's own `pipelines.next.attention.v1` (deliberately + not the legacy web key, so neither client rewrites the other's local state). +- Only `waiting` and `failed` statuses qualify, after trimming/lowercasing. A + waiting run with a session audit/export handoff (`export_pending_sequence > 0`) + asks no person and is excluded; a failed run stays failed. `resource_wait` is + deliberately not consulted, matching `web/src/attention.js` and `Attention.kt` + (the server retired the field, and a stale value must not hide a decision). +- The surface is today's work: `attentionEntries` accepts an optional `since` + cutoff and drops an entry when its recency parses and is before it, keeping a + blank or unreadable recency, exactly as the browser does. No cutoff (or an + epoch-zero one) shows everything. Callers pass `startOfLocalDay()` to the bell, + the sheet and the Clear-all snapshot, so yesterday's failures become history. + Stored dismissals themselves still never expire. +- `startOfLocalDay({now})` returns local midnight and takes an injectable `now` + so the UI does not re-derive it and tests stay deterministic. +- Ordering is kind rank, then `finished_at` else `created_at` descending using the + server's timestamp text, then run id descending. The label is the trimmed title + else pipeline name; the detail is `Waiting for your decision`, or the trimmed + diagnostic else `Run failed`. +- Entries retain the whole source summary map, so fields this model does not read + (and unknown future fields) are preserved. `AttentionEntry` is constructed only + by `attentionEntryFor`, so its `runId` is always a validated positive id. +- `attention_transitions.dart` is a pure detector: a seed/first-seen run, + duplicate frame, nonqualifying status, export wait, reconnect reseed or a + snapshot bracketed with `beginSeed`/`endSeed` never emits. It emits once when a + known run enters `failed` or a human `waiting`, forgets the key when the run + leaves that state, and keeps the emitted set across `resetForReconnect`/`reseed` + so a gap cannot replay a transition. A reseed keeps the key of a run that still + qualifies (or that is absent from the read) and prunes one whose run no longer + asks. Dismissed identities are marked seen but suppressed. + +Focused tests in `test/features/attention/` cover qualification and exclusions, +ordering and tie-breaks, the local-day cutoff (older/newer, unparseable/blank +recency, no cutoff, decisions, dismissal composition), wording/labels, identity, +dismissal filtering, the clear-all snapshot, defensive copying, malformed/blank +storage, unknown-field preservation, and transition dedupe/first-seen/ +nonqualifying/reconnect reseed/emitted-key retention. + +Verification: `flutter test test/features/attention` passed all 44 tests; +`flutter analyze` reported no issues. No browser capture applies to this +nonvisual domain slice. + +Not done here: no `Needs you` screen/sheet, badge, storage write, store/controller +wiring or notification permission was added, and `PARITY.md` remains `Missing` +until those land. The older `orderAttention` helper in +`lib/features/runs/domain/run_models.dart` was left untouched for lane ownership; +the runs UI must delegate to this model when it is wired, so the two authorities +cannot diverge. Mobile is unverified. diff --git a/app/notes/T1-gallery.md b/app/notes/T1-gallery.md new file mode 100644 index 00000000..42d08564 --- /dev/null +++ b/app/notes/T1-gallery.md @@ -0,0 +1,183 @@ +# T1 — reusable native Templates gallery + +Manager acceptance: re-ran the templates suite (38 tests) and rebuilt the +in-process fixture. Seven probe checks pass with seven captures under approved +temp/templates-gallery-browser; the selected-template capture was inspected and +shows metadata, the verbatim selectable source and the native create action with +one bar. No real template was created or submitted; every request came from the +fixture gateway. Settings/route registration and a post-create pipelines-list +refresh are still manager wiring, not claimed here. + +## Result + +`TemplatesScreen` is one reusable gallery over the server's actual template +catalogue. It lists every `list_templates` row, opens the selected template's +metadata and its source byte-for-byte in the host's selectable body, and offers +the browser's one create action. That action calls the already-landed +`showTemplateCreateDialog` unchanged, so validate-then-submit, Cancel, +create-only `submit` and the single accepted `detail` stay in the existing +prompt. The accepted detail is forwarded through the optional `onCreated` +callback. + +A refused refresh is reported above whichever body is current, including an open +template, with the host's native Retry; the selection and already-read rows are +kept. The screen's loading state, late-reply guard and single create path are +unchanged. + +Nothing is registered in the shell, Settings, routes or application; the +manager owns that next. No pipeline/gallery/create code was rewritten and no +run, schedule, publish, cancel or graph control exists here. + +## Files (all new; no tracked file modified) + +| File | Lines | Responsibility | +| --- | ---: | --- | +| `lib/features/templates/screen.dart` | 208 | Load/selection/create state, late-reply sequencing, failure banner above either body, embedded flag, system back | +| `lib/features/templates/ui/template_gallery.dart` | 138 | Catalog rows and honest loading/empty/full-failure states | +| `lib/features/templates/ui/template_detail.dart` | 168 | Browser wording, metadata, verbatim selectable source, create action, embedded Back row | +| `lib/features/templates/ui/templates_failure.dart` | 118 | Full failure state and the screen-level failed-refresh banner, each with native Retry | +| `lib/features/templates/ui/templates_frame.dart` | 104 | Native standalone app bar or embedded Refresh row; Back/Refresh controls | +| `test/features/templates/ui/template_gallery_test_support.dart` | 112 | Recording gateway, catalogue fixtures, Material/Cupertino host pump | +| `test/features/templates/ui/template_gallery_screen_test.dart` | 379 | States, retry, refresh, detail-refresh failure (both hosts, embedded), back, embedded, 2x, late/disposed replies | +| `test/features/templates/ui/template_gallery_create_test.dart` | 104 | Cancel sends nothing, verify+submit once, optional callback, Cupertino prompt | +| `tool/templates_gallery_probe.dart` | 178 | Isolated in-process fixture entry; default, empty and detail-refresh-refusal scenarios | +| `tool/templates_gallery_probe.mjs` | 386 | Loopback static server + real headless Chrome driver | +| `notes/T1-gallery.md` | — | This evidence | + +`TemplateEntry`, `TemplateRepository`, `TemplateRepositoryException`, +`ApiGateway`, `showTemplateCreateDialog` and its wording/keys are reused +unchanged. `pubspec.*`, `lib/main.dart`, `lib/application/`, `lib/shell/`, +Settings, routes, Pipelines, `web/`, the Go server and `android/` were not +touched. + +## Behaviour + +- Gallery wording is the browser's: `Loading templates…`, `No templates are + available on this server.`, a blank catalogue name as `(unnamed template)`, + description verbatim, and a blank detail heading falling back to the key. +- Detail shows the description (when non-blank), `Key`, `Includes a schedule` + (when true), `Definition source`, and the server's complete source in + `SelectableText`. The source is never trimmed, re-indented or re-encoded. +- The action is exactly `Create pipeline from this template`. It calls + `showTemplateCreateDialog` with the current repository, the selected entry and + the host's native flag. Opening the prompt, typing, or Cancel sends nothing. + Only the dialog's Create validates and then submits create-only; an accepted + detail reaches `onCreated` exactly once. +- Standalone Material uses `Scaffold`/`AppBar` with a native `BackButton` when a + template is open and a tooltip `Refresh` action; Cupertino uses + `CupertinoPageScaffold`/`CupertinoNavigationBar` with the native back chevron + and refresh icon. Doors are opened on the detail as this screen's own page, so + Android system back also returns to the gallery via `PopScope`. +- `embedded: true` drops the app bar, keeps a Refresh control at the body's + trailing top edge and shows a native Back row inside the detail, matching the + shell-owned-navigation contract used by other feature screens. +- Loading, empty and refusal have their own truthful states. A refusal shows the + server's own text and `Retry`; a refresh failure keeps already-loaded rows and + shows the refusal/`Retry` above them instead of blanking the gallery. The same + banner is rendered above an open template, so pressing Refresh on the detail + never fails silently; Retry re-reads with the template and rows kept. +- Only the newest `list_templates` generation may publish. A gateway change + clears the old server's rows and selection, an older reply is ignored, and a + reply completing after disposal is dropped (no `setState`). +- No stage-count read, stage list, Graph tab or mini graph is included: this + slice deliberately sends no per-card `validate`. The browser's stage count is + therefore not claimed here. The detail's metadata is description, key and + schedule flag; its source is complete. + +## Checks actually run + +``` +cd app +flutter analyze # No issues found +dart format --output=none --set-exit-if-changed \ + lib/features/templates test/features/templates/ui/template_gallery_*.dart \ + tool/templates_gallery_probe.dart # 0 changed +flutter test test/features/templates # 37 passed +flutter test # 690 passed +flutter build web -o /web-normal # ✓ Built +flutter build web --target=tool/templates_gallery_probe.dart \ + -o /probe-web # ✓ Built +``` + +The focused suite covers: loading then catalogue; empty; refusal + Retry; +failed refresh retaining rows; a failed refresh with the detail open on Material +and Cupertino, including the native Retry control and the template staying +open; the same failure in embedded mode; refresh re-reading without losing +selection; selection showing metadata/source with no validate/submit; +native/system back; embedded framing; Cupertino list/back/detail controls; 2x at +360×640 with no overflow; stale reply ignored after a gateway replacement; late +reply after disposal; Cancel sending nothing; exact `validate`/`submit` payloads; +callback once; optional callback; Cupertino prompt. + +## Browser evidence (real headless Chrome, loopback only) + +The probe's gateway is in-process; it never opens a socket and never contacts a +real Pipelines server. All runs are dark (`MaterialApp` standard dark theme / +`CupertinoThemeData(brightness: dark)`), with no font, colour or component-size +overrides. Each default run asserts: refusal + Retry; loading; actual rows; +selection metadata + `Definition source`; back; refresh adding +`Added after refresh`; Cancel with zero requests; accepted create with exactly +one validate and submit, exact +`{name: "Probe release", source: , create_only: true}`, +callback once, and Close sending nothing. + +- Material dark, 390×844, 1x — `public/t1-gallery/` + (`error`, `loading`, `gallery`, `detail`, `refreshed`, `create-blank`, `created`). +- Material dark, 360×640, 2x text — `public/t1-gallery-2x/` (same seven states). +- Cupertino dark, 390×844, 1x — `public/t1-gallery-cupertino-1x/` (same seven). +- Cupertino dark, 360×640, 2x text — `public/t1-gallery-cupertino/` (same seven). +- Material dark empty catalogue — `public/t1-gallery-empty/t1-gallery-empty-empty.png`. +- Material dark failed refresh with the detail open — + `public/t1-gallery-detail-refresh/` (`detail-refresh-error`, + `detail-refresh-retried`). +- Cupertino dark failed refresh with the detail open — + `public/t1-gallery-detail-refresh-cupertino/` (same two states). + +The new scenario loads the catalogue, opens `Release workflow`, presses Refresh +and the fixture read genuinely refuses. The run asserts the refusal and Retry +are present above the still-open definition source, that exactly two +`list_templates` reads and no `validate`/`submit` happened, then presses Retry, +asserts the banner clears, the template stays open and a third read happened. +Inspected both Material and Cupertino captures: the native banner sits above the +detail, then disappears after Retry without losing the template. + +Inspected screenshots: the Material dark gallery/detail, the 2x detail with +wrapped action and title, the Cupertino 1x gallery/detail, the 2x Cupertino +gallery (names now wrap to two lines rather than ellipsizing), the error/Retry +state and the created dialog with the exact success line. + +## Task diff + +``` +?? app/lib/features/templates/screen.dart +?? app/lib/features/templates/ui/template_detail.dart +?? app/lib/features/templates/ui/template_gallery.dart +?? app/lib/features/templates/ui/templates_failure.dart +?? app/lib/features/templates/ui/templates_frame.dart +?? app/test/features/templates/ui/template_gallery_create_test.dart +?? app/test/features/templates/ui/template_gallery_screen_test.dart +?? app/test/features/templates/ui/template_gallery_test_support.dart +?? app/tool/templates_gallery_probe.dart +?? app/tool/templates_gallery_probe.mjs +?? app/notes/T1-gallery.md +``` + +All are additions in the working tree. No tracked file changed, no concurrent +lane or manager commit was modified, and nothing was staged, committed, pushed +or deployed. `git diff --check` is clean. + +## Honest limits + +- Not wired into the shell/Settings/routes; this is reusable source, not a + normal-app preview entry. The manager owns registration. +- No real Pipelines server, credentials, operator pipeline or create request was + touched. Browser evidence uses the in-process fake gateway. +- Mobile (Android/iOS) is unverified: no Android/iOS build, emulator, device or + ADB. The Cupertino captures are Chrome's rendering of Cupertino widgets, not + iOS; VoiceOver/TalkBack was not run. +- Stage counts, stage lists and the Graph tab are intentionally not implemented + in this slice (no per-card validate), so they are not claimed as parity here. +- Browser captures remain standalone use only; `embedded: true` is covered by + widget tests, not by the headless-Chrome probe. +- `/artifacts`/live authenticated data and the real dark app-shell theme were + not exercised; the probe supplies the standard dark host themes. diff --git a/app/test/application/app_route_test.dart b/app/test/application/app_route_test.dart index 598dce52..eb2968d3 100644 --- a/app/test/application/app_route_test.dart +++ b/app/test/application/app_route_test.dart @@ -7,6 +7,10 @@ void main() { expect(AppRoute.parse('/runs'), AppRoute.runs); expect(AppRoute.parse('/runs/12'), AppRoute.run(12)); expect(AppRoute.parse('/chat'), AppRoute.chat); + expect( + AppRoute.parse('/chat/abc_DEF-123'), + AppRoute.chatSession('abc_DEF-123'), + ); expect(AppRoute.parse('/settings'), AppRoute.settings); }); @@ -18,6 +22,14 @@ void main() { AppRoute.run(7), ); expect(AppRoute.parse('/runs/7/'), AppRoute.run(7)); + expect( + AppRoute.parse('/chat/session/?x=1'), + AppRoute.chatSession('session'), + ); + expect( + AppRoute.parse('/chat/probe%2Dchat'), + AppRoute.chatSession('probe-chat'), + ); }); test('a malformed or unknown location is the default Pipelines route', () { @@ -29,7 +41,9 @@ void main() { '/runs/-1', '/runs/1/extra', '/pipelines/2', - '/chat/session', + '/chat/a/b', + '/chat/%2F', + '/chat/${'x' * 201}', '/unknown', '/runs/%E0%A4%A', ]) { @@ -43,10 +57,13 @@ void main() { AppRoute.runs, AppRoute.run(3), AppRoute.chat, + AppRoute.chatSession('probe_open-1'), AppRoute.settings, ]) { expect(AppRoute.parse(route.path), route); } expect(AppRoute.run(3).path, '/runs/3'); + expect(AppRoute.chatSession('probe_open-1').path, '/chat/probe_open-1'); + expect(AppRoute.chatSession('bad id').path, '/chat'); }); } diff --git a/app/test/application/app_router_test.dart b/app/test/application/app_router_test.dart new file mode 100644 index 00000000..e713f173 --- /dev/null +++ b/app/test/application/app_router_test.dart @@ -0,0 +1,31 @@ +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/app_route.dart'; +import 'package:pipelines_app/application/app_router.dart'; + +AppRouterDelegate delegate(AppRoute initial, {void Function()? onChat}) => + AppRouterDelegate( + builder: (context, route) => const SizedBox.shrink(), + onPopToRuns: () {}, + onPopToChat: onChat ?? () {}, + cupertino: false, + initial: initial, + ); + +void main() { + test('system Back leaves one chat session for the chat list', () async { + var left = 0; + final router = delegate(AppRoute.chatSession('s1'), onChat: () => left++); + addTearDown(router.dispose); + + expect(await router.popRoute(), isTrue); + expect(left, 1); + }); + + test('system Back on a list destination stays with the platform', () async { + final router = delegate(AppRoute.chat); + addTearDown(router.dispose); + + expect(await router.popRoute(), isFalse); + }); +} diff --git a/app/test/application/chat_destination_test.dart b/app/test/application/chat_destination_test.dart new file mode 100644 index 00000000..eaca79ae --- /dev/null +++ b/app/test/application/chat_destination_test.dart @@ -0,0 +1,113 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/app_session.dart'; +import 'package:pipelines_app/application/chat_destination.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; + +import '../core/transport/pipelines_client_test.dart' show FakeChannel; +import 'chat_registration_test.dart' + show + replyHistory, + replySessions, + replySubscribe, + requestOf, + waitForRequest, + webServer; + +Widget host(AppSession session, {String? initialSessionId}) => MaterialApp( + home: Scaffold( + body: ChatDestination( + session: session, + server: webServer(), + initialSessionId: initialSessionId, + ), + ), +); + +void main() { + testWidgets('nothing is requested before the shared socket is ready', ( + tester, + ) async { + final channel = FakeChannel(); + final client = PipelinesClient(channelFactory: (_) => channel); + final server = webServer(); + final session = AppSession(endpoint: server.uri, client: client); + addTearDown(session.dispose); + + final starting = session.start(); + await tester.pumpWidget(host(session, initialSessionId: 's1')); + expect(find.text('Connecting to Pipelines…'), findsOneWidget); + expect(find.byType(ChatThreadView), findsNothing); + expect(channel.outgoing, isEmpty); + + channel.readyCompleter.complete(); + await starting; + }); + + testWidgets('a reconnect resyncs the open session without losing it', ( + tester, + ) async { + final first = FakeChannel()..readyCompleter.complete(); + final second = FakeChannel()..readyCompleter.complete(); + var sockets = 0; + final client = PipelinesClient( + channelFactory: (_) => sockets++ == 0 ? first : second, + backoffBase: const Duration(milliseconds: 10), + ); + final server = webServer(); + final session = AppSession(endpoint: server.uri, client: client); + addTearDown(session.dispose); + + await session.start(); + await tester.pumpWidget(host(session, initialSessionId: 's1')); + await tester.pump(); + + await replySessions(tester, first); + await replySubscribe(tester, first); + await replyHistory(tester, first); + expect(find.text('The stored reply stays readable.'), findsOneWidget); + + first.incoming.addError(StateError('network drop')); + await tester.pump(); + expect(find.byType(ChatThreadView), findsOneWidget); + expect(find.text('The stored reply stays readable.'), findsOneWidget); + + // The mounted session list re-reads on reconnect: a session created while + // the socket was gone must not stay invisible until Refresh. Requests are + // serialized, so this reply also lets the thread's resync proceed. + final relisted = await waitForRequest(tester, second, 'chat_sessions'); + second.incoming.add( + jsonEncode({ + 'id': relisted['id'], + 'type': 'chat_sessions', + 'chat_sessions': [ + {'id': 's1', 'title': 'Wire chat'}, + {'id': 's2', 'title': 'Created while offline'}, + ], + }), + ); + await tester.pump(); + + final resubscribe = await waitForRequest(tester, second, 'chat_subscribe'); + second.incoming.add( + jsonEncode({'id': resubscribe['id'], 'type': 'chat_subscribe'}), + ); + await tester.pump(); + await replyHistory(tester, second, text: 'Refreshed after reconnect.'); + expect(find.byType(ChatThreadView), findsOneWidget); + expect(find.text('Refreshed after reconnect.'), findsOneWidget); + expect(find.text('The stored reply stays readable.'), findsNothing); + expect(requestOf(second, 'chat_messages')!['chat_query'], { + 'session_id': 's1', + 'limit': 200, + 'cursor': '', + }); + expect( + find.text('Created while offline', skipOffstage: false), + findsOneWidget, + ); + }); +} diff --git a/app/test/application/chat_registration_test.dart b/app/test/application/chat_registration_test.dart new file mode 100644 index 00000000..91a452a1 --- /dev/null +++ b/app/test/application/chat_registration_test.dart @@ -0,0 +1,235 @@ +import 'dart:convert'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/pipelines_app.dart'; +import 'package:pipelines_app/application/server_endpoint.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_screen.dart'; + +import '../core/transport/pipelines_client_test.dart' show FakeChannel; + +ServerEndpoint webServer() => ServerEndpoint.resolve( + base: Uri.parse('http://127.0.0.1:8096/'), + web: true, +); + +Map? requestOf( + FakeChannel channel, + String type, { + int index = 0, +}) => channel.outgoing + .map((frame) => jsonDecode(frame as String) as Map) + .where((frame) => frame['type'] == type) + .skip(index) + .firstOrNull; + +Future> waitForRequest( + WidgetTester tester, + FakeChannel channel, + String type, { + int index = 0, +}) async { + for (var attempt = 0; attempt < 80; attempt++) { + final request = requestOf(channel, type, index: index); + if (request != null) return request; + await tester.pump(const Duration(milliseconds: 5)); + } + fail('Timed out waiting for $type #$index'); +} + +Future replySessions( + WidgetTester tester, + FakeChannel channel, { + int index = 0, +}) async { + final request = await waitForRequest( + tester, + channel, + 'chat_sessions', + index: index, + ); + channel.incoming.add( + jsonEncode({ + 'id': request['id'], + 'type': 'chat_sessions', + 'chat_sessions': [ + {'id': 's1', 'title': 'Wire chat', 'directory': '/workspace/demo'}, + ], + }), + ); + await tester.pump(); +} + +Future replySubscribe( + WidgetTester tester, + FakeChannel channel, { + int index = 0, +}) async { + final request = await waitForRequest( + tester, + channel, + 'chat_subscribe', + index: index, + ); + channel.incoming.add( + jsonEncode({'id': request['id'], 'type': 'chat_subscribe'}), + ); + await tester.pump(); + await tester.pump(); +} + +Future replyHistory( + WidgetTester tester, + FakeChannel channel, { + int index = 0, + String text = 'The stored reply stays readable.', +}) async { + final request = await waitForRequest( + tester, + channel, + 'chat_messages', + index: index, + ); + channel.incoming.add( + jsonEncode({ + 'id': request['id'], + 'type': 'chat_history', + 'chat_history': { + 'messages': [ + { + 'id': 'u1', + 'role': 'user', + 'parts': [ + {'type': 'text', 'text': 'Open this chat from its route.'}, + ], + }, + { + 'id': 'a1', + 'role': 'assistant', + 'parts': [ + {'type': 'text', 'text': text}, + {'type': 'reasoning', 'text': 'Kept behind a native disclosure.'}, + {'type': 'tool', 'name': 'shell'}, + ], + }, + ], + 'next_cursor': '', + 'has_more': false, + }, + }), + ); + await tester.pump(); + await tester.pump(); +} + +void main() { + for (final cupertino in [false, true]) { + testWidgets( + 'a /chat/s1 deep link renders that thread and Back returns to /chat ($cupertino)', + (tester) async { + tester.view.physicalSize = const Size(900, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + if (cupertino) { + tester.platformDispatcher.platformBrightnessTestValue = + Brightness.dark; + addTearDown( + tester.platformDispatcher.clearPlatformBrightnessTestValue, + ); + } + + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('/chat/s1')), + ); + addTearDown(provider.dispose); + + await tester.pumpWidget( + PipelinesApp( + server: webServer(), + client: client, + cupertino: cupertino, + routeInformationProvider: provider, + ), + ); + await tester.pump(); + + await replySessions(tester, channel); + await replySubscribe(tester, channel); + await replyHistory(tester, channel); + + expect(provider.value.uri.path, '/chat/s1'); + expect(find.byType(ChatThreadView), findsOneWidget); + // The exact route names the session; the request carries the same id. + expect(requestOf(channel, 'chat_subscribe')!['chat_subscribe'], { + 'session_id': 's1', + }); + expect(requestOf(channel, 'chat_messages')!['chat_query'], { + 'session_id': 's1', + 'limit': 200, + 'cursor': '', + }); + expect(find.text('The stored reply stays readable.'), findsOneWidget); + expect(find.text('Reasoning'), findsOneWidget); + expect(find.text('shell'), findsOneWidget); + expect(find.text('Kept behind a native disclosure.'), findsNothing); + + // One shell bar only: the embedded list/thread adds no second one. + if (cupertino) { + expect(find.byType(CupertinoNavigationBar), findsOneWidget); + expect(find.byType(AppBar), findsNothing); + } else { + expect(find.byType(AppBar), findsOneWidget); + expect(find.byType(CupertinoNavigationBar), findsNothing); + } + + // A live frame updates the held thread. + channel.incoming.add( + jsonEncode({ + 'type': 'chat_event', + 'chat_event': { + 'session_id': 's1', + 'message_id': 'a1', + 'kind': 'text', + 'part': {'id': 'p2', 'type': 'text'}, + 'delta': 'A live line arrived.', + }, + }), + ); + await tester.pump(); + await tester.pump(); + expect(find.text('A live line arrived.'), findsOneWidget); + + await tester.tap(find.text(cupertino ? 'Back' : 'Back to chats')); + await tester.pump(); + expect(provider.value.uri.path, '/chat'); + expect(find.byType(ChatThreadView), findsNothing); + expect(find.byType(ChatSessionsScreen), findsOneWidget); + expect(find.text('Wire chat'), findsOneWidget); + + // Browser Forward re-opens the same session through its route. + await provider.didPushRouteInformation( + RouteInformation(uri: Uri.parse('/chat/s1')), + ); + await tester.pump(); + expect(provider.value.uri.path, '/chat/s1'); + await replySubscribe(tester, channel, index: 1); + await replyHistory( + tester, + channel, + index: 1, + text: 'Reopened from the route.', + ); + expect(find.text('Reopened from the route.'), findsOneWidget); + + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + }, + ); + } +} diff --git a/app/test/features/artifacts/domain/artifact_kind_test.dart b/app/test/features/artifacts/domain/artifact_kind_test.dart index a95ccfab..98ffb2eb 100644 --- a/app/test/features/artifacts/domain/artifact_kind_test.dart +++ b/app/test/features/artifacts/domain/artifact_kind_test.dart @@ -91,6 +91,7 @@ void main() { ('video/mp4', 'clip.mp4'), ('text/markdown', 'input.md'), ('text/plain', 'memory.txt'), + ('text/plain', 'run.log'), ('', 'output.md'), ]) { expect(isViewerArtifact(contentType, name), isTrue, reason: name); @@ -100,7 +101,6 @@ void main() { ('text/csv', 'rows.csv'), ('application/json', 'payload.json'), ('text/x-python', 'main.py'), - ('text/plain', 'run.log'), ('application/octet-stream', 'blob.bin'), ('', ''), ]) { diff --git a/app/test/features/artifacts/domain/artifact_preview_test.dart b/app/test/features/artifacts/domain/artifact_preview_test.dart new file mode 100644 index 00000000..10f62055 --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_preview_test.dart @@ -0,0 +1,99 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_preview.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart'; + +import 'artifact_fixtures.dart'; + +const _endpoint = 'ws://127.0.0.1:8081/connect'; + +ArtifactRecord _record(String name, {String? url, String contentType = ''}) => + ArtifactRecord.fromJson(artifact(name, url: url, contentType: contentType)); + +ArtifactPreviewPlan _plan( + ArtifactRecord artifact, { + String endpoint = _endpoint, +}) => planArtifactPreview(artifact: artifact, configuredEndpoint: endpoint); + +void main() { + test('an image on the configured origin is fetched locally', () { + final plan = _plan(_record('shot.png', contentType: 'image/png')); + expect(plan.kind, ArtifactPreviewKind.image); + expect(plan.canFetch, isTrue); + expect(plan.resolved?.url, 'http://127.0.0.1:8081/artifacts/1/1/shot.png'); + expect(plan.message, isEmpty); + }); + + test('text/plain and markdown are selectable text plans', () { + expect( + _plan(_record('build.log', contentType: 'text/plain')).kind, + ArtifactPreviewKind.text, + ); + expect( + _plan(_record('notes.txt', contentType: 'text/plain')).kind, + ArtifactPreviewKind.text, + ); + expect( + _plan(_record('notes.md', contentType: 'text/markdown')).kind, + ArtifactPreviewKind.markdown, + ); + expect( + _plan( + _record('notes.markdown', contentType: 'application/octet-stream'), + ).kind, + ArtifactPreviewKind.markdown, + ); + }); + + test('an external origin is marked and never fetchable', () { + final plan = _plan( + _record( + 'shot.png', + url: 'https://elsewhere.test/shot.png', + contentType: 'image/png', + ), + ); + expect(plan.kind, ArtifactPreviewKind.unavailable); + expect(plan.canFetch, isFalse); + expect(plan.message, artifactPreviewExternalUrl); + expect(plan.resolved?.url, 'https://elsewhere.test/shot.png'); + }); + + test('unsafe and absent urls are explicit and never fetchable', () { + final unsafe = _plan( + _record( + 'shot.png', + url: '//evil.test/shot.png', + contentType: 'image/png', + ), + ); + expect(unsafe.kind, ArtifactPreviewKind.unavailable); + expect(unsafe.canFetch, isFalse); + expect(unsafe.message, artifactPreviewUnsafeUrl); + + final absent = _plan( + ArtifactRecord.fromJson({ + 'name': 'shot.png', + 'url': '', + 'content_type': 'image/png', + 'size_bytes': 1, + }), + ); + expect(absent.kind, ArtifactPreviewKind.unavailable); + expect(absent.canFetch, isFalse); + expect(absent.message, artifactPreviewNoUrl); + }); + + test('unsupported types are explicit instead of a fake preview', () { + for (final record in [ + _record('result.csv', contentType: 'text/csv'), + _record('clip.mp4', contentType: 'video/mp4'), + _record('bundle.zip', contentType: 'application/zip'), + ]) { + final plan = _plan(record); + expect(plan.kind, ArtifactPreviewKind.unsupported); + expect(plan.canFetch, isFalse); + expect(plan.message, 'This file type cannot be previewed here.'); + expect(plan.resolved, isNotNull); + } + }); +} diff --git a/app/test/features/artifacts/domain/gallery_navigation_test.dart b/app/test/features/artifacts/domain/gallery_navigation_test.dart index af8b72ed..d642dba1 100644 --- a/app/test/features/artifacts/domain/gallery_navigation_test.dart +++ b/app/test/features/artifacts/domain/gallery_navigation_test.dart @@ -37,6 +37,7 @@ void main() { expect(pagedArtifacts(groups).map((page) => page.artifact.name), [ 'input.md', + 'run.log', 'shot.png', 'clip.mp4', 'memory.txt', @@ -161,7 +162,7 @@ void main() { artifacts: >[ artifact('session.html', contentType: 'text/html'), artifact('main.py', contentType: 'text/x-python'), - artifact('run.log', contentType: 'text/plain'), + artifact('result.csv', contentType: 'text/csv'), ], ), ]); diff --git a/app/test/features/artifacts/ui/artifact_gallery_page_test.dart b/app/test/features/artifacts/ui/artifact_gallery_page_test.dart new file mode 100644 index 00000000..c1a4fe72 --- /dev/null +++ b/app/test/features/artifacts/ui/artifact_gallery_page_test.dart @@ -0,0 +1,321 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_gallery_page.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_visit_list.dart'; + +import '../domain/artifact_fixtures.dart'; + +enum _Platform { material, cupertino } + +JsonMap _recorded( + String name, { + String url = '', + String contentType = 'text/csv', + int sizeBytes = 2048, +}) => artifact( + name, + url: url.isEmpty ? null : url, + contentType: contentType, + sizeBytes: sizeBytes, +); + +/// Two visits of `review` record the same filename; the second visit also +/// records `notes.md`. `build` records one file. +List _steps() => [ + step( + stage: 'build', + sequence: 1, + visit: 1, + artifacts: [_recorded('build.log', contentType: 'text/plain')], + ), + step( + stage: 'review', + sequence: 2, + visit: 1, + artifacts: [ + _recorded('result.csv'), + _recorded('notes.md', contentType: 'text/markdown'), + ], + ), + step( + stage: 'review', + sequence: 3, + visit: 2, + artifacts: [_recorded('result.csv', url: '/artifacts/1/2/result.csv')], + ), +]; + +Future _pumpGallery( + WidgetTester tester, + _Platform platform, + List steps, { + String configuredEndpoint = '', + bool executing = false, + Future Function(Uri)? openExternal, +}) async { + final page = ArtifactGalleryPage( + steps: steps, + executing: executing, + configuredEndpoint: configuredEndpoint, + openExternal: openExternal ?? (_) async => true, + ); + await tester.pumpWidget( + platform == _Platform.material + ? MaterialApp(home: page) + : CupertinoApp(home: page), + ); + await tester.pumpAndSettle(); +} + +Finder _inDialog(_Platform platform, String text) => find.descendant( + of: find.byType( + platform == _Platform.material ? AlertDialog : CupertinoAlertDialog, + ), + matching: find.text(text), +); + +void main() { + for (final platform in _Platform.values) { + testWidgets('${platform.name}: lists recorded groups and rows', ( + tester, + ) async { + await _pumpGallery(tester, platform, _steps()); + expect(find.text('Artifacts · 4 recorded'), findsOneWidget); + expect(find.text('build · visit 1'), findsOneWidget); + expect(find.text('review · visit 1'), findsOneWidget); + expect(find.text('review · visit 2'), findsOneWidget); + expect(find.text('result.csv'), findsNWidgets(2)); + expect(find.text('notes.md'), findsOneWidget); + expect(find.text('text/markdown · 2.0\u00a0KiB'), findsOneWidget); + }); + + testWidgets('${platform.name}: duplicate filename stays visit distinct', ( + tester, + ) async { + final steps = _steps(); + await _pumpGallery(tester, platform, steps); + await tester.tap(find.text('result.csv').at(1)); + await tester.pumpAndSettle(); + + final groups = artifactGroups(steps); + final visitTwo = groups.firstWhere( + (group) => group.stageKey == 'review' && group.visit == 2, + ); + final list = tester.widget( + find.byType(ArtifactVisitList), + ); + expect( + list.selectedIdentity, + artifactVisitIdentity(visitTwo, visitTwo.artifacts.single), + ); + expect(_inDialog(platform, 'review · visit 2'), findsOneWidget); + expect(_inDialog(platform, 'review · visit 1'), findsNothing); + expect(_inDialog(platform, 'Artifacts · 1 recorded'), findsOneWidget); + }); + } + + testWidgets('capture notes and partial label come from the visit step', ( + tester, + ) async { + await _pumpGallery(tester, _Platform.material, [ + step( + stage: 'review', + visit: 1, + artifacts: [_recorded('result.csv'), _recorded('notes.md')], + skipped: 2, + truncated: 3, + ), + ]); + expect( + find.text('Artifacts · 2 recorded · partial capture'), + findsOneWidget, + ); + await tester.tap(find.text('result.csv')); + await tester.pumpAndSettle(); + expect( + _inDialog(_Platform.material, 'Artifacts · 2 recorded · partial capture'), + findsOneWidget, + ); + expect( + _inDialog(_Platform.material, '2 files excluded from artifact capture.'), + findsOneWidget, + ); + expect( + _inDialog( + _Platform.material, + '3 files omitted by artifact capture limits.', + ), + findsOneWidget, + ); + }); + + testWidgets('an unavailable capture never claims nothing was recorded', ( + tester, + ) async { + await _pumpGallery(tester, _Platform.material, [ + step(stage: 'review', visit: 1, includeArtifacts: false), + ]); + expect(find.text('Artifacts · capture unavailable'), findsOneWidget); + expect(find.text('No artifacts recorded for this run.'), findsNothing); + }); + + testWidgets('a recorded empty capture says nothing was recorded', ( + tester, + ) async { + await _pumpGallery(tester, _Platform.material, [ + step(stage: 'review', visit: 1, artifacts: const []), + ]); + expect(find.text('No artifacts recorded for this run.'), findsOneWidget); + expect(find.byType(ArtifactVisitList), findsNothing); + }); + + testWidgets('a page with no steps says so explicitly', (tester) async { + await _pumpGallery(tester, _Platform.material, const []); + expect(find.text('No steps recorded for this run.'), findsOneWidget); + }); + + testWidgets('Open uses the resolved recorded url only', (tester) async { + final opened = []; + await _pumpGallery( + tester, + _Platform.material, + [ + step( + stage: 'review', + visit: 1, + artifacts: [ + _recorded('result.csv', url: '/artifacts/1/1/result.csv'), + ], + ), + ], + configuredEndpoint: 'ws://127.0.0.1:8081/connect', + openExternal: (uri) async { + opened.add(uri); + return true; + }, + ); + await tester.tap(find.text('result.csv')); + await tester.pumpAndSettle(); + await tester.tap(_inDialog(_Platform.material, 'Open')); + await tester.pumpAndSettle(); + + expect(opened, [ + Uri.parse('http://127.0.0.1:8081/artifacts/1/1/result.csv'), + ]); + expect(find.text('Link opened externally.'), findsOneWidget); + expect(find.byType(AlertDialog), findsNothing); + }); + + testWidgets('an unsafe recorded url offers no open or copy action', ( + tester, + ) async { + await _pumpGallery(tester, _Platform.material, [ + step( + stage: 'review', + visit: 1, + artifacts: [_recorded('result.csv', url: '//evil.test/result.csv')], + ), + ], configuredEndpoint: 'ws://127.0.0.1:8081/connect'); + await tester.tap(find.text('result.csv')); + await tester.pumpAndSettle(); + expect( + _inDialog( + _Platform.material, + 'The recorded artifact URL cannot be opened safely.', + ), + findsOneWidget, + ); + expect(_inDialog(_Platform.material, 'Open'), findsNothing); + expect(_inDialog(_Platform.material, 'Copy link'), findsNothing); + }); + + testWidgets('a record with no url is explicit and offers no action', ( + tester, + ) async { + await _pumpGallery(tester, _Platform.material, [ + step( + stage: 'review', + visit: 1, + artifacts: [ + { + 'name': 'result.csv', + 'url': '', + 'content_type': 'text/csv', + 'size_bytes': 10, + }, + ], + ), + ]); + await tester.tap(find.text('result.csv')); + await tester.pumpAndSettle(); + expect( + _inDialog(_Platform.material, 'No artifact URL recorded.'), + findsOneWidget, + ); + expect(_inDialog(_Platform.material, 'Open'), findsNothing); + }); + + testWidgets('Copy link copies the resolved url, separate from Open', ( + tester, + ) async { + final copied = []; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'Clipboard.setData') { + copied.add((call.arguments as Map)['text'] as String); + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + final opened = []; + await _pumpGallery( + tester, + _Platform.material, + [ + step( + stage: 'review', + visit: 1, + artifacts: [ + _recorded('result.csv', url: '/artifacts/1/1/result.csv'), + ], + ), + ], + configuredEndpoint: 'ws://127.0.0.1:8081/connect', + openExternal: (uri) async { + opened.add(uri); + return true; + }, + ); + await tester.tap(find.text('result.csv')); + await tester.pumpAndSettle(); + await tester.tap(_inDialog(_Platform.material, 'Copy link')); + await tester.pumpAndSettle(); + + expect(copied, ['http://127.0.0.1:8081/artifacts/1/1/result.csv']); + expect(opened, isEmpty); + expect(find.text('Link copied.'), findsOneWidget); + }); + + testWidgets('an executing run says capture pending', (tester) async { + await _pumpGallery(tester, _Platform.material, [ + step( + stage: 'review', + visit: 1, + includeArtifacts: false, + status: 'running', + ), + ], executing: true); + expect(find.text('Artifacts · capture pending'), findsOneWidget); + }); +} diff --git a/app/test/features/artifacts/ui/artifact_viewer_page_test.dart b/app/test/features/artifacts/ui/artifact_viewer_page_test.dart new file mode 100644 index 00000000..6dd7e450 --- /dev/null +++ b/app/test/features/artifacts/ui/artifact_viewer_page_test.dart @@ -0,0 +1,406 @@ +import 'dart:async'; +import 'dart:convert'; +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/domain/artifact_groups.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_external_open.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_gallery_page.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_fetch.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_page.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_visit_list.dart'; + +import '../domain/artifact_fixtures.dart'; +import 'artifact_visit_list_fixture.dart'; + +const _endpoint = 'ws://127.0.0.1:8081/connect'; + +/// A real 1x1 PNG so the image preview decodes instead of only holding bytes. +final Uint8List _png = base64Decode( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAE' + 'hQGAhKmMIQAAAABJRU5ErkJggg==', +); + +ArtifactGroup _group( + List artifacts, { + String stageKey = 'review', + int visit = 1, +}) => visitGroup(stageKey: stageKey, visit: visit, artifacts: artifacts); + +Future _pumpViewer( + WidgetTester tester, { + required List groups, + required String selected, + bool cupertino = false, + ArtifactFetch? fetch, + Widget Function(String)? markdownBuilder, + ArtifactExternalOpen? openExternal, +}) async { + final page = ArtifactViewerPage( + groups: groups, + selectedIdentity: selected, + configuredEndpoint: _endpoint, + fetch: fetch ?? (_) async => ArtifactFetchResult(status: 200, bytes: _png), + markdownBuilder: markdownBuilder ?? (value) => SelectableText(value), + openExternal: openExternal ?? (_) async => true, + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp(home: page) + : MaterialApp(home: Scaffold(body: page)), + ); + await tester.pumpAndSettle(); +} + +TextButton _textButton(WidgetTester tester, String label) { + return tester.widget( + find + .ancestor(of: find.text(label), matching: find.byType(TextButton)) + .first, + ); +} + +void main() { + testWidgets('an image is previewed in-app without opening a tab', ( + tester, + ) async { + final fetched = []; + final opened = []; + await tester.pumpWidget( + MaterialApp( + home: ArtifactGalleryPage( + steps: [ + step( + stage: 'review', + visit: 1, + artifacts: [ + artifact( + 'shot.png', + url: '/artifacts/1/1/shot.png', + contentType: 'image/png', + sizeBytes: 1024, + ), + ], + ), + ], + configuredEndpoint: _endpoint, + fetch: (uri) async { + fetched.add(uri); + return ArtifactFetchResult(status: 200, bytes: _png); + }, + openExternal: (uri) async { + opened.add(uri); + return true; + }, + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('shot.png')); + await tester.pumpAndSettle(); + + expect(find.byType(ArtifactViewerPage), findsOneWidget); + expect(fetched, [ + Uri.parse('http://127.0.0.1:8081/artifacts/1/1/shot.png'), + ]); + expect(find.byType(Image), findsOneWidget); + expect(find.text('1 of 1 · image/png'), findsOneWidget); + expect(find.text('image/png · 1.0\u00a0KiB'), findsOneWidget); + expect(opened, isEmpty); + expect(find.byType(AlertDialog), findsNothing); + }); + + testWidgets('text/plain is fetched and shown as selectable text', ( + tester, + ) async { + final text = recordedArtifact( + 'build.log', + url: '/artifacts/1/1/build.log', + contentType: 'text/plain; charset=utf-8', + ); + await _pumpViewer( + tester, + groups: [ + _group([text]), + ], + selected: artifactVisitIdentity(_group([text]), text), + fetch: (_) async => + ArtifactFetchResult(status: 200, bytes: utf8.encode('build ok\n')), + ); + + expect(find.byType(SelectableText), findsOneWidget); + expect(find.text('build ok\n'), findsOneWidget); + expect(find.text('text/plain · 0\u00a0B'), findsOneWidget); + }); + + testWidgets('markdown uses the injected builder and defaults to text', ( + tester, + ) async { + final markdown = recordedArtifact( + 'notes.md', + url: '/artifacts/1/1/notes.md', + contentType: 'text/markdown', + ); + final group = _group([markdown]); + final identity = artifactVisitIdentity(group, markdown); + await _pumpViewer( + tester, + groups: [group], + selected: identity, + fetch: (_) async => + ArtifactFetchResult(status: 200, bytes: utf8.encode('# Title')), + markdownBuilder: (value) => Text('MARKDOWN $value'), + ); + expect(find.text('MARKDOWN # Title'), findsOneWidget); + + await tester.pumpWidget(const SizedBox()); + await _pumpViewer( + tester, + groups: [group], + selected: identity, + fetch: (_) async => + ArtifactFetchResult(status: 200, bytes: utf8.encode('# Raw title')), + ); + expect(find.byType(SelectableText), findsOneWidget); + expect(find.text('# Raw title'), findsOneWidget); + }); + + testWidgets('an external origin is marked and never fetched', (tester) async { + final fetched = []; + final opened = []; + final image = recordedArtifact( + 'shot.png', + url: 'https://elsewhere.test/shot.png', + contentType: 'image/png', + ); + final group = _group([image]); + await _pumpViewer( + tester, + groups: [group], + selected: artifactVisitIdentity(group, image), + fetch: (uri) async { + fetched.add(uri); + return ArtifactFetchResult(status: 200, bytes: _png); + }, + openExternal: (uri) async { + opened.add(uri); + return true; + }, + ); + + expect( + find.text( + 'This artifact is hosted on another origin and is not previewed here.', + ), + findsOneWidget, + ); + expect(fetched, isEmpty); + expect(find.byType(Image), findsNothing); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + expect(opened, [Uri.parse('https://elsewhere.test/shot.png')]); + }); + + testWidgets('the gallery marks an external viewer artifact without fetching', ( + tester, + ) async { + final fetched = []; + await tester.pumpWidget( + MaterialApp( + home: ArtifactGalleryPage( + steps: [ + step( + stage: 'review', + visit: 1, + artifacts: [ + artifact( + 'shot.png', + url: 'https://elsewhere.test/shot.png', + contentType: 'image/png', + sizeBytes: 10, + ), + ], + ), + ], + configuredEndpoint: _endpoint, + fetch: (uri) async { + fetched.add(uri); + return ArtifactFetchResult(status: 200, bytes: _png); + }, + openExternal: (_) async => true, + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('shot.png')); + await tester.pumpAndSettle(); + + expect(find.byType(ArtifactViewerPage), findsOneWidget); + expect( + find.text( + 'This artifact is hosted on another origin and is not previewed here.', + ), + findsOneWidget, + ); + expect(fetched, isEmpty); + expect(find.byType(Image), findsNothing); + }); + + testWidgets('an unsupported type is explicit, with Open and Copy link', ( + tester, + ) async { + final video = recordedArtifact( + 'clip.mp4', + url: '/artifacts/1/1/clip.mp4', + contentType: 'video/mp4', + ); + final group = _group([video]); + var fetches = 0; + await _pumpViewer( + tester, + groups: [group], + selected: artifactVisitIdentity(group, video), + fetch: (_) async { + fetches += 1; + return ArtifactFetchResult(status: 200, bytes: _png); + }, + ); + + expect( + find.text('This file type cannot be previewed here.'), + findsOneWidget, + ); + expect(find.text('Open'), findsOneWidget); + expect(find.text('Copy link'), findsOneWidget); + expect(fetches, 0); + expect(find.byType(Image), findsNothing); + }); + + testWidgets('paging clamps at both ends and keeps the visit facts', ( + tester, + ) async { + final first = recordedArtifact( + 'a.png', + url: '/artifacts/1/1/a.png', + contentType: 'image/png', + ); + final second = recordedArtifact( + 'b.png', + url: '/artifacts/1/2/b.png', + contentType: 'image/png', + ); + final third = recordedArtifact( + 'c.png', + url: '/artifacts/1/3/c.png', + contentType: 'image/png', + ); + final groups = [ + _group([first], visit: 1), + _group([second], visit: 2), + _group([third], visit: 3), + ]; + await _pumpViewer( + tester, + groups: groups, + selected: artifactVisitIdentity(groups[0], first), + ); + + expect(find.text('1 of 3 · image/png'), findsOneWidget); + expect(_textButton(tester, 'Previous artifact').onPressed, isNull); + expect(_textButton(tester, 'Next artifact').onPressed, isNotNull); + + await tester.tap(find.text('Next artifact')); + await tester.pumpAndSettle(); + expect(find.text('2 of 3 · image/png'), findsOneWidget); + expect(find.text('review · visit 2'), findsOneWidget); + expect(_textButton(tester, 'Previous artifact').onPressed, isNotNull); + + await tester.tap(find.text('Next artifact')); + await tester.pumpAndSettle(); + expect(find.text('3 of 3 · image/png'), findsOneWidget); + expect(_textButton(tester, 'Next artifact').onPressed, isNull); + await tester.tap(find.text('Next artifact')); + await tester.pumpAndSettle(); + expect(find.text('3 of 3 · image/png'), findsOneWidget); + + await tester.tap(find.text('Previous artifact')); + await tester.pumpAndSettle(); + expect(find.text('2 of 3 · image/png'), findsOneWidget); + }); + + testWidgets('loading and HTTP failure are honest', (tester) async { + final text = recordedArtifact( + 'notes.txt', + url: '/artifacts/1/1/notes.txt', + contentType: 'text/plain', + ); + final group = _group([text]); + final pending = Completer(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ArtifactViewerPage( + groups: [group], + selectedIdentity: artifactVisitIdentity(group, text), + configuredEndpoint: _endpoint, + fetch: (_) => pending.future, + openExternal: (_) async => true, + ), + ), + ), + ); + await tester.pump(); + expect(find.text('Loading preview…'), findsOneWidget); + + pending.complete(ArtifactFetchResult(status: 404, bytes: Uint8List(0))); + await tester.pumpAndSettle(); + expect(find.text('The server answered 404.'), findsOneWidget); + expect(find.byType(SelectableText), findsNothing); + }); + + testWidgets('a network failure is reported instead of an empty preview', ( + tester, + ) async { + final text = recordedArtifact( + 'notes.txt', + url: '/artifacts/1/1/notes.txt', + contentType: 'text/plain', + ); + final group = _group([text]); + await _pumpViewer( + tester, + groups: [group], + selected: artifactVisitIdentity(group, text), + fetch: (_) async => throw const ArtifactFetchException('network down'), + ); + expect(find.textContaining('Could not load preview'), findsOneWidget); + expect(find.textContaining('network down'), findsOneWidget); + }); + + testWidgets('Cupertino draws the same text preview and controls', ( + tester, + ) async { + final text = recordedArtifact( + 'notes.txt', + url: '/artifacts/1/1/notes.txt', + contentType: 'text/plain', + ); + final group = _group([text]); + await _pumpViewer( + tester, + cupertino: true, + groups: [group], + selected: artifactVisitIdentity(group, text), + fetch: (_) async => ArtifactFetchResult( + status: 200, + bytes: utf8.encode('cupertino text'), + ), + ); + expect(find.text('cupertino text'), findsOneWidget); + expect(find.byType(CupertinoButton), findsWidgets); + }); +} diff --git a/app/test/features/attention/attention_dismissals_test.dart b/app/test/features/attention/attention_dismissals_test.dart new file mode 100644 index 00000000..3d2addd7 --- /dev/null +++ b/app/test/features/attention/attention_dismissals_test.dart @@ -0,0 +1,114 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/domain/attention_models.dart'; + +Map run([Map overrides = const {}]) => { + 'id': 1, + 'name': 'Plan and land', + 'title': null, + 'status': 'failed', + 'created_at': '2026-10-19T10:00:00Z', + 'finished_at': '2026-10-19T10:05:00Z', + 'diagnostic': '', + ...overrides, +}; + +void main() { + group('dismissal and clear-all snapshot', () { + test('a dismissed identity is filtered out and never returns', () { + final rows = [ + run({'id': 7, 'status': 'waiting', 'title': 'Wait'}), + ]; + final dismissed = attentionDismiss(const {}, '7:Decision'); + expect(attentionEntries(rows, dismissed: dismissed), isEmpty); + expect(attentionEntries(rows, dismissed: dismissed), isEmpty); + }); + + test('a different kind for the same run is a different identity', () { + final dismissed = attentionDismiss(const {}, '7:Decision'); + final failed = run({'id': 7, 'status': 'failed', 'diagnostic': 'later'}); + final entries = attentionEntries([failed], dismissed: dismissed); + expect(entries.single.key, '7:Failed'); + expect(entries.single.detail, 'later'); + }); + + test('dismiss ignores a blank key and adds once', () { + final one = attentionDismiss(const {}, '1:Failed'); + expect(one, {'1:Failed'}); + expect(attentionDismiss(one, '1:Failed'), {'1:Failed'}); + expect(attentionDismiss(one, ' '), {'1:Failed'}); + expect(one, {'1:Failed'}, reason: 'input set is not mutated'); + }); + + test('clear all applies only the identities in the open snapshot', () { + final a = attentionEntryFor(run({'id': 1}))!; + final snapshot = attentionDismissalSnapshot([a]); + final b = attentionEntryFor(run({'id': 2}))!; + final after = attentionDismissAll(const {}, snapshot); + expect(after, {'1:Failed'}); + expect(after.contains(b.key), isFalse); + expect( + attentionEntries([ + run({'id': 1}), + run({'id': 2}), + ], dismissed: after).map((entry) => entry.runId), + [2], + ); + }); + + test('the snapshot is a defensive copy', () { + final a = attentionEntryFor(run({'id': 1}))!; + final b = attentionEntryFor(run({'id': 2}))!; + final live = [a, b]; + final snapshot = attentionDismissalSnapshot(live); + live.add(attentionEntryFor(run({'id': 3}))!); + expect(snapshot.map((entry) => entry.runId), [1, 2]); + expect(snapshot, isNot(same(live))); + }); + }); + + group('persistence', () { + test('the key is the documented one', () { + expect(attentionStorageKey, 'pipelines.next.attention.v1'); + expect(attentionStorageKey, isNot('pipelines.web.attention.v1')); + }); + + test('encoding is one sorted JSON array and round-trips', () { + final encoded = encodeAttentionDismissals({ + '9:Failed', + '1:Decision', + '4:Failed', + }); + expect(encoded, '["1:Decision","4:Failed","9:Failed"]'); + expect(decodeAttentionDismissals(encoded), { + '1:Decision', + '4:Failed', + '9:Failed', + }); + expect(encodeAttentionDismissals(const {}), '[]'); + }); + + test('blank or unreadable storage decodes to empty and never throws', () { + for (final stored in [ + null, + '', + ' ', + 'not json', + '{', + '"a string"', + '{}', + '42', + ]) { + expect(decodeAttentionDismissals(stored), isEmpty); + } + }); + + test('a JSON array keeps only non-empty strings', () { + expect( + decodeAttentionDismissals( + '["1:Failed", 2, null, {"a":1}, "3:Decision", ""]', + ), + {'1:Failed', '3:Decision'}, + ); + }); + }); +} diff --git a/app/test/features/attention/attention_models_test.dart b/app/test/features/attention/attention_models_test.dart new file mode 100644 index 00000000..bc3ba0c8 --- /dev/null +++ b/app/test/features/attention/attention_models_test.dart @@ -0,0 +1,334 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/domain/attention_models.dart'; + +Map run([Map overrides = const {}]) => { + 'id': 1, + 'name': 'Plan and land', + 'title': null, + 'status': 'failed', + 'created_at': '2026-10-19T10:00:00Z', + 'finished_at': '2026-10-19T10:05:00Z', + 'diagnostic': '', + ...overrides, +}; + +void main() { + group('qualification', () { + test('only waiting and failed qualify; every other status asks nobody', () { + expect(attentionKindOf('waiting'), AttentionKind.decision); + expect(attentionKindOf('failed'), AttentionKind.failed); + for (final status in [ + 'queued', + 'running', + 'succeeded', + 'canceled', + 'cancelled', + 'interrupted', + 'active', + 'blocked', + 'skipped', + 'unknown', + '', + ' ', + null, + 'FAILED?', + ]) { + expect( + attentionKindOf(status), + isNull, + reason: 'status ${status ?? 'null'} must not qualify', + ); + } + }); + + test('trims and lowercases the server words', () { + expect(attentionKindOf(' Waiting '), AttentionKind.decision); + expect(attentionKindOf('Failed\n'), AttentionKind.failed); + expect(attentionKindOf('WAITING'), AttentionKind.decision); + }); + + test('ranks are Decision 0 then Failed 1', () { + expect(AttentionKind.decision.rank, 0); + expect(AttentionKind.failed.rank, 1); + }); + + test('waiting excludes audit/export handoffs, not resource waits', () { + expect( + attentionKindForRun(run({'status': 'waiting'})), + AttentionKind.decision, + ); + expect( + attentionKindForRun( + run({'status': 'waiting', 'export_pending_sequence': 4}), + ), + isNull, + ); + expect( + attentionKindForRun( + run({'status': 'waiting', 'export_pending_sequence': ' 2 '}), + ), + isNull, + ); + expect( + attentionKindForRun( + run({'status': 'waiting', 'export_pending_sequence': 0}), + ), + AttentionKind.decision, + ); + // web/src/attention.js and Attention.kt never consult resource_wait; the + // server retired it, so a stale value must not hide a real decision. + for (final stale in [ + {'resource': 'device-1'}, + 'device-1', + true, + 1, + ]) { + expect( + attentionKindForRun( + run({'status': 'waiting', 'resource_wait': stale}), + ), + AttentionKind.decision, + reason: 'resource_wait $stale must not suppress a decision', + ); + } + // A failed run stays failed even if a stale export field survived. + expect( + attentionKindForRun( + run({'status': 'failed', 'export_pending_sequence': 4}), + ), + AttentionKind.failed, + ); + }); + + test( + 'nonqualifying runs are dropped entirely, including malformed ids', + () { + final entries = attentionEntries([ + run({'id': 1, 'status': 'succeeded'}), + run({'id': 2, 'status': 'running'}), + run({'id': 3, 'status': 'failed'}), + run({'id': 4, 'status': 'queued'}), + run({'id': 'not-a-number', 'status': 'failed'}), + run({'id': 0, 'status': 'failed'}), + ]); + expect(entries.map((entry) => entry.runId), [3]); + expect(attentionEntries(null), isEmpty); + }, + ); + }); + + group('identity and wording', () { + test('identity is exactly {runId}:{kind}', () { + expect(attentionKey(440, AttentionKind.failed), '440:Failed'); + expect(attentionKey(12, AttentionKind.decision), '12:Decision'); + }); + + test('label is the trimmed title else the pipeline name', () { + expect(attentionEntryFor(run({'title': ' My run '}))!.label, 'My run'); + expect(attentionEntryFor(run({'title': ' '}))!.label, 'Plan and land'); + expect(attentionEntryFor(run({'title': null}))!.label, 'Plan and land'); + }); + + test( + 'detail is the decision line or the trimmed diagnostic else Run failed', + () { + expect( + attentionDetail(AttentionKind.decision, run({'status': 'waiting'})), + 'Waiting for your decision', + ); + expect( + attentionDetail( + AttentionKind.failed, + run({'diagnostic': ' boom '}), + ), + 'boom', + ); + expect( + attentionDetail(AttentionKind.failed, run({'diagnostic': ' '})), + 'Run failed', + ); + expect( + attentionDetail(AttentionKind.failed, run({'diagnostic': null})), + 'Run failed', + ); + }, + ); + + test('row description is exactly {pipeline} · {detail}', () { + final entry = attentionEntryFor( + run({'title': 'T', 'diagnostic': 'failed hard'}), + )!; + expect(attentionRowDescription(entry), 'Plan and land · failed hard'); + }); + + test('badge label is bare Notifications when empty, else the count', () { + expect(attentionBadgeLabel(0), 'Notifications'); + expect(attentionBadgeLabel(-3), 'Notifications'); + expect(attentionBadgeLabel(1), 'Notifications, 1 needing attention'); + expect(attentionBadgeLabel(171), 'Notifications, 171 needing attention'); + }); + + test('the entry keeps the whole summary, including unknown fields', () { + final source = run({ + 'unknown_future_field': {'keep': true}, + 'id': 7, + }); + final entry = attentionEntryFor(source)!; + expect(entry.run['unknown_future_field'], {'keep': true}); + expect(entry.run, same(source)); + }); + }); + + group('ordering', () { + test('kind rank, then recency descending, then run id descending', () { + final entries = attentionEntries([ + run({ + 'id': 10, + 'status': 'failed', + 'finished_at': '2026-10-19T10:00:00Z', + }), + run({ + 'id': 11, + 'status': 'waiting', + 'finished_at': '2026-10-19T09:00:00Z', + }), + run({ + 'id': 12, + 'status': 'failed', + 'finished_at': '2026-10-19T11:00:00Z', + }), + run({ + 'id': 13, + 'status': 'waiting', + 'finished_at': '2026-10-19T08:00:00Z', + }), + ]); + expect(entries.map((entry) => entry.runId), [11, 13, 12, 10]); + }); + + test('recency falls back to created_at when finished_at is blank', () { + final entries = attentionEntries([ + run({ + 'id': 1, + 'status': 'failed', + 'finished_at': '', + 'created_at': '2026-10-19T12:00:00Z', + }), + run({ + 'id': 2, + 'status': 'failed', + 'finished_at': '2026-10-19T11:00:00Z', + }), + ]); + expect(entries.map((entry) => entry.runId), [1, 2]); + }); + + test('equal kind and recency tie by run id descending and stay stable', () { + final rows = [ + run({'id': 3, 'finished_at': '2026-10-19T10:00:00Z'}), + run({'id': 9, 'finished_at': '2026-10-19T10:00:00Z'}), + run({'id': 5, 'finished_at': '2026-10-19T10:00:00Z'}), + ]; + expect(attentionEntries(rows).map((entry) => entry.runId), [9, 5, 3]); + expect(attentionEntries(rows.reversed).map((entry) => entry.runId), [ + 9, + 5, + 3, + ]); + }); + }); + + group('local-day window', () { + final since = DateTime.utc(2026, 10, 20); + final rows = [ + run({'id': 1, 'finished_at': '2026-10-19T21:33:27Z'}), + run({'id': 2, 'finished_at': '2026-10-20T10:00:00Z'}), + ]; + + test('startOfLocalDay is local midnight, injectable for tests', () { + final now = DateTime(2026, 10, 20, 15, 4, 5, 6); + final start = startOfLocalDay(now: now); + expect(start, DateTime(2026, 10, 20)); + expect(start.hour, 0); + expect(start.minute, 0); + expect(start.second, 0); + expect(start.millisecond, 0); + expect(start.isBefore(now), isTrue); + expect(start.toLocal(), start); + }); + + test('a cutoff drops older work and keeps newer work', () { + expect(attentionEntries(rows, since: since).map((entry) => entry.runId), [ + 2, + ]); + }); + + test('no cutoff, and an epoch-zero cutoff, show everything', () { + expect(attentionEntries(rows).map((entry) => entry.runId), [2, 1]); + expect( + attentionEntries( + rows, + since: DateTime.fromMillisecondsSinceEpoch(0), + ).map((entry) => entry.runId), + [2, 1], + ); + }); + + test('the cutoff applies to waiting decisions as well as failures', () { + expect( + attentionEntries([ + run({ + 'id': 3, + 'status': 'waiting', + 'finished_at': '2026-10-19T09:00:00Z', + }), + ], since: since), + isEmpty, + ); + }); + + test('unparseable or blank recency is kept, as in the browser', () { + for (final recency in ['', ' ', 'not a timestamp']) { + final kept = attentionEntries([ + run({'id': 4, 'finished_at': recency, 'created_at': recency}), + ], since: since); + expect( + kept.map((entry) => entry.runId), + [4], + reason: 'recency ${recency.isEmpty ? '' : recency} is kept', + ); + } + }); + + test('finished_at is the recency the cutoff reads, else created_at', () { + expect( + attentionEntries([ + run({ + 'id': 5, + 'created_at': '2026-10-18T09:00:00Z', + 'finished_at': '2026-10-20T09:00:00Z', + }), + ], since: since).map((entry) => entry.runId), + [5], + ); + expect( + attentionEntries([ + run({ + 'id': 6, + 'created_at': '2026-10-18T09:00:00Z', + 'finished_at': '', + }), + ], since: since), + isEmpty, + ); + }); + + test('dismissal and the cutoff compose', () { + final dismissed = attentionDismiss(const {}, '2:Failed'); + expect( + attentionEntries(rows, dismissed: dismissed, since: since), + isEmpty, + ); + }); + }); +} diff --git a/app/test/features/attention/attention_transitions_test.dart b/app/test/features/attention/attention_transitions_test.dart new file mode 100644 index 00000000..a63da11e --- /dev/null +++ b/app/test/features/attention/attention_transitions_test.dart @@ -0,0 +1,224 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/domain/attention_models.dart'; +import 'package:pipelines_app/features/attention/domain/attention_transitions.dart'; + +Map run([Map overrides = const {}]) => { + 'id': 1, + 'name': 'Plan and land', + 'title': null, + 'status': 'failed', + 'created_at': '2026-10-19T10:00:00Z', + 'finished_at': '2026-10-19T10:05:00Z', + 'diagnostic': '', + ...overrides, +}; + +void main() { + test('a seeded failed/waiting run raises nothing', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 1, 'status': 'failed'}), + run({'id': 2, 'status': 'waiting'}), + ]); + expect(detector.observe(run({'id': 1, 'status': 'failed'})), isNull); + expect(detector.observe(run({'id': 2, 'status': 'waiting'})), isNull); + expect(detector.emittedKeys, isEmpty); + }); + + test('a first-seen run raises nothing and becomes the baseline', () { + final detector = AttentionTransitionDetector(); + expect(detector.observe(run({'id': 5, 'status': 'failed'})), isNull); + expect(detector.statusOf(5), 'failed'); + expect(detector.observe(run({'id': 5, 'status': 'failed'})), isNull); + expect(detector.emittedKeys, isEmpty); + }); + + test('entering failed from a known running run emits exactly once', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 5, 'status': 'running'}), + ]); + final first = detector.observe(run({'id': 5, 'status': 'failed'})); + expect(first, isNotNull); + expect(first!.runId, 5); + expect(first.kind, AttentionKind.failed); + expect(first.key, '5:Failed'); + expect(first.entry.label, 'Plan and land'); + expect(first.entry.detail, 'Run failed'); + + expect(detector.observe(run({'id': 5, 'status': 'failed'})), isNull); + expect(detector.emittedKeys, {'5:Failed'}); + }); + + test('entering a human waiting state emits a Decision', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 6, 'status': 'running'}), + ]); + final transition = detector.observe( + run({'id': 6, 'status': 'waiting', 'title': ' Decide '}), + ); + expect(transition, isNotNull); + expect(transition!.kind, AttentionKind.decision); + expect(transition.key, '6:Decision'); + expect(transition.entry.label, 'Decide'); + expect(transition.entry.detail, 'Waiting for your decision'); + }); + + test('waiting to failed is a new kind and emits once', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 7, 'status': 'waiting'}), + ]); + final transition = detector.observe(run({'id': 7, 'status': 'failed'})); + expect(transition!.key, '7:Failed'); + expect(detector.emittedKeys, {'7:Failed'}); + }); + + test('a run that leaves the state and returns may emit again', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 8, 'status': 'running'}), + ]); + expect(detector.observe(run({'id': 8, 'status': 'failed'})), isNotNull); + expect(detector.observe(run({'id': 8, 'status': 'running'})), isNull); + expect(detector.emittedKeys, isEmpty); + final again = detector.observe(run({'id': 8, 'status': 'failed'})); + expect(again, isNotNull); + expect(detector.observe(run({'id': 8, 'status': 'failed'})), isNull); + }); + + test('nonqualifying statuses never emit', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 9, 'status': 'queued'}), + ]); + for (final status in [ + 'running', + 'succeeded', + 'canceled', + 'interrupted', + 'unknown', + ]) { + expect( + detector.observe(run({'id': 9, 'status': status})), + isNull, + reason: 'status $status must not emit', + ); + } + expect(detector.emittedKeys, isEmpty); + }); + + test( + 'an export wait never emits a Decision even though status is waiting', + () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 10, 'status': 'running'}), + ]); + expect( + detector.observe( + run({'id': 10, 'status': 'waiting', 'export_pending_sequence': 2}), + ), + isNull, + ); + expect(detector.emittedKeys, isEmpty); + }, + ); + + test('dismissed identities are marked seen but do not emit', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 11, 'status': 'running'}), + ]); + expect( + detector.observe( + run({'id': 11, 'status': 'failed'}), + dismissed: {'11:Failed'}, + ), + isNull, + ); + expect(detector.emittedKeys, {'11:Failed'}); + expect(detector.observe(run({'id': 11, 'status': 'failed'})), isNull); + }); + + test('a reconnect reseed produces no transition and no replay', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 12, 'status': 'failed'}), + ]); + detector.resetForReconnect(); + detector.reseed([ + run({'id': 12, 'status': 'failed'}), + ]); + expect(detector.observe(run({'id': 12, 'status': 'failed'})), isNull); + expect(detector.emittedKeys, isEmpty); + }); + + test('a reseed keeps still-qualifying keys and prunes the rest', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 20, 'status': 'running'}), + run({'id': 21, 'status': 'running'}), + ]); + expect(detector.observe(run({'id': 20, 'status': 'failed'})), isNotNull); + expect(detector.observe(run({'id': 21, 'status': 'waiting'})), isNotNull); + expect(detector.emittedKeys, {'20:Failed', '21:Decision'}); + + detector.reseed([ + run({'id': 20, 'status': 'failed'}), + run({'id': 21, 'status': 'succeeded'}), + ]); + // 20 still qualifies, so its key survives; 21 no longer asks, so its key is + // pruned and a genuine later transition can be raised once more. + expect(detector.emittedKeys, {'20:Failed'}); + expect(detector.observe(run({'id': 20, 'status': 'failed'})), isNull); + expect(detector.observe(run({'id': 21, 'status': 'waiting'})), isNotNull); + expect(detector.observe(run({'id': 21, 'status': 'waiting'})), isNull); + }); + + test('a reseed keeps the key of a run absent from the read', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 22, 'status': 'running'}), + ]); + expect(detector.observe(run({'id': 22, 'status': 'failed'})), isNotNull); + + detector.reseed([ + run({'id': 23, 'status': 'running'}), + ]); + expect(detector.emittedKeys, {'22:Failed'}); + // Absence says nothing, so seeing the same state again is not a transition. + expect(detector.observe(run({'id': 22, 'status': 'failed'})), isNull); + }); + + test('a snapshot bracketed as a seed does not emit or replay', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 13, 'status': 'running'}), + ]) + ..beginSeed(); + expect(detector.observe(run({'id': 13, 'status': 'waiting'})), isNull); + detector.endSeed(); + expect(detector.observe(run({'id': 13, 'status': 'waiting'})), isNull); + expect(detector.emittedKeys, isEmpty); + }); + + test('the transition keeps the whole frame, including unknown fields', () { + final detector = AttentionTransitionDetector() + ..seed([ + run({'id': 14, 'status': 'running'}), + ]); + final frame = run({ + 'id': 14, + 'run_id': 14, + 'status': 'failed', + 'diagnostic': ' boom ', + 'unknown_future_field': ['keep'], + }); + final transition = detector.observe(frame); + expect(transition!.entry.detail, 'boom'); + expect(transition.run, same(frame)); + expect(transition.run['unknown_future_field'], ['keep']); + }); +} diff --git a/app/test/features/chat/conversation/chat_row_keys_test.dart b/app/test/features/chat/conversation/chat_row_keys_test.dart new file mode 100644 index 00000000..b57e5b9e --- /dev/null +++ b/app/test/features/chat/conversation/chat_row_keys_test.dart @@ -0,0 +1,101 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_row_keys.dart'; +import 'package:pipelines_app/features/chat/domain/chat_transcript.dart'; + +import 'chat_thread_fixtures.dart'; + +JsonMap _assistant(String id) => chatMessage( + id, + 'assistant', + parts: [ + {'type': 'reasoning', 'id': 'r-$id', 'text': 'reasoning $id'}, + {'type': 'text', 'id': 't-$id', 'text': 'answer $id'}, + ], +); + +JsonMap _user(String id) => chatMessage( + id, + 'user', + parts: [ + {'type': 'text', 'text': 'question $id'}, + ], +); + +void main() { + test('an older page prepended into a folded turn keeps its key', () { + final keys = ChatRowKeys(); + final newest = keys.forRows( + transcriptRows([_assistant('msg_6'), _assistant('msg_4')]), + ); + final paged = keys.forRows( + transcriptRows([ + _assistant('msg_2'), + _assistant('msg_0'), + _assistant('msg_6'), + _assistant('msg_4'), + ]), + ); + + expect(newest, hasLength(1)); + expect(paged, hasLength(1)); + expect(paged.single, newest.single); + }); + + test('a live assistant message appended to a folded turn keeps its key', () { + final keys = ChatRowKeys(); + final newest = keys.forRows(transcriptRows([_assistant('msg_6')])); + final streamed = keys.forRows( + transcriptRows([_assistant('msg_6'), _assistant('msg_live')]), + ); + + expect(streamed.single, newest.single); + }); + + test('user rows keep their key and folded turns stay distinct', () { + final keys = ChatRowKeys(); + final first = keys.forRows( + transcriptRows([ + _user('u1'), + _assistant('a1'), + _user('u2'), + _assistant('a2'), + ]), + ); + final paged = keys.forRows( + transcriptRows([ + _user('u0'), + _assistant('a0'), + _user('u1'), + _assistant('a1'), + _user('u2'), + _assistant('a2'), + ]), + ); + + expect(first.toSet(), hasLength(4)); + expect(paged.toSet(), hasLength(6)); + expect(paged.sublist(2), first); + }); + + test('an id-less prepended turn never collides with a held key', () { + final keys = ChatRowKeys(); + keys.forRows(transcriptRows([_assistant('a1')])); + final paged = keys.forRows( + transcriptRows([ + // No id: only a positional fallback is possible. + chatMessage( + '', + 'assistant', + parts: [ + {'type': 'text', 'text': 'anonymous older answer'}, + ], + ), + _user('u1'), + _assistant('a1'), + ]), + ); + + expect(paged.toSet(), hasLength(paged.length)); + }); +} diff --git a/app/test/features/chat/conversation/chat_thread_view_test.dart b/app/test/features/chat/conversation/chat_thread_view_test.dart new file mode 100644 index 00000000..54cdb555 --- /dev/null +++ b/app/test/features/chat/conversation/chat_thread_view_test.dart @@ -0,0 +1,368 @@ +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_thread_view.dart'; + +import 'chat_thread_fixtures.dart'; + +Widget host(Widget child) => MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + home: Scaffold(body: child), +); + +Widget cupertinoHost(Widget child) => CupertinoApp( + theme: const CupertinoThemeData(brightness: Brightness.dark), + home: CupertinoPageScaffold(child: child), +); + +void main() { + testWidgets('live-subscription refusal is separate from readable history', ( + tester, + ) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.subscribe = () async => throw StateError('live watch refused'); + gateway.history = (_) async => chatPage([ + chatMessage( + 'u1', + 'user', + parts: [ + {'type': 'text', 'text': 'History still renders.'}, + ], + ), + ]); + + await tester.pumpWidget( + host(ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {})), + ); + await tester.pumpAndSettle(); + + expect(find.text('History still renders.'), findsOneWidget); + expect(find.byKey(const Key('chat-live-error')), findsOneWidget); + expect(find.textContaining('Live updates unavailable'), findsOneWidget); + expect(find.textContaining('live watch refused'), findsOneWidget); + expect(find.byKey(const Key('chat-history-error')), findsNothing); + + // A later resync that attaches clears only the live notice. + gateway.subscribe = () async => const {}; + gateway.history = (_) async => chatPage([ + chatMessage( + 'u1', + 'user', + parts: [ + {'type': 'text', 'text': 'History still renders.'}, + ], + ), + ]); + var attempts = 0; + for ( + var i = 0; + i < 80 && find.byKey(const Key('chat-live-error')).evaluate().isNotEmpty; + i++ + ) { + if (attempts == 0) { + await tester.tap(find.text('Retry').last); + attempts++; + } + await tester.pump(const Duration(milliseconds: 5)); + } + expect(find.byKey(const Key('chat-live-error')), findsNothing); + }); + + testWidgets('Load older passes the server cursor back and shows older text', ( + tester, + ) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => chatPage( + [ + chatMessage( + 'a2', + 'assistant', + parts: [ + {'type': 'text', 'text': 'Newest reply.'}, + ], + ), + ], + cursor: 'opaque/next?x=1', + hasMore: true, + ); + + await tester.pumpWidget( + host(ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {})), + ); + await tester.pumpAndSettle(); + + expect(find.text('Newest reply.'), findsOneWidget); + expect(find.text('Load older'), findsOneWidget); + + final older = Completer(); + gateway.history = (_) => older.future; + await tester.tap(find.text('Load older')); + await tester.pump(); + + expect(gateway.calls.last.fields['chat_query'], { + 'session_id': 's', + 'limit': 200, + 'cursor': 'opaque/next?x=1', + }); + older.complete( + chatPage( + [ + chatMessage( + 'a1', + 'assistant', + parts: [ + {'type': 'text', 'text': 'Older stored reply.'}, + ], + ), + ], + cursor: '', + hasMore: false, + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Older stored reply.'), findsOneWidget); + expect(find.text('Newest reply.'), findsOneWidget); + expect(find.text('Load older'), findsNothing); + }); + + // Paging prepends messages, so an unkeyed transcript would reuse the element + // at a message's old index: the operator's open reasoning would move to the + // previous answer, or be dropped when `Load older` disappears. + for (final cupertino in [false, true]) { + testWidgets( + 'an open reasoning block stays on its answer while has_more remains ' + '($cupertino)', + (tester) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + var reads = 0; + gateway.history = (_) async => ++reads == 1 + ? pagedChatPage( + 'a2', + 'NEWEST reasoning body that belongs to the newest answer.', + cursor: 'opaque/older', + hasMore: true, + ) + : pagedChatPage( + 'a1', + 'OLDER reasoning body that must not steal the newest disclosure.', + cursor: 'opaque/older-2', + hasMore: true, + ); + + await tester.pumpWidget( + (cupertino ? cupertinoHost : host)( + ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Reasoning')); + await tester.pumpAndSettle(); + expect( + find.text('NEWEST reasoning body that belongs to the newest answer.'), + findsOneWidget, + ); + + await tester.tap(find.text('Load older')); + await tester.pumpAndSettle(); + + // Both answers are present; only the one the operator opened is open. + expect(find.text('Reasoning'), findsNWidgets(2)); + expect(find.text('Load older'), findsOneWidget); + expect( + find.text('NEWEST reasoning body that belongs to the newest answer.'), + findsOneWidget, + ); + expect( + find.text( + 'OLDER reasoning body that must not steal the newest disclosure.', + ), + findsNothing, + ); + }, + ); + + testWidgets( + 'an open reasoning block survives the removal of Load older ($cupertino)', + (tester) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + var reads = 0; + gateway.history = (_) async => ++reads == 1 + ? pagedChatPage( + 'a2', + 'NEWEST reasoning body that belongs to the newest answer.', + cursor: 'opaque/older', + hasMore: true, + ) + : pagedChatPage( + 'a1', + 'OLDER reasoning body that must not steal the newest disclosure.', + cursor: '', + hasMore: false, + ); + + await tester.pumpWidget( + (cupertino ? cupertinoHost : host)( + ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Reasoning')); + await tester.pumpAndSettle(); + expect( + find.text('NEWEST reasoning body that belongs to the newest answer.'), + findsOneWidget, + ); + + await tester.tap(find.text('Load older')); + await tester.pumpAndSettle(); + + expect(find.text('Reasoning'), findsNWidgets(2)); + expect(find.text('Load older'), findsNothing); + expect( + find.text('NEWEST reasoning body that belongs to the newest answer.'), + findsOneWidget, + ); + expect( + find.text( + 'OLDER reasoning body that must not steal the newest disclosure.', + ), + findsNothing, + ); + }, + ); + } + + // The repository's own paged-history fixture pages consecutive assistant + // messages, so an older page can prepend into the one folded turn. Its first + // message id changes; the row must still be the same element and keep the + // operator's open disclosure. + for (final cupertino in [false, true]) { + for (final keepsControl in [true, false]) { + testWidgets( + 'an open reasoning block in a folded assistant turn survives paging ' + '(keeps Load older: $keepsControl, $cupertino)', + (tester) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + var reads = 0; + gateway.history = (_) async => ++reads == 1 + ? assistantFoldPage( + const ['msg_6', 'msg_4'], + const [ + 'NEWEST folded reasoning body.', + 'FOURTH folded reasoning body.', + ], + cursor: 'opaque/fold', + hasMore: true, + ) + : assistantFoldPage( + const ['msg_2', 'msg_0'], + const [ + 'SECOND folded reasoning body.', + 'OLDEST folded reasoning body.', + ], + cursor: keepsControl ? 'opaque/fold-2' : '', + hasMore: keepsControl, + ); + + await tester.pumpWidget( + (cupertino ? cupertinoHost : host)( + ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), + ), + ); + await tester.pumpAndSettle(); + + // Before paging the turn holds two messages, so two disclosures. + expect(find.text('Reasoning'), findsNWidgets(2)); + await tester.tap(find.text('Reasoning').first); + await tester.pumpAndSettle(); + expect(find.text('NEWEST folded reasoning body.'), findsOneWidget); + + await tester.tap(find.text('Load older')); + await tester.pumpAndSettle(); + + // All four assistant messages now fold into the same turn. The + // newest block stays open; no older block may open. + expect(find.text('Reasoning'), findsNWidgets(4)); + expect(find.text('NEWEST folded reasoning body.'), findsOneWidget); + expect(find.text('FOURTH folded reasoning body.'), findsNothing); + expect(find.text('SECOND folded reasoning body.'), findsNothing); + expect(find.text('OLDEST folded reasoning body.'), findsNothing); + expect( + find.text('Load older'), + keepsControl ? findsOneWidget : findsNothing, + ); + }, + ); + } + } +} + +/// The paged-history fixture shape: a page of consecutive assistant messages, +/// each with its own reasoning and text part. +JsonMap assistantFoldPage( + List ids, + List reasoning, { + required String cursor, + required bool hasMore, +}) => chatPage( + [ + for (var index = 0; index < ids.length; index++) + chatMessage( + ids[index], + 'assistant', + parts: [ + { + 'type': 'reasoning', + 'id': 'r-${ids[index]}', + 'text': reasoning[index], + }, + { + 'type': 'text', + 'id': 't-${ids[index]}', + 'text': 'Answer stored as ${ids[index]}.', + }, + ], + ), + ], + cursor: cursor, + hasMore: hasMore, +); + +/// A newest page with one user prompt and one answer carrying [reasoning]. +JsonMap pagedChatPage( + String answerId, + String reasoning, { + required String cursor, + required bool hasMore, +}) => chatPage( + [ + chatMessage( + 'u-$answerId', + 'user', + parts: [ + {'type': 'text', 'text': 'A question for $answerId.'}, + ], + ), + chatMessage( + answerId, + 'assistant', + parts: [ + {'type': 'reasoning', 'text': reasoning}, + {'type': 'text', 'text': 'The answer stored as $answerId.'}, + ], + ), + ], + cursor: cursor, + hasMore: hasMore, +); diff --git a/app/test/features/graph/domain/stage_definition_test.dart b/app/test/features/graph/domain/stage_definition_test.dart new file mode 100644 index 00000000..e4b11dd8 --- /dev/null +++ b/app/test/features/graph/domain/stage_definition_test.dart @@ -0,0 +1,159 @@ +import 'package:flutter_test/flutter_test.dart'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/graph/domain/stage_definition.dart'; + +import 'graph_fixtures.dart'; + +JsonMap _stage() => { + 'key': 'build', + 'prompt': 'Implement the planned change.', + 'output': 'A committed change.', + 'edges': { + 'success': 'audit', + 'approved': '#', + 'error': '#failure', + }, + 'fallback_error': true, + 'configs': { + 'provider': 'openai', + 'model': 'gpt-5', + 'budget_usd': 12.5, + 'retries': 2, + 'harness': 'codex', + 'timeout': '15m', + 'skipped_blank': ' ', + 'skipped_null': null, + }, + 'blocks': {'tools': 'shell\nread_file'}, + 'limits': { + 'max_visits': 3, + 'on': ['success', 'error'], + }, + 'memory': {'context': 'latest', 'notes': 'keep'}, + 'notify': { + 'on': ['failure'], + 'destination': 'ops@example.test', + 'artifacts': ['run.log'], + }, + 'custom_flag': true, +}; + +void main() { + group('stage fields', () { + test('follow the web pane order, labels and blank-field rules', () { + final fields = stageDefinitionFields(_stage()); + + expect(fields.map((field) => field.label), [ + 'Type', + 'Prompt', + 'Output', + 'Outcomes', + 'Budget (USD)', + 'Harness', + 'Model', + 'Provider', + 'Retries', + 'Timeout', + 'Tools', + 'Max visits', + 'Limit on', + 'Memory', + 'Notify on', + 'Notify destination', + 'Notify artifacts', + ]); + expect(fields.first.value, 'model'); + expect(fields[1].block, isTrue); + expect(fields[2].value, 'A committed change.'); + expect( + fields[3].value, + 'success → audit\n' + 'approved → SUCCESS (terminal)\n' + 'error → FAILURE (terminal)', + ); + expect(fields[4].value, '12.5'); + expect(fields[5].value, 'codex'); + expect(fields[10].value, 'shell\nread_file'); + expect(fields[11].value, '3'); + expect(fields[12].value, 'success, error'); + expect(fields[13].value, 'context: latest\nnotes: keep'); + expect(fields[14].value, 'failure'); + expect(fields[15].value, 'ops@example.test'); + expect(fields[16].value, 'run.log'); + }); + + test('a blank or absent type reads model; an authored type is kept', () { + expect(effectiveStageType(null), 'model'); + expect(effectiveStageType(' '), 'model'); + expect(effectiveStageType('shell'), 'shell'); + expect( + stageDefinitionFields({'key': 'a'}).single.value, + 'model', + ); + }); + + test('config keys outside the known labels are shown verbatim', () { + final fields = stageDefinitionFields({ + 'key': 'a', + 'configs': {'temperature': 0}, + }); + + expect(fields.map((field) => field.label), contains('temperature')); + expect( + fields.firstWhere((field) => field.label == 'temperature').value, + '0', + ); + }); + + test('zero visits and missing limits emit no invented rows', () { + final fields = stageDefinitionFields({ + 'key': 'a', + 'limits': {'max_visits': 0, 'on': []}, + }); + + expect(fields.map((field) => field.label), ['Type']); + }); + + test( + 'the stage lookup preserves unknown keys and the last declaration', + () { + final graph = { + 'stages': [ + {'key': 'build', 'type': 'old'}, + _stage(), + ], + }; + final stage = stageDefinitionFor(graph, 'build'); + + expect(stage?['type'], isNull); + expect(effectiveStageType(stage?['type']), 'model'); + expect(stage?['custom_flag'], isTrue); + expect(stageDefinitionFor(graph, 'ghost'), isNull); + }, + ); + }); + + group('terminal fields', () { + test('list incoming definition routes, including the fallback marker', () { + expect(terminalDefinitionFields(linearGraph(), '#failure'), hasLength(1)); + final fields = terminalDefinitionFields(linearGraph(), '#failure'); + expect( + fields.single.value, + 'plan · error* → FAILURE\nship · error → FAILURE', + ); + expect(fields.single.block, isTrue); + expect( + terminalDefinitionFields(linearGraph(), '#success').single.value, + 'ship · success → SUCCESS', + ); + }); + + test('a terminal with no routes has no fields to invent', () { + expect( + terminalDefinitionFields({}, '#success'), + isEmpty, + ); + }); + }); +} diff --git a/app/test/features/graph/widgets/stage_definition_view_test.dart b/app/test/features/graph/widgets/stage_definition_view_test.dart new file mode 100644 index 00000000..d226e467 --- /dev/null +++ b/app/test/features/graph/widgets/stage_definition_view_test.dart @@ -0,0 +1,286 @@ +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/domain/stage_definition.dart'; +import 'package:pipelines_app/features/graph/widgets/stage_definition_view.dart'; + +JsonMap _graph() => { + 'stages': [ + { + 'key': 'plan', + 'type': 'model', + 'prompt': 'Plan the change.', + 'edges': {'success': 'build', 'error': '#'}, + 'fallback_error': true, + 'configs': {'provider': 'openai', 'model': 'gpt-5'}, + 'limits': { + 'max_visits': 2, + 'on': ['error'], + }, + 'future_field': {'kept': true}, + }, + { + 'key': 'build', + 'type': 'shell', + 'edges': {'success': '#success', 'error': '#failure'}, + }, + ], +}; + +Widget _material(Widget child) => MaterialApp( + home: Scaffold( + appBar: AppBar(title: const Text('plan definition')), + body: child, + ), +); + +Widget _cupertino(Widget child, {bool dark = false}) => CupertinoApp( + theme: CupertinoThemeData( + brightness: dark ? Brightness.dark : Brightness.light, + ), + home: CupertinoPageScaffold(child: child), +); + +StageDefinitionView _view({String key = 'plan'}) => StageDefinitionView( + graph: _graph(), + stageKey: key, + pipelineId: 41, + pipelineName: 'Demo pipeline', + version: 7, +); + +/// Finds visible text, including SelectableText's editable body. +Finder _text(String value) => find.byWidgetPredicate( + (widget) => + (widget is Text && widget.data == value) || + (widget is SelectableText && widget.data == value), +); + +void main() { + testWidgets('a declared stage shows pinned identity and web field values', ( + tester, + ) async { + await tester.pumpWidget(_material(_view())); + + expect(_text('Demo pipeline · v7'), findsOneWidget); + expect(_text('model'), findsOneWidget); + expect(_text('Plan the change.'), findsOneWidget); + expect( + _text('success → build\nerror → FAILURE (terminal)'), + findsOneWidget, + ); + expect(_text('Provider'), findsOneWidget); + expect(_text('openai'), findsOneWidget); + expect(_text('Model'), findsOneWidget); + expect(_text('gpt-5'), findsOneWidget); + expect(_text('Max visits'), findsOneWidget); + expect(_text('2'), findsOneWidget); + expect(_text('Limit on'), findsOneWidget); + expect(_text('error'), findsOneWidget); + }); + + testWidgets('the raw section keeps unknown fields exact and selectable', ( + tester, + ) async { + await tester.pumpWidget(_material(_view())); + + expect(_text(rawStageDefinitionTitle), findsOneWidget); + final raw = tester + .widgetList(find.byType(SelectableText)) + .map((widget) => widget.data ?? '') + .join('\n'); + expect(raw, contains('"future_field": {')); + expect(raw, contains('"kept": true')); + expect(raw, contains('"fallback_error": true')); + expect(tester.takeException(), isNull); + }); + + testWidgets('unknown stages get an explicit missing state, never defaults', ( + tester, + ) async { + await tester.pumpWidget(_material(_view(key: 'ghost'))); + + expect(_text(unknownStageDefinition), findsOneWidget); + expect(_text('model'), findsNothing); + expect(_text(rawStageDefinitionTitle), findsNothing); + expect(find.byType(SelectableText), findsNothing); + }); + + testWidgets('terminals explain definition targets and incoming routes', ( + tester, + ) async { + await tester.pumpWidget(_material(_view(key: '#failure'))); + + expect(_text(terminalDefinitionNote), findsOneWidget); + expect(_text('Incoming routes'), findsOneWidget); + expect( + _text('plan · error* → FAILURE\nbuild · error → FAILURE'), + findsOneWidget, + ); + expect(_text(rawStageDefinitionTitle), findsNothing); + expect(_text('successful'), findsNothing); + }); + + testWidgets('Cupertino uses its theme roles in dark mode', (tester) async { + late Color secondary; + await tester.pumpWidget( + _cupertino( + Builder( + builder: (context) { + secondary = CupertinoColors.secondaryLabel.resolveFrom(context); + return _view(); + }, + ), + dark: true, + ), + ); + + final identity = tester.widget(_text('Demo pipeline · v7')); + expect(identity.style?.color, secondary); + expect(_text('Plan the change.'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('the Material helper opens one bar and Back closes it', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () => openStageDefinition( + context, + graph: _graph(), + stageKey: 'plan', + pipelineId: 41, + pipelineName: 'Demo pipeline', + version: 7, + ), + child: const Text('Open definition'), + ), + ), + ), + ), + ); + + await tester.tap(find.text('Open definition')); + await tester.pumpAndSettle(); + + expect(_text('plan definition'), findsOneWidget); + expect(find.byType(AppBar), findsOneWidget); + expect(find.byType(BackButton), findsOneWidget); + final route = ModalRoute.of( + tester.element(find.byType(StageDefinitionView)), + ); + expect(route?.settings.name, 'stage-definition/41/7/plan'); + + await tester.pageBack(); + await tester.pumpAndSettle(); + expect(_text('Open definition'), findsOneWidget); + expect(find.byType(StageDefinitionView), findsNothing); + }); + + testWidgets('the Cupertino helper opens one native bar and Back closes it', ( + tester, + ) async { + await tester.pumpWidget( + CupertinoApp( + home: Builder( + builder: (context) => CupertinoPageScaffold( + child: CupertinoButton( + onPressed: () => openStageDefinition( + context, + graph: _graph(), + stageKey: '#success', + pipelineId: 41, + pipelineName: 'Demo pipeline', + version: 7, + ), + child: const Text('Open terminal'), + ), + ), + ), + ), + ); + + await tester.tap(find.text('Open terminal')); + await tester.pumpAndSettle(); + + expect(_text('Success definition'), findsOneWidget); + expect(_text('#success definition'), findsNothing); + expect(find.byType(CupertinoNavigationBar), findsOneWidget); + expect(find.byType(CupertinoNavigationBarBackButton), findsOneWidget); + expect(_text('Incoming routes'), findsOneWidget); + + await tester.tap(find.byType(CupertinoNavigationBarBackButton)); + await tester.pumpAndSettle(); + expect(_text('Open terminal'), findsOneWidget); + expect(find.byType(StageDefinitionView), findsNothing); + }); + + testWidgets('the Material helper titles a terminal with its display label', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () => openStageDefinition( + context, + graph: _graph(), + stageKey: '#failure', + pipelineId: 41, + pipelineName: 'Demo pipeline', + version: 7, + ), + child: const Text('Open failure'), + ), + ), + ), + ), + ); + + await tester.tap(find.text('Open failure')); + await tester.pumpAndSettle(); + + expect(_text('Failure definition'), findsOneWidget); + expect(_text('#failure definition'), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets('selectable blocks force the host strut for one line rhythm', ( + tester, + ) async { + await tester.pumpWidget(_cupertino(_view())); + + final selectable = tester + .widgetList(find.byType(SelectableText)) + .toList(); + expect(selectable.length, greaterThanOrEqualTo(2)); + for (final widget in selectable) { + final strut = widget.strutStyle; + expect(strut, isNotNull); + // The host's own metrics, forced: a fallback glyph cannot widen a block. + expect(strut!.forceStrutHeight, isTrue); + expect(strut.fontFamily, widget.style?.fontFamily); + expect(strut.fontSize, widget.style?.fontSize); + } + final outcomes = selectable.firstWhere( + (widget) => (widget.data ?? '').contains('success → build'), + ); + final raw = selectable.firstWhere( + (widget) => (widget.data ?? '').startsWith('{'), + ); + expect(outcomes.strutStyle, raw.strutStyle); + }); + + test('field labels are the web words', () { + expect(stageConfigLabel('budget_usd'), 'Budget (USD)'); + expect(stageConfigLabel('budget_tokens'), 'Budget (tokens)'); + expect(stageConfigLabel('custom'), 'custom'); + }); +} diff --git a/app/test/features/runs/actions/retry_action_test.dart b/app/test/features/runs/actions/retry_action_test.dart index ca11fa8b..c8a2eed6 100644 --- a/app/test/features/runs/actions/retry_action_test.dart +++ b/app/test/features/runs/actions/retry_action_test.dart @@ -40,6 +40,22 @@ void main() { ); }); + test('the full entropy width still forms a bounded request key', () { + // The web build once rejected every retry because `1 << 32` is 0 there; + // the generator now uses a literal 2^32 bound. This pins the largest + // entropy value it may consume. + final key = newRetryRequestKey( + 7, + now: DateTime.utc(2026, 1, 1), + random: 0xFFFFFFFF, + ); + expect( + key, + 'app-retry-7-${DateTime.utc(2026, 1, 1).microsecondsSinceEpoch}-1z141z3', + ); + expect(key.length, lessThanOrEqualTo(128)); + }); + testWidgets( 'material retry asks first, Keep sends nothing, then omits retry_mode', (tester) async { diff --git a/app/test/features/runs/actions/retry_intent_web_test.dart b/app/test/features/runs/actions/retry_intent_web_test.dart new file mode 100644 index 00000000..e0e64c34 --- /dev/null +++ b/app/test/features/runs/actions/retry_intent_web_test.dart @@ -0,0 +1,25 @@ +@TestOn('browser') +library; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/runs/actions/retry_intent.dart'; + +void main() { + test('a fresh key uses the full entropy bound under dart2js', () { + // `1 << 32` compiles to 0 on the web, so Random.nextInt threw a RangeError + // and no retry request was ever sent. Generating without an injected + // random value exercises the real bound; a VM test cannot catch this + // class of bug, so this file runs only in a browser: + // + // flutter test --platform chrome \ + // test/features/runs/actions/retry_intent_web_test.dart + final keys = {}; + for (var index = 0; index < 32; index++) { + final key = newRetryRequestKey(7); + expect(key, startsWith('app-retry-7-')); + expect(key.length, lessThanOrEqualTo(128)); + keys.add(key); + } + expect(keys, hasLength(32)); + }); +} diff --git a/app/test/features/runs/ui/run_artifacts_action_test.dart b/app/test/features/runs/ui/run_artifacts_action_test.dart new file mode 100644 index 00000000..1a654187 --- /dev/null +++ b/app/test/features/runs/ui/run_artifacts_action_test.dart @@ -0,0 +1,161 @@ +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/ui/artifact_gallery_action.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_view.dart'; +import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; + +import '../../artifacts/domain/artifact_fixtures.dart'; + +enum _Platform { material, cupertino } + +class _FakeGateway implements ApiGateway { + _FakeGateway(this.detail); + final JsonMap detail; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type != 'get_run') throw UnsupportedError(type); + return Future.value({'run_detail': detail}); + } +} + +JsonMap _run({required List steps}) => { + 'id': 21, + 'title': 'Artifacts wiring run', + 'name': 'gallery', + 'status': 'succeeded', + 'steps': steps, +}; + +Future _pumpDetail( + WidgetTester tester, + _Platform platform, + RunsController controller, + ApiGateway gateway, +) async { + tester.view.physicalSize = const Size(500, 1200); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final view = RunDetailView( + controller: controller, + gateway: gateway, + onBack: () {}, + ); + await tester.pumpWidget( + platform == _Platform.material + ? MaterialApp(home: Scaffold(body: view)) + : CupertinoApp( + builder: (context, app) => Theme( + data: ThemeData(platform: TargetPlatform.iOS), + child: app!, + ), + home: CupertinoPageScaffold(child: view), + ), + ); + await tester.pumpAndSettle(); +} + +Future _loaded(ApiGateway gateway) async { + final controller = RunsController(RunsRepository(gateway)); + await controller.select(21); + return controller; +} + +void main() { + for (final platform in _Platform.values) { + testWidgets('${platform.name}: the action opens the recorded groups', ( + tester, + ) async { + final gateway = _FakeGateway( + _run( + steps: [ + step( + stage: 'implementer', + sequence: 1, + artifacts: [ + artifact( + 'build.log', + contentType: 'text/plain', + sizeBytes: 2337, + ), + ], + ), + step( + stage: 'reviewer', + sequence: 2, + artifacts: [ + artifact( + 'shot.png', + contentType: 'image/png', + sizeBytes: 80544, + ), + ], + ), + ], + ), + ); + final controller = await _loaded(gateway); + addTearDown(controller.dispose); + await _pumpDetail(tester, platform, controller, gateway); + + expect(find.byKey(runArtifactsButtonKey), findsOneWidget); + await tester.tap(find.byKey(runArtifactsButtonKey)); + await tester.pumpAndSettle(); + + expect(find.text('Artifacts · 2 recorded'), findsOneWidget); + expect(find.text('build.log'), findsOneWidget); + expect(find.text('shot.png'), findsOneWidget); + expect(find.text('implementer · visit 1'), findsOneWidget); + expect(find.text('reviewer · visit 1'), findsOneWidget); + }); + } + + testWidgets('the action is offered only when the detail has steps', ( + tester, + ) async { + final gateway = _FakeGateway(_run(steps: const [])); + final controller = await _loaded(gateway); + addTearDown(controller.dispose); + await _pumpDetail(tester, _Platform.material, controller, gateway); + expect(find.byKey(runArtifactsButtonKey), findsNothing); + }); + + testWidgets('a recorded empty capture keeps its explicit wording', ( + tester, + ) async { + final gateway = _FakeGateway( + _run( + steps: [step(stage: 'reviewer', visit: 1, artifacts: const [])], + ), + ); + final controller = await _loaded(gateway); + addTearDown(controller.dispose); + await _pumpDetail(tester, _Platform.material, controller, gateway); + + await tester.tap(find.byKey(runArtifactsButtonKey)); + await tester.pumpAndSettle(); + expect(find.text('No artifacts recorded for this run.'), findsOneWidget); + }); + + testWidgets('an unavailable capture is never reported as empty', ( + tester, + ) async { + final gateway = _FakeGateway( + _run(steps: [step(stage: 'reviewer', visit: 1, includeArtifacts: false)]), + ); + final controller = await _loaded(gateway); + addTearDown(controller.dispose); + await _pumpDetail(tester, _Platform.material, controller, gateway); + + await tester.tap(find.byKey(runArtifactsButtonKey)); + await tester.pumpAndSettle(); + expect(find.text('Artifacts · capture unavailable'), findsOneWidget); + expect(find.text('No artifacts recorded for this run.'), findsNothing); + }); +} diff --git a/app/test/features/runs/ui/run_retry_guard_test.dart b/app/test/features/runs/ui/run_retry_guard_test.dart new file mode 100644 index 00000000..c0c0cc33 --- /dev/null +++ b/app/test/features/runs/ui/run_retry_guard_test.dart @@ -0,0 +1,114 @@ +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; +import 'package:pipelines_app/features/runs/actions/title_wording.dart'; + +import 'run_retry_wiring_support.dart'; + +void main() { + testWidgets('a reply without an id never opens a guessed run', ( + tester, + ) async { + final gateway = RetryWiringGateway(); + addTearDown(gateway.framesController.close); + final opened = []; + await mountRetryScreen( + tester, + gateway, + cupertino: false, + onRunSelected: opened.add, + ); + + await confirmRetry(tester); + gateway.retries.last.complete({ + 'run_detail': {'title': 'Unknown run', 'status': 'running'}, + }); + await tester.pumpAndSettle(); + + expect(opened, isEmpty); + expect(find.text(retryFailedTitle), findsOneWidget); + expect(find.text('Unknown run'), findsNothing); + expect(gateway.calls.where((call) => call.type == 'get_run'), hasLength(1)); + }); + + testWidgets('a refused retry stays on the failed run', (tester) async { + final gateway = RetryWiringGateway(); + addTearDown(gateway.framesController.close); + final opened = []; + await mountRetryScreen( + tester, + gateway, + cupertino: false, + onRunSelected: opened.add, + ); + + await confirmRetry(tester); + gateway.refuseRetry(const ProtocolError('the run is still executing')); + await tester.pumpAndSettle(); + + expect(find.text('the run is still executing'), findsOneWidget); + expect(opened, isEmpty); + expect(find.text(retryFailedTitle), findsOneWidget); + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(find.byKey(retryActionKey), findsOneWidget); + }); + + testWidgets('a retry reply that lands after leaving is ignored', ( + tester, + ) async { + final gateway = RetryWiringGateway(); + addTearDown(gateway.framesController.close); + final opened = []; + await mountRetryScreen( + tester, + gateway, + cupertino: false, + onRunSelected: opened.add, + ); + + await confirmRetry(tester); + expect(gateway.retryCalls, hasLength(1)); + await tester.pumpWidget(const SizedBox.shrink()); + gateway.acceptRetry(retryCreatedDetail()); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(opened, isEmpty); + expect(gateway.calls.where((call) => call.type == 'get_run'), hasLength(1)); + }); + + testWidgets('a reply naming the source run opens nothing', (tester) async { + final gateway = RetryWiringGateway(); + addTearDown(gateway.framesController.close); + final opened = []; + await mountRetryScreen( + tester, + gateway, + cupertino: false, + onRunSelected: opened.add, + ); + + await confirmRetry(tester); + gateway.acceptRetry(retryCreatedDetail(id: 7)); + await tester.pumpAndSettle(); + + // The accepted detail still folds, but its id is the source run, so there + // is no new run to open and no second read. + expect(opened, isEmpty); + expect(find.text(retryCreatedTitle), findsOneWidget); + expect(gateway.calls.where((call) => call.type == 'get_run'), hasLength(1)); + }); + + testWidgets('a failed run that is still executing exposes no retry', ( + tester, + ) async { + final gateway = RetryWiringGateway(executing: true); + addTearDown(gateway.framesController.close); + await mountRetryScreen(tester, gateway, cupertino: false); + + expect(find.byKey(runTitleActionKey), findsOneWidget); + expect(find.byKey(retryActionKey), findsNothing); + }); +} diff --git a/app/test/features/runs/ui/run_retry_layout_test.dart b/app/test/features/runs/ui/run_retry_layout_test.dart new file mode 100644 index 00000000..d4ee08a2 --- /dev/null +++ b/app/test/features/runs/ui/run_retry_layout_test.dart @@ -0,0 +1,151 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/runs/actions/cancel_wording.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; +import 'package:pipelines_app/features/runs/actions/title_wording.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_actions.dart'; + +import 'run_retry_wiring_support.dart'; + +void main() { + testWidgets('a hidden retry adds no extra gap for Rename and Cancel', ( + tester, + ) async { + final gateway = RetryWiringGateway(); + addTearDown(gateway.framesController.close); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Padding( + padding: const EdgeInsets.all(16), + child: RunDetailActions( + run: retryCreatedDetail(id: 7), + gateway: gateway, + onRunChanged: (_) {}, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // Retry is not eligible on the running run and must not consume spacing. + expect(find.byKey(retryActionKey), findsNothing); + final rename = tester.getRect(find.byKey(runTitleActionKey)); + final cancel = tester.getRect(find.byKey(cancelActionKey)); + expect(cancel.left - rename.right, closeTo(8, 0.5)); + }); + + for (final cupertino in [false, true]) { + testWidgets('adjacent actions keep native spacing at 320 px ($cupertino)', ( + tester, + ) async { + tester.view.physicalSize = const Size(320, 480); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + final gateway = RetryWiringGateway(); + addTearDown(gateway.framesController.close); + final row = Padding( + padding: const EdgeInsets.all(16), + child: RunDetailActions( + run: retryFailedDetail(), + gateway: gateway, + onRunChanged: (_) {}, + ), + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp( + home: CupertinoPageScaffold(child: SafeArea(child: row)), + ) + : MaterialApp(home: Scaffold(body: row)), + ); + await tester.pumpAndSettle(); + + expectNativeActionSpacing(tester); + }); + } + + for (final cupertino in [false, true]) { + testWidgets('320 px at 2x keeps Rename and Retry reachable ($cupertino)', ( + tester, + ) async { + tester.view.physicalSize = const Size(320, 480); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + final gateway = RetryWiringGateway(); + addTearDown(gateway.framesController.close); + Widget scale(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: const TextScaler.linear(2)), + child: app!, + ); + // The action row itself, in the detail's 16 px inset, so the narrow + // accessibility state is measured without unrelated header controls. + final row = Padding( + padding: const EdgeInsets.all(16), + child: RunDetailActions( + run: retryFailedDetail(), + gateway: gateway, + onRunChanged: (_) {}, + ), + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp( + builder: scale, + home: CupertinoPageScaffold(child: SafeArea(child: row)), + ) + : MaterialApp( + builder: scale, + home: Scaffold(body: row), + ), + ); + await tester.pumpAndSettle(); + + expect(find.byKey(runTitleActionKey).hitTestable(), findsOneWidget); + expect(find.byKey(retryActionKey).hitTestable(), findsOneWidget); + final rect = tester.getRect(find.byKey(retryActionKey)); + expect(rect.left, greaterThanOrEqualTo(0)); + expect(rect.right, lessThanOrEqualTo(320)); + expectNativeActionSpacing(tester); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + expect(find.text(retryDialogTitle(7)), findsOneWidget); + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(gateway.retryCalls, isEmpty); + }); + } +} + +/// Asserts the action row uses the detail's native 8 dp / 4 dp spacing. +/// +/// The row previously had no `spacing`, leaving the outlined Rename border +/// touching the filled Retry button; browser measurement at 320 px reported a +/// 0.008 px gap. A hidden action must not consume spacing either. +void expectNativeActionSpacing(WidgetTester tester) { + final rename = tester.getRect(find.byKey(runTitleActionKey)); + final retry = tester.getRect(find.byKey(retryActionKey)); + final sameRow = retry.top < rename.bottom && rename.top < retry.bottom; + if (sameRow) { + expect( + retry.left - rename.right, + greaterThanOrEqualTo(8 - 0.01), + reason: 'side-by-side actions need the 8 dp Wrap spacing', + ); + } else { + expect( + retry.top - rename.bottom, + greaterThanOrEqualTo(4 - 0.01), + reason: 'wrapped actions need the 4 dp Wrap run spacing', + ); + } +} diff --git a/app/test/features/runs/ui/run_retry_wiring_support.dart b/app/test/features/runs/ui/run_retry_wiring_support.dart new file mode 100644 index 00000000..d590e617 --- /dev/null +++ b/app/test/features/runs/ui/run_retry_wiring_support.dart @@ -0,0 +1,113 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; +import 'package:pipelines_app/features/runs/screen.dart'; + +const retryFailedTitle = 'Fixture failed run'; +const retryCreatedTitle = 'Retry of fixture'; + +JsonMap retryFailedDetail({bool executing = false}) => { + 'id': 7, + 'title': retryFailedTitle, + 'name': 'fixture', + 'status': 'failed', + 'executing': executing, + 'input': {'prompt': 'the stored prompt'}, + 'steps': const [], +}; + +JsonMap retryCreatedDetail({num id = 8}) => { + 'id': id, + 'title': retryCreatedTitle, + 'name': 'fixture', + 'status': 'running', + 'executing': true, + 'retry_of': 7, + 'input': {'prompt': 'the stored prompt'}, + 'steps': const [], +}; + +JsonMap _summary(JsonMap run) => { + 'id': run['id'], + 'title': run['title'], + 'name': run['name'], + 'status': run['status'], + 'executing': run['executing'] ?? false, +}; + +/// Serves the same envelopes as the app server and holds each retry reply until +/// the test releases it, so nothing can be applied optimistically. +class RetryWiringGateway implements ApiGateway { + RetryWiringGateway({bool executing = false}) { + details[7] = retryFailedDetail(executing: executing); + } + + final framesController = StreamController.broadcast(); + final calls = <({String type, JsonMap fields})>[]; + final retries = >[]; + final details = {}; + + @override + Stream get frames => framesController.stream; + + @override + Future call(String type, [JsonMap fields = const {}]) { + calls.add((type: type, fields: Map.from(fields))); + switch (type) { + case 'list_runs': + return Future.value({ + 'runs': [for (final run in details.values) _summary(run)], + }); + case 'get_run': + final id = fields['run_id'] as num; + return Future.value({'run_detail': details[id] ?? retryFailedDetail()}); + case 'retry_run': + final reply = Completer(); + retries.add(reply); + return reply.future; + } + return Future.error(UnsupportedError(type)); + } + + Iterable<({String type, JsonMap fields})> get retryCalls => + calls.where((call) => call.type == 'retry_run'); + + void acceptRetry(JsonMap detail) { + details[detail['id'] as num] = detail; + retries.last.complete({'run_detail': detail}); + } + + void refuseRetry(Object error) => retries.last.completeError(error); +} + +Future mountRetryScreen( + WidgetTester tester, + RetryWiringGateway gateway, { + required bool cupertino, + ValueChanged? onRunSelected, +}) async { + final screen = RunsScreen( + gateway: gateway, + initialRunId: 7, + onRunSelected: onRunSelected, + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp( + home: CupertinoPageScaffold(child: SafeArea(child: screen)), + ) + : MaterialApp(home: Scaffold(body: screen)), + ); + await tester.pumpAndSettle(); +} + +Future confirmRetry(WidgetTester tester) async { + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pump(); +} diff --git a/app/test/features/runs/ui/run_retry_wiring_test.dart b/app/test/features/runs/ui/run_retry_wiring_test.dart new file mode 100644 index 00000000..7a45fd1c --- /dev/null +++ b/app/test/features/runs/ui/run_retry_wiring_test.dart @@ -0,0 +1,102 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/runs/actions/cancel_wording.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; +import 'package:pipelines_app/features/runs/actions/title_wording.dart'; + +import 'run_retry_wiring_support.dart'; + +void main() { + for (final cupertino in [false, true]) { + testWidgets( + 'accepted retry reply opens the server-identified run ($cupertino)', + (tester) async { + final gateway = RetryWiringGateway(); + addTearDown(gateway.framesController.close); + final opened = []; + await mountRetryScreen( + tester, + gateway, + cupertino: cupertino, + onRunSelected: opened.add, + ); + + expect(find.text(retryFailedTitle), findsOneWidget); + expect(find.byKey(runTitleActionKey), findsOneWidget); + expect(find.byKey(retryActionKey), findsOneWidget); + expect(find.byKey(cancelActionKey), findsNothing); + expect(gateway.retryCalls, isEmpty); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + expect(find.text(retryDialogTitle(7)), findsOneWidget); + expect(find.text(retryDialogMessage), findsOneWidget); + expect(gateway.retryCalls, isEmpty); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(gateway.retryCalls, isEmpty); + expect(opened, isEmpty); + expect(find.byKey(retryActionKey), findsOneWidget); + + await confirmRetry(tester); + expect(gateway.retryCalls, hasLength(1)); + final fields = gateway.retryCalls.single.fields; + expect(fields.keys.toSet(), {'run_id', 'request_key'}); + expect(fields['run_id'], 7); + expect(fields['request_key'], startsWith('app-retry-7-')); + expect( + (fields['request_key'] as String).length, + lessThanOrEqualTo(128), + ); + // The prompt closes only from server truth; no navigation is guessed. + expect(opened, isEmpty); + expect(find.text(retryFailedTitle), findsOneWidget); + + gateway.acceptRetry(retryCreatedDetail()); + await tester.pumpAndSettle(); + + expect(opened, [8]); + expect(find.text(retryCreatedTitle), findsOneWidget); + expect(find.text(retryFailedTitle), findsNothing); + expect(find.byKey(retryActionKey), findsNothing); + expect( + gateway.calls.where((call) => call.type == 'get_run').last.fields, + {'run_id': 8}, + ); + }, + ); + } + + testWidgets('restart sends its explicit mode through the real detail row', ( + tester, + ) async { + final gateway = RetryWiringGateway(); + addTearDown(gateway.framesController.close); + final opened = []; + await mountRetryScreen( + tester, + gateway, + cupertino: false, + onRunSelected: opened.add, + ); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + expect(find.text(restartDialogTitle(7)), findsOneWidget); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pump(); + + final fields = gateway.retryCalls.single.fields; + expect(fields.keys.toSet(), {'run_id', 'request_key', 'retry_mode'}); + expect(fields['run_id'], 7); + expect(fields['retry_mode'], 'restart'); + expect(fields['request_key'], startsWith('app-retry-7-')); + + gateway.acceptRetry(retryCreatedDetail()); + await tester.pumpAndSettle(); + expect(opened, [8]); + expect(find.text(retryCreatedTitle), findsOneWidget); + }); +} diff --git a/app/test/features/templates/ui/template_gallery_create_test.dart b/app/test/features/templates/ui/template_gallery_create_test.dart new file mode 100644 index 00000000..3308d4fb --- /dev/null +++ b/app/test/features/templates/ui/template_gallery_create_test.dart @@ -0,0 +1,104 @@ +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/templates/screen.dart'; +import 'package:pipelines_app/features/templates/ui/template_create_wording.dart'; + +import '../data/template_test_support.dart' show source; +import 'template_gallery_test_support.dart'; + +Future openRelease(WidgetTester tester) async { + await tester.tap(find.byKey(templateRowKey('release'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(templateCreateActionKey)); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets( + 'Cancel sends nothing; Create validates and submits the verbatim source ' + 'once through the existing prompt', + (tester) async { + final gateway = GalleryGateway((type, fields) async { + if (type == 'list_templates') return templatesReply(galleryTemplates); + return acceptedCreate(type, fields); + }); + final created = []; + await pumpGallery(tester, gateway, onCreated: created.add); + await openRelease(tester); + + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text('Create from Release workflow'), findsOneWidget); + await tester.enterText(find.byKey(templateCreateNameKey), 'Café'); + await tester.pump(); + await tester.tap(find.byKey(templateCreateCancelKey)); + await tester.pumpAndSettle(); + + expect(find.byType(AlertDialog), findsNothing); + expect(gateway.callsOf('validate'), isEmpty); + expect(gateway.callsOf('submit'), isEmpty); + expect(created, isEmpty); + + await tester.tap(find.byKey(templateCreateActionKey)); + await tester.pumpAndSettle(); + expect(find.byKey(templateCreateNameKey), findsOneWidget); + await tester.enterText(find.byKey(templateCreateNameKey), ' Café '); + await tester.pump(); + await tester.tap(find.byKey(templateCreateConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.callsOf('validate').single.fields, {'source': source}); + expect(gateway.callsOf('submit').single.fields, { + 'name': 'Café', + 'source': source, + 'create_only': true, + }); + expect(gateway.callsOf('submit').single.fields.keys, [ + 'name', + 'source', + 'create_only', + ]); + expect(created, [ + {'id': 7, 'name': 'Created release'}, + ]); + expect( + find.text('Created "Created release". It is in the Pipelines list.'), + findsOneWidget, + ); + expect(find.text('Close'), findsOneWidget); + + await tester.tap(find.byKey(templateCreateCancelKey)); + await tester.pumpAndSettle(); + expect(find.byKey(templateDetailKey), findsOneWidget); + expect(created, hasLength(1)); + expect(gateway.callsOf('submit'), hasLength(1)); + }, + ); + + testWidgets('the callback is optional and Cupertino uses its native prompt', ( + tester, + ) async { + final gateway = GalleryGateway((type, fields) async { + if (type == 'list_templates') return templatesReply(galleryTemplates); + return acceptedCreate(type, fields); + }); + await pumpGallery(tester, gateway, cupertino: true); + await openRelease(tester); + + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.byType(AlertDialog), findsNothing); + await tester.enterText(find.byKey(templateCreateNameKey), 'Cupertino'); + await tester.pump(); + await tester.tap(find.byKey(templateCreateConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.callsOf('validate'), hasLength(1)); + expect(gateway.callsOf('submit'), hasLength(1)); + expect( + find.text('Created "Created release". It is in the Pipelines list.'), + findsOneWidget, + ); + expect(find.byKey(templateCreateCancelKey), findsOneWidget); + }); +} diff --git a/app/test/features/templates/ui/template_gallery_screen_test.dart b/app/test/features/templates/ui/template_gallery_screen_test.dart new file mode 100644 index 00000000..ca4d93dc --- /dev/null +++ b/app/test/features/templates/ui/template_gallery_screen_test.dart @@ -0,0 +1,379 @@ +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/templates/screen.dart'; +import 'package:pipelines_app/features/templates/ui/template_detail.dart'; + +import '../data/template_test_support.dart' show source; +import 'template_gallery_test_support.dart'; + +void main() { + testWidgets('loading shows the exact line, then the server catalogue', ( + tester, + ) async { + final reply = Completer(); + final gateway = GalleryGateway((type, fields) => reply.future); + + await pumpGallery(tester, gateway, settle: false); + await tester.pump(); + + expect(find.byKey(templatesLoadingKey), findsOneWidget); + expect(find.text('Loading templates…'), findsOneWidget); + expect(gateway.calls.single.type, 'list_templates'); + expect(gateway.calls.single.fields, isEmpty); + + reply.complete(templatesReply(galleryTemplates)); + await tester.pumpAndSettle(); + + expect(find.byKey(templatesGalleryKey), findsOneWidget); + expect(find.text('Release workflow'), findsOneWidget); + expect(find.text('Ship a version'), findsOneWidget); + expect(find.text('(unnamed template)'), findsOneWidget); + expect(find.byKey(templatesLoadingKey), findsNothing); + }); + + testWidgets('an empty catalogue states it without inventing rows', ( + tester, + ) async { + final gateway = GalleryGateway( + (type, fields) async => templatesReply(const []), + ); + + await pumpGallery(tester, gateway); + + expect(find.byKey(templatesEmptyKey), findsOneWidget); + expect( + find.text('No templates are available on this server.'), + findsOneWidget, + ); + expect(find.byKey(templatesGalleryKey), findsNothing); + }); + + testWidgets('a refusal offers Retry; a failed refresh keeps the rows', ( + tester, + ) async { + var mode = 'refuse'; + final gateway = GalleryGateway((type, fields) async { + if (type != 'list_templates') throw StateError('unexpected $type'); + if (mode == 'refuse') { + throw Exception('catalogue unavailable'); + } + return templatesReply(galleryTemplates); + }); + + await pumpGallery(tester, gateway); + + expect(find.byKey(templatesErrorKey), findsOneWidget); + expect(find.text('catalogue unavailable'), findsOneWidget); + expect(find.byKey(templatesGalleryKey), findsNothing); + + mode = 'ok'; + await tester.tap(find.byKey(templatesRetryKey)); + await tester.pumpAndSettle(); + expect(find.byKey(templatesGalleryKey), findsOneWidget); + expect(find.text('Release workflow'), findsOneWidget); + + mode = 'refuse'; + await tester.tap(find.byKey(templatesRefreshKey)); + await tester.pumpAndSettle(); + expect(find.byKey(templatesGalleryKey), findsOneWidget); + expect(find.text('Release workflow'), findsOneWidget); + expect(find.text('catalogue unavailable'), findsOneWidget); + expect(find.byKey(templatesErrorBannerKey), findsOneWidget); + expect(find.byKey(templatesErrorKey), findsNothing); + + mode = 'ok'; + await tester.tap(find.byKey(templatesBannerRetryKey)); + await tester.pumpAndSettle(); + expect(find.text('catalogue unavailable'), findsNothing); + expect(find.byKey(templatesErrorBannerKey), findsNothing); + expect(find.text('Release workflow'), findsOneWidget); + }); + + testWidgets('refresh re-reads the catalogue and keeps the selection', ( + tester, + ) async { + var calls = 0; + final gateway = GalleryGateway((type, fields) async { + calls++; + return templatesReply( + calls == 1 + ? galleryTemplates + : [ + ...galleryTemplates, + templateJson(key: 'new', name: 'New template'), + ], + ); + }); + + await pumpGallery(tester, gateway); + await tester.tap(find.byKey(templateRowKey('release'))); + await tester.pumpAndSettle(); + expect(find.byKey(templateDetailKey), findsOneWidget); + + await tester.tap(find.byKey(templatesRefreshKey)); + await tester.pumpAndSettle(); + + expect(find.byKey(templateDetailKey), findsOneWidget); + expect(find.text('Release workflow'), findsOneWidget); + expect(gateway.callsOf('list_templates'), hasLength(2)); + + await tester.tap(find.byKey(templatesBackKey)); + await tester.pumpAndSettle(); + expect(find.text('New template'), findsOneWidget); + }); + + testWidgets('selecting a template shows metadata and verbatim source only', ( + tester, + ) async { + final gateway = GalleryGateway( + (type, fields) async => templatesReply(galleryTemplates), + ); + + await pumpGallery(tester, gateway); + expect(gateway.callsOf('list_templates'), hasLength(1)); + + await tester.tap(find.byKey(templateRowKey('release'))); + await tester.pumpAndSettle(); + + expect(find.byKey(templateDetailKey), findsOneWidget); + expect(find.text('Release workflow'), findsOneWidget); + expect(find.text('Ship a version'), findsOneWidget); + expect(find.text('Key'), findsOneWidget); + expect(find.text('Includes a schedule'), findsOneWidget); + expect(find.text(templateSourceLabel), findsOneWidget); + expect(selectableSource(source), findsOneWidget); + expect(selectableSource('release'), findsOneWidget); + expect(find.text(templateCreateActionLabel), findsOneWidget); + expect(gateway.callsOf('validate'), isEmpty); + expect(gateway.callsOf('submit'), isEmpty); + + await tester.tap(find.byKey(templatesBackKey)); + await tester.pumpAndSettle(); + expect(find.byKey(templatesGalleryKey), findsOneWidget); + expect(find.byKey(templateDetailKey), findsNothing); + }); + + testWidgets('native back returns to the gallery', (tester) async { + final gateway = GalleryGateway( + (type, fields) async => templatesReply(galleryTemplates), + ); + await pumpGallery(tester, gateway); + await tester.tap(find.byKey(templateRowKey('blank'))); + await tester.pumpAndSettle(); + expect(find.byKey(templateDetailKey), findsOneWidget); + expect(selectableSource('blank'), findsOneWidget); + + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + + expect(find.byKey(templatesGalleryKey), findsOneWidget); + expect(find.byKey(templateDetailKey), findsNothing); + }); + + testWidgets('embedded use drops the app bar and keeps native detail back', ( + tester, + ) async { + final gateway = GalleryGateway( + (type, fields) async => templatesReply(galleryTemplates), + ); + await pumpGallery(tester, gateway, embedded: true); + + expect(find.byType(AppBar), findsNothing); + expect(find.byKey(templatesRefreshKey), findsOneWidget); + await tester.tap(find.byKey(templateRowKey('release'))); + await tester.pumpAndSettle(); + expect(find.byKey(templateDetailKey), findsOneWidget); + + await tester.tap(find.byKey(templateDetailBackKey)); + await tester.pumpAndSettle(); + expect(find.byKey(templatesGalleryKey), findsOneWidget); + }); + + testWidgets('Cupertino host uses its own list, back and detail controls', ( + tester, + ) async { + final gateway = GalleryGateway( + (type, fields) async => templatesReply(galleryTemplates), + ); + await pumpGallery(tester, gateway, cupertino: true); + + expect(find.byType(CupertinoListTile), findsNWidgets(2)); + expect(find.byType(Scaffold), findsNothing); + await tester.tap(find.byKey(templateRowKey('release'))); + await tester.pumpAndSettle(); + + expect(find.byKey(templateDetailKey), findsOneWidget); + expect(selectableSource(source), findsOneWidget); + expect( + tester + .widget(find.byKey(templateCreateActionKey)) + .onPressed, + isNotNull, + ); + expect(find.byType(BackButton), findsNothing); + + await tester.tap(find.byKey(templatesBackKey)); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoListTile), findsNWidgets(2)); + }); + + testWidgets( + 'a failed refresh with a template open is visible and retryable', + (tester) async { + for (final cupertino in [false, true]) { + var mode = 'ok'; + final gateway = GalleryGateway((type, fields) async { + if (type != 'list_templates') throw StateError('unexpected $type'); + if (mode == 'refuse') throw Exception('refresh unavailable'); + return templatesReply(galleryTemplates); + }); + + await pumpGallery(tester, gateway, cupertino: cupertino); + await tester.tap(find.byKey(templateRowKey('release'))); + await tester.pumpAndSettle(); + expect(find.byKey(templateDetailKey), findsOneWidget); + + mode = 'refuse'; + await tester.tap(find.byKey(templatesRefreshKey)); + await tester.pumpAndSettle(); + + expect(gateway.callsOf('list_templates'), hasLength(2)); + expect(find.byKey(templateDetailKey), findsOneWidget); + expect(find.byKey(templatesErrorBannerKey), findsOneWidget); + expect(find.text('refresh unavailable'), findsOneWidget); + expect(find.byKey(templatesBannerRetryKey), findsOneWidget); + expect(find.byKey(templatesErrorKey), findsNothing); + expect(find.text(templateSourceLabel), findsOneWidget); + expect(find.text(templateCreateActionLabel), findsOneWidget); + expect( + tester.widget(find.byKey(templatesBannerRetryKey)), + cupertino ? isA() : isA(), + ); + expect(tester.takeException(), isNull); + + mode = 'ok'; + await tester.tap(find.byKey(templatesBannerRetryKey)); + await tester.pumpAndSettle(); + + expect(find.text('refresh unavailable'), findsNothing); + expect(find.byKey(templatesErrorBannerKey), findsNothing); + expect(find.byKey(templateDetailKey), findsOneWidget); + expect(find.text(templateSourceLabel), findsOneWidget); + expect(gateway.callsOf('list_templates'), hasLength(3)); + + await tester.tap(find.byKey(templatesBackKey)); + await tester.pumpAndSettle(); + expect(find.byKey(templatesGalleryKey), findsOneWidget); + expect(find.text('Release workflow'), findsOneWidget); + expect(find.text('(unnamed template)'), findsOneWidget); + } + }, + ); + + testWidgets('an embedded failed refresh is visible above the open template', ( + tester, + ) async { + var mode = 'ok'; + final gateway = GalleryGateway((type, fields) async { + if (type != 'list_templates') throw StateError('unexpected $type'); + if (mode == 'refuse') throw Exception('refresh unavailable'); + return templatesReply(galleryTemplates); + }); + + await pumpGallery(tester, gateway, embedded: true); + await tester.tap(find.byKey(templateRowKey('release'))); + await tester.pumpAndSettle(); + expect(find.byKey(templateDetailBackKey), findsOneWidget); + + mode = 'refuse'; + await tester.tap(find.byKey(templatesRefreshKey)); + await tester.pumpAndSettle(); + + expect(find.byKey(templatesErrorBannerKey), findsOneWidget); + expect(find.text('refresh unavailable'), findsOneWidget); + expect(find.byKey(templateDetailKey), findsOneWidget); + expect(find.byKey(templateDetailBackKey), findsOneWidget); + + mode = 'ok'; + await tester.tap(find.byKey(templatesBannerRetryKey)); + await tester.pumpAndSettle(); + + expect(find.byKey(templatesErrorBannerKey), findsNothing); + expect(find.byKey(templateDetailKey), findsOneWidget); + expect(gateway.callsOf('list_templates'), hasLength(3)); + }); + + testWidgets('2x text on a short phone has no overflow and stays reachable', ( + tester, + ) async { + final gateway = GalleryGateway( + (type, fields) async => templatesReply(galleryTemplates), + ); + await pumpGallery( + tester, + gateway, + size: const Size(360, 640), + textScale: 2, + ); + + expect(tester.takeException(), isNull); + await tester.tap(find.byKey(templateRowKey('release'))); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(find.text(templateCreateActionLabel), findsOneWidget); + expect(selectableSource(source), findsOneWidget); + expect(find.byKey(templatesBackKey), findsOneWidget); + }); + + testWidgets('only the newest reply wins and a disposed screen ignores one', ( + tester, + ) async { + final first = Completer(); + final stale = Completer(); + var calls = 0; + final gateway = GalleryGateway((type, fields) { + calls++; + if (calls == 1) return first.future; + if (calls == 2) return stale.future; + return Future.value( + templatesReply([templateJson(key: 'fresh', name: 'Fresh')]), + ); + }); + + await pumpGallery(tester, gateway, settle: false); + first.complete( + templatesReply([templateJson(key: 'old', name: 'Old reply')]), + ); + await tester.pumpAndSettle(); + expect(find.text('Old reply'), findsOneWidget); + + await tester.tap(find.byKey(templatesRefreshKey)); + await tester.pump(); + final replacement = GalleryGateway( + (type, fields) async => + templatesReply([templateJson(key: 'other', name: 'Other server')]), + ); + await pumpGallery(tester, replacement); + expect(find.text('Other server'), findsOneWidget); + + stale.complete( + templatesReply([templateJson(key: 'stale', name: 'Stale reply')]), + ); + await tester.pumpAndSettle(); + expect(find.text('Stale reply'), findsNothing); + expect(find.text('Other server'), findsOneWidget); + + final pending = Completer(); + final disposedGateway = GalleryGateway((type, fields) => pending.future); + await pumpGallery(tester, disposedGateway, settle: false); + await tester.pumpWidget(const SizedBox.shrink()); + pending.complete(templatesReply(galleryTemplates)); + await tester.pump(); + expect(tester.takeException(), isNull); + }); +} diff --git a/app/test/features/templates/ui/template_gallery_test_support.dart b/app/test/features/templates/ui/template_gallery_test_support.dart new file mode 100644 index 00000000..9c94f9c4 --- /dev/null +++ b/app/test/features/templates/ui/template_gallery_test_support.dart @@ -0,0 +1,112 @@ +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/templates/screen.dart'; + +import '../data/template_test_support.dart' show source; + +typedef GalleryHandler = + FutureOr Function(String type, JsonMap fields); + +/// A recording gateway whose replies come from [handler]. +class GalleryGateway implements ApiGateway { + GalleryGateway(this.handler); + + final GalleryHandler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); + + List<({String type, JsonMap fields})> callsOf(String type) => + calls.where((call) => call.type == type).toList(growable: false); +} + +JsonMap templateJson({ + required String key, + String name = '', + String description = '', + String? definition, + bool scheduled = false, +}) => { + 'key': key, + 'name': name, + 'description': description, + 'source': definition ?? source, + 'scheduled': scheduled, +}; + +JsonMap templatesReply(List templates) => {'templates': templates}; + +final galleryTemplates = [ + templateJson( + key: 'release', + name: 'Release workflow', + description: 'Ship a version', + scheduled: true, + ), + templateJson(key: 'blank', description: 'No display name'), +]; + +Future acceptedCreate(String type, JsonMap fields) async { + if (type == 'validate') return {'graph': {}}; + if (type == 'submit') { + return { + 'detail': {'id': 7, 'name': 'Created release'}, + }; + } + throw StateError('Unexpected request $type'); +} + +/// Pumps the gallery in a real Material or Cupertino host without fixed sizes. +Future pumpGallery( + WidgetTester tester, + GalleryGateway gateway, { + bool cupertino = false, + bool embedded = false, + ValueChanged? onCreated, + double textScale = 1, + Size size = const Size(800, 1000), + bool settle = true, +}) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + final screen = TemplatesScreen( + gateway: gateway, + embedded: embedded, + onCreated: onCreated, + ); + final home = embedded + ? (cupertino + ? CupertinoPageScaffold(child: screen) + : Scaffold(body: screen)) + : screen; + await tester.pumpWidget( + cupertino + ? CupertinoApp(builder: media, home: home) + : MaterialApp(builder: media, home: home), + ); + if (settle) await tester.pumpAndSettle(); +} + +Finder selectableSource(String text) => find.byWidgetPredicate( + (widget) => widget is SelectableText && widget.data == text, +); diff --git a/app/tool/artifact_gallery_probe.dart b/app/tool/artifact_gallery_probe.dart new file mode 100644 index 00000000..3190fa10 --- /dev/null +++ b/app/tool/artifact_gallery_probe.dart @@ -0,0 +1,309 @@ +// Standalone fixture entry for real-browser run-detail Artifacts evidence. +// +// Build and probe (from app/): +// flutter build web --target tool/artifact_gallery_probe.dart --output build/probe-gallery +// node tool/artifact_gallery_probe.mjs --root build/probe-gallery --out DIR +// +// Server-shaped fixtures only: a fake gateway answers the same get_run envelope +// the app consumes. The recorded urls point at the probe's own loopback origin, +// so the external Open action has a real target. No server or operator run is +// touched. +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_gallery_page.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_view.dart'; +import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; + +class _FakeGateway implements ApiGateway { + _FakeGateway(this.detail); + + final JsonMap detail; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type != 'get_run') throw UnsupportedError(type); + return Future.value({'run_detail': detail}); + } +} + +JsonMap _file( + String name, { + required String url, + required String contentType, + required int sizeBytes, +}) => { + 'name': name, + 'url': url, + 'content_type': contentType, + 'size_bytes': sizeBytes, +}; + +/// The recorded steps for one probe state. `default` carries two visits that +/// both record `result.csv` plus a partial capture on the second visit. +List _steps(String origin, String state) { + if (state == 'unavailable') { + return [ + { + 'stage': 'implementer', + 'sequence': 1, + 'status': 'completed', + 'control': {'visit': 1}, + }, + ]; + } + if (state == 'empty') { + return [ + { + 'stage': 'implementer', + 'sequence': 1, + 'status': 'completed', + 'control': {'visit': 1}, + 'artifacts': const [], + }, + ]; + } + if (state == 'unsafe' || state == 'nourl') { + return [ + { + 'stage': 'reviewer', + 'sequence': 1, + 'status': 'completed', + 'control': {'visit': 1}, + 'artifacts': [ + _file( + 'result.csv', + url: state == 'unsafe' ? '//evil.test/result.csv' : '', + contentType: 'text/csv', + sizeBytes: 2048, + ), + ], + }, + ]; + } + if (state == 'missing') { + return [ + { + 'stage': 'reviewer', + 'sequence': 1, + 'status': 'completed', + 'control': {'visit': 1}, + 'artifacts': [ + _file( + 'missing.png', + url: '$origin/fixture/missing.png', + contentType: 'image/png', + sizeBytes: 128, + ), + ], + }, + ]; + } + if (state == 'external') { + return [ + { + 'stage': 'reviewer', + 'sequence': 1, + 'status': 'completed', + 'control': {'visit': 1}, + 'artifacts': [ + _file( + 'elsewhere.png', + url: 'https://elsewhere.test/elsewhere.png', + contentType: 'image/png', + sizeBytes: 4096, + ), + ], + }, + ]; + } + return [ + { + 'stage': 'implementer', + 'sequence': 1, + 'status': 'completed', + 'control': {'visit': 1}, + 'artifacts': [ + _file( + 'build.log', + url: '$origin/fixture/build.log', + contentType: 'text/plain; charset=utf-8', + sizeBytes: 2337, + ), + _file( + 'notes.txt', + url: '$origin/fixture/notes.txt', + contentType: 'text/plain', + sizeBytes: 2337, + ), + ], + }, + { + 'stage': 'reviewer', + 'sequence': 2, + 'status': 'completed', + 'control': {'visit': 1}, + 'artifacts': [ + _file( + 'result.csv', + url: '$origin/fixture/result.csv', + contentType: 'text/csv', + sizeBytes: 2048, + ), + _file( + 'shot.png', + url: '$origin/fixture/shot.png', + contentType: 'image/png', + sizeBytes: 80544, + ), + _file( + 'clip.mp4', + url: '$origin/fixture/clip.mp4', + contentType: 'video/mp4', + sizeBytes: 40544, + ), + ], + }, + { + 'stage': 'reviewer', + 'sequence': 3, + 'status': 'completed', + 'control': {'visit': 2}, + 'artifacts': [ + _file( + 'result.csv', + url: '$origin/fixture/result-2.csv', + contentType: 'text/csv', + sizeBytes: 4096, + ), + ], + 'artifacts_skipped': 2, + }, + ]; +} + +JsonMap _run(String origin, String state) => { + 'id': 31, + 'title': 'Artifacts gallery probe', + 'name': 'gallery', + 'status': 'succeeded', + 'steps': _steps(origin, state), +}; + +void main() { + final params = Uri.base.queryParameters; + final cupertino = params['platform'] == 'cupertino'; + final theme = params['theme'] == 'dark' ? Brightness.dark : Brightness.light; + final origin = params['origin'] ?? 'https://artifacts.invalid'; + final state = params['state'] ?? 'default'; + final gallery = params['view'] == 'gallery'; + final originUrl = Uri.tryParse(origin); + final endpoint = originUrl == null + ? '' + : originUrl + .replace( + scheme: originUrl.scheme == 'https' ? 'wss' : 'ws', + path: '/connect', + query: null, + ) + .toString(); + // Browser text scaling is a fixture input like platform and theme. + final textScale = double.tryParse(params['scale'] ?? '') ?? 1; + final body = _ProbeBody( + run: _run(origin, state), + gallery: gallery, + endpoint: endpoint, + ); + Widget scaled(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + if (cupertino) { + runApp( + CupertinoApp( + title: 'Artifacts probe', + theme: CupertinoThemeData(brightness: theme), + builder: (context, app) => Theme( + data: ThemeData(platform: TargetPlatform.iOS), + child: scaled(context, app), + ), + home: body, + ), + ); + } else { + runApp( + MaterialApp( + title: 'Artifacts probe', + theme: ThemeData(brightness: theme, platform: TargetPlatform.android), + builder: scaled, + home: body, + ), + ); + } +} + +class _ProbeBody extends StatefulWidget { + const _ProbeBody({ + required this.run, + required this.gallery, + required this.endpoint, + }); + + final JsonMap run; + final bool gallery; + final String endpoint; + + @override + State<_ProbeBody> createState() => _ProbeBodyState(); +} + +class _ProbeBodyState extends State<_ProbeBody> { + late final _FakeGateway _gateway = _FakeGateway(widget.run); + late final RunsController _controller = RunsController( + RunsRepository(_gateway), + ); + + @override + void initState() { + super.initState(); + _controller.select(31); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + if (widget.gallery) { + final steps = (widget.run['steps'] as List).cast(); + return ArtifactGalleryPage( + steps: steps, + configuredEndpoint: widget.endpoint, + ); + } + final detail = RunDetailView( + controller: _controller, + gateway: _gateway, + onBack: () {}, + ); + if (Theme.of(context).platform == TargetPlatform.iOS) { + return CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar(middle: Text('Runs')), + child: SafeArea(child: detail), + ); + } + return Scaffold( + appBar: AppBar(title: const Text('Runs')), + body: detail, + ); + } +} diff --git a/app/tool/artifact_gallery_probe.mjs b/app/tool/artifact_gallery_probe.mjs new file mode 100644 index 00000000..d0e42c4a --- /dev/null +++ b/app/tool/artifact_gallery_probe.mjs @@ -0,0 +1,601 @@ +// Real-browser evidence for the run-detail Artifacts action and gallery page. +// +// Usage (from app/): +// flutter build web --target tool/artifact_gallery_probe.dart --output build/probe-gallery +// node tool/artifact_gallery_probe.mjs --root build/probe-gallery --out DIR +// +// Serves the built fixture on an OS-assigned loopback port, drives headless +// Chrome, and records the actual recorded rows, the selection dialog, the safe +// external Open, the empty/unavailable states, both native hosts, dark +// Cupertino and the 320/2x states. No server or operator run is touched. +import { createServer } from 'node:http'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { setTimeout as delay } from 'node:timers/promises'; +import { extname, join, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; +import zlib from 'node:zlib'; + +const args = new Map(); +for (let i = 2; i < process.argv.length; i++) { + const value = process.argv[i]; + if (value.startsWith('--')) args.set(value.slice(2), process.argv[++i]); +} +const root = resolve(args.get('root') ?? 'build/probe-gallery'); +const out = resolve(args.get('out') ?? 'build/artifact-gallery-probe'); +const chromePath = + process.env.CHROME_PATH ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +await mkdir(out, { recursive: true }); + +const mime = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.svg': 'image/svg+xml', + '.ico': 'image/x-icon', + '.ttf': 'font/ttf', + '.otf': 'font/otf', + '.woff': 'font/woff', + '.woff2': 'font/woff2', + '.bin': 'application/octet-stream', + '.frag': 'application/octet-stream', +}; + +const crcTable = Array.from({ length: 256 }, (_, n) => { + let c = n; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + return c >>> 0; +}); +const crc32 = (buffer) => { + let c = 0xffffffff; + for (const byte of buffer) c = crcTable[(c ^ byte) & 0xff] ^ (c >>> 8); + return (c ^ 0xffffffff) >>> 0; +}; +const pngChunk = (type, data) => { + const length = Buffer.alloc(4); + length.writeUInt32BE(data.length); + const body = Buffer.concat([Buffer.from(type), data]); + const crc = Buffer.alloc(4); + crc.writeUInt32BE(crc32(body)); + return Buffer.concat([length, body, crc]); +}; +// A real 160x100 gradient, so the preview evidence shows an actual image +// rather than a one-pixel probe. +const probePng = () => { + const width = 160; + const height = 100; + const rows = Buffer.alloc(height * (width * 3 + 1)); + for (let y = 0; y < height; y++) { + const offset = y * (width * 3 + 1); + rows[offset] = 0; + for (let x = 0; x < width; x++) { + rows[offset + 1 + x * 3] = 40 + Math.trunc((x * 120) / width); + rows[offset + 2 + x * 3] = 90 + Math.trunc((y * 130) / height); + rows[offset + 3 + x * 3] = 200 - Math.trunc((x * 80) / width); + } + } + const header = Buffer.alloc(13); + header.writeUInt32BE(width, 0); + header.writeUInt32BE(height, 4); + header[8] = 8; + header[9] = 2; + return Buffer.concat([ + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + pngChunk('IHDR', header), + pngChunk('IDAT', zlib.deflateSync(rows, { level: 9 })), + pngChunk('IEND', Buffer.alloc(0)), + ]); +}; +const png = probePng(); + +const server = createServer(async (req, res) => { + const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname); + if (pathname.startsWith('/fixture/')) { + if (pathname.endsWith('/missing.png')) { + res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); + res.end('missing artifact\n'); + return; + } + if (pathname.endsWith('.png')) { + res.writeHead(200, { 'content-type': 'image/png' }); + res.end(png); + return; + } + res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' }); + res.end(`recorded artifact ${pathname}\n`); + return; + } + try { + let filePath = resolve(root, '.' + pathname); + if (filePath !== root && !filePath.startsWith(root + sep)) { + res.writeHead(403).end(); + return; + } + if (pathname === '/' || pathname.endsWith('/')) filePath = join(filePath, 'index.html'); + const file = await readFile(filePath); + res.writeHead(200, { 'content-type': mime[extname(filePath)] ?? 'application/octet-stream' }).end(file); + } catch { + res.writeHead(404).end('not found'); + } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const origin = `http://127.0.0.1:${server.address().port}`; + +const profile = await mkdtemp(join(tmpdir(), 'a1w-chrome-')); +const chrome = spawn( + chromePath, + ['--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu', + '--disable-popup-blocking', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'], + { stdio: ['ignore', 'ignore', 'pipe'] }, +); +let stderr = ''; +chrome.stderr.on('data', (data) => { + stderr += data; +}); + +const waitFor = async (fn, what) => { + for (let i = 0; i < 120; i++) { + const value = await fn(); + if (value) return value; + await delay(100); + } + throw new Error(`Timed out waiting for ${what}: ${stderr.slice(-1500)}`); +}; + +const evidence = { origin, captures: [], checks: [] }; +let ws; +try { + const endpoint = await waitFor( + () => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1], + 'Chrome DevTools', + ); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', (event) => { + const message = JSON.parse(event.data); + if (message.id && pending.has(message.id)) { + pending.get(message.id)(message); + pending.delete(message.id); + } + }); + const send = (method, params = {}, sessionId) => + new Promise((resolveCall) => { + const callId = ++id; + pending.set(callId, resolveCall); + ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + + const created = await send('Target.createTarget', { url: 'about:blank' }); + const session = (await send('Target.attachToTarget', { + targetId: created.result.targetId, + flatten: true, + })).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + await send('Browser.grantPermissions', { + origin, + permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'], + }); + await send('Emulation.setDeviceMetricsOverride', { + width: 390, height: 844, deviceScaleFactor: 1, mobile: true, + }, session); + + const evaluate = async (expression) => { + const response = await send( + 'Runtime.evaluate', + { expression, returnByValue: true, awaitPromise: true }, + session, + ); + if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); + return response.result?.result?.value; + }; + const labels = () => + evaluate( + "[...document.querySelectorAll('flt-semantics')].map(x => x.getAttribute('aria-label') || (x.innerText || '').trim()).filter(Boolean)", + ); + const bodyText = () => evaluate('document.body.innerText'); + const visibleText = async () => `${await bodyText()}\n${(await labels()).join('\n')}`; + const hasLabel = async (label) => (await labels()).includes(label); + const clickExact = async (label) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(label)}; + const text = (x) => x.getAttribute('aria-label') || (x.innerText || '').trim(); + const nodes = [...document.querySelectorAll('flt-semantics')]; + const tappable = nodes.filter(x => x.hasAttribute('flt-tappable')); + // The tappable node is the one the engine listens to; a labelled wrapper + // above it would swallow a synthetic click. + const node = tappable.find(x => text(x) === wanted) + || tappable.find(x => text(x).startsWith(wanted)) + || nodes.find(x => text(x) === wanted); + if (!node) return false; + node.click(); + return true; + })()`); + if (!clicked) throw new Error(`No exact semantics label ${JSON.stringify(label)}: ${JSON.stringify(await labels())}`); + await delay(500); + }; + // The lowest matching row is the later visit's duplicate filename. + const clickLowestPrefix = async (prefix) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(prefix)}; + const text = (x) => x.getAttribute('aria-label') || (x.innerText || '').trim(); + const candidates = [...document.querySelectorAll('flt-semantics')] + .filter(x => text(x).startsWith(wanted)) + .filter(x => x.hasAttribute('flt-tappable')); + if (!candidates.length) return false; + candidates.sort((a, b) => b.getBoundingClientRect().y - a.getBoundingClientRect().y); + candidates[0].click(); + return true; + })()`); + if (!clicked) throw new Error(`No tappable label starting ${JSON.stringify(prefix)}: ${JSON.stringify(await labels())}`); + await delay(600); + }; + const activate = async (expected = 'Artifacts gallery probe') => { + await delay(3200); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(900); + const current = await labels(); + if (expected !== null && !current.some((label) => label.includes(expected))) { + throw new Error(`Flutter semantics unavailable: ${JSON.stringify(current)}`); + } + }; + const navigate = async (url, expected = 'Artifacts gallery probe') => { + const navigation = await send('Page.navigate', { url }, session); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + await activate(expected); + }; + const targetCount = async () => + (await send('Target.getTargets')).result.targetInfos.filter( + (target) => target.type === 'page', + ).length; + const capture = async (name, width = 390, height = 844, scale = 1) => { + await send('Emulation.setDeviceMetricsOverride', { + width, height, deviceScaleFactor: scale, mobile: width < 600, + }, session); + await delay(350); + const data = (await send('Page.captureScreenshot', { format: 'png' }, session)).result.data; + const path = join(out, `${name}.png`); + await writeFile(path, Buffer.from(data, 'base64')); + evidence.captures.push(path); + }; + const rectOfPrefix = (prefix) => + evaluate(`(() => { + const wanted = ${JSON.stringify(prefix)}; + const text = (x) => x.getAttribute('aria-label') || (x.innerText || '').trim(); + const node = [...document.querySelectorAll('flt-semantics')].find(x => text(x).startsWith(wanted)); + if (!node) return null; + const r = node.getBoundingClientRect(); + return { x: r.x, y: r.y, width: r.width, height: r.height }; + })()`); + const brightestPixel = async (rect) => { + const shot = await send('Page.captureScreenshot', { + format: 'png', + clip: { ...rect, scale: 2 }, + }, session); + return evaluate(`(async () => { + const img = new Image(); + img.src = 'data:image/png;base64,${shot.result.data}'; + await img.decode(); + const canvas = document.createElement('canvas'); + canvas.width = img.width; + canvas.height = img.height; + const ctx = canvas.getContext('2d'); + ctx.drawImage(img, 0, 0); + const data = ctx.getImageData(0, 0, img.width, img.height).data; + let max = 0; + for (let i = 0; i < data.length; i += 4) { + const lum = (0.2126 * data[i] + 0.7152 * data[i + 1] + 0.0722 * data[i + 2]) / 255; + if (lum > max) max = lum; + } + return { max, width: img.width, height: img.height }; + })()`); + }; + const openGallery = async (query) => { + await navigate(`${origin}/?${query}`); + if (!(await hasLabel('Artifacts'))) { + throw new Error(`Run detail has no Artifacts action: ${JSON.stringify(await labels())}`); + } + await clickExact('Artifacts'); + await delay(600); + }; + + // Material: recorded rows, duplicate filename, visit-2 capture facts and the + // safe external Open. + await navigate(`${origin}/?origin=${encodeURIComponent(origin)}`); + if (!(await hasLabel('Artifacts'))) { + throw new Error(`Material run detail has no Artifacts action: ${JSON.stringify(await labels())}`); + } + evidence.checks.push({ check: 'the run detail offers the native Artifacts action', value: true }); + await capture('a1w-material-detail'); + + await clickExact('Artifacts'); + const galleryBody = await bodyText(); + for (const recorded of ['build.log', 'shot.png', 'text/csv', 'implementer · visit 1', 'reviewer · visit 2']) { + if (!galleryBody.includes(recorded)) { + throw new Error(`Gallery is missing recorded row ${recorded}: ${JSON.stringify(galleryBody)}`); + } + } + if (!galleryBody.includes('Artifacts · 6 recorded')) { + throw new Error(`Gallery summary missing: ${JSON.stringify(galleryBody)}`); + } + const resultRows = (await labels()).filter((label) => label.startsWith('result.csv')).length; + if (resultRows < 2) { + throw new Error(`Duplicate result.csv rows missing: ${JSON.stringify(await labels())}`); + } + evidence.checks.push({ check: 'the gallery lists the actual recorded rows, not nav labels', value: true }); + await capture('a1w-material-gallery'); + + await clickLowestPrefix('result.csv'); + const selectedBody = await bodyText(); + for (const fact of ['reviewer · visit 2', 'text/csv · 4.0\u00a0KiB', 'Artifacts · 1 recorded · partial capture', '2 files excluded from artifact capture.']) { + if (!selectedBody.includes(fact)) { + throw new Error(`Selected visit-2 facts missing ${fact}: ${JSON.stringify(selectedBody)}`); + } + } + if (!(await hasLabel('Open')) || !(await hasLabel('Copy link'))) { + throw new Error(`Selection offers no Open/Copy link: ${JSON.stringify(await labels())}`); + } + evidence.checks.push({ check: 'the duplicate filename selected visit 2 with its own capture facts', value: true }); + await capture('a1w-material-selected'); + + // The selection offers the safe external Open and a separate Copy link. + // Headless Chrome cannot carry a user activation through a synthetic + // semantics click, so the tab itself is proven by the widget test that + // records the exact uri handed to the opener; the browser proves the actions + // appear only for a url that resolves through the safe rules. + if (!(await hasLabel('Open')) || !(await hasLabel('Copy link'))) { + throw new Error(`Selection offers no Open/Copy link: ${JSON.stringify(await labels())}`); + } + evidence.checks.push({ + check: 'the selection offers the native Open and separate Copy link for a safe recorded url', + value: true, + }); + await capture('a1w-material-open'); + + await navigate(`${origin}/?origin=${encodeURIComponent(origin)}&state=unsafe`); + await clickExact('Artifacts'); + await clickLowestPrefix('result.csv'); + const unsafeBody = await bodyText(); + if (!unsafeBody.includes('The recorded artifact URL cannot be opened safely.')) { + throw new Error(`Unsafe url wording missing: ${JSON.stringify(unsafeBody)}`); + } + if ((await hasLabel('Open')) || (await hasLabel('Copy link'))) { + throw new Error(`Unsafe url still offered an action: ${JSON.stringify(await labels())}`); + } + evidence.checks.push({ check: 'a protocol-relative url offers no open or copy action', value: true }); + await capture('a1w-material-unsafe'); + + await navigate(`${origin}/?origin=${encodeURIComponent(origin)}&state=nourl`); + await clickExact('Artifacts'); + await clickLowestPrefix('result.csv'); + const nourlBody = await bodyText(); + if (!nourlBody.includes('No artifact URL recorded.')) { + throw new Error(`No-url wording missing: ${JSON.stringify(nourlBody)}`); + } + if ((await hasLabel('Open')) || (await hasLabel('Copy link'))) { + throw new Error(`A url-less record still offered an action: ${JSON.stringify(await labels())}`); + } + evidence.checks.push({ check: 'a record with no url is explicit and offers no action', value: true }); + await capture('a1w-material-nourl'); + + await navigate(`${origin}/?origin=${encodeURIComponent(origin)}&state=empty`); + await clickExact('Artifacts'); + const emptyBody = await bodyText(); + if (!emptyBody.includes('No artifacts recorded for this run.')) { + throw new Error(`Recorded empty capture wording missing: ${JSON.stringify(emptyBody)}`); + } + evidence.checks.push({ check: 'a recorded empty capture says nothing was recorded', value: true }); + await capture('a1w-material-empty'); + + await navigate(`${origin}/?origin=${encodeURIComponent(origin)}&state=unavailable`); + await clickExact('Artifacts'); + const unavailableBody = await bodyText(); + if (!unavailableBody.includes('Artifacts · capture unavailable')) { + throw new Error(`Unavailable capture wording missing: ${JSON.stringify(unavailableBody)}`); + } + if (unavailableBody.includes('No artifacts recorded for this run.')) { + throw new Error('Unavailable capture claimed nothing was recorded'); + } + evidence.checks.push({ check: 'an unavailable capture is never reported as empty', value: true }); + await capture('a1w-material-unavailable'); + + // In-app artifact viewer: image, text, unsupported, paging, back and HTTP + // failure. The fixture serves same-origin artifact urls on this loopback + // origin, so the viewer is allowed to fetch them; no browser tab may open. + const galleryView = (extra = '', platform = 'material') => + `${origin}/?view=gallery&platform=${platform}&origin=${encodeURIComponent(origin)}${extra}`; + const beforeViewerTargets = await targetCount(); + await navigate(galleryView(), 'Artifacts'); + await clickLowestPrefix('shot.png'); + await delay(700); + const imageBody = await bodyText(); + for (const fact of [ + 'shot.png', + 'image/png · 78.7\u00a0KiB', + '3 of 4 · image/png', + 'reviewer · visit 1', + ]) { + if (!imageBody.includes(fact)) { + throw new Error(`Image preview missing ${fact}: ${JSON.stringify(imageBody)}`); + } + } + if (!(await hasLabel('Previous artifact')) || !(await hasLabel('Next artifact'))) { + throw new Error(`Viewer has no paging controls: ${JSON.stringify(await labels())}`); + } + const afterViewerTargets = await targetCount(); + if (afterViewerTargets !== beforeViewerTargets) { + throw new Error(`Image preview opened a browser tab: ${beforeViewerTargets} -> ${afterViewerTargets}`); + } + evidence.checks.push({ + check: 'an image is previewed in-app from the same-origin url without a new tab', + value: true, + targets: afterViewerTargets, + }); + await capture('a1w-viewer-image'); + + await clickExact('Next artifact'); + const videoBody = await bodyText(); + if (!videoBody.includes('4 of 4 · video/mp4')) { + throw new Error(`Viewer did not page to the video: ${JSON.stringify(videoBody)}`); + } + if (!videoBody.includes('This file type cannot be previewed here.')) { + throw new Error(`Video was not marked unpresentable: ${JSON.stringify(videoBody)}`); + } + if (!(await hasLabel('Open')) || !(await hasLabel('Copy link'))) { + throw new Error(`Unsupported page lost its actions: ${JSON.stringify(await labels())}`); + } + await clickExact('Next artifact'); + if (!(await bodyText()).includes('4 of 4 · video/mp4')) { + throw new Error('Next past the last artifact changed the page'); + } + evidence.checks.push({ check: 'unsupported types are explicit with Open/Copy and paging clamps', value: true }); + await capture('a1w-viewer-unsupported'); + + await clickExact('Previous artifact'); + await clickExact('Previous artifact'); + await clickExact('Previous artifact'); + await delay(500); + const textBody = await visibleText(); + if (!textBody.includes('1 of 4 · text/plain')) { + throw new Error(`Text page missing: ${JSON.stringify(textBody)}`); + } + evidence.checks.push({ check: 'text/plain pages in the viewer with its recorded facts', value: true }); + await capture('a1w-viewer-text'); + + await clickExact('Back'); + await delay(500); + const returnedBody = await bodyText(); + if (!returnedBody.includes('shot.png') || !returnedBody.includes('reviewer · visit 2')) { + throw new Error(`Back did not return to the gallery: ${JSON.stringify(returnedBody)}`); + } + evidence.checks.push({ check: 'native Back returns to the gallery row list', value: true }); + + await navigate(galleryView('&state=missing'), 'Artifacts'); + await clickLowestPrefix('missing.png'); + await delay(700); + const missingBody = await visibleText(); + if (!missingBody.includes('The server answered 404.')) { + throw new Error(`Missing fetch status was not reported: ${JSON.stringify(missingBody)}`); + } + evidence.checks.push({ check: 'an HTTP failure reports its status instead of an empty preview', value: true }); + await capture('a1w-viewer-http-error'); + + await navigate(galleryView('&state=external'), 'Artifacts'); + await clickLowestPrefix('elsewhere.png'); + await delay(500); + const externalBody = await visibleText(); + if (!externalBody.includes('This artifact is hosted on another origin and is not previewed here.')) { + throw new Error(`External artifact was not marked: ${JSON.stringify(externalBody)}`); + } + if (!externalBody.includes('1 of 1 · image/png') || !(await hasLabel('Open'))) { + throw new Error(`External artifact lost its facts/Open action: ${JSON.stringify(externalBody)}`); + } + evidence.checks.push({ check: 'an external artifact opens marked, unfetched, with facts and actions', value: true }); + await capture('a1w-viewer-external'); + + // 320 px at 2x text on both hosts: the viewer keeps its facts, paging and + // controls whole. + const scaledViewer = async (platform, prefix) => { + await navigate(galleryView('', platform), 'Artifacts'); + await clickLowestPrefix('shot.png'); + await delay(700); + const scaledBody = await bodyText(); + for (const fact of ['image/png · 78.7\u00a0KiB', '3 of 4 · image/png', 'reviewer · visit 1']) { + if (!scaledBody.includes(fact)) { + throw new Error(`2x viewer missing ${fact}: ${JSON.stringify(scaledBody)}`); + } + } + if (!(await hasLabel('Previous artifact')) || !(await hasLabel('Next artifact'))) { + throw new Error(`2x viewer lost paging: ${JSON.stringify(await labels())}`); + } + await capture(`${prefix}-viewer`, 320, 720, 1); + }; + await scaledViewer('material', 'a1w-material-2x-320'); + evidence.checks.push({ check: 'Material 2x/320 viewer keeps facts and paging', value: true }); + await scaledViewer('cupertino', 'a1w-cupertino-2x-320'); + evidence.checks.push({ check: 'Cupertino 2x/320 viewer keeps facts and paging', value: true }); + + // Cupertino light: the tinted action, the native dialog and its actions. + await openGallery(`platform=cupertino&theme=light&origin=${encodeURIComponent(origin)}`); + const cupertinoBody = await bodyText(); + if (!cupertinoBody.includes('shot.png') || !cupertinoBody.includes('reviewer · visit 2')) { + throw new Error(`Cupertino gallery missing recorded rows: ${JSON.stringify(cupertinoBody)}`); + } + evidence.checks.push({ check: 'Cupertino lists the same recorded rows', value: true }); + await capture('a1w-cupertino-gallery'); + await clickLowestPrefix('result.csv'); + if (!(await hasLabel('Open')) || !(await hasLabel('Copy link'))) { + throw new Error(`Cupertino selection offers no actions: ${JSON.stringify(await labels())}`); + } + const cupertinoSelected = await bodyText(); + if (!cupertinoSelected.includes('Artifacts · 1 recorded · partial capture')) { + throw new Error(`Cupertino selection lost its capture facts: ${JSON.stringify(cupertinoSelected)}`); + } + evidence.checks.push({ check: 'Cupertino selection shows the recorded facts and native actions', value: true }); + await capture('a1w-cupertino-selected'); + + // Cupertino dark: the gallery and its dialog on the dark host. + await openGallery(`platform=cupertino&theme=dark&origin=${encodeURIComponent(origin)}`); + await capture('a1w-cupertino-dark-gallery'); + await clickLowestPrefix('result.csv'); + const darkLabels = await labels(); + const darkTitle = darkLabels.find((label) => label.startsWith('result.csv')); + const titleRect = await rectOfPrefix('result.csv'); + const darkText = [await bodyText(), ...darkLabels].join('\n'); + if (!darkText.includes('Artifacts · 1 recorded · partial capture')) { + throw new Error(`Dark Cupertino dialog did not render: ${JSON.stringify(darkText)}`); + } + if (!titleRect) throw new Error(`Dark Cupertino dialog title missing: ${JSON.stringify(darkLabels)}`); + const luminance = await brightestPixel(titleRect); + if (luminance.max < 0.5) { + throw new Error(`Dark Cupertino dialog text is not light: ${JSON.stringify(luminance)}`); + } + evidence.checks.push({ + check: 'dark Cupertino dialog text is light on the popup surface', + value: true, + luminance: luminance.max, + title: darkTitle, + }); + await capture('a1w-cupertino-dark-selected'); + + // 320 px at 2x text on both hosts: the recorded rows and facts stay whole. + const openScaled = async (platform, prefix) => { + await openGallery(`platform=${platform}&theme=light&scale=2&origin=${encodeURIComponent(origin)}`); + const scaled = await bodyText(); + for (const recorded of ['build.log', 'shot.png', 'reviewer · visit 1']) { + if (!scaled.includes(recorded)) { + throw new Error(`2x gallery missing ${recorded}: ${JSON.stringify(scaled)}`); + } + } + await capture(`${prefix}-gallery`, 320, 720, 1); + await clickLowestPrefix('result.csv'); + const facts = await bodyText(); + if (!facts.includes('Artifacts · 3 recorded') && + !facts.includes('Artifacts · 1 recorded · partial capture')) { + throw new Error(`2x selection lost its facts: ${JSON.stringify(facts)}`); + } + if (!(await hasLabel('Open')) || !(await hasLabel('Copy link'))) { + throw new Error(`2x selection lost its actions: ${JSON.stringify(await labels())}`); + } + await capture(`${prefix}-selected`, 320, 720, 1); + }; + await openScaled('material', 'a1w-material-2x-320'); + evidence.checks.push({ check: 'Material 2x/320 keeps the recorded rows, facts and actions', value: true }); + await openScaled('cupertino', 'a1w-cupertino-2x-320'); + evidence.checks.push({ check: 'Cupertino 2x/320 keeps the recorded rows, facts and actions', value: true }); + + console.log(JSON.stringify(evidence, null, 2)); +} finally { + ws?.close(); + chrome.kill('SIGTERM'); + await Promise.race([once(chrome, 'exit'), delay(3000)]); + server.close(); + await rm(profile, { recursive: true, force: true }); +} diff --git a/app/tool/chat_wire_probe.dart b/app/tool/chat_wire_probe.dart new file mode 100644 index 00000000..dcd07254 --- /dev/null +++ b/app/tool/chat_wire_probe.dart @@ -0,0 +1,255 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/screen.dart'; + +/// Browser fixture for the Chat destination wiring: the real session list opens +/// the real controller/view against a scripted gateway. Server data only; no +/// composer, routes, sockets or production store are involved. +/// +/// Sessions page with different server answers so the driver can reproduce the +/// disclosure-state variants: alternating turns with the older page keeping or +/// ending history, and pages of consecutive assistant messages that fold into +/// one turn at the page boundary. +class _FixtureGateway implements ApiGateway { + final _frames = StreamController.broadcast(); + + @override + Stream get frames => _frames.stream; + + void _pushLiveDelta() { + Timer(const Duration(milliseconds: 500), () { + _frames.add({ + 'type': 'chat_event', + 'chat_event': { + 'session_id': 'probe-session', + 'message_id': 'a-NEWEST', + 'kind': 'text', + 'part': {'id': 'p-live', 'type': 'text'}, + 'delta': 'A live delta updated this thread.', + }, + }); + }); + } + + @override + Future call(String type, [JsonMap fields = const {}]) async { + switch (type) { + case 'chat_sessions': + return { + 'chat_sessions': [ + { + 'id': 'probe-session', + 'title': 'Probe conversation', + 'directory': '/workspace/demo', + 'starred': true, + }, + { + 'id': 'probe-more', + 'title': 'Probe paging session', + 'directory': '/workspace/demo', + }, + { + 'id': 'probe-other', + 'title': 'Another stored chat', + 'directory': '/workspace/demo', + }, + { + 'id': 'probe-fold', + 'title': 'Probe assistant fold session', + 'directory': '/workspace/demo', + }, + { + 'id': 'probe-fold-end', + 'title': 'Probe assistant fold last page', + 'directory': '/workspace/demo', + }, + ], + }; + case 'chat_subscribe': + return {}; + case 'chat_messages': + final query = fields['chat_query'] as Map? ?? const {}; + final cursor = '${query['cursor'] ?? ''}'; + if (query['session_id'] == 'probe-fold' || + query['session_id'] == 'probe-fold-end') { + final keepsPaging = query['session_id'] == 'probe-fold'; + if (cursor.isEmpty) { + return _foldPage( + prefix: 'FOLD_NEWEST', + ids: const ['fold-newest', 'fold-fourth'], + reasoning: const [ + 'FOLD NEWEST reasoning body.', + 'FOLD FOURTH reasoning body.', + ], + cursor: 'probe/opaque?fold=2', + hasMore: true, + ); + } + return _foldPage( + prefix: 'FOLD_OLDER', + ids: const ['fold-second', 'fold-oldest'], + reasoning: const [ + 'FOLD SECOND reasoning body.', + 'FOLD OLDEST reasoning body.', + ], + cursor: keepsPaging ? 'probe/opaque?fold=3' : '', + hasMore: keepsPaging, + ); + } + if (query['session_id'] == 'probe-more') { + return cursor.isEmpty + ? _page( + prefix: 'MORE_NEWEST', + user: 'A second read-only question from the server.', + reasoning: 'MORE NEWEST reasoning body.', + reply: 'The second stored assistant reply.', + cursor: 'probe/opaque?more=2', + hasMore: true, + ) + : _page( + prefix: 'MORE_OLDER', + user: 'An even older message for the second chat.', + reasoning: + 'MORE OLDER reasoning body that must stay collapsed.', + reply: 'Second older reply.', + cursor: 'probe/opaque?more=3', + hasMore: true, + ); + } + if (cursor.isEmpty) { + // Deliver the live delta only after the initial history page, so the + // merge cannot be mistaken for the delta being lost. + _pushLiveDelta(); + return _page( + prefix: 'NEWEST', + user: 'Please keep this exact read-only message from the server.', + reasoning: + 'NEWEST reasoning body that belongs to the newest answer.', + reply: + 'The stored assistant reply is rendered by the existing ' + 'native message view.', + cursor: 'probe/opaque?page=2', + hasMore: true, + ); + } + return _page( + prefix: 'OLDER', + user: 'This older stored message came from the opaque cursor page.', + reasoning: + 'OLDER reasoning body that must not steal the newest ' + 'disclosure.', + reply: 'Older reply kept in order.', + cursor: '', + hasMore: false, + ); + } + return {}; + } + + JsonMap _page({ + required String prefix, + required String user, + required String reasoning, + required String reply, + required String cursor, + required bool hasMore, + }) => { + 'chat_history': { + 'messages': [ + { + 'id': 'u-$prefix', + 'role': 'user', + 'client': 'Probe host', + 'parts': [ + {'type': 'text', 'text': user}, + ], + }, + { + 'id': 'a-$prefix', + 'role': 'assistant', + 'parts': [ + {'type': 'reasoning', 'text': reasoning}, + {'type': 'text', 'text': reply}, + {'type': 'tool', 'name': 'shell'}, + ], + }, + ], + 'next_cursor': cursor, + 'has_more': hasMore, + }, + }; + + /// The paged-history fixture shape: a page of consecutive assistant messages + /// with no user message at the page boundary, so paging folds into one turn. + JsonMap _foldPage({ + required String prefix, + required List ids, + required List reasoning, + required String cursor, + required bool hasMore, + }) => { + 'chat_history': { + 'messages': [ + for (var index = 0; index < ids.length; index++) + { + 'id': ids[index], + 'role': 'assistant', + 'parts': [ + { + 'type': 'reasoning', + 'id': 'r-${ids[index]}', + 'text': reasoning[index], + }, + { + 'type': 'text', + 'id': 't-${ids[index]}', + 'text': 'Answer $prefix stored as ${ids[index]}.', + }, + ], + }, + ], + 'next_cursor': cursor, + 'has_more': hasMore, + }, + }; +} + +const _style = String.fromEnvironment( + 'CHAT_WIRE_PROBE_STYLE', + defaultValue: 'material', +); + +void main() { + final screen = ChatScreen( + gateway: _FixtureGateway(), + onSessionSelected: null, + ); + if (_style == 'cupertino') { + runApp( + CupertinoApp( + theme: const CupertinoThemeData(brightness: Brightness.dark), + home: CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar(middle: Text('Chat')), + child: SafeArea(child: screen), + ), + ), + ); + return; + } + runApp( + MaterialApp( + theme: ThemeData( + brightness: Brightness.dark, + platform: TargetPlatform.android, + ), + home: Scaffold( + appBar: AppBar(title: const Text('Chat')), + body: screen, + ), + ), + ); +} diff --git a/app/tool/chat_wire_probe.mjs b/app/tool/chat_wire_probe.mjs new file mode 100644 index 00000000..6d3b6013 --- /dev/null +++ b/app/tool/chat_wire_probe.mjs @@ -0,0 +1,530 @@ +// Real-browser evidence for the Chat destination wiring fixture. +// +// Build one host, then run from app/: +// flutter build web -t tool/chat_wire_probe.dart \ +// --dart-define=CHAT_WIRE_PROBE_STYLE=material \ +// --output build/probe-chat-wire-material +// node tool/chat_wire_probe.mjs --root build/probe-chat-wire-material \ +// --out DIR --style material +// +// The Cupertino host is the same fixture built with CHAT_WIRE_PROBE_STYLE=cupertino. +// Requires Google Chrome and Tesseract: Flutter web paints selectable text on +// the canvas, so OCR confirms the actual message body, not just nav labels. +import { createServer } from 'node:http'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { spawn, execFile } from 'node:child_process'; +import { once } from 'node:events'; +import { promisify } from 'node:util'; +import { setTimeout as delay } from 'node:timers/promises'; +import { extname, join, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; + +const args = new Map(); +for (let i = 2; i < process.argv.length; i++) { + const value = process.argv[i]; + if (value.startsWith('--')) args.set(value.slice(2), process.argv[++i]); +} +const root = resolve(args.get('root') ?? 'build/probe-chat-wire-material'); +const out = resolve(args.get('out') ?? 'build/chat-wire-probe'); +const style = args.get('style') ?? 'material'; +const chromePath = + process.env.CHROME_PATH ?? + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +await mkdir(out, { recursive: true }); + +const mime = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.svg': 'image/svg+xml', + '.ico': 'image/x-icon', + '.ttf': 'font/ttf', + '.otf': 'font/otf', + '.woff': 'font/woff', + '.woff2': 'font/woff2', + '.bin': 'application/octet-stream', +}; + +const server = createServer(async (req, res) => { + try { + const pathname = decodeURIComponent( + new URL(req.url, 'http://localhost').pathname, + ); + let filePath = resolve(root, '.' + pathname); + if (filePath !== root && !filePath.startsWith(root + sep)) { + res.writeHead(403).end(); + return; + } + if (pathname === '/' || pathname.endsWith('/')) { + filePath = join(filePath, 'index.html'); + } + const file = await readFile(filePath); + res.writeHead(200, { + 'content-type': mime[extname(filePath)] ?? 'application/octet-stream', + }); + res.end(file); + } catch { + res.writeHead(404).end('not found'); + } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const origin = `http://127.0.0.1:${server.address().port}`; + +const profile = await mkdtemp(join(tmpdir(), 'c2-wire-chrome-')); +const chrome = spawn( + chromePath, + [ + '--headless=new', + '--no-first-run', + '--no-default-browser-check', + '--disable-gpu', + '--remote-debugging-port=0', + `--user-data-dir=${profile}`, + 'about:blank', + ], + { stdio: ['ignore', 'ignore', 'pipe'] }, +); +let stderr = ''; +chrome.stderr.on('data', (data) => { + stderr += data; +}); +const waitFor = async (fn, what) => { + for (let i = 0; i < 180; i++) { + const value = await fn(); + if (value) return value; + await delay(100); + } + throw new Error(`Timed out waiting for ${what}: ${stderr.slice(-1500)}`); +}; + +let ws; +const evidence = { origin, style, captures: [], checks: [] }; +try { + const endpoint = await waitFor( + () => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1], + 'Chrome DevTools', + ); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', (event) => { + const message = JSON.parse(event.data); + if (message.id && pending.has(message.id)) { + pending.get(message.id)(message); + pending.delete(message.id); + } + }); + const send = (method, params = {}, sessionId) => + new Promise((resolveCall) => { + const callId = ++id; + pending.set(callId, resolveCall); + ws.send( + JSON.stringify({ + id: callId, + method, + params, + ...(sessionId ? { sessionId } : {}), + }), + ); + }); + + const created = await send('Target.createTarget', { url: 'about:blank' }); + if (!created.result) throw new Error('Target creation failed'); + const target = created.result.targetId; + const session = ( + await send('Target.attachToTarget', { targetId: target, flatten: true }) + ).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + await send( + 'Emulation.setDeviceMetricsOverride', + { width: 390, height: 844, deviceScaleFactor: 2, mobile: true }, + session, + ); + await send( + 'Emulation.setEmulatedMedia', + { features: [{ name: 'prefers-color-scheme', value: 'dark' }] }, + session, + ); + + const evaluate = async (expression) => { + const response = await send( + 'Runtime.evaluate', + { expression, returnByValue: true, awaitPromise: true }, + session, + ); + if (response.error) { + throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); + } + return response.result?.result?.value; + }; + const nodes = () => + evaluate(`[...document.querySelectorAll('flt-semantics')].map(x => { + const r = x.getBoundingClientRect(); + return { + label: x.getAttribute('aria-label'), + text: (x.innerText || '').trim(), + x: r.x, y: r.y, w: r.width, h: r.height, + }; + })`); + const findNode = async (name) => { + const all = await nodes(); + return all.find((node) => node.label === name || node.text === name); + }; + const requireNode = async (name) => { + const node = await findNode(name); + if (!node) { + const shown = (await nodes()) + .map((entry) => entry.label ?? entry.text) + .filter(Boolean); + throw new Error( + `Missing semantics ${JSON.stringify(name)}: ${JSON.stringify(shown)}`, + ); + } + return node; + }; + const click = async (name, { large = false } = {}) => { + const point = await evaluate(`(() => { + const wanted = ${JSON.stringify(name)}; + const large = ${large}; + const matches = [...document.querySelectorAll('flt-semantics')] + .map(x => { + const label = x.getAttribute('aria-label') || ''; + const text = (x.innerText || '').trim(); + const r = x.getBoundingClientRect(); + const labelHit = label.includes(wanted) ? 0 : 1; + return { x, label, text, labelHit, area: r.width * r.height }; + }) + .filter(x => large ? x.labelHit === 0 : (x.labelHit === 0 || x.text.includes(wanted))) + .sort(large + ? (a, b) => b.area - a.area + : (a, b) => a.labelHit - b.labelHit || a.area - b.area); + const node = matches[0]?.x; + if (!node) return null; + const r = node.getBoundingClientRect(); + return { + x: large ? r.x + Math.min(r.width / 2, 100) : r.x + r.width / 2, + y: r.y + r.height / 2, + }; + })()`); + if (!point) { + const shown = (await nodes()) + .map((entry) => entry.label ?? entry.text) + .filter(Boolean); + throw new Error( + `Could not find ${JSON.stringify(name)}: ${JSON.stringify(shown)}`, + ); + } + await send( + 'Input.dispatchMouseEvent', + { type: 'mousePressed', x: point.x, y: point.y, button: 'left', clickCount: 1 }, + session, + ); + await send( + 'Input.dispatchMouseEvent', + { type: 'mouseReleased', x: point.x, y: point.y, button: 'left', clickCount: 1 }, + session, + ); + await delay(700); + }; + // The first matching control in document order. A folded assistant turn can + // hold several `Reasoning` labels; the newest message renders first. + const clickFirst = async (name) => { + const node = (await nodes()).find( + (entry) => entry.label === name || entry.text === name, + ); + if (!node) { + const shown = (await nodes()) + .map((entry) => entry.label ?? entry.text) + .filter(Boolean); + throw new Error( + `Could not find ${JSON.stringify(name)}: ${JSON.stringify(shown)}`, + ); + } + const x = node.x + node.w / 2; + const y = node.y + node.h / 2; + for (const type of ['mousePressed', 'mouseReleased']) { + await send( + 'Input.dispatchMouseEvent', + { type, x, y, button: 'left', clickCount: 1 }, + session, + ); + } + await delay(700); + }; + const capture = async (name) => { + const data = ( + await send('Page.captureScreenshot', { format: 'png' }, session) + ).result.data; + const file = join(out, `${style}-${name}.png`); + await writeFile(file, Buffer.from(data, 'base64')); + evidence.captures.push(file); + return file; + }; + const ocr = async (path) => { + const { stdout } = await promisify(execFile)('tesseract', [path, 'stdout']); + return stdout.replace(/\s+/g, ' '); + }; + const assertOcr = async (path, text) => { + const read = await ocr(path); + if (!read.toLowerCase().includes(text.toLowerCase())) { + throw new Error( + `OCR of ${path} lacks ${JSON.stringify(text)}:\n${read.slice(0, 1600)}`, + ); + } + }; + + const hasText = async (fragment) => { + const all = await nodes(); + return all.some((node) => + `${node.label ?? ''} ${node.text ?? ''}` + .toLowerCase() + .includes(fragment.toLowerCase()), + ); + }; + + await send('Page.navigate', { url: `${origin}/` }, session); + await delay(3500); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(1200); + await waitFor( + async () => hasText('Probe conversation'), + 'session list semantics', + ); + + const list = await capture('list'); + await assertOcr(list, 'Probe conversation'); + await assertOcr(list, 'Another stored chat'); + if (!(await hasText('New chat'))) { + throw new Error('Embedded list lost its New chat action'); + } + if (!(await hasText('Refresh'))) { + throw new Error('Embedded list lost its Refresh action'); + } + evidence.checks.push({ + check: 'embedded list renders server rows and actions', + labels: (await nodes()) + .map((node) => node.label) + .filter(Boolean) + .slice(0, 20), + }); + + await click('Probe conversation', { large: true }); + await waitFor( + async () => Boolean(await findNode('Assistant message')), + 'thread semantics', + ); + for (const name of [ + 'User message', + 'Assistant message', + 'Reasoning', + 'shell', + ]) { + await requireNode(name); + } + const thread = await capture('thread'); + for (const text of [ + 'read-only message from the server', + 'stored assistant reply', + 'existing native message view', + 'Probe conversation', + ]) { + await assertOcr(thread, text); + } + const closed = await ocr(thread); + for (const hidden of [ + 'Reasoning stays behind', + 'NEWEST reasoning body', + ]) { + if (closed.toLowerCase().includes(hidden.toLowerCase())) { + throw new Error(`Collapsed disclosure leaked ${JSON.stringify(hidden)}`); + } + } + evidence.checks.push({ + check: 'actual stored message body renders in the thread', + style, + }); + + await delay(1500); + const live = await capture('live'); + await assertOcr(live, 'A live delta updated this thread'); + evidence.checks.push({ + check: 'a pushed chat_event delta updates the open thread', + style, + }); + + // Repro B: expand the newest reasoning, then load the one older page whose + // `has_more` is false, so the `Load older` child disappears. + await click('Reasoning'); + const expanded = await capture('expanded'); + await assertOcr(expanded, 'NEWEST reasoning body'); + + await click('Load older'); + await delay(1200); + const afterOlder = await capture('older'); + const afterOlderText = await ocr(afterOlder); + const newestKept = afterOlderText.includes('NEWEST reasoning body'); + const olderLeaked = afterOlderText.includes('OLDER reasoning body'); + const loadOlderGone = !(await findNode('Load older')); + evidence.observations = { + ...evidence.observations, + afterOlderRemovesControl: { newestKept, olderLeaked, loadOlderGone }, + }; + if (!newestKept) { + throw new Error( + `The newest open reasoning was lost after Load older:\n${afterOlderText.slice(0, 1600)}`, + ); + } + if (olderLeaked) { + throw new Error( + `The older reasoning stole the newest disclosure:\n${afterOlderText.slice(0, 1600)}`, + ); + } + if (!loadOlderGone) { + throw new Error('Load older stayed visible after has_more became false'); + } + await assertOcr(afterOlder, 'older stored message came from the opaque cursor page'); + await assertOcr(afterOlder, 'Older reply kept in order'); + evidence.checks.push({ + check: 'Load older keeps the open disclosure and renders the opaque page', + style, + }); + + // Repro A: the same action while the server still reports `has_more`, so the + // paging control remains in the indexed list. + await click(style === 'cupertino' ? 'Back' : 'Back to chats'); + await waitFor( + async () => hasText('Probe paging session'), + 'list after Back', + ); + await click('Probe paging session', { large: true }); + await waitFor( + async () => Boolean(await findNode('Assistant message')), + 'second thread semantics', + ); + await click('Reasoning'); + const moreExpanded = await capture('more-expanded'); + await assertOcr(moreExpanded, 'MORE NEWEST reasoning body'); + + await click('Load older'); + await delay(1200); + const moreAfterOlder = await capture('more-older'); + const moreAfterOlderText = await ocr(moreAfterOlder); + const moreNewestKept = moreAfterOlderText.includes('MORE NEWEST reasoning body'); + const moreOlderLeaked = moreAfterOlderText.includes('MORE OLDER reasoning body'); + const moreControlStays = Boolean(await findNode('Load older')); + evidence.observations.afterOlderKeepsControl = { + newestKept: moreNewestKept, + olderLeaked: moreOlderLeaked, + loadOlderPresent: moreControlStays, + }; + if (!moreNewestKept) { + throw new Error( + `The newest open reasoning was lost while has_more stayed true:\n${moreAfterOlderText.slice(0, 1600)}`, + ); + } + if (moreOlderLeaked) { + throw new Error( + `The older reasoning stole the newest disclosure while has_more stayed true:\n${moreAfterOlderText.slice(0, 1600)}`, + ); + } + if (!moreControlStays) { + throw new Error('Load older disappeared although has_more stayed true'); + } + evidence.checks.push({ + check: 'an open disclosure follows its part while paging keeps has_more', + style, + }); + + // New repro: the paged-history fixture's shape. Both pages hold only + // consecutive assistant messages, so an older page prepends into the single + // folded turn and changes its first message id. The row element must survive + // that identity change and keep the operator's open block. + for (const fold of [ + { + title: 'Probe assistant fold session', + tag: 'fold', + keepsControl: true, + }, + { + title: 'Probe assistant fold last page', + tag: 'fold-end', + keepsControl: false, + }, + ]) { + await click(style === 'cupertino' ? 'Back' : 'Back to chats'); + await waitFor( + async () => hasText(fold.title), + `list before ${fold.tag}`, + ); + await click(fold.title, { large: true }); + await waitFor( + async () => Boolean(await findNode('Assistant message')), + `${fold.tag} thread semantics`, + ); + await clickFirst('Reasoning'); + await delay(400); + const foldExpanded = await capture(`${fold.tag}-expanded`); + await assertOcr(foldExpanded, 'FOLD NEWEST reasoning body'); + + await click('Load older'); + await delay(1200); + const foldAfter = await capture(`${fold.tag}-older`); + const foldText = await ocr(foldAfter); + const foldNewestKept = foldText.includes('FOLD NEWEST reasoning body'); + const foldOlderLeaked = [ + 'FOLD SECOND reasoning body', + 'FOLD OLDEST reasoning body', + ].some((body) => foldText.includes(body)); + const foldControlStays = Boolean(await findNode('Load older')); + evidence.observations = { + ...evidence.observations, + [`${fold.tag}AfterOlder`]: { + newestKept: foldNewestKept, + olderLeaked: foldOlderLeaked, + loadOlderPresent: foldControlStays, + }, + }; + if (!foldNewestKept) { + throw new Error( + `The folded turn lost the open reasoning after Load older:\n${foldText.slice(0, 1600)}`, + ); + } + if (foldOlderLeaked) { + throw new Error( + `An older block in the folded turn opened itself:\n${foldText.slice(0, 1600)}`, + ); + } + if (foldControlStays !== fold.keepsControl) { + throw new Error( + `Load older presence ${foldControlStays} did not match has_more ${fold.keepsControl}`, + ); + } + evidence.checks.push({ + check: + 'an open disclosure survives paging inside a folded assistant turn', + style, + case: fold.tag, + }); + } + + const report = JSON.stringify(evidence, null, 2); + await writeFile(join(out, `${style}-evidence.json`), report); + console.log(report); +} finally { + ws?.close(); + chrome.kill(); + server.close(); + for (let attempt = 0; attempt < 10; attempt++) { + try { + await rm(profile, { recursive: true, force: true }); + break; + } catch { + await delay(200); + } + } +} diff --git a/app/tool/retry_wiring_probe.dart b/app/tool/retry_wiring_probe.dart new file mode 100644 index 00000000..8ec171c2 --- /dev/null +++ b/app/tool/retry_wiring_probe.dart @@ -0,0 +1,22 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:pipelines_app/application/bootstrap.dart'; + +/// Browser acceptance entrypoint for the run-retry wiring probe. +/// +/// This is the normal app composition; the deterministic failed run, retry +/// replies and new-run details come from the isolated loopback fixture in +/// `tool/retry_wiring_probe.mjs`, never from app-side fake data. The zone and +/// `FlutterError` hooks only report probe failures to the driver; they do not +/// alter composition or behavior. +void main() { + FlutterError.onError = (details) { + debugPrint('FLUTTER ERROR: ${details.exceptionAsString()}'); + FlutterError.presentError(details); + }; + runZonedGuarded( + runPipelinesApp, + (error, stack) => debugPrint('ZONE ERROR: $error\n$stack'), + ); +} diff --git a/app/tool/retry_wiring_probe.mjs b/app/tool/retry_wiring_probe.mjs new file mode 100644 index 00000000..a29a76cb --- /dev/null +++ b/app/tool/retry_wiring_probe.mjs @@ -0,0 +1,772 @@ +import { spawn, execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import { mkdtemp, mkdir, rm, writeFile, readFile, realpath, stat } from 'node:fs/promises'; +import { once } from 'node:events'; +import { createServer } from 'node:http'; +import { createHash } from 'node:crypto'; +import { tmpdir } from 'node:os'; +import { extname, join, resolve, sep } from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; + +// Real-browser acceptance for the run-retry wiring. +// +// Usage (from app/): +// flutter build web --target=tool/retry_wiring_probe.dart -o build/retry_probe_web +// OPENCODE_ARTIFACT_DIR= node tool/retry_wiring_probe.mjs build/retry_probe_web +// +// Environment: +// OPENCODE_ARTIFACT_DIR required; receives the PNG captures +// PROBE_THEME `dark` (default) or `light` +// CHROME_PATH Chrome binary; defaults to the macOS install +// TESSERACT OCR binary; defaults to `tesseract` on PATH +// +// The fixture serves the real bundle over loopback and answers the same +// websocket protocol as the app server: one stopped failed run, `get_run`, +// and `retry_run`. It records the exact retry payload, replies with the new +// run's `run_started` detail and pushes the matching compact run event, so the +// real app must open only the id the server names. Chrome is required; OCR +// checks cover the canvas-rendered titles. +const output = process.env.OPENCODE_ARTIFACT_DIR; +if (!output) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures'); +await mkdir(output, { recursive: true }); +const theme = process.env.PROBE_THEME === 'light' ? 'light' : 'dark'; +const chromePath = + process.env.CHROME_PATH ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +const tesseract = process.env.TESSERACT ?? 'tesseract'; +const root = await realpath(process.argv[2] ?? 'build/retry_probe_web'); + +const SOURCE_ID = 7; +const RUN = { + id: SOURCE_ID, + pipeline_id: 3, + title: 'Fixture failed run', + name: 'fixture-retry', + version: 2, + status: 'failed', + executing: false, + created_at: '2026-10-21T12:00:00Z', + finished_at: '2026-10-21T12:04:00Z', +}; +const retries = []; +const counters = { listRuns: 0, getRun: 0 }; +let nextRunId = SOURCE_ID + 1; +const runs = new Map([[SOURCE_ID, { ...RUN }]]); + +function runRow(run) { + return { + id: run.id, + pipeline_id: run.pipeline_id, + title: run.title, + name: run.name, + version: run.version, + status: run.status, + executing: run.executing, + created_at: run.created_at, + finished_at: run.finished_at, + }; +} + +function runDetail(run) { + return { + ...runRow(run), + retry_of: run.retry_of, + input: { prompt: ' fixture prompt with spaces ' }, + steps: [ + { stage: 'build', sequence: 3, status: 'completed', outcome: 'success' }, + ], + }; +} + +function newRetry(mode) { + const id = nextRunId++; + const label = mode === 'restart' ? 'Restart' : 'Resume'; + const run = { + id, + pipeline_id: RUN.pipeline_id, + title: `${label} of ${SOURCE_ID}`, + name: RUN.name, + version: RUN.version, + status: 'running', + executing: true, + retry_of: SOURCE_ID, + created_at: '2026-10-21T12:05:00Z', + finished_at: '', + }; + runs.set(id, run); + return run; +} + +const MIME = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.wasm': 'application/wasm', + '.css': 'text/css; charset=utf-8', + '.png': 'image/png', + '.svg': 'image/svg+xml', + '.ico': 'image/x-icon', + '.ttf': 'font/ttf', + '.otf': 'font/otf', + '.woff': 'font/woff', + '.woff2': 'font/woff2', +}; + +function accept(key) { + return createHash('sha1') + .update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`) + .digest('base64'); +} + +function frame(opcode, payload) { + const length = payload.length; + let header; + if (length < 126) { + header = Buffer.from([0x80 | opcode, length]); + } else if (length < 65536) { + header = Buffer.alloc(4); + header[0] = 0x80 | opcode; + header[1] = 126; + header.writeUInt16BE(length, 2); + } else { + header = Buffer.alloc(10); + header[0] = 0x80 | opcode; + header[1] = 127; + header.writeBigUInt64BE(BigInt(length), 2); + } + return Buffer.concat([header, payload]); +} + +class Connection { + constructor(socket) { + this.socket = socket; + this.buffer = Buffer.alloc(0); + } + + push(chunk) { + if (chunk?.length) this.buffer = Buffer.concat([this.buffer, chunk]); + while (this.buffer.length >= 2) { + const first = this.buffer[0]; + const second = this.buffer[1]; + const opcode = first & 0x0f; + let length = second & 0x7f; + let offset = 2; + if (length === 126) { + if (this.buffer.length < 4) return; + length = this.buffer.readUInt16BE(2); + offset = 4; + } else if (length === 127) { + if (this.buffer.length < 10) return; + length = Number(this.buffer.readBigUInt64BE(2)); + offset = 10; + } + const masked = (second & 0x80) !== 0; + const maskOffset = offset; + if (masked) { + if (this.buffer.length < offset + 4) return; + offset += 4; + } + if (this.buffer.length < offset + length) return; + let payload = Buffer.from(this.buffer.subarray(offset, offset + length)); + if (masked) { + const mask = this.buffer.subarray(maskOffset, maskOffset + 4); + for (let index = 0; index < payload.length; index++) { + payload[index] ^= mask[index % 4]; + } + } + this.buffer = this.buffer.subarray(offset + length); + if (opcode === 0x8) return this.close(); + if (opcode === 0x9) { + this.socket.write(frame(0x0a, payload)); + continue; + } + if (opcode !== 0x1) continue; + let request; + try { + request = JSON.parse(payload.toString('utf8')); + } catch { + continue; + } + this.message(request); + } + } + + message(request) { + if (request.type === 'subscribe' || request.type === 'unsubscribe') return; + if (request.type === 'ping') { + this.send({ id: request.id, type: 'pong', build: { version: 'Retry fixture' } }); + return; + } + if (request.type === 'list_runs') { + counters.listRuns++; + this.send({ + id: request.id, + type: 'runs', + runs: [...runs.values()].map(runRow), + usage: null, + }); + return; + } + if (request.type === 'get_run') { + counters.getRun++; + const run = runs.get(request.run_id); + if (!run) { + this.send({ id: request.id, type: 'error', error: `no run ${request.run_id}` }); + return; + } + this.send({ id: request.id, type: 'run', run_detail: runDetail(run) }); + return; + } + if (request.type === 'retry_run') { + const record = { + run_id: request.run_id, + request_key: request.request_key, + keys: Object.keys(request).filter((key) => !['type', 'id'].includes(key)).sort(), + }; + if (request.retry_mode != null) record.retry_mode = request.retry_mode; + retries.push(record); + const source = runs.get(request.run_id); + if (!source || source.status !== 'failed' || source.executing) { + this.send({ id: request.id, type: 'error', error: 'only failed stopped runs can be retried' }); + return; + } + if (!request.request_key) { + this.send({ id: request.id, type: 'error', error: 'retry requires an idempotency request key' }); + return; + } + const created = newRetry(request.retry_mode === 'restart' ? 'restart' : 'resume'); + this.send({ id: request.id, type: 'run_started', run_detail: runDetail(created) }); + // The real server also pushes the new run to the compact watch; that row + // is what makes the retried run appear in the list after Back. + this.send({ + type: 'run_event', + run_id: created.id, + pipeline_id: created.pipeline_id, + name: created.name, + title: created.title, + version: created.version, + status: created.status, + created_at: created.created_at, + finished_at: '', + }); + return; + } + this.send({ + id: request.id, + type: 'error', + error: `Fixture does not implement ${request.type}`, + }); + } + + send(value) { + if (!this.socket.destroyed) { + this.socket.write(frame(0x1, Buffer.from(JSON.stringify(value)))); + } + } + + close() { + if (!this.socket.destroyed) this.socket.end(); + } +} + +async function staticFile(base, pathname, res) { + let file = resolve(base, `.${pathname}`); + if (file !== base && !file.startsWith(base + sep)) { + res.writeHead(403).end(); + return; + } + try { + if ((await stat(file)).isDirectory()) file = join(file, 'index.html'); + } catch { + if (extname(pathname)) { + res.writeHead(404).end('not found'); + return; + } + file = join(base, 'index.html'); + } + try { + const body = await readFile(file); + res + .writeHead(200, { + 'content-type': MIME[extname(file)] ?? 'application/octet-stream', + 'cache-control': 'no-store', + }) + .end(body); + } catch { + res.writeHead(404).end('not found'); + } +} + +const sockets = new Set(); +const server = createServer(async (req, res) => { + const pathname = new URL(req.url, 'http://fixture').pathname; + if (pathname === '/fixture/state') { + res + .writeHead(200, { 'content-type': 'application/json' }) + .end(JSON.stringify({ retries, runs: [...runs.values()], ...counters })); + return; + } + if (req.method !== 'GET' && req.method !== 'HEAD') { + res.writeHead(405).end(); + return; + } + await staticFile(root, pathname, res); +}); +server.on('upgrade', (req, socket, head) => { + const url = new URL(req.url, 'http://fixture'); + if ( + url.pathname !== '/connect' || + req.headers.upgrade?.toLowerCase() !== 'websocket' || + !req.headers['sec-websocket-key'] + ) { + socket.end('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n'); + return; + } + socket.write( + 'HTTP/1.1 101 Switching Protocols\r\n' + + 'Upgrade: websocket\r\n' + + 'Connection: Upgrade\r\n' + + `Sec-WebSocket-Accept: ${accept(req.headers['sec-websocket-key'])}\r\n\r\n`, + ); + const connection = new Connection(socket); + socket.on('data', (chunk) => connection.push(chunk)); + socket.on('error', () => socket.destroy()); + sockets.add(socket); + socket.on('close', () => sockets.delete(socket)); + connection.push(head); +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const fixtureUrl = `http://127.0.0.1:${server.address().port}`; + +const profile = await mkdtemp(join(tmpdir(), 'r2-title-chrome-')); +const chrome = spawn( + chromePath, + [ + '--headless=new', + '--no-first-run', + '--no-default-browser-check', + '--disable-gpu', + '--remote-debugging-port=0', + `--user-data-dir=${profile}`, + 'about:blank', + ], + { stdio: ['ignore', 'ignore', 'pipe'] }, +); +let stderr = ''; +chrome.stderr.on('data', (data) => { + stderr += data; +}); + +async function waitFor(check, label, attempts = 160) { + for (let attempt = 0; attempt < attempts; attempt++) { + const value = await check(); + if (value) return value; + await delay(100); + } + throw new Error(`Timed out waiting for ${label}\n${stderr.slice(-1200)}`); +} + +let ws; +try { + const endpoint = await waitFor( + () => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1], + 'Chrome DevTools', + ); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', (event) => { + const message = JSON.parse(event.data); + if (message.method === 'Runtime.exceptionThrown') { + console.error('PAGE EXCEPTION', JSON.stringify(message.params?.exceptionDetails)); + } + if (message.method === 'Runtime.consoleAPICalled') { + const values = (message.params?.args ?? []).map((arg) => arg.value ?? arg.description); + if (values.some((value) => String(value).includes('ERROR'))) { + console.error('PAGE CONSOLE', values.join(' ')); + } + } + if (message.id && pending.has(message.id)) { + pending.get(message.id)(message); + pending.delete(message.id); + } + }); + const send = (method, params = {}, sessionId) => + new Promise((resolveCall) => { + const callId = ++id; + pending.set(callId, resolveCall); + ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + + const target = (await send('Target.createTarget', { url: 'about:blank' })).result.targetId; + const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + + const evaluate = async (expression) => { + const response = await send( + 'Runtime.evaluate', + { expression, returnByValue: true, awaitPromise: true }, + session, + ); + if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); + if (response.result?.exceptionDetails) { + throw new Error(`Page exception: ${JSON.stringify(response.result.exceptionDetails)}`); + } + return response.result?.result?.value; + }; + + const enableSemantics = async () => { + await waitFor( + () => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"), + 'Flutter semantics placeholder', + ); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(700); + }; + + const semanticText = () => + evaluate(`(() => { + const chunks = []; + for (const el of document.querySelectorAll('flt-semantics')) { + const label = el.getAttribute('aria-label'); + if (label) chunks.push(label); + const value = el.getAttribute('aria-valuetext'); + if (value) chunks.push(value); + if (el.value) chunks.push(String(el.value)); + if (!el.children.length && el.innerText) chunks.push(el.innerText); + } + for (const el of document.querySelectorAll('input, textarea')) { + const label = el.getAttribute('aria-label'); + if (label) chunks.push(label); + if (el.value) chunks.push(String(el.value)); + } + if (document.body?.innerText) chunks.push(document.body.innerText); + return [...new Set(chunks)].join('\\n'); + })()`); + + const assertBody = async (text) => { + try { + await waitFor( + async () => (await semanticText()).includes(text), + `body to contain ${JSON.stringify(text)}`, + ); + } catch (error) { + throw new Error(`${error.message}\nBody now:\n${(await semanticText()).slice(0, 3000)}`); + } + }; + + // The action row once had no Wrap spacing, so the outlined Rename border met + // the filled Retry button at 320 px. Measure the real controls' bounds; a + // screenshot alone cannot prove the 8 dp convention was restored. + const actionGap = async (check) => { + const rects = await evaluate(`(() => { + const found = {}; + for (const el of document.querySelectorAll('flt-semantics')) { + const label = (el.getAttribute('aria-label') || el.innerText || '').trim(); + if (label !== 'Rename' && label !== 'Retry') continue; + const r = el.getBoundingClientRect(); + const area = r.width * r.height; + if (!found[label] || area > found[label].area) { + found[label] = { left: r.left, right: r.right, top: r.top, bottom: r.bottom, area }; + } + } + return found; + })()`); + if (!rects.Rename || !rects.Retry) { + throw new Error(`${check}: action bounds missing ${JSON.stringify(rects)}`); + } + const sameRow = + Math.min(rects.Rename.bottom, rects.Retry.bottom) > + Math.max(rects.Rename.top, rects.Retry.top); + const gap = sameRow + ? rects.Retry.left - rects.Rename.right + : rects.Retry.top - rects.Rename.bottom; + const minimum = sameRow ? 8 : 4; + if (gap < minimum - 0.5) { + throw new Error( + `${check}: Rename/Retry are ${gap.toFixed(3)} px apart, expected at least ${minimum} dp`, + ); + } + return { + check: `${check} actions stay ${minimum} dp apart`, + gap: Number(gap.toFixed(3)), + sameRow, + }; + }; + + const clickText = async (text, { last = false } = {}) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(text)}; + const all = [...document.querySelectorAll('flt-semantics')].filter((el) => { + const label = (el.getAttribute('aria-label') || el.innerText || '').trim(); + return label === wanted; + }); + const candidates = all.filter((el) => + ['button', 'tab', 'link', 'checkbox', 'menuitem'].includes(el.getAttribute('role')), + ); + const pool = candidates.length ? candidates : all; + // A modal route is appended after the page: choosing the last match + // targets the dialog confirm instead of the page action underneath. + const target = ${last ? 'pool.at(-1)' : 'pool[0]'}; + if (!target) return false; + target.click(); + return true; + })()`); + if (!clicked) { + const labels = await evaluate(`[...document.querySelectorAll('flt-semantics')] + .map((el) => (el.getAttribute('aria-label') || el.innerText || '').trim()).filter(Boolean)`); + throw new Error(`Could not click ${JSON.stringify(text)}. Labels: ${JSON.stringify(labels)}`); + } + await delay(400); + }; + + const clickContains = async (text) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(text)}; + const all = [...document.querySelectorAll('flt-semantics')].filter((el) => { + const label = (el.getAttribute('aria-label') || el.innerText || '').trim(); + return label.includes(wanted); + }); + const target = all.find((el) => + ['button', 'link', 'tab'].includes(el.getAttribute('role')), + ) ?? all.at(-1); + if (!target) return false; + target.click(); + return true; + })()`); + if (!clicked) throw new Error(`Could not click a row containing ${JSON.stringify(text)}`); + await delay(400); + }; + + const capture = async (name) => { + const data = (await send('Page.captureScreenshot', { format: 'png' }, session)).result.data; + const path = join(output, `${name}.png`); + await writeFile(path, Buffer.from(data, 'base64')); + return path; + }; + + const ocr = async (path) => + (await promisify(execFile)(tesseract, [path, 'stdout'])).stdout; + + const assertOcr = async (path, text) => { + const read = await ocr(path); + if (!read.toLowerCase().includes(text.toLowerCase())) { + throw new Error(`OCR of ${path} lacks ${JSON.stringify(text)}:\n${read.slice(0, 2000)}`); + } + }; + + const state = async () => (await (await fetch(`${fixtureUrl}/fixture/state`)).json()); + + const setView = async ({ width, height, deviceScaleFactor = 1 }) => { + await send( + 'Emulation.setDeviceMetricsOverride', + { width, height, deviceScaleFactor, mobile: width < 600 }, + session, + ); + await send( + 'Emulation.setEmulatedMedia', + { features: [{ name: 'prefers-color-scheme', value: theme }] }, + session, + ); + await delay(400); + }; + + const retryPromptOpen = async () => + (await semanticText()).includes(`Retry run ${SOURCE_ID}?`); + const restartPromptOpen = async () => + (await semanticText()).includes(`Restart run ${SOURCE_ID}?`); + + const assertPayload = (record, { restart, check }) => { + if (!record) throw new Error(`${check}: the server recorded no retry`); + const keys = restart + ? ['request_key', 'retry_mode', 'run_id'] + : ['request_key', 'run_id']; + if (JSON.stringify(record.keys) !== JSON.stringify(keys)) { + throw new Error(`${check}: unexpected request fields ${JSON.stringify(record)}`); + } + if (record.run_id !== SOURCE_ID) { + throw new Error(`${check}: wrong run id ${JSON.stringify(record)}`); + } + if (!String(record.request_key).startsWith(`app-retry-${SOURCE_ID}-`)) { + throw new Error(`${check}: wrong request key ${JSON.stringify(record)}`); + } + if (String(record.request_key).length > 128) { + throw new Error(`${check}: request key too long ${JSON.stringify(record)}`); + } + if (restart && record.retry_mode !== 'restart') { + throw new Error(`${check}: restart mode missing ${JSON.stringify(record)}`); + } + if (!restart && record.retry_mode != null) { + throw new Error(`${check}: resume must omit retry_mode ${JSON.stringify(record)}`); + } + return record; + }; + + const captures = []; + const checks = []; + + await setView({ width: 320, height: 480, deviceScaleFactor: 2 }); + if ( + !(await evaluate(`matchMedia('(prefers-color-scheme: ${theme})').matches`)) + ) { + throw new Error(`The fixture host is not in ${theme} mode`); + } + + const open = async (id, expectedTitle) => { + const navigation = await send( + 'Page.navigate', + { url: `${fixtureUrl}/runs/${id}` }, + session, + ); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + await enableSemantics(); + await assertBody(expectedTitle); + if ((await evaluate('location.pathname')) !== `/runs/${id}`) { + throw new Error(`Deep link moved to ${await evaluate('location.pathname')}`); + } + }; + + const waitNewRun = async (id, title) => { + await waitFor( + async () => (await evaluate('location.pathname')) === `/runs/${id}`, + `the route to open run ${id}`, + ); + await assertBody(title); + await assertBody('Original prompt'); + }; + + // Cupertino host (macOS browser), 320 CSS px at DPR 2 in dark mode. + await open(SOURCE_ID, 'Fixture failed run'); + await assertBody('Rename'); + await assertBody('Retry'); + captures.push(await capture(`r2c-retry-cupertino-${theme}-failed`)); + await assertOcr(captures.at(-1), 'Fixture failed run'); + checks.push(await actionGap('Cupertino')); + checks.push({ check: `Cupertino ${theme} 320px detail offers Retry`, path: await evaluate('location.pathname') }); + + await clickText('Retry'); + await waitFor(retryPromptOpen, 'the retry prompt'); + await assertBody('Only failed runs can be retried'); + captures.push(await capture(`r2c-retry-cupertino-${theme}-prompt`)); + await assertOcr(captures.at(-1), 'Retry run 7?'); + + await clickText('Keep'); + await waitFor(async () => !(await retryPromptOpen()), 'the closed retry prompt'); + if ((await state()).retries.length !== 0) { + throw new Error('Keep sent retry_run'); + } + checks.push({ check: 'Cupertino Keep sent nothing', sent: 0 }); + captures.push(await capture(`r2c-retry-cupertino-${theme}-kept`)); + + // Restart: the browser-only second confirmation, then the server-named run. + await clickText('Retry'); + await waitFor(retryPromptOpen, 'the retry prompt again'); + await clickText('Restart from start'); + await waitFor(restartPromptOpen, 'the restart prompt'); + await assertBody('replays the whole pipeline'); + captures.push(await capture(`r2c-retry-cupertino-${theme}-restart-prompt`)); + await clickText('Restart from start', { last: true }); + try { + await waitFor(async () => (await state()).retries.length === 1, 'the first retry request'); + } catch (error) { + console.error('STATE', JSON.stringify(await state())); + console.error('TEXT', (await semanticText()).slice(0, 2000)); + await capture('r2c-retry-debug'); + throw error; + } + const restart = assertPayload((await state()).retries[0], { + restart: true, + check: 'Cupertino restart', + }); + await waitNewRun(SOURCE_ID + 1, 'Restart of 7'); + captures.push(await capture(`r2c-retry-cupertino-${theme}-restart-run`)); + await assertOcr(captures.at(-1), 'Restart of 7'); + checks.push({ check: 'Cupertino restart opened only the server-named run', restart, path: await evaluate('location.pathname') }); + + await clickText('Back'); + await assertBody('Fixture failed run'); + await assertBody('Restart of 7'); + captures.push(await capture(`r2c-retry-cupertino-${theme}-list`)); + await assertOcr(captures.at(-1), 'Restart of 7'); + + // Resume after returning to the still-failed source run. + await clickContains('Fixture failed run'); + await waitFor( + async () => (await evaluate('location.pathname')) === `/runs/${SOURCE_ID}`, + 'the source run again', + ); + await assertBody('Retry'); + await clickText('Retry'); + await waitFor(retryPromptOpen, 'the resume prompt'); + await clickText('Retry', { last: true }); + await waitFor(async () => (await state()).retries.length === 2, 'the resume request'); + const resume = assertPayload((await state()).retries[1], { + restart: false, + check: 'Cupertino resume', + }); + await waitNewRun(SOURCE_ID + 2, 'Resume of 7'); + captures.push(await capture(`r2c-retry-cupertino-${theme}-resume-run`)); + await assertOcr(captures.at(-1), 'Resume of 7'); + checks.push({ check: 'Cupertino resume omitted retry_mode and opened the reply run', resume, path: await evaluate('location.pathname') }); + + // Material host: the same deep link, shared gateway and normal app build. + await send( + 'Emulation.setUserAgentOverride', + { + userAgent: + 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 ' + + '(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36', + platform: 'Linux x86_64', + }, + session, + ); + await open(SOURCE_ID, 'Fixture failed run'); + await assertBody('Rename'); + await assertBody('Retry'); + captures.push(await capture(`r2c-retry-material-${theme}-failed`)); + await assertOcr(captures.at(-1), 'Fixture failed run'); + checks.push(await actionGap('Material')); + checks.push({ check: `Material ${theme} 320px detail offers Retry`, path: await evaluate('location.pathname') }); + + await clickText('Retry'); + await waitFor(retryPromptOpen, 'the material retry prompt'); + captures.push(await capture(`r2c-retry-material-${theme}-prompt`)); + await clickText('Keep'); + await waitFor(async () => !(await retryPromptOpen()), 'the closed material prompt'); + if ((await state()).retries.length !== 2) { + throw new Error('Material Keep sent retry_run'); + } + checks.push({ check: 'Material Keep sent nothing', sent: 0 }); + + await clickText('Retry'); + await waitFor(retryPromptOpen, 'the material resume prompt'); + await clickText('Retry', { last: true }); + await waitFor(async () => (await state()).retries.length === 3, 'the material retry request'); + const material = assertPayload((await state()).retries[2], { + restart: false, + check: 'Material resume', + }); + await waitNewRun(SOURCE_ID + 3, 'Resume of 7'); + captures.push(await capture(`r2c-retry-material-${theme}-run`)); + await assertOcr(captures.at(-1), 'Resume of 7'); + checks.push({ check: 'Material resume sent the exact payload and opened the reply run', material, path: await evaluate('location.pathname') }); + + const finalState = await state(); + if (finalState.retries.length !== 3) { + throw new Error(`Expected three retry requests, saw ${JSON.stringify(finalState.retries)}`); + } + if (finalState.runs.filter((run) => run.id !== SOURCE_ID).length !== 3) { + throw new Error(`Expected three server-created runs, saw ${JSON.stringify(finalState.runs)}`); + } + console.log(JSON.stringify({ ok: true, fixture: fixtureUrl, checks, captures }, null, 2)); +} finally { + ws?.close(); + for (const socket of sockets) socket.destroy(); + await new Promise((resolveClose) => server.close(resolveClose)); + chrome.kill('SIGTERM'); + await Promise.race([once(chrome, 'exit'), delay(3000)]); + await rm(profile, { recursive: true, force: true }); +} diff --git a/app/tool/runs_probe.mjs b/app/tool/runs_probe.mjs index 846cc110..e5bc3635 100644 --- a/app/tool/runs_probe.mjs +++ b/app/tool/runs_probe.mjs @@ -260,35 +260,75 @@ try { await assertBody('Original prompt'); await assertBody('Timeline'); await assertBody('build · visit 3'); - captures.push(await capture('i1-runs-phone-detail')); - await assertOcr(captures[5], 'fixture prompt with spaces'); + const detailCapture = await capture('i1-runs-phone-detail'); + captures.push(detailCapture); + await assertOcr(detailCapture, 'fixture prompt with spaces'); + + // The recorded Changes action opens the landed viewer for this run's steps: + // the recorded file, its rendered diff, and back to the same detail. + await clickText('Changes'); + await assertBody('1 file changed'); + await assertBody('lib/features/fixture.dart'); + captures.push(await capture('changes-phone-list')); + await clickText('lib/features/fixture.dart', { contains: true }); + await assertBody('Rendered'); + await assertBody('added fixture line'); + await assertBody('removed fixture line'); + captures.push(await capture('changes-phone-diff')); + await clickText('Close diff'); + await assertBody('lib/features/fixture.dart'); + await delay(600); + await clickText('Back', { contains: true }); + await assertBody('Original prompt'); + + // The recorded artifacts action lists each visit's own files, keeps a + // repeated filename distinct, and shows the selected record's facts. + await clickText('Artifacts'); + await assertBody('build · visit 1'); + await assertBody('test · visit 1'); + await assertBody('build-report.html'); + await assertBody('result.csv'); + captures.push(await capture('artifacts-phone-list')); + await delay(500); + await clickText('result.csv', { contains: true }); + await assertBody('text/csv'); + await assertBody('4.0'); + captures.push(await capture('artifacts-phone-selected')); + await clickText('Close'); + await delay(400); + await clickText('Back', { contains: true }); + await assertBody('Original prompt'); await setSize(1280, 800); await assertBody('Original prompt'); - captures.push(await capture('i1-runs-desktop-detail')); - await assertOcr(captures[6], 'fixture prompt with spaces'); + const desktopDetail = await capture('i1-runs-desktop-detail'); + captures.push(desktopDetail); + await assertOcr(desktopDetail, 'fixture prompt with spaces'); await setSize(390, 844); await clickText('Input'); await wheel(250); await delay(300); - captures.push(await capture('i1-runs-phone-detail-input')); - await assertOcr(captures[7], 'input payload'); + const inputCapture = await capture('i1-runs-phone-detail-input'); + captures.push(inputCapture); + await assertOcr(inputCapture, 'input payload'); await scrollUntil('Output'); await clickText('Output'); await wheel(250); await delay(300); - captures.push(await capture('i1-runs-phone-detail-output')); - await assertOcr(captures[8], 'answer'); + const outputCapture = await capture('i1-runs-phone-detail-output'); + captures.push(outputCapture); + await assertOcr(outputCapture, 'answer'); await scrollUntil('Metrics'); await clickText('Metrics'); await wheel(300); await delay(300); - captures.push(await capture('i1-runs-phone-detail-metrics')); - await assertOcr(captures[9], 'Total tokens'); - await assertOcr(captures[9], 'Reported cost'); + const metricsCapture = await capture('i1-runs-phone-detail-metrics'); + captures.push(metricsCapture); + await assertOcr(metricsCapture, 'Total tokens'); + await assertOcr(metricsCapture, 'Reported cost'); // Browser Back/Forward move between the in-app routes, not out of the app. const path = () => evaluate('location.pathname'); @@ -305,8 +345,9 @@ try { async () => (await semanticText()).includes('Fixture live run'), 'browser Back to the runs list', ); - captures.push(await capture('i1-runs-phone-browser-back-list')); - await assertOcr(captures[10], 'Fixture live run'); + const backListCapture = await capture('i1-runs-phone-browser-back-list'); + captures.push(backListCapture); + await assertOcr(backListCapture, 'Fixture live run'); await evaluate('history.forward()'); await waitFor( @@ -333,8 +374,9 @@ try { if (duringDrop.includes(raw)) throw new Error(`Raw transport text shown: ${raw}`); } if ((await path()) !== '/runs/1') throw new Error(`Drop moved the URL to ${await path()}`); - captures.push(await capture('i1-reconnect-detail-retained-phone')); - await assertOcr(captures[13], 'Original prompt'); + const retainedCapture = await capture('i1-reconnect-detail-retained-phone'); + captures.push(retainedCapture); + await assertOcr(retainedCapture, 'Original prompt'); // Accepting again plus Retry restores the same detail without a remount. const accepted = await fetch(`${fixture.url}/fixture/accept`, { method: 'POST' }); @@ -359,12 +401,13 @@ try { for (const raw of ['WebSocketException', 'WebSocketChannelException', 'Failed to connect']) { if (gate.includes(raw)) throw new Error(`Gate printed raw transport text: ${raw}`); } - captures.push(await capture('i1-gate-unavailable-friendly-phone')); + const gateCapture = await capture('i1-gate-unavailable-friendly-phone'); + captures.push(gateCapture); await delay(1500); if (!(await semanticText()).includes('Pipelines server unavailable')) { throw new Error('Gate left the unavailable state while retrying'); } - await assertOcr(captures[15], 'Pipelines server unavailable'); + await assertOcr(gateCapture, 'Pipelines server unavailable'); await fetch(`${fixture.url}/fixture/accept`, { method: 'POST' }); await clickText('Retry'); @@ -427,6 +470,28 @@ try { } captures.push(await capture('settings-material-registered-phone')); + // The registered Chat destination opens a real conversation over the shared + // socket: list row -> session route -> stored turn, then Back to the list. + await clickText('Chat'); + await assertBody('Probe conversation'); + captures.push(await capture('chat-material-list')); + await clickText('Probe conversation', { contains: true }); + await assertBody('User message'); + await assertBody('Assistant message'); + if ((await path()) !== '/chat/ses_probechat') { + throw new Error(`Chat selection did not update the route: ${await path()}`); + } + await delay(900); + const threadCapture = await capture('chat-material-thread'); + captures.push(threadCapture); + await assertOcr(threadCapture, 'Read-only probe question.'); + await assertOcr(threadCapture, 'Stored probe answer.'); + await clickText('Back', { contains: true }); + await assertBody('Probe conversation'); + if ((await path()) !== '/chat') { + throw new Error(`Chat Back left the route at ${await path()}`); + } + await clickText('Runs'); await clickText('Fixture cancel run', { contains: true }); await assertBody('Original prompt'); diff --git a/app/tool/runs_probe_server.mjs b/app/tool/runs_probe_server.mjs index b9ece509..c9fcbe61 100644 --- a/app/tool/runs_probe_server.mjs +++ b/app/tool/runs_probe_server.mjs @@ -110,6 +110,34 @@ function detail(id, live, canceled = false) { status: 'completed', outcome: 'success', target: '#success', + file_changes: { + status: 'complete', + scope: 'Git tracked and nonignored files in the run directory', + files: [ + { + path: 'lib/features/fixture.dart', + kind: 'modified', + patch: + '--- a/lib/features/fixture.dart\n' + + '+++ b/lib/features/fixture.dart\n' + + '@@ -1,2 +1,2 @@\n' + + ' context line\n' + + '-removed fixture line\n' + + '+added fixture line\n', + }, + ], + skipped: 0, + omitted: 0, + diagnostic: '', + }, + artifacts: [ + { + name: 'build-report.html', + size_bytes: 2048, + content_type: 'text/html; charset=utf-8', + url: '/artifacts/1/3/build-report.html', + }, + ], }, { stage: 'test', @@ -117,6 +145,14 @@ function detail(id, live, canceled = false) { status: status === 'failed' ? 'failed' : 'completed', outcome: status === 'failed' ? 'failure' : 'success', target: status === 'failed' ? '#failure' : '#success', + artifacts: [ + { + name: 'result.csv', + size_bytes: 4096, + content_type: 'text/csv', + url: '/artifacts/1/4/result.csv', + }, + ], }, ], }; @@ -288,6 +324,15 @@ export async function startFixture({ root }) { const cancelRequests = []; let decisionAccepted = false; const decisionRequests = []; + let chatSubscribed = 0; + let chatHistory = 0; + const CHAT_SESSION = { + id: 'ses_probechat', + title: 'Probe conversation', + kind: 'operator', + directory: '/srv/probe', + updated_at: '2026-10-21T12:00:00Z', + }; const dropConnections = () => { for (const connection of connections) connection.close(); @@ -336,6 +381,8 @@ export async function startFixture({ root }) { getRun, cancelRequests, decisionRequests, + chatSubscribed, + chatHistory, })); return; } @@ -427,6 +474,32 @@ export async function startFixture({ root }) { client.send({ id: request.id, type: 'run', run_detail: humanDetail(true) }); return; } + if (request.type === 'chat_sessions') { + client.send({ id: request.id, type: 'chat_sessions', + chat_sessions: [CHAT_SESSION] }); + return; + } + if (request.type === 'chat_subscribe') { + chatSubscribed++; + client.send({ id: request.id, type: 'chat_subscribe' }); + return; + } + if (request.type === 'chat_messages') { + chatHistory++; + client.send({ + id: request.id, type: 'chat_history', + chat_history: { + messages: [ + { id: 'm1', session_id: CHAT_SESSION.id, role: 'user', + parts: [{ type: 'text', text: 'Read-only probe question.' }] }, + { id: 'm2', session_id: CHAT_SESSION.id, role: 'assistant', + parts: [{ type: 'text', text: 'Stored probe answer.' }] }, + ], + next_cursor: '', has_more: false, + }, + }); + return; + } client.send({ id: request.id, type: 'error', diff --git a/app/tool/stage_definition_probe.dart b/app/tool/stage_definition_probe.dart new file mode 100644 index 00000000..046bf874 --- /dev/null +++ b/app/tool/stage_definition_probe.dart @@ -0,0 +1,148 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/graph/widgets/stage_definition_view.dart'; +import 'package:pipelines_app/ui/adaptive/host.dart'; + +/// A definition with an authored stage (including an unknown future field), a +/// declared route to a terminal, and no declaration for `ghost`. +JsonMap _graph() => { + 'stages': [ + { + 'key': 'plan', + 'type': 'model', + 'prompt': 'Plan the change.', + 'output': 'A short plan.', + 'edges': {'success': 'build', 'error': '#'}, + 'fallback_error': true, + 'configs': { + 'provider': 'openai', + 'model': 'gpt-5', + 'budget_usd': 12.5, + }, + 'blocks': {'tools': 'shell\nread_file'}, + 'limits': { + 'max_visits': 2, + 'on': ['error'], + }, + 'memory': {'context': 'latest'}, + 'notify': { + 'on': ['failure'], + 'destination': 'ops@example.test', + 'artifacts': ['run.log'], + }, + 'future_field': {'kept': true}, + }, + { + 'key': 'build', + 'type': 'shell', + 'edges': {'success': '#success', 'error': '#failure'}, + }, + ], +}; + +/// Isolated browser fixture for the read-only stage definition pane. +/// +/// `style=cupertino` selects the Cupertino host, `dark=1` its dark theme, +/// `scale=2` a real 2x text scale. Every button opens the exact helper the +/// pipeline graph hook will call; nothing contacts a server or reads a run. +void main() { + final parameters = Uri.base.queryParameters; + runApp( + _ProbeApp( + cupertino: parameters['style'] == 'cupertino', + dark: parameters['dark'] == '1', + scale: double.tryParse(parameters['scale'] ?? '') ?? 1, + ), + ); +} + +class _ProbeApp extends StatelessWidget { + const _ProbeApp({ + required this.cupertino, + required this.dark, + required this.scale, + }); + + final bool cupertino; + final bool dark; + final double scale; + + @override + Widget build(BuildContext context) { + Widget scaled(BuildContext context, Widget? child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(scale)), + child: child ?? const SizedBox.shrink(), + ); + if (cupertino) { + return CupertinoApp( + theme: CupertinoThemeData( + brightness: dark ? Brightness.dark : Brightness.light, + ), + builder: scaled, + home: const CupertinoPageScaffold( + navigationBar: CupertinoNavigationBar( + middle: Text('Stage definition fixture'), + ), + child: SafeArea(child: _Launcher()), + ), + ); + } + return MaterialApp( + theme: ThemeData( + platform: TargetPlatform.android, + brightness: Brightness.light, + ), + darkTheme: ThemeData( + platform: TargetPlatform.android, + brightness: Brightness.dark, + ), + themeMode: dark ? ThemeMode.dark : ThemeMode.light, + builder: scaled, + home: Scaffold( + appBar: AppBar(title: const Text('Stage definition fixture')), + body: const SafeArea(child: _Launcher()), + ), + ); + } +} + +class _Launcher extends StatelessWidget { + const _Launcher(); + + void _open(BuildContext context, String key) => openStageDefinition( + context, + graph: _graph(), + stageKey: key, + pipelineId: 41, + pipelineName: 'Demo pipeline', + version: 7, + ); + + @override + Widget build(BuildContext context) { + final cupertino = usesCupertinoHost(context); + return ListView( + padding: const EdgeInsets.all(16), + children: [ + const Text('Fixture home'), + for (final key in ['plan', '#failure', 'ghost']) + Padding( + padding: const EdgeInsets.only(top: 8), + child: cupertino + ? CupertinoButton.filled( + onPressed: () => _open(context, key), + child: Text('$key definition'), + ) + : FilledButton( + onPressed: () => _open(context, key), + child: Text('$key definition'), + ), + ), + ], + ); + } +} diff --git a/app/tool/stage_definition_probe.mjs b/app/tool/stage_definition_probe.mjs new file mode 100644 index 00000000..50377753 --- /dev/null +++ b/app/tool/stage_definition_probe.mjs @@ -0,0 +1,380 @@ +// Browser acceptance for the isolated read-only stage definition pane. +// +// Serves the probe build (`flutter build web -t tool/stage_definition_probe.dart`) +// on an OS-assigned loopback port, drives real headless Chrome, opens the pane +// through the same native helper the manager graph hook uses, asserts the +// pinned identity, actual field values, outcomes, raw unknown fields, terminal +// and unknown-stage states, closes it with Back on both hosts, and writes +// captures. +// +// PROBE_VARIANT=material|cupertino PROBE_SCHEME=dark|light PROBE_SCALE=1|2 \ +// PROBE_WIDTH=1280 PROBE_HEIGHT=900 PROBE_WEB_ROOT= \ +// OPENCODE_ARTIFACT_DIR= node tool/stage_definition_probe.mjs +import { createServer } from 'node:http'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { setTimeout as delay } from 'node:timers/promises'; +import { join, extname, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; +import { createHash } from 'node:crypto'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; + +const root = resolve( + process.env.PROBE_WEB_ROOT ?? join(process.cwd(), 'build/stage_definition_probe_web'), +); +const variant = process.env.PROBE_VARIANT ?? 'material'; +const scheme = process.env.PROBE_SCHEME ?? 'dark'; +const scale = process.env.PROBE_SCALE ?? '1'; +const width = Number(process.env.PROBE_WIDTH ?? 1280); +const height = Number(process.env.PROBE_HEIGHT ?? 900); +const chromePath = process.env.CHROME_PATH ?? + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +const artifactDir = process.env.OPENCODE_ARTIFACT_DIR; +if (!artifactDir) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures'); +await mkdir(artifactDir, { recursive: true }); +const prefix = `stage-definition-${variant}-${scheme}-${scale}x` + + (width === 1280 && height === 900 ? '' : `-${width}x${height}`); +const mime = { + '.html': 'text/html', + '.js': 'text/javascript', + '.json': 'application/json', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.ico': 'image/x-icon', + '.otf': 'font/otf', + '.ttf': 'font/ttf', +}; +const server = createServer(async (req, res) => { + try { + const path = resolve(root, '.' + decodeURIComponent(new URL(req.url, 'http://localhost').pathname)); + if (path !== root && !path.startsWith(root + sep)) return res.writeHead(403).end(); + const filePath = path === root || path.endsWith('/') ? join(path, 'index.html') : path; + const file = await readFile(filePath); + res.writeHead(200, { 'content-type': mime[extname(filePath)] ?? 'application/octet-stream' }).end(file); + } catch { + res.writeHead(404).end('not found'); + } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const port = server.address().port; +const profile = await mkdtemp(join(tmpdir(), 'stage-definition-chrome-')); +const chrome = spawn(chromePath, [ + '--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu', + '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank', +], { stdio: ['ignore', 'ignore', 'pipe'] }); +let stderr = ''; +chrome.stderr.on('data', (data) => { stderr += data; }); +const waitFor = async (fn) => { + for (let i = 0; i < 140; i++) { + const value = await fn(); + if (value) return value; + await delay(100); + } + throw new Error('Timed out waiting for Chrome DevTools'); +}; +let ws; +try { + const endpoint = await waitFor(() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1]); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', (event) => { + const message = JSON.parse(event.data); + if (message.method === 'Runtime.exceptionThrown') { + console.error('PAGE EXCEPTION', JSON.stringify(message.params?.exceptionDetails?.exception?.description)); + } + if (message.id && pending.has(message.id)) { + pending.get(message.id)(message); + pending.delete(message.id); + } + }); + const send = (method, params = {}, sessionId) => new Promise((resolveCall) => { + const callId = ++id; + pending.set(callId, resolveCall); + ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + const created = await send('Target.createTarget', { url: 'about:blank' }); + const target = created.result.targetId; + const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + await send('Emulation.setEmulatedMedia', { + features: [{ name: 'prefers-color-scheme', value: scheme }], + }, session); + await send('Emulation.setDeviceMetricsOverride', { + width, height, deviceScaleFactor: 1, mobile: false, + }, session); + const query = `?style=${variant}&dark=${scheme === 'dark' ? 1 : 0}&scale=${scale}`; + const navigation = await send('Page.navigate', { url: `http://127.0.0.1:${port}/${query}` }, session); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + const evaluate = async (expression) => { + const response = await send('Runtime.evaluate', { + expression, returnByValue: true, awaitPromise: true, + }, session); + if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); + return response.result?.result?.value; + }; + await delay(3500); + const loaded = await evaluate('({url:location.href, ready:document.readyState})'); + if (!loaded?.url.includes(`127.0.0.1:${port}/${query}`)) { + throw new Error(`Fixture did not load: ${JSON.stringify(loaded)}`); + } + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(2200); + + const labels = () => evaluate( + "[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||(x.innerText||'').trim()).filter(Boolean)", + ); + const bodyText = async () => [await evaluate('document.body.innerText'), ...(await labels())].join('\n'); + const clickExact = async (label) => { + const point = await evaluate(`(() => { + const e = [...document.querySelectorAll('flt-semantics')].find(x => + (x.getAttribute('aria-label')||(x.innerText||'').trim()).trim() === ${JSON.stringify(label)}); + if (!e) return null; + const r = e.getBoundingClientRect(); + return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; + })()`); + if (!point) throw new Error(`Missing control ${label}: ${JSON.stringify(await labels())}`); + await send('Input.dispatchMouseEvent', { + type: 'mousePressed', x: point.x, y: point.y, button: 'left', clickCount: 1, + }, session); + await send('Input.dispatchMouseEvent', { + type: 'mouseReleased', x: point.x, y: point.y, button: 'left', clickCount: 1, + }, session); + await delay(1000); + }; + const capture = async (name) => { + const data = (await send('Page.captureScreenshot', { + format: 'png', captureBeyondViewport: false, + }, session)).result.data; + const buffer = Buffer.from(data, 'base64'); + const file = `${prefix}-${name}.png`; + await writeFile(join(artifactDir, file), buffer); + return { file, sha1: createHash('sha1').update(buffer).digest('hex') }; + }; + const visible = async (needle, exact = false) => evaluate(`(() => { + const found = [...document.querySelectorAll('flt-semantics')].filter(x => { + const label = (x.getAttribute('aria-label')||(x.innerText||'')).trim(); + return ${exact ? `label === ${JSON.stringify(needle)}` : `label.includes(${JSON.stringify(needle)})`}; + }); + if (!found.length) return null; + found.sort((a, b) => { + const ra = a.getBoundingClientRect(), rb = b.getBoundingClientRect(); + return ra.width * ra.height - rb.width * rb.height; + }); + const r = found[0].getBoundingClientRect(); + return { x: r.x, y: r.y, width: r.width, height: r.height, + visible: r.width > 0 && r.height > 0 && r.bottom > 0 && r.top < innerHeight }; + })()`); + // Scroll by the measured delta instead of fixed steps: a fixed gesture can + // stop with a target half-entered (and its neighbours not built), which is + // exactly what made the raw-section check fail on shorter content. + const scrollTo = async (needle, { exact = false, maxTop = null } = {}) => { + for (let attempt = 0; attempt < 24; attempt++) { + const r = await visible(needle, exact); + const fullyVisible = r && r.width > 0 && r.height > 0 && + r.y >= 32 && r.y + r.height <= height - 32; + if (fullyVisible && (maxTop == null || r.y <= maxTop)) return r; + // Scroll down until the target is fully in view; for a target that must + // sit high (the raw title above its JSON), keep scrolling until it does. + const wanted = r + ? Math.round(r.y - (maxTop ?? height / 2)) + : Math.round(height / 3); + const distance = Math.sign(wanted || 1) * + Math.max(60, Math.min(400, Math.abs(wanted))); + await send('Input.synthesizeScrollGesture', { + x: Math.round(width / 2), y: Math.round(height / 2), + yDistance: -distance, gestureSourceType: 'mouse', speed: 900, + preventFling: true, + }, session); + await delay(300); + } + throw new Error( + `${needle} never scrolled into view: ${JSON.stringify(await bodyText())}`, + ); + }; + // The raw section is one selectable block whose whole value must be + // inspected. Scroll to the pane's end so the JSON tail (the unknown fields + // the raw section exists for) is really on screen, not just built. + const scrollToRaw = async () => { + let previous = null; + for (let attempt = 0; attempt < 16; attempt++) { + const r = await visible('future_field'); + if (r && previous != null && Math.abs(r.y - previous) < 1) { + if (!r.visible || r.y + r.height > height + 1) { + throw new Error(`The raw JSON did not settle in view: ${JSON.stringify(r)}`); + } + return r; + } + previous = r?.y ?? null; + await send('Input.synthesizeScrollGesture', { + x: Math.round(width / 2), y: Math.round(height / 2), + yDistance: -600, gestureSourceType: 'mouse', speed: 900, + preventFling: true, + }, session); + await delay(300); + } + throw new Error( + `The raw JSON never settled: ${JSON.stringify(await bodyText())}`, + ); + }; + const evidence = { variant, scheme, scale, checks: [], captures: [] }; + const expectText = async (needle, context) => { + const text = await bodyText(); + if (!text.includes(needle)) throw new Error(`${context}: missing ${JSON.stringify(needle)}\n${text}`); + }; + + await expectText('Fixture home', 'fixture home'); + await clickExact('plan definition'); + for (const needle of [ + 'Demo pipeline · v7', + 'Plan the change.', + 'A short plan.', + 'success → build', + 'error → FAILURE (terminal)', + ]) { + await expectText(needle, 'declared stage'); + } + // Two two-line blocks must share the host line rhythm. A fallback font for + // the outcomes arrow must not stretch only that block, so compare the whole + // label+value block: equal line counts mean equal heights. + if (width >= 1000) { + const blockHeight = async (prefixText) => evaluate(`(() => { + const found = [...document.querySelectorAll('flt-semantics')].filter(x => + (x.getAttribute('aria-label')||(x.innerText||'')).trim().startsWith(${JSON.stringify(prefixText)})); + if (!found.length) return null; + found.sort((a, b) => { + const ra = a.getBoundingClientRect(), rb = b.getBoundingClientRect(); + return ra.width * ra.height - rb.width * rb.height; + }); + const r = found[0].getBoundingClientRect(); + return { height: r.height, width: r.width }; + })()`); + const outcomes = await blockHeight('Outcomes'); + const tools = await blockHeight('Tools'); + const ratio = outcomes && tools ? outcomes.height / tools.height : 0; + if (!(ratio >= 0.8 && ratio <= 1.25)) { + throw new Error( + `Outcomes line rhythm differs from Tools: ${JSON.stringify({ outcomes, tools, ratio })}`, + ); + } + evidence.rhythm = { + outcomesHeight: outcomes.height, + toolsHeight: tools.height, + ratio, + }; + evidence.checks.push({ + check: 'the outcomes block keeps the host line rhythm of other two-line blocks', + value: ratio, + }); + } + evidence.checks.push({ + check: 'declared stage shows pinned identity and the web field values', + value: true, + }); + const declaredCapture = await capture('declared'); + evidence.captures.push(declaredCapture); + + // Remaining declared fields, reached by scrolling so the probe also covers + // viewports shorter than the full pane. + for (const needle of [ + 'Provider', 'openai', 'Model', 'gpt-5', 'Budget (USD)', '12.5', + 'Tools', 'shell', 'read_file', 'Max visits', 'Limit on', 'Memory', + 'context: latest', + ]) { + await scrollTo(needle); + await expectText(needle, 'declared stage'); + } + evidence.checks.push({ + check: 'every declared field value is present in the rendered pane', + value: true, + }); + + await scrollTo('Notify destination'); + for (const needle of ['Notify on', 'failure', 'Notify destination', 'ops@example.test', 'Notify artifacts', 'run.log']) { + await expectText(needle, 'notify definition'); + } + + const rawJson = await scrollToRaw(); + evidence.rawJsonRect = rawJson; + evidence.rawSectionSeen = (await bodyText()).includes('Raw stage definition'); + for (const needle of ['future_field', 'kept', 'fallback_error']) { + await expectText(needle, 'raw unknown fields'); + } + evidence.checks.push({ + check: 'unknown stage fields remain in the selectable raw JSON', + value: true, + }); + const rawCapture = await capture('raw'); + if (rawCapture.sha1 === declaredCapture.sha1) { + throw new Error('The raw capture is identical to the unscrolled pane'); + } + evidence.captures.push(rawCapture); + + await clickExact('Back'); + await expectText('Fixture home', 'Back'); + evidence.checks.push({ check: 'Back returned to the graph host', value: true }); + + await clickExact('#failure definition'); + const terminalText = await bodyText(); + if (terminalText.includes('#failure')) { + throw new Error(`The terminal title still exposes the raw key: ${terminalText}`); + } + await expectText('Failure definition', 'terminal title'); + for (const needle of [ + 'Success and Failure are definition targets, not recorded visits.', + 'Incoming routes', + 'plan · error* → FAILURE', + 'build · error → FAILURE', + ]) { + await expectText(needle, 'terminal definition'); + } + evidence.checks.push({ + check: 'the terminal page is titled with its display label, not the protocol key', + value: true, + }); + evidence.checks.push({ + check: 'terminal explains definition routes without claiming a visit', + value: true, + }); + evidence.captures.push(await capture('terminal')); + await clickExact('Back'); + await expectText('Fixture home', 'terminal Back'); + + await clickExact('ghost definition'); + await expectText( + 'This stage is not declared in this pipeline version.', + 'unknown stage', + ); + const unknown = await bodyText(); + if (unknown.includes('Raw stage definition') || unknown.includes('Incoming routes')) { + throw new Error(`Unknown stage invented definition content: ${unknown}`); + } + evidence.checks.push({ + check: 'unknown stage has an explicit missing state with no defaults', + value: true, + }); + evidence.captures.push(await capture('unknown')); + await clickExact('Back'); + await expectText('Fixture home', 'unknown Back'); + evidence.checks.push({ check: 'every open used one native bar and Back', value: true }); + evidence.captures.push(await capture('closed')); + + console.log(JSON.stringify(evidence, null, 2)); +} finally { + if (ws?.readyState === WebSocket.OPEN) { + ws.send(JSON.stringify({ id: 2147483647, method: 'Browser.close' })); + } + await Promise.race([once(chrome, 'exit'), delay(3000)]); + ws?.close(); + if (chrome.exitCode === null) chrome.kill('SIGTERM'); + chrome.stderr.destroy(); + chrome.unref(); + await new Promise((resolveClose) => { + server.close(resolveClose); + server.closeAllConnections(); + }); + await rm(profile, { recursive: true, force: true }); +} diff --git a/app/tool/templates_gallery_probe.dart b/app/tool/templates_gallery_probe.dart new file mode 100644 index 00000000..c42d26af --- /dev/null +++ b/app/tool/templates_gallery_probe.dart @@ -0,0 +1,178 @@ +import 'dart:async'; +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/templates/screen.dart'; + +/// Browser capture entrypoint for the reusable Templates gallery. +/// +/// The fixture gateway is in-process and records every request; nothing here +/// opens a socket or contacts a real server. Query parameters: +/// `host=material|cupertino`, `scale=` and +/// `scenario=default|empty|refresh-refusal`. The state published at +/// `globalThis.templatesGalleryProbe` is read by the driver. +const _source = ' name: "release"\n\tstages:\n - key: "añadir" 😀 \n'; + +const _galleryRows = [ + { + 'key': 'release', + 'name': 'Release workflow', + 'description': 'Ship a version', + 'source': _source, + 'scheduled': true, + }, + { + 'key': 'blank', + 'name': '', + 'description': 'No display name', + 'source': 'name: "unnamed"\n', + 'scheduled': false, + }, +]; + +class _ProbeGateway implements ApiGateway { + _ProbeGateway( + this.publish, { + required this.empty, + required this.failingRefresh, + }); + + final VoidCallback publish; + final bool empty; + final bool failingRefresh; + int listCalls = 0; + int validates = 0; + int submits = 0; + final List created = []; + String? lastSource; + JsonMap? lastSubmit; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) async { + if (type == 'list_templates') { + listCalls++; + publish(); + if (failingRefresh) { + // The catalogue loads, then a Refresh from the open template refuses so + // the driver can prove the failure is visible above that detail. + if (listCalls == 2) { + await Future.delayed(const Duration(milliseconds: 250)); + throw const ProtocolError('fixture refresh unavailable'); + } + return {'templates': _galleryRows}; + } + if (listCalls == 1 && !empty) { + // The first read refuses, so the driver can exercise the honest error + // state and Retry on a real host. + await Future.delayed(const Duration(milliseconds: 250)); + throw const ProtocolError('fixture catalogue unavailable'); + } + if (listCalls == 2) { + // Enough time to capture the loading state after Retry. + await Future.delayed(const Duration(milliseconds: 1200)); + } + if (empty) return {'templates': const []}; + return { + 'templates': [ + ..._galleryRows, + if (listCalls >= 3) + { + 'key': 'added', + 'name': 'Added after refresh', + 'description': 'Proves the catalogue was re-read', + 'source': 'name: "added"\n', + 'scheduled': false, + }, + ], + }; + } + if (type == 'validate') { + validates++; + lastSource = fields['source'] as String?; + publish(); + await Future.delayed(const Duration(milliseconds: 200)); + return { + 'graph': {'stages': const []}, + }; + } + if (type == 'submit') { + submits++; + lastSubmit = Map.from(fields); + publish(); + return { + 'detail': {'id': 41, 'name': 'Probe created'}, + }; + } + throw StateError('The templates probe does not implement $type'); + } +} + +void main() => runApp(const _ProbeApp()); + +class _ProbeApp extends StatefulWidget { + const _ProbeApp(); + + @override + State<_ProbeApp> createState() => _ProbeAppState(); +} + +class _ProbeAppState extends State<_ProbeApp> { + late final _params = Uri.base.queryParameters; + late final _cupertino = _params['host'] == 'cupertino'; + late final _scale = double.tryParse(_params['scale'] ?? '') ?? 1; + late final _gateway = _ProbeGateway( + _publish, + empty: _params['scenario'] == 'empty', + failingRefresh: _params['scenario'] == 'refresh-refusal', + ); + + void _publish() { + globalContext.setProperty( + 'templatesGalleryProbe'.toJS, + { + 'listCalls': _gateway.listCalls, + 'validates': _gateway.validates, + 'submits': _gateway.submits, + 'created': _gateway.created, + 'lastSource': _gateway.lastSource, + 'lastSubmit': _gateway.lastSubmit, + }.jsify(), + ); + } + + void _created(JsonMap detail) { + _gateway.created.add(detail); + _publish(); + } + + @override + Widget build(BuildContext context) { + Widget scaled(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(_scale)), + child: app!, + ); + final screen = TemplatesScreen(gateway: _gateway, onCreated: _created); + if (_cupertino) { + return CupertinoApp( + theme: CupertinoThemeData(brightness: Brightness.dark), + builder: scaled, + home: screen, + ); + } + return MaterialApp( + theme: ThemeData(brightness: Brightness.dark), + builder: scaled, + home: screen, + ); + } +} diff --git a/app/tool/templates_gallery_probe.mjs b/app/tool/templates_gallery_probe.mjs new file mode 100644 index 00000000..6ad5bac1 --- /dev/null +++ b/app/tool/templates_gallery_probe.mjs @@ -0,0 +1,386 @@ +import { createServer } from 'node:http'; +import { readFile, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { setTimeout as delay } from 'node:timers/promises'; +import { join, extname, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; + +// Real-browser acceptance for the reusable Templates gallery. +// +// Usage (from app/): +// flutter build web --target=tool/templates_gallery_probe.dart \ +// -o build/templates_gallery_probe_web +// OPENCODE_ARTIFACT_DIR= node tool/templates_gallery_probe.mjs +// +// PROBE_HOST (material|cupertino), PROBE_SCALE, PROBE_WIDTH/PROBE_HEIGHT, +// PROBE_SCENARIO (default|empty|refresh-refusal) and PROBE_CAPTURE_PREFIX +// select the host and evidence. The fixture gateway is in-process: no socket +// is opened and no real Pipelines server is contacted. + +const root = resolve(process.env.PROBE_WEB_ROOT ?? 'build/templates_gallery_probe_web'); +const artifactDir = process.env.OPENCODE_ARTIFACT_DIR; +if (!artifactDir) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures'); +await mkdir(artifactDir, { recursive: true }); +const width = Number(process.env.PROBE_WIDTH ?? 390); +const height = Number(process.env.PROBE_HEIGHT ?? 844); +const textScale = process.env.PROBE_SCALE ?? '1'; +const host = process.env.PROBE_HOST ?? 'material'; +const scenario = process.env.PROBE_SCENARIO ?? 'default'; +const capturePrefix = process.env.PROBE_CAPTURE_PREFIX ?? 't1-gallery'; +const deviceScaleFactor = Number(process.env.PROBE_DPR ?? 1); + +const MIME = { + '.html': 'text/html', + '.js': 'text/javascript', + '.json': 'application/json', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.ico': 'image/x-icon', + '.otf': 'font/otf', + '.ttf': 'font/ttf', +}; +const server = createServer(async (req, res) => { + try { + const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname); + const path = resolve(root, `.${pathname}`); + if (path !== root && !path.startsWith(root + sep)) { + res.writeHead(403).end(); + return; + } + const filePath = path === root || path.endsWith('/') ? join(path, 'index.html') : path; + const file = await readFile(filePath); + res.writeHead(200, { 'content-type': MIME[extname(filePath)] ?? 'application/octet-stream' }).end(file); + } catch { + res.writeHead(404).end('not found'); + } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const origin = `http://127.0.0.1:${server.address().port}`; + +const profile = await mkdtemp(join(tmpdir(), 'templates-gallery-chrome-')); +const chrome = spawn('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', [ + '--headless=new', + '--no-first-run', + '--no-default-browser-check', + '--disable-gpu', + '--remote-debugging-port=0', + `--user-data-dir=${profile}`, + 'about:blank', +], { stdio: ['ignore', 'ignore', 'pipe'] }); +let stderr = ''; +chrome.stderr.on('data', (data) => { + stderr += data; +}); + +async function waitFor(check, label, attempts = 160) { + for (let attempt = 0; attempt < attempts; attempt++) { + const value = await check(); + if (value) return value; + await delay(100); + } + throw new Error(`Timed out waiting for ${label}\n${stderr.slice(-1200)}`); +} + +let ws; +try { + const endpoint = await waitFor( + () => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1], + 'Chrome DevTools', + ); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', (event) => { + const message = JSON.parse(event.data); + if (message.method === 'Runtime.exceptionThrown') { + console.error('PAGE EXCEPTION', JSON.stringify(message.params?.exceptionDetails?.exception?.description)); + } + if (message.id && pending.has(message.id)) { + pending.get(message.id)(message); + pending.delete(message.id); + } + }); + const send = (method, params = {}, sessionId) => + new Promise((resolveCall) => { + const callId = ++id; + pending.set(callId, resolveCall); + ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + + const target = (await send('Target.createTarget', { url: 'about:blank' })).result.targetId; + const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + await send( + 'Emulation.setDeviceMetricsOverride', + { width, height, deviceScaleFactor, mobile: true }, + session, + ); + await send( + 'Emulation.setEmulatedMedia', + { features: [{ name: 'prefers-color-scheme', value: 'dark' }] }, + session, + ); + + const evaluate = async (expression) => { + const response = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, session); + if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); + if (response.result?.exceptionDetails) { + throw new Error(`Page exception: ${JSON.stringify(response.result.exceptionDetails)}`); + } + return response.result?.result?.value; + }; + + const semanticText = () => + evaluate(`(() => { + const chunks = []; + for (const el of document.querySelectorAll('flt-semantics')) { + const label = el.getAttribute('aria-label'); + if (label) chunks.push(label); + if (!el.children.length && el.innerText) chunks.push(el.innerText); + } + for (const el of document.querySelectorAll('input, textarea')) { + if (el.getAttribute('aria-label')) chunks.push(el.getAttribute('aria-label')); + if (el.value) chunks.push(String(el.value)); + } + if (document.body?.innerText) chunks.push(document.body.innerText); + return [...new Set(chunks)].join('\\n'); + })()`); + + const labels = () => + evaluate( + "[...document.querySelectorAll('flt-semantics')].map((el) => (el.getAttribute('aria-label') || el.innerText || '').trim()).filter(Boolean)", + ); + + const assertBody = async (text) => { + try { + await waitFor( + async () => (await semanticText()).includes(text), + `body to contain ${JSON.stringify(text)}`, + ); + } catch (error) { + throw new Error(`${error.message}\nBody now:\n${(await semanticText()).slice(0, 3000)}`); + } + }; + + const clickLabel = async (label, { contains = false } = {}) => { + const point = await evaluate(`(() => { + const needle = ${JSON.stringify(label)}; + const candidates = [...document.querySelectorAll('flt-semantics')].filter((el) => { + const text = (el.getAttribute('aria-label') || el.innerText || '').trim(); + return ${contains ? 'text.includes(needle)' : 'text === needle'}; + }); + const target = candidates.find((el) => + ['button', 'tab', 'link', 'checkbox', 'menuitem'].includes(el.getAttribute('role')), + ) ?? candidates[0]; + if (!target) return null; + const r = target.getBoundingClientRect(); + if (r.width === 0 || r.height === 0) return null; + return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; + })()`); + if (!point) { + throw new Error(`Could not click ${JSON.stringify(label)}. Labels: ${JSON.stringify(await labels())}`); + } + await send('Input.dispatchMouseEvent', { type: 'mousePressed', x: point.x, y: point.y, button: 'left', clickCount: 1 }, session); + await send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: point.x, y: point.y, button: 'left', clickCount: 1 }, session); + await delay(400); + }; + + const typeName = async (value) => { + const focused = await evaluate(`(() => { + const input = document.querySelector('input'); + if (!input) return false; + input.focus(); + input.select?.(); + input.setSelectionRange?.(0, (input.value || '').length); + return true; + })()`); + if (!focused) throw new Error('The name field was not exposed as a semantics input'); + await delay(300); + await send('Input.insertText', { text: value }, session); + await delay(400); + }; + + const state = () => evaluate('globalThis.templatesGalleryProbe ?? null'); + const capture = async (name) => { + const data = (await send('Page.captureScreenshot', { format: 'png' }, session)).result.data; + const path = join(artifactDir, `${name}.png`); + await writeFile(path, Buffer.from(data, 'base64')); + return path; + }; + + const checks = []; + const captures = []; + await send( + 'Page.navigate', + { url: `${origin}/?scale=${textScale}&host=${host}&scenario=${scenario}` }, + session, + ); + await waitFor( + () => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"), + 'semantics placeholder', + ); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(900); + + if (scenario === 'empty') { + await assertBody('No templates are available on this server.'); + const emptyState = await state(); + if (emptyState?.listCalls !== 1) { + throw new Error(`The empty catalogue made unexpected requests: ${JSON.stringify(emptyState)}`); + } + captures.push(await capture(`${capturePrefix}-empty`)); + checks.push({ check: 'empty catalogue stated honestly', state: emptyState }); + } else if (scenario === 'refresh-refusal') { + // The catalogue loads, a template is open, and Refresh genuinely refuses: + // the refusal must stay visible above that detail, with Retry. + await assertBody('Release workflow'); + await clickLabel('Release workflow', { contains: true }); + await assertBody('Definition source'); + const before = await state(); + if (before?.listCalls !== 1 || before?.validates !== 0 || before?.submits !== 0) { + throw new Error(`Opening the template made unexpected requests: ${JSON.stringify(before)}`); + } + + await clickLabel('Refresh'); + await assertBody('fixture refresh unavailable'); + await assertBody('Retry'); + await assertBody('Definition source'); + await assertBody('Create pipeline from this template'); + const refused = await state(); + if (refused?.listCalls !== 2 || refused?.validates !== 0 || refused?.submits !== 0) { + throw new Error(`The failed refresh did not stay read-only: ${JSON.stringify(refused)}`); + } + captures.push(await capture(`${capturePrefix}-detail-refresh-error`)); + checks.push({ check: 'failed refresh visible above the open template', state: refused }); + + await clickLabel('Retry'); + await waitFor( + async () => !(await semanticText()).includes('fixture refresh unavailable'), + 'the refusal banner to clear after Retry', + ); + await assertBody('Definition source'); + const retried = await state(); + if (retried?.listCalls !== 3) { + throw new Error(`Retry did not re-read exactly once: ${JSON.stringify(retried)}`); + } + captures.push(await capture(`${capturePrefix}-detail-refresh-retried`)); + checks.push({ check: 'Retry re-read while keeping the template open', state: retried }); + } else { + // The first read genuinely refuses; the screen must say so and retry. + await assertBody('fixture catalogue unavailable'); + await assertBody('Retry'); + const failed = await state(); + if (failed?.listCalls !== 1) { + throw new Error(`The refusal state made unexpected requests: ${JSON.stringify(failed)}`); + } + captures.push(await capture(`${capturePrefix}-error`)); + checks.push({ check: 'catalogue refusal shown with Retry', state: failed }); + + await clickLabel('Retry'); + await assertBody('Loading templates…'); + captures.push(await capture(`${capturePrefix}-loading`)); + await assertBody('Release workflow'); + await assertBody('(unnamed template)'); + await assertBody('Ship a version'); + const gallery = await state(); + if (gallery?.listCalls !== 2) { + throw new Error(`Retry did not re-read exactly once: ${JSON.stringify(gallery)}`); + } + captures.push(await capture(`${capturePrefix}-gallery`)); + checks.push({ check: 'retry loaded the actual catalogue rows', state: gallery }); + + await clickLabel('Release workflow', { contains: true }); + await assertBody('Definition source'); + await assertBody('Key'); + await assertBody('Includes a schedule'); + await assertBody('Create pipeline from this template'); + const detail = await state(); + if (detail?.validates !== 0 || detail?.submits !== 0) { + throw new Error(`Opening a template sent a write: ${JSON.stringify(detail)}`); + } + captures.push(await capture(`${capturePrefix}-detail`)); + checks.push({ check: 'selected template shows metadata and verbatim source', state: detail }); + + await clickLabel('Back'); + await assertBody('Release workflow'); + await clickLabel('Refresh'); + await assertBody('Added after refresh'); + const refreshed = await state(); + if (refreshed?.listCalls !== 3) { + throw new Error(`Refresh made unexpected requests: ${JSON.stringify(refreshed)}`); + } + captures.push(await capture(`${capturePrefix}-refreshed`)); + checks.push({ check: 'native back returned and refresh re-read the catalogue', state: refreshed }); + + await clickLabel('Release workflow', { contains: true }); + await assertBody('Create pipeline from this template'); + await clickLabel('Create pipeline from this template'); + await assertBody('Create from Release workflow'); + await assertBody('New pipeline name (required)'); + captures.push(await capture(`${capturePrefix}-create-blank`)); + await typeName('Probe release'); + await clickLabel('Cancel'); + await waitFor(async () => !(await semanticText()).includes('Create from Release workflow'), 'the prompt to close'); + const cancelled = await state(); + if (cancelled?.validates !== 0 || cancelled?.submits !== 0 || cancelled?.created?.length !== 0) { + throw new Error(`Cancel sent a request: ${JSON.stringify(cancelled)}`); + } + checks.push({ check: 'Cancel sent nothing', state: cancelled }); + + await waitFor( + async () => (await semanticText()).includes('Create pipeline from this template'), + 'the detail after the prompt closed', + ); + await clickLabel('Create pipeline from this template'); + await assertBody('Create from Release workflow'); + await typeName('Probe release'); + await clickLabel('Create'); + await assertBody('Created "Probe created". It is in the Pipelines list.'); + const created = await state(); + if (created?.validates !== 1 || created?.submits !== 1 || created?.created?.length !== 1) { + throw new Error(`The accepted create was not reported exactly once: ${JSON.stringify(created)}`); + } + if (created.lastSubmit?.name !== 'Probe release' || created.lastSubmit?.create_only !== true) { + throw new Error(`Submit payload drifted: ${JSON.stringify(created.lastSubmit)}`); + } + const verbatim = ' name: "release"\n\tstages:\n - key: "añadir" 😀 \n'; + if (created.lastSubmit?.source !== created.lastSource || created.lastSource !== verbatim) { + throw new Error(`Source was not sent verbatim: ${JSON.stringify(created)}`); + } + captures.push(await capture(`${capturePrefix}-created`)); + checks.push({ + check: 'accepted create forwarded the detail once with the verbatim source', + state: created, + }); + + await clickLabel('Close'); + await waitFor(async () => !(await semanticText()).includes('Create from Release workflow'), 'the prompt to close'); + const closed = await state(); + if (closed?.created?.length !== 1 || closed?.submits !== 1) { + throw new Error(`Close changed the request counts: ${JSON.stringify(closed)}`); + } + checks.push({ check: 'Close dismissed without another request', state: closed }); + } + + console.log(JSON.stringify({ + ok: true, + origin, + viewport: { width, height }, + deviceScaleFactor, + textScale, + host, + scenario, + checks, + captures, + }, null, 2)); +} finally { + ws?.close(); + chrome.kill('SIGTERM'); + await Promise.race([once(chrome, 'exit'), delay(3000)]); + server.close(); + await rm(profile, { recursive: true, force: true }); +}