Merge branch 'main' into flutter/chat-cmd-stop

This commit is contained in:
2026-10-22 22:22:44 +01:00
48 changed files with 3777 additions and 89 deletions
+2 -2
View File
@@ -44,8 +44,8 @@ or scratch servers only, never real operator sessions/runs/workflows.
| Chat history/live transport | Preview: `/chat` list and `/chat/:id` history, paging, live failure notice; composer integrated with the thread | run-detail-style reconnect verification in the real app |
| Chat message surfaces | Preview: formatted assistant markdown (safe links/headings/lists/tables/fences), user text exact, disclosures plain | exact attachments, unknown-part rendering beyond retained placeholders |
| Chat activity/reasoning/tools | Preview: one activity line, expanded native overlay with lifecycle/input/output/error/duration/edit diff | compaction wording variants |
| Chat composer | Preview: field, Send/Stop, persisted draft, queued/refusal lines; attachments sent with the prompt (87bb518c); slash palette with no-send routing (63babc59); one verified send in the real app flow | paste; slash command actions |
| Chat attachments | Preview: host picker, bounded 1 MiB draft, composer chips, base64 wire payload, sent with the prompt (87bb518c) | paste, history reconciliation |
| Chat composer | Preview: field, Send/Stop, persisted draft, queued/refusal lines; attachments sent with the prompt (87bb518c); slash palette with no-send routing (63babc59); file and text paste (copied text keeps the field's caret and draft); one verified send in the real app flow | slash command actions |
| Chat attachments | Preview: host picker, pasted files through the same bounded 1 MiB draft, composer chips, base64 wire payload, sent with the prompt (87bb518c) | history reconciliation |
| Chat permissions/questions | Preview: native approval/risk and question cards in the conversation view, Chrome fixture captures under the C4 probe (`notes/C4-approvals.md`) | authenticated smoke with a real pending approval/question; live multi-client resolution; no production decision sent |
| Chat model/Info/background tasks | Preview: numeric Info sheet (unknown != 0); header model control and chooser (`notes/chat-model-picker.md`); `Background tasks` bar with `N running`, capped scrolling rows, selected-task detail and one bounded `chat_shell_output` page (cursor 0, 64 KiB) that reports empty/unavailable/refused states, re-read on reconnect; the bar keeps half the viewport and the output pane twelve scaled lines (run 139 + manager fix; widget tests, published, no rendered capture yet) | rendered browser captures of the model chooser and the task bar; authenticated smoke with a real running shell |
| Chat commands/notices/scroll | Preview: dismissible local notices with reconnect clearing; slash palette with the unknown-command report and `Send as message` / `Cancel` (63babc59, `notes/C9-commands.md`); streamed follow and restored read position (e4c196d7) | command actions `/new`, `/close`, `/rename`, `/stop`, `/help` |
+54
View File
@@ -585,3 +585,57 @@ the Pipelines server binds `127.0.0.1:8080` only, so the phone needs a tailnet
TLS-terminated TCP forward (`wss://…ts.net:<port>/connect`), which is the
operator's call; the native build has no baked endpoint and takes it in Settings.
Nothing installed on any device; mobile remains unverified.
## Open wave handoff (2026-10-22 ~18:45)
Briefs with exact web wording for every remaining PARITY gap are in the manager
scratchpad `briefs/` (runs, start-templates-transport, chat-sessions,
chat-surfaces); the run prompts below embed what each lane needs.
Pipeline runs left executing (Task v6, Luna), one worktree each under `tmp/`
on branch `flutter/<name>`; when a run lands, merge its branch, run the full
suite + analyze, publish by rename:
- 140 chat `/stop` `/help` actions (`flutter/chat-cmd-stop`); the web's accepted
`/stop` notice is `Stopping the running turn…` — add it at merge if missing.
- 143 runs filter menu: Pipeline/Time range sections, duration sorts, Reset
(`flutter/runs-filter-menu`).
- 144 runs day groups (`flutter/runs-day-groups`); the row meta/usage/empty-state
wording lane (brief runs §1 item 5, §2 item 3) is still to start after it.
- 145 runs pipeline filter from the URL + pipeline detail `Runs` action
(`flutter/runs-pipeline-url`).
- 146 run dialog Report format (`flutter/run-report-format`).
- 147 run dialog recent directories (`flutter/run-directories`).
- 148 composer paste attachments (`flutter/chat-paste`).
- 149 background question notices (`flutter/chat-question-notice`).
- 152 chat create dialog parity (`flutter/chat-create-dialog`).
Direct work in progress (Claude agents, branches `worktree-agent-*` under
`.claude/worktrees/`): chat tasks + model chooser probe; graph pulse + session
repair probe; search selection probe; shell Runs-tab attention badge with a
lifted AttentionController. The `/new` `/close` `/rename` commands are being
implemented directly on `flutter/chat-cmd-session` after Luna blocked three
times (runs 141, 142, 150) on the coordination scope.
Preserved partial: run 151 live `New` marks is a WIP commit faa5cc00 on
`flutter/chat-live-new` (frame listener + persisted unseen set; needs the lint
fix at chat_session_local.dart:59, focused tests, and an `activeSessionId` clear
when the conversation is left).
Still to start after this wave: pending run intent persisted across reload;
persisted endpoint boot for native; foreground-while-connected list refresh;
compaction frame fold (`Compacting context…`); dismiss control for the chat row
refusal; hide closing an open conversation + deep-link `markOpened`; run Summary
`Pipeline` row as a link; `Open repaired export` link + recovery attempts line.
Template provenance on runs is a server gap (no template origin recorded).
## Lane sizing (contextual, task-sized)
A task is one outcome an operator can see or an API client can observe, with
its own regression. File count follows the task: one file is fine, and a task
that truly needs three files (widget + call site + fixture) is still one task.
The line is unrelated work: no refactors, redesigns or extra behaviours riding
along, and no second outcome that could ship on its own.
Size by uncertainty, not file count: if the outcome needs the reviewer to judge
a look, mock or probe, keep it small and put the evidence expectation in the
prompt. Target tens of minutes, not hours; if a lane exceeds ~20 minutes with
nothing landed, cancel it and land or split the tree. Plumbing (routes,
providers, composition) stays a manager edit.
+103 -3
View File
@@ -1,6 +1,7 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
@@ -9,7 +10,10 @@ import '../core/transport/pipelines_client.dart';
import '../shell/adaptive_shell.dart';
import '../shell/destination.dart';
import '../features/attention/notify/notification_controller.dart';
import '../features/attention/notify/chat_question_notices.dart';
import '../features/attention/notify/notification_store.dart';
import '../features/attention/runtime/attention_controller.dart';
import '../features/attention/runtime/attention_store.dart';
import '../features/runs/ui/run_search_selection.dart';
import '../features/search/domain/search_target.dart';
import '../features/settings/settings_screen.dart';
@@ -88,6 +92,21 @@ class _PipelinesAppState extends State<PipelinesApp>
late final NotificationController _notifications = NotificationController(
store: const SharedPreferencesNotificationStore(),
);
ChatQuestionNotices? _chatQuestionNotices;
/// One attention surface for the app: the Runs heading's bell draws from it
/// and the shell mirrors its count on the Runs tab, so the badge is visible
/// from every destination. The Runs list seeds the rows when it loads; pushed
/// `run_event` frames are folded here so the count moves while another
/// destination is shown, and a replaced socket drops the status baseline.
late final AttentionController _attention = AttentionController(
store: const SharedPreferencesAttentionStore(),
);
StreamSubscription<JsonMap>? _attentionFrames;
int _attentionEpoch = 0;
/// The count the shell's Runs tab shows; only a changed count rebuilds it.
final ValueNotifier<int> _attentionCount = ValueNotifier<int>(0);
@override
void initState() {
@@ -115,6 +134,12 @@ class _PipelinesAppState extends State<PipelinesApp>
_cupertino = widget.cupertino ?? _platformIsCupertino;
_notifications.onOpenRun = (id) => _delegate.goTo(AppRoute.run(id));
unawaited(_notifications.load());
unawaited(_attention.load());
_attentionFrames = _session.gateway.frames
.where((frame) => frame['type'] == 'run_event')
.listen(_attention.observeFrame);
_session.addListener(_attentionSessionChanged);
_attention.addListener(_attentionChanged);
_delegate = AppRouterDelegate(
initial: initial,
cupertino: _cupertino,
@@ -126,6 +151,17 @@ class _PipelinesAppState extends State<PipelinesApp>
builder: _buildShell,
);
_delegate.addListener(_routeChanged);
_chatQuestionNotices = ChatQuestionNotices(
gateway: _session.gateway,
canNotify: () => _notifications.canNotify,
activeChatSessionId: () {
final route = _delegate.shellRoute;
return route.kind == AppRouteKind.chat ? route.chatSessionId : null;
},
sessionTitle: _chatSessionTitle,
openChat: (id) => _delegate.goTo(AppRoute.chatSession(id)),
bridge: _notifications.bridge,
);
_config = RouterConfig<AppRoute>(
routeInformationParser: const AppRouteParser(),
routerDelegate: _delegate,
@@ -137,7 +173,13 @@ class _PipelinesAppState extends State<PipelinesApp>
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_session.removeListener(_attentionSessionChanged);
unawaited(_attentionFrames?.cancel());
_attention.removeListener(_attentionChanged);
_attention.dispose();
_attentionCount.dispose();
_notifications.dispose();
_chatQuestionNotices?.dispose();
_delegate.removeListener(_routeChanged);
_delegate.dispose();
if (_ownsProvider) {
@@ -161,6 +203,33 @@ class _PipelinesAppState extends State<PipelinesApp>
unawaited(_session.retry());
}
/// A replaced socket drops the attention status baseline so the gap cannot
/// replay a transition; the Runs list's next read reseeds the rows.
void _attentionSessionChanged() {
final epoch = _session.connectionEpoch;
if (epoch == _attentionEpoch) return;
_attentionEpoch = epoch;
_attention.resetForReconnect();
}
/// Mirrors the controller's entry count for the shell. The Runs list seeds
/// the rows from inside its own build, and the shell sits above that layout
/// scope, so a count that changes mid-build lands after the frame; a pushed
/// frame arrives outside any build and applies at once.
void _attentionChanged() {
if (!mounted) return;
final count = _attention.entries.length;
if (count == _attentionCount.value) return;
if (SchedulerBinding.instance.schedulerPhase ==
SchedulerPhase.persistentCallbacks) {
SchedulerBinding.instance.addPostFrameCallback(
(_) => _attentionChanged(),
);
return;
}
_attentionCount.value = count;
}
@override
Widget build(BuildContext context) =>
MyApp.router(cupertino: _cupertino, routerConfig: _config);
@@ -199,9 +268,12 @@ class _PipelinesAppState extends State<PipelinesApp>
case SearchRunTarget(:final runId):
route = AppRoute.run(runId);
case SearchStepTarget(:final runId, :final stage, :final visit):
// The server records a 1-based visit number; the route's `visit` is the
// zero-based index into the recorded timeline.
final index = visit == null || visit < 1 ? null : visit - 1;
route = stage == null
? AppRoute.run(runId)
: AppRoute.run.stage(runId, stage, visit: visit);
: AppRoute.run.stage(runId, stage, visit: index);
case SearchFieldTarget(:final runId, :final sequence, :final field):
selection = RunSearchSelection(
runId: runId,
@@ -242,6 +314,16 @@ class _PipelinesAppState extends State<PipelinesApp>
setState(() => _pendingRunSearch = null);
}
Future<String?> _chatSessionTitle(String id) async {
final reply = await _session.gateway.call('chat_sessions');
final sessions = reply['chat_sessions'];
if (sessions is! List) return null;
for (final value in sessions) {
if (value is Map && value['id'] == id) return '${value['title'] ?? ''}';
}
return null;
}
/// The Templates page above Settings. Closing it restores the same Settings
/// screen instance, so an edited field or an open connection state survives.
Widget _buildSchedules(BuildContext context) => SchedulesDestination(
@@ -277,7 +359,16 @@ class _PipelinesAppState extends State<PipelinesApp>
_delegate.goTo(AppRoute.run(id));
}
Widget _buildShell(BuildContext context, AppRoute route) => AdaptiveShell(
/// The shell rebuilds its Runs tab badge from the attention count alone; the
/// destination bodies keep their state through it.
Widget _buildShell(BuildContext context, AppRoute route) =>
ValueListenableBuilder<int>(
valueListenable: _attentionCount,
builder: (context, count, _) => _shellFor(route, count),
);
Widget _shellFor(AppRoute route, int attentionCount) => AdaptiveShell(
attentionCount: attentionCount,
cupertino: _cupertino,
destination: _destinationOf(route.kind),
onDestinationSelected: (destination) =>
@@ -289,6 +380,8 @@ class _PipelinesAppState extends State<PipelinesApp>
server: widget.server,
refreshToken: _pipelinesRefresh,
onRunStarted: _runStarted,
onViewPipelineRuns: (id) =>
_delegate.goTo(AppRoute.runsForPipeline(id)),
initialPipelineId: route.pipelineId,
initialVersion: route.version,
initialStageKey: route.stageKey,
@@ -302,13 +395,20 @@ class _PipelinesAppState extends State<PipelinesApp>
session: _session,
server: widget.server,
initialRunId: route.runId,
initialPipelineId: route.pipelineId,
initialStageKey: route.stageKey,
initialVisit: route.visit,
initialDecide: route.decide,
listRefreshToken: _runsRefresh,
notifications: _notifications,
attention: _attention,
onRunSelected: (id) => _delegate.goTo(AppRoute.run(id)),
onBack: () => _delegate.goTo(AppRoute.runs),
onBack: (id) => _delegate.goTo(
id == null ? AppRoute.runs : AppRoute.runsForPipeline(id),
),
onPipelineFilterChanged: (id) => _delegate.goTo(
id == null ? AppRoute.runs : AppRoute.runsForPipeline(id),
),
),
),
AppDestination.chat: (_) => ChatDestination(
@@ -19,6 +19,7 @@ class PipelinesDestination extends StatelessWidget {
required this.server,
this.refreshToken = 0,
this.onRunStarted,
this.onViewPipelineRuns,
this.initialPipelineId,
this.initialVersion = 0,
this.initialStageKey,
@@ -34,6 +35,7 @@ class PipelinesDestination extends StatelessWidget {
/// Receives the run id an accepted launch named; the shell opens that route.
final ValueChanged<int>? onRunStarted;
final ValueChanged<int>? onViewPipelineRuns;
/// The pipeline and pinned version a deep link names.
final int? initialPipelineId;
@@ -77,6 +79,7 @@ class PipelinesDestination extends StatelessWidget {
gateway: session.gateway,
embedded: true,
onRunStarted: onRunStarted,
onViewPipelineRuns: onViewPipelineRuns,
initialPipelineId: initialPipelineId,
initialVersion: initialVersion,
initialStageKey: initialStageKey,
+13 -1
View File
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import '../features/attention/notify/notification_controller.dart';
import '../features/attention/runtime/attention_controller.dart';
import '../features/runs/screen.dart';
import '../ui/adaptive/host.dart';
import 'app_session.dart';
@@ -19,18 +20,22 @@ class RunsDestination extends StatelessWidget {
required this.session,
required this.server,
this.initialRunId,
this.initialPipelineId,
this.initialStageKey,
this.initialVisit,
this.initialDecide = false,
this.onRunSelected,
this.onBack,
this.onPipelineFilterChanged,
this.listRefreshToken = 0,
this.notifications,
this.attention,
});
final AppSession session;
final ServerEndpoint server;
final int? initialRunId;
final int? initialPipelineId;
/// The stage key and optional visit a `/runs/:id/stage/:key[?visit=N]` route
/// names. They reach the detail only through [RunsScreen]; the destination
@@ -43,7 +48,8 @@ class RunsDestination extends StatelessWidget {
final bool initialDecide;
final ValueChanged<int>? onRunSelected;
final VoidCallback? onBack;
final ValueChanged<int?>? onBack;
final ValueChanged<int?>? onPipelineFilterChanged;
/// Advances when a launch was accepted elsewhere. The mounted Runs screen
/// re-reads its list once; no row is inserted locally.
@@ -52,6 +58,9 @@ class RunsDestination extends StatelessWidget {
/// The app-level notification capability shared with Settings.
final NotificationController? notifications;
/// The app-level attention controller the shell's Runs tab badge reads.
final AttentionController? attention;
@override
Widget build(BuildContext context) => AnimatedBuilder(
animation: session,
@@ -87,13 +96,16 @@ class RunsDestination extends StatelessWidget {
Widget _runsScreen() => RunsScreen(
gateway: session.gateway,
initialRunId: initialRunId,
initialPipelineId: initialPipelineId,
initialStageKey: initialStageKey,
initialVisit: initialVisit,
initialDecide: initialDecide,
syncToken: session.connectionEpoch,
listRefreshToken: listRefreshToken,
notifications: notifications,
attention: attention,
onRunSelected: onRunSelected,
onBack: onBack,
onPipelineFilterChanged: onPipelineFilterChanged,
);
}
@@ -0,0 +1,73 @@
import 'dart:async';
import '../../../core/api_gateway.dart';
import 'notification_bridge.dart';
import 'notification_models.dart';
/// Delivers live unanswered chat questions through the shared notification
/// capability, without coupling chat event folding to platform notifications.
class ChatQuestionNotices {
ChatQuestionNotices({
required ApiGateway gateway,
required this.canNotify,
required this.activeChatSessionId,
required this.sessionTitle,
required this.openChat,
required this.bridge,
}) {
_frames = gateway.frames.listen(_onEnvelope);
}
final bool Function() canNotify;
final String? Function() activeChatSessionId;
final Future<String?> Function(String sessionId) sessionTitle;
final void Function(String sessionId) openChat;
final NotificationBridge bridge;
late final StreamSubscription<JsonMap> _frames;
bool _disposed = false;
void _onEnvelope(JsonMap envelope) {
if (envelope['type'] != 'chat_event') return;
final event = envelope['chat_event'];
if (event is! Map || event['kind'] != 'form') return;
final sessionId = event['session_id'];
final form = event['form'];
if (sessionId is! String || sessionId.isEmpty ||
form is! Map || form['kind'] != 'question' ||
form['resolved'] == true || form['cancelled'] == true ||
form['id'] == null || !canNotify() ||
activeChatSessionId() == sessionId) {
return;
}
unawaited(_show(sessionId, Map<String, dynamic>.from(form)));
}
Future<void> _show(String sessionId, JsonMap form) async {
String? session;
try {
session = await sessionTitle(sessionId);
} catch (_) {
// An unavailable session list is equivalent to an unknown session title.
}
if (_disposed || !canNotify() || activeChatSessionId() == sessionId) return;
final title = (session ?? '').trim();
try {
bridge.show(
NotificationMessage(
chatSessionId: sessionId,
title: '${title.isEmpty ? 'Chat' : title} needs your answer',
body: '${form['title'] ?? 'The agent asked a question.'}',
tag: 'chat-question:${form['id']}',
),
onTap: () => openChat(sessionId),
);
} catch (_) {
// Notification delivery must not interfere with the in-page question.
}
}
void dispose() {
_disposed = true;
unawaited(_frames.cancel());
}
}
@@ -156,13 +156,15 @@ String notificationAlertBody(AttentionEntry entry) {
/// the stable identity used as the browser's coalescing tag.
class NotificationMessage {
const NotificationMessage({
required this.runId,
this.runId,
this.chatSessionId,
required this.title,
required this.body,
required this.tag,
});
final int runId;
final int? runId;
final String? chatSessionId;
final String title;
final String body;
final String tag;
@@ -28,6 +28,7 @@ class NeedsYouRunsHeading extends StatefulWidget {
this.now,
this.cupertino,
this.notifications,
this.attention,
});
/// The run summaries the Runs destination already holds.
@@ -55,23 +56,36 @@ class NeedsYouRunsHeading extends StatefulWidget {
/// the bell, so no store or platform bridge is touched there.
final NotificationController? notifications;
/// The app's shared attention controller, so the shell can mirror the same
/// count on the Runs tab. The heading seeds it with [rows]; its owner folds
/// [frames] and resets it on reconnect. Absent, the heading owns a private
/// controller fed from [frames], which fixtures and the list tests rely on.
final AttentionController? attention;
@override
State<NeedsYouRunsHeading> createState() => _NeedsYouRunsHeadingState();
}
class _NeedsYouRunsHeadingState extends State<NeedsYouRunsHeading> {
late final AttentionController _attention = AttentionController(
store: widget.store,
now: widget.now,
);
late final AttentionController _attention =
widget.attention ??
AttentionController(store: widget.store, now: widget.now);
StreamSubscription<JsonMap>? _frames;
bool get _ownsController => widget.attention == null;
@override
void initState() {
super.initState();
_attention.seedRows(widget.rows);
unawaited(_attention.load());
_listen();
if (_ownsController) {
unawaited(_attention.load());
_listen();
} else {
// The owner folds frames; publishing after every change it makes is the
// same idempotent call the private path makes after each frame.
_attention.addListener(_publish);
}
final notifications = widget.notifications;
if (notifications != null) {
notifications.onOpenRun = _openRunById;
@@ -115,7 +129,7 @@ class _NeedsYouRunsHeadingState extends State<NeedsYouRunsHeading> {
@override
void didUpdateWidget(covariant NeedsYouRunsHeading oldWidget) {
super.didUpdateWidget(oldWidget);
if (!identical(oldWidget.frames, widget.frames)) {
if (_ownsController && !identical(oldWidget.frames, widget.frames)) {
unawaited(_frames?.cancel());
_frames = null;
_listen();
@@ -135,7 +149,11 @@ class _NeedsYouRunsHeadingState extends State<NeedsYouRunsHeading> {
@override
void dispose() {
unawaited(_frames?.cancel());
_attention.dispose();
if (_ownsController) {
_attention.dispose();
} else {
_attention.removeListener(_publish);
}
super.dispose();
}
@@ -8,6 +8,7 @@ import '../../../core/api_gateway.dart';
import '../domain/chat_attachment_draft.dart';
import '../domain/chat_attachment_picker.dart';
import '../domain/chat_attachment_wire.dart';
import '../domain/chat_clipboard_paste.dart';
import '../domain/chat_commands.dart';
import '../ui/sessions/chat_adaptive.dart';
import 'chat_command_palette.dart';
@@ -50,13 +51,16 @@ const String chatQueuedNotice =
/// their names are shown with the host's own remove action and the bounded
/// draft owns every refusal. Send carries the chips as the landed wire parts,
/// keeps them until the prompt is accepted and leaves them in place on a
/// refusal; paste is not wired.
/// refusal. Pasting files takes the same draft path as the picker; pasting text
/// stays with the host field, so its caret, selection and draft behave exactly
/// as typing does.
class ChatComposerBar extends StatefulWidget {
const ChatComposerBar({
super.key,
required this.composer,
required this.running,
this.picker,
this.paste,
});
final ChatComposerController composer;
@@ -67,6 +71,9 @@ class ChatComposerBar extends StatefulWidget {
/// The host picker seam; production uses [hostChatAttachmentPicker].
final ChatAttachmentPicker? picker;
/// The host clipboard-file seam; production uses [hostChatClipboardPaste].
final ChatClipboardPaste? paste;
@override
State<ChatComposerBar> createState() => _ChatComposerBarState();
}
@@ -99,11 +106,15 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
bool _commandFailed = false;
ChatAttachmentPicker get _picker => widget.picker ?? hostChatAttachmentPicker;
ChatClipboardPaste get _paste => widget.paste ?? hostChatClipboardPaste;
ChatPasteUnsubscribe? _stopPaste;
@override
void initState() {
super.initState();
widget.composer.addListener(_syncDraft);
_listenForPaste();
unawaited(widget.composer.loadDraft());
}
@@ -115,6 +126,42 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
widget.composer.addListener(_syncDraft);
_syncDraft();
}
if (oldWidget.paste != widget.paste) {
_stopListeningForPaste();
_listenForPaste();
}
}
void _listenForPaste() {
if (!_paste.isSupported) return;
_stopPaste = _paste.listen(
onFiles: _onPastedFiles,
canAccept: _canAcceptPaste,
onError: _onPasteError,
);
}
void _stopListeningForPaste() {
final stop = _stopPaste;
_stopPaste = null;
stop?.call();
}
/// A pasted file is taken only while this composer owns the field and no
/// prompt is in flight, which is the same window as the attach control. The
/// host checks this before it suppresses the paste's default behaviour, so a
/// paste elsewhere is never swallowed.
bool _canAcceptPaste() =>
mounted && _focus.hasFocus && !widget.composer.sending;
void _onPastedFiles(List<ChatPickedFile> files) {
if (!mounted) return;
_addFiles(files);
}
void _onPasteError(Object error) {
if (!mounted) return;
setState(() => _attachmentError = '$error');
}
/// External draft changes (saved-draft load, send clear, refusal restore)
@@ -355,12 +402,19 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
return;
}
if (!mounted || files == null) return;
final picked = files;
_addFiles(files);
}
/// Adds each file through the landed attachment draft. A refusal keeps every
/// attachment already in the draft and shows the draft's own words; the
/// refused file's bytes are never retained. Picking and pasting share this
/// path so both apply the same name and 1 MiB decisions.
void _addFiles(List<ChatPickedFile> files) {
if (!mounted) return;
setState(() {
_attachmentError = null;
for (final file in picked) {
final attachment = file.attachment;
final refusal = _attachments.add(attachment);
for (final file in files) {
final refusal = _attachments.add(file.attachment);
if (refusal != null) {
_attachmentError = refusal.message;
} else {
@@ -410,6 +464,7 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
@override
void dispose() {
_stopListeningForPaste();
widget.composer.removeListener(_syncDraft);
_text.dispose();
_focus.dispose();
@@ -0,0 +1,82 @@
import 'chat_attachment_picker.dart';
import 'chat_clipboard_paste_stub.dart'
if (dart.library.js_interop) 'chat_clipboard_paste_web.dart'
as impl;
/// Receives the files one paste carried, in clipboard order.
typedef ChatPasteFiles = void Function(List<ChatPickedFile> files);
/// Whether the composer would take a pasted file right now. The host asks this
/// before it suppresses the paste's default behaviour.
typedef ChatPasteCanAccept = bool Function();
/// Reports a clipboard file whose bytes could not be read.
typedef ChatPasteFailed = void Function(Object error);
/// Stops observing paste events for one composer.
typedef ChatPasteUnsubscribe = void Function();
/// Registers [onFiles] for file pastes the composer may take and returns the
/// cancellation for that registration.
///
/// A text-only paste is never reported: it stays with the host field, so caret,
/// selection and the draft update exactly as typing does.
typedef ChatPasteSubscribe =
ChatPasteUnsubscribe Function(
ChatPasteFiles onFiles,
ChatPasteCanAccept canAccept,
ChatPasteFailed onError,
);
/// The clipboard seam for one host.
///
/// The web host observes the browser's own `paste` event. A paste carrying at
/// least one file is consumed ([ChatPasteCanAccept] permitting) and handed to
/// the composer as [ChatPickedFile] rows, so the landed attachment draft owns
/// every size decision and refusal. A clipboard file the browser recorded
/// without a name takes the web client's pasted name. A host without
/// clipboard-file paste constructs [ChatClipboardPaste.unsupported] and the
/// composer simply keeps its native text behaviour. Tests inject a fake
/// [subscribe].
class ChatClipboardPaste {
const ChatClipboardPaste({required ChatPasteSubscribe this.subscribe})
: unsupportedMessage = null;
const ChatClipboardPaste.unsupported(String message)
: subscribe = null,
unsupportedMessage = message;
/// The host's paste listener, or null when this host cannot observe files.
final ChatPasteSubscribe? subscribe;
/// Why this host cannot observe pasted files, when [subscribe] is null.
final String? unsupportedMessage;
bool get isSupported => subscribe != null;
/// Starts observing the host's paste event. A host without the capability
/// throws [UnsupportedError] with [unsupportedMessage].
ChatPasteUnsubscribe listen({
required ChatPasteFiles onFiles,
required ChatPasteCanAccept canAccept,
required ChatPasteFailed onError,
}) {
final subscribe = this.subscribe;
if (subscribe == null) throw UnsupportedError(unsupportedMessage!);
return subscribe(onFiles, canAccept, onError);
}
}
/// The web composer's recorded name for a clipboard file that arrived without
/// one: the MIME subtype becomes the extension, with the web client's `jpeg`
/// to `jpg` mapping and `bin` fallback.
String chatPastedAttachmentName(String mime, int sequence) {
final subtype = mime.split('/').last.toLowerCase();
final extension = subtype == 'jpeg'
? 'jpg'
: subtype.replaceAll(RegExp('[^a-z0-9]'), '');
return 'pasted-$sequence.${extension.isEmpty ? 'bin' : extension}';
}
/// The clipboard seam for the running host.
ChatClipboardPaste get hostChatClipboardPaste => impl.hostChatClipboardPaste;
@@ -0,0 +1,12 @@
import 'chat_clipboard_paste.dart';
/// Native fallback for clipboard-file paste.
///
/// The composer keeps the host field's own text paste on every platform; this
/// slice observes clipboard files on web only. A non-web host reports that
/// missing capability rather than pretending no paste happened.
const String chatClipboardPasteUnsupportedMessage =
'Pasting files is not supported on this platform yet.';
ChatClipboardPaste get hostChatClipboardPaste =>
const ChatClipboardPaste.unsupported(chatClipboardPasteUnsupportedMessage);
@@ -0,0 +1,126 @@
import 'dart:async';
import 'dart:js_interop';
import 'dart:js_interop_unsafe';
import 'chat_attachment_picker.dart';
import 'chat_clipboard_paste.dart';
/// The browser's clipboard-file paste, observed at the document once per
/// composer.
///
/// Declared with `dart:js_interop` rather than `package:web`, so the same source
/// compiles for the JavaScript and WebAssembly web targets. A paste carrying no
/// file is left completely alone: the field's own text paste keeps its caret,
/// selection and draft behaviour. Only a paste with files the composer will
/// accept is consumed, and its bytes are read before the files join the
/// composer's attachment draft.
@JS('document')
external _Document get _document;
extension type _Document._(JSObject _) implements JSObject {
external void addEventListener(JSString type, JSFunction listener);
external void removeEventListener(JSString type, JSFunction listener);
}
extension type _ClipboardEvent._(JSObject _) implements JSObject {
external bool get defaultPrevented;
external _ClipboardData? get clipboardData;
external void preventDefault();
}
extension type _ClipboardData._(JSObject _) implements JSObject {
external _DataTransferItemList get items;
}
extension type _DataTransferItemList._(JSObject _) implements JSObject {
external int get length;
}
extension type _DataTransferItem._(JSObject _) implements JSObject {
external JSString get kind;
external _ClipboardFile? getAsFile();
}
extension type _ClipboardFile._(JSObject _) implements JSObject {
external JSString get name;
external JSString get type;
external JSPromise<JSArrayBuffer> arrayBuffer();
}
ChatClipboardPaste get hostChatClipboardPaste =>
const ChatClipboardPaste(subscribe: _subscribeToPaste);
ChatPasteUnsubscribe _subscribeToPaste(
ChatPasteFiles onFiles,
ChatPasteCanAccept canAccept,
ChatPasteFailed onError,
) {
var sequence = 0;
void handlePaste(JSObject raw) {
final event = _ClipboardEvent._(raw);
if (event.defaultPrevented) return;
final data = event.clipboardData;
if (data == null) return;
final items = data.items;
final files = <_ClipboardFile>[];
for (var index = 0; index < items.length; index += 1) {
// DataTransferItemList is indexed, not a method list like FileList.
final raw = items.getProperty<JSObject?>('$index'.toJS);
if (raw == null) continue;
final item = _DataTransferItem._(raw);
if (item.kind.toDart != 'file') continue;
final file = item.getAsFile();
if (file != null) files.add(file);
}
// A text-only clipboard keeps the field's native paste untouched.
if (files.isEmpty || !canAccept()) return;
event.preventDefault();
unawaited(_readFiles(files, onFiles, onError, () => ++sequence));
}
final listener = handlePaste.toJS;
_document.addEventListener('paste'.toJS, listener);
return () => _document.removeEventListener('paste'.toJS, listener);
}
Future<void> _readFiles(
List<_ClipboardFile> files,
ChatPasteFiles onFiles,
ChatPasteFailed onError,
int Function() nextSequence,
) async {
final pasted = <ChatPickedFile>[];
final failures = <Object>[];
for (final file in files) {
try {
final buffer = await file.arrayBuffer().toDart;
final mime = file.type.toDart;
final recorded = file.name.toDart.trim();
pasted.add(
ChatPickedFile(
name: recorded.isEmpty
? chatPastedAttachmentName(mime, nextSequence())
: recorded,
mime: mime,
bytes: buffer.toDart.asUint8List(),
),
);
} catch (error) {
// One unreadable clipboard file must not hide the others.
failures.add(error);
}
}
// Deliver the readable files first: the composer's add clears an older
// error, so a partial failure is reported after its kept files.
if (pasted.isNotEmpty) onFiles(pasted);
for (final failure in failures) {
onError(failure);
}
}
@@ -21,6 +21,18 @@ enum RunNotifyMode {
};
}
/// Optional report requirement requested for a manually started run.
enum RunOutputFormat {
none('No report requirement', ''),
html('HTML report', 'html'),
markdown('Markdown report', 'markdown');
const RunOutputFormat(this.label, this.wireValue);
final String label;
final String wireValue;
}
/// One confirmed launch intent: the pinned pipeline identity, the operator's
/// fields and the idempotency key that belongs to them.
///
@@ -34,6 +46,7 @@ class RunPipelineIntent {
required this.prompt,
required this.workspace,
required this.notifyMode,
this.outputFormat = RunOutputFormat.none,
required this.requestKey,
});
@@ -42,6 +55,7 @@ class RunPipelineIntent {
final String prompt;
final String workspace;
final RunNotifyMode notifyMode;
final RunOutputFormat outputFormat;
final String requestKey;
/// The same key is only ever reused for the same pinned definition.
+4
View File
@@ -28,6 +28,7 @@ class PipelinesScreen extends StatefulWidget {
this.embedded = false,
this.syncToken = 0,
this.onRunStarted,
this.onViewPipelineRuns,
this.initialPipelineId,
this.initialVersion = 0,
this.initialStageKey,
@@ -45,6 +46,7 @@ class PipelinesScreen extends StatefulWidget {
/// Receives the run id an accepted launch names, so the composition can open
/// the existing run route. The feature never navigates on its own.
final ValueChanged<int>? onRunStarted;
final ValueChanged<int>? onViewPipelineRuns;
/// The pipeline a deep link names, opened after the list read starts.
final int? initialPipelineId;
@@ -170,6 +172,7 @@ class _PipelinesScreenState extends State<PipelinesScreen> {
gateway: widget.gateway,
showBack: true,
onRunStarted: widget.onRunStarted,
onViewPipelineRuns: widget.onViewPipelineRuns,
stageKey: stageKey,
stagePipelineId: widget.initialPipelineId,
stageVersion: widget.initialVersion,
@@ -192,6 +195,7 @@ class _PipelinesScreenState extends State<PipelinesScreen> {
gateway: widget.gateway,
showBack: false,
onRunStarted: widget.onRunStarted,
onViewPipelineRuns: widget.onViewPipelineRuns,
stageKey: stageKey,
stagePipelineId: widget.initialPipelineId,
stageVersion: widget.initialVersion,
@@ -51,6 +51,7 @@ class _RunPipelineActionState extends State<RunPipelineAction> {
await showRunPipelineDialog(
context: context,
detail: widget.detail,
gateway: widget.gateway,
pending: widget.controller.pendingRunFor(_pipelineId, _version),
onSubmit: _submit,
onPendingChanged: (intent) {
@@ -102,6 +103,7 @@ class _RunPipelineActionState extends State<RunPipelineAction> {
workspace: intent.workspace,
requestKey: intent.requestKey,
notifyMode: intent.notifyMode.wireValue,
outputFormat: intent.outputFormat.wireValue,
);
final accepted = _accept(run);
if (accepted is RunPipelineAccepted) return accepted;
@@ -2,6 +2,7 @@ import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../settings/settings_store.dart';
import '../../../ui/adaptive/host.dart';
import '../pipeline_models.dart';
import '../run_pipeline_intent.dart';
@@ -16,6 +17,7 @@ import 'run_pipeline_wording.dart';
Future<void> showRunPipelineDialog({
required BuildContext context,
required PipelineDetail detail,
required ApiGateway gateway,
required RunPipelineIntent? pending,
required Future<RunPipelineOutcome> Function(RunPipelineIntent intent)
onSubmit,
@@ -24,6 +26,7 @@ Future<void> showRunPipelineDialog({
}) {
final dialog = _RunPipelineDialog(
detail: detail,
gateway: gateway,
pending: pending,
cupertino: usesCupertinoHost(context),
onSubmit: onSubmit,
@@ -46,6 +49,7 @@ Future<void> showRunPipelineDialog({
class _RunPipelineDialog extends StatefulWidget {
const _RunPipelineDialog({
required this.detail,
required this.gateway,
required this.pending,
required this.cupertino,
required this.onSubmit,
@@ -54,6 +58,7 @@ class _RunPipelineDialog extends StatefulWidget {
});
final PipelineDetail detail;
final ApiGateway gateway;
final RunPipelineIntent? pending;
final bool cupertino;
final Future<RunPipelineOutcome> Function(RunPipelineIntent intent) onSubmit;
@@ -68,8 +73,11 @@ class _RunPipelineDialogState extends State<_RunPipelineDialog> {
late final TextEditingController _prompt;
late final TextEditingController _workspace;
late RunNotifyMode _notify;
late RunOutputFormat _outputFormat;
late RunPipelineIntent? _intent;
bool _sending = false;
bool _directoriesLoading = true;
List<String> _directories = const [];
String? _error;
@override
@@ -83,11 +91,49 @@ class _RunPipelineDialogState extends State<_RunPipelineDialog> {
: null;
_intent = restored;
_notify = restored?.notifyMode ?? RunNotifyMode.pipelineDefault;
_outputFormat = restored?.outputFormat ?? RunOutputFormat.none;
_prompt = TextEditingController(text: restored?.prompt ?? '');
_workspace = TextEditingController(text: restored?.workspace ?? '');
_error = restored == null ? null : runPipelineUnknownAdmission;
_loadDirectories(restored);
}
Future<void> _loadDirectories(RunPipelineIntent? restored) async {
final savedWorkspace = const SharedPreferencesSettingsStore().load().then(
(settings) => settings.workspace,
);
try {
final reply = await _gateway.call('chat_directories');
final value = reply['chat_directories'];
final directories = value is List
? value.whereType<String>().toList()
: <String>[];
final saved = await savedWorkspace;
if (!mounted) return;
setState(() {
_directories = directories
.where((path) => path.startsWith('/'))
.toList();
if (_workspace.text.isEmpty) {
_workspace.text = saved.startsWith('/')
? saved
: _directories.isEmpty
? ''
: _directories.first;
}
_directoriesLoading = false;
});
} catch (error) {
if (!mounted) return;
setState(() {
_directoriesLoading = false;
_error = '$error';
});
}
}
ApiGateway get _gateway => widget.gateway;
@override
void dispose() {
_prompt.dispose();
@@ -122,6 +168,7 @@ class _RunPipelineDialogState extends State<_RunPipelineDialog> {
prompt: prompt,
workspace: workspace.trim(),
notifyMode: _notify,
outputFormat: _outputFormat,
requestKey: newRunPipelineRequestKey(
widget.detail.id,
widget.detail.resolvedVersion,
@@ -213,10 +260,21 @@ class _RunPipelineDialogState extends State<_RunPipelineDialog> {
RunPipelineFields(
prompt: _prompt,
workspace: _workspace,
directories: _directories,
cupertino: widget.cupertino,
onChooseDirectory: _chooseDirectory,
notifyMode: _notify,
outputFormat: _outputFormat,
locked: _locked,
onNotifyChanged: (mode) => setState(() => _notify = mode),
onOutputFormatChanged: (format) =>
setState(() => _outputFormat = format),
),
if (_directoriesLoading)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(runPipelineDirectoriesLoading),
),
if (_error case final error?)
Padding(
padding: const EdgeInsets.only(top: 12),
@@ -228,4 +286,8 @@ class _RunPipelineDialogState extends State<_RunPipelineDialog> {
],
);
}
void _chooseDirectory(String directory) {
_workspace.text = directory;
}
}
@@ -14,16 +14,26 @@ class RunPipelineFields extends StatelessWidget {
super.key,
required this.prompt,
required this.workspace,
required this.directories,
required this.cupertino,
required this.onChooseDirectory,
required this.notifyMode,
required this.outputFormat,
required this.locked,
required this.onNotifyChanged,
required this.onOutputFormatChanged,
});
final TextEditingController prompt;
final TextEditingController workspace;
final List<String> directories;
final bool cupertino;
final ValueChanged<String> onChooseDirectory;
final RunNotifyMode notifyMode;
final RunOutputFormat outputFormat;
final bool locked;
final ValueChanged<RunNotifyMode> onNotifyChanged;
final ValueChanged<RunOutputFormat> onOutputFormatChanged;
@override
Widget build(BuildContext context) {
@@ -41,6 +51,10 @@ class RunPipelineFields extends StatelessWidget {
const SizedBox(height: 12),
_FieldLabel(runPipelineNotifyLabel, cupertino: cupertino),
_notifyField(context, cupertino),
const SizedBox(height: 12),
_FieldLabel(runPipelineOutputFormatLabel, cupertino: cupertino),
_outputFormatField(context, cupertino),
_helper(context, runPipelineOutputFormatHelper, cupertino),
],
);
}
@@ -77,18 +91,51 @@ class RunPipelineFields extends StatelessWidget {
}
Widget _workspaceField(BuildContext context, bool cupertino) {
if (cupertino) {
return CupertinoTextField(
key: runPipelineWorkspaceKey,
controller: workspace,
placeholder: runPipelineWorkspacePlaceholder,
placeholderStyle: _cupertinoPlaceholder(context),
style: CupertinoTheme.of(context).textTheme.textStyle,
enabled: !locked,
autocorrect: false,
padding: const EdgeInsets.all(8),
);
}
final field = cupertino
? _cupertinoWorkspace(context)
: _materialWorkspace();
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: field),
if (directories.isNotEmpty)
cupertino
? CupertinoButton(
key: runPipelineWorkspaceSuggestionsKey,
padding: EdgeInsets.zero,
onPressed: locked
? null
: () => _chooseCupertinoDirectory(context),
child: const Icon(CupertinoIcons.folder),
)
: PopupMenuButton<String>(
key: runPipelineWorkspaceSuggestionsKey,
tooltip: runPipelineWorkspaceLabel,
enabled: !locked,
onSelected: onChooseDirectory,
itemBuilder: (_) => [
for (final path in directories)
PopupMenuItem(value: path, child: Text(path)),
],
),
],
);
}
Widget _cupertinoWorkspace(BuildContext context) {
return CupertinoTextField(
key: runPipelineWorkspaceKey,
controller: workspace,
placeholder: runPipelineWorkspacePlaceholder,
placeholderStyle: _cupertinoPlaceholder(context),
style: CupertinoTheme.of(context).textTheme.textStyle,
enabled: !locked,
autocorrect: false,
padding: const EdgeInsets.all(8),
);
}
Widget _materialWorkspace() {
return TextField(
key: runPipelineWorkspaceKey,
controller: workspace,
@@ -101,6 +148,27 @@ class RunPipelineFields extends StatelessWidget {
);
}
Future<void> _chooseCupertinoDirectory(BuildContext context) async {
final chosen = await showCupertinoModalPopup<String>(
context: context,
builder: (sheetContext) => CupertinoActionSheet(
title: const Text(runPipelineWorkspaceLabel),
actions: [
for (final path in directories)
CupertinoActionSheetAction(
onPressed: () => Navigator.of(sheetContext).pop(path),
child: Text(path),
),
],
cancelButton: CupertinoActionSheetAction(
onPressed: () => Navigator.of(sheetContext).pop(),
child: const Text(runPipelineCancelLabel),
),
),
);
if (chosen != null) onChooseDirectory(chosen);
}
Widget _notifyField(BuildContext context, bool cupertino) {
if (cupertino) {
return CupertinoButton(
@@ -156,10 +224,67 @@ class RunPipelineFields extends StatelessWidget {
if (chosen != null) onNotifyChanged(chosen);
}
Widget _outputFormatField(BuildContext context, bool cupertino) {
if (cupertino) {
return CupertinoButton(
key: runPipelineOutputFormatKey,
padding: EdgeInsets.zero,
alignment: AlignmentDirectional.centerStart,
onPressed: locked ? null : () => _chooseOutputFormat(context),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(child: Text(outputFormat.label)),
const SizedBox(width: 4),
const Icon(CupertinoIcons.chevron_down, size: 14),
],
),
);
}
return DropdownButtonFormField<RunOutputFormat>(
key: runPipelineOutputFormatKey,
initialValue: outputFormat,
decoration: const InputDecoration(border: OutlineInputBorder()),
items: [
for (final format in RunOutputFormat.values)
DropdownMenuItem(value: format, child: Text(format.label)),
],
onChanged: locked
? null
: (format) {
if (format != null) onOutputFormatChanged(format);
},
);
}
Future<void> _chooseOutputFormat(BuildContext context) async {
final chosen = await showCupertinoModalPopup<RunOutputFormat>(
context: context,
builder: (sheetContext) => CupertinoActionSheet(
title: const Text(runPipelineOutputFormatLabel),
actions: [
for (final format in RunOutputFormat.values)
CupertinoActionSheetAction(
onPressed: () => Navigator.of(sheetContext).pop(format),
child: Text(format.label),
),
],
cancelButton: CupertinoActionSheetAction(
isDefaultAction: true,
onPressed: () => Navigator.of(sheetContext).pop(),
child: const Text(runPipelineCancelLabel),
),
),
);
if (chosen != null) onOutputFormatChanged(chosen);
}
TextStyle _cupertinoPlaceholder(BuildContext context) {
// The host's own dynamic placeholder colour (light and dark), resolved for
// the dialog's inherited Cupertino brightness.
return TextStyle(color: CupertinoColors.placeholderText.resolveFrom(context));
return TextStyle(
color: CupertinoColors.placeholderText.resolveFrom(context),
);
}
Widget _helper(BuildContext context, String text, bool cupertino) {
@@ -12,7 +12,14 @@ const runPipelineWorkspaceLabel = 'Working directory (on the server)';
const runPipelineWorkspaceHelper =
'Choose a recent directory or type an absolute path.';
const runPipelineWorkspacePlaceholder = '/absolute/path/on/the/server';
const runPipelineDirectoriesLoading = 'Loading directories…';
const runPipelineWorkspaceSuggestionsKey = ValueKey<String>(
'run-pipeline-workspace-suggestions',
);
const runPipelineNotifyLabel = 'Notifications for this run';
const runPipelineOutputFormatLabel = 'Report format';
const runPipelineOutputFormatHelper =
'Requires a nonempty server-written report before success. Structure only; facts are not verified.';
const runPipelineCancelLabel = 'Cancel';
const runPipelineConfirmLabel = 'Run';
const runPipelineSendingLabel = 'Starting…';
@@ -37,13 +44,12 @@ const runPipelineActionKey = ValueKey<String>('run-pipeline-action');
const runPipelinePromptKey = ValueKey<String>('run-pipeline-prompt');
const runPipelineWorkspaceKey = ValueKey<String>('run-pipeline-workspace');
const runPipelineNotifyKey = ValueKey<String>('run-pipeline-notify');
const runPipelineOutputFormatKey = ValueKey<String>('run-pipeline-output-format');
const runPipelineCancelKey = ValueKey<String>('run-pipeline-cancel');
const runPipelineConfirmKey = ValueKey<String>('run-pipeline-confirm');
const runPipelineErrorKey = ValueKey<String>('run-pipeline-error');
/// The server's refusal, verbatim. Only a blank error gets a sentence so the
/// prompt never claims a run that was not admitted.
String describeRunPipelineError(Object error) => describeErrorReason(
error,
fallback: 'The server did not start the run.',
);
String describeRunPipelineError(Object error) =>
describeErrorReason(error, fallback: 'The server did not start the run.');
@@ -30,6 +30,7 @@ class PipelineDetailPanel extends StatefulWidget {
required this.gateway,
required this.showBack,
this.onRunStarted,
this.onViewPipelineRuns,
this.stageKey,
this.stagePipelineId,
this.stageVersion = 0,
@@ -45,6 +46,7 @@ class PipelineDetailPanel extends StatefulWidget {
/// A run started from this detail's Run action; receives the server's id.
final ValueChanged<int>? onRunStarted;
final ValueChanged<int>? onViewPipelineRuns;
/// The stage the route names for this detail, or null when it names none.
final String? stageKey;
@@ -337,6 +339,25 @@ class _PipelineDetailPanelState extends State<PipelineDetailPanel> {
onRunStarted: widget.onRunStarted,
),
),
Align(
alignment: AlignmentDirectional.centerStart,
child: Semantics(
button: true,
label: detail.name.trim().isEmpty
? 'View runs of this pipeline'
: 'View runs of ${detail.name}',
child: ExcludeSemantics(
child: TextButton.icon(
onPressed: widget.onViewPipelineRuns == null
? null
: () => widget.onViewPipelineRuns!(detail.id),
icon: const Icon(Icons.list_alt),
label: const Text('Runs'),
key: const Key('pipeline-view-runs'),
),
),
),
),
],
),
);
@@ -15,6 +15,55 @@ const runStates = [
/// `0x7fffffffffffffff` literals failed dart2js compilation.
const int _maxMillis = 8640000000000000;
String localDayKey(DateTime date) {
final local = date.toLocal();
String two(int value) => value.toString().padLeft(2, '0');
return '${local.year}-${two(local.month)}-${two(local.day)}';
}
String runDayLabel(String createdAt, DateTime today) {
final created = DateTime.tryParse(createdAt)?.toLocal();
if (created == null) return 'Unknown date';
final day = localDayKey(created);
if (day == localDayKey(today)) return 'Today';
final yesterday = DateTime(
today.year,
today.month,
today.day,
).subtract(const Duration(days: 1));
if (day == localDayKey(yesterday)) return 'Yesterday';
const months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
return '${created.day} ${months[created.month - 1]} ${created.year}';
}
List<({String label, List<JsonMap> runs})> groupRunsByDay(
List<JsonMap> sortedRuns,
DateTime today,
) {
final groups = <({String label, List<JsonMap> runs})>[];
for (final run in sortedRuns) {
final label = runDayLabel('${run['created_at'] ?? ''}', today);
if (groups.isEmpty || groups.last.label != label) {
groups.add((label: label, runs: <JsonMap>[]));
}
groups.last.runs.add(run);
}
return groups;
}
({String label, String? pipeline}) runIdentity(dynamic title, dynamic name) {
final stored = '${title ?? ''}'.trim();
return (
+49 -2
View File
@@ -5,6 +5,7 @@ import 'package:flutter/widgets.dart';
import '../../core/api_gateway.dart';
import '../../ui/adaptive/host.dart';
import '../attention/notify/notification_controller.dart';
import '../attention/runtime/attention_controller.dart';
import '../attention/runtime/attention_store.dart';
import 'actions/decision_action.dart';
import 'data/runs_repository.dart';
@@ -24,6 +25,7 @@ class RunsScreen extends StatefulWidget {
super.key,
required this.gateway,
this.initialRunId,
this.initialPipelineId,
this.initialStageKey,
this.initialVisit,
this.initialDecide = false,
@@ -31,15 +33,18 @@ class RunsScreen extends StatefulWidget {
this.listRefreshToken = 0,
this.onRunSelected,
this.onBack,
this.onPipelineFilterChanged,
this.attentionStore = const SharedPreferencesAttentionStore(),
this.attentionNow,
this.notifications,
this.attention,
});
final ApiGateway gateway;
/// The run the current route names, or null for the list.
final int? initialRunId;
final int? initialPipelineId;
/// The recorded stage visit the route names inside [initialRunId]. The detail
/// applies it once per route target; the feature never invents a visit.
@@ -60,7 +65,8 @@ class RunsScreen extends StatefulWidget {
final int listRefreshToken;
final ValueChanged<int>? onRunSelected;
final VoidCallback? onBack;
final ValueChanged<int?>? onBack;
final ValueChanged<int?>? onPipelineFilterChanged;
/// Persisted attention dismissals and the clock for its local-day window.
/// The app uses SharedPreferences; tests and fixtures inject a memory store.
@@ -70,6 +76,9 @@ class RunsScreen extends StatefulWidget {
/// App-level notification delivery for live attention transitions.
final NotificationController? notifications;
/// The app's shared attention controller, mirrored on the shell's Runs tab.
final AttentionController? attention;
@override
State<RunsScreen> createState() => _RunsScreenState();
}
@@ -77,6 +86,8 @@ class RunsScreen extends StatefulWidget {
class _RunsScreenState extends State<RunsScreen> {
late final RunsController controller;
num? _shownRunId;
int? _reportedPipelineId;
bool _applyingRoutePipeline = false;
/// The route's decision request is one-shot: the first loaded detail for the
/// named run consumes it, whether or not that run is waiting.
@@ -86,8 +97,14 @@ class _RunsScreenState extends State<RunsScreen> {
void initState() {
super.initState();
controller = RunsController(RunsRepository(widget.gateway));
_reportedPipelineId = widget.initialPipelineId;
if (widget.initialPipelineId != null) {
controller.clearFilters();
controller.setPipeline(widget.initialPipelineId);
}
controller.listen(widget.gateway.frames);
controller.addListener(_selectionChanged);
controller.addListener(_pipelineFilterChanged);
controller.addListener(_detailChanged);
controller.load(widget.initialRunId);
}
@@ -99,6 +116,21 @@ class _RunsScreenState extends State<RunsScreen> {
widget.initialDecide != oldWidget.initialDecide) {
_decideConsumed = false;
}
if (widget.initialPipelineId != oldWidget.initialPipelineId) {
final id = widget.initialPipelineId;
// A run detail replaces the list URL but retains its active list filter.
// Only a route back to the list can explicitly clear that facet.
if (id != null || widget.initialRunId == null) {
_applyingRoutePipeline = true;
try {
if (id != null) controller.clearFilters();
controller.setPipeline(id);
_reportedPipelineId = id;
} finally {
_applyingRoutePipeline = false;
}
}
}
if (widget.syncToken != oldWidget.syncToken) {
controller.resync();
}
@@ -132,6 +164,19 @@ class _RunsScreenState extends State<RunsScreen> {
if (mounted) setState(() {});
}
void _pipelineFilterChanged() {
final id = controller.pipelineId;
if (_applyingRoutePipeline) {
_reportedPipelineId = id;
return;
}
if (id == _reportedPipelineId) return;
_reportedPipelineId = id;
if (controller.selectedRunId == null) {
widget.onPipelineFilterChanged?.call(id);
}
}
/// Opens the route's decision prompt after the named detail has arrived.
/// A non-waiting run consumes the request without a prompt, and the prompt
/// itself only closes; the detail underneath is left as it is.
@@ -166,12 +211,13 @@ class _RunsScreenState extends State<RunsScreen> {
void _back() {
controller.back();
widget.onBack?.call();
widget.onBack?.call(controller.pipelineId);
}
@override
void dispose() {
controller.removeListener(_selectionChanged);
controller.removeListener(_pipelineFilterChanged);
controller.removeListener(_detailChanged);
controller.dispose();
super.dispose();
@@ -193,6 +239,7 @@ class _RunsScreenState extends State<RunsScreen> {
attentionStore: widget.attentionStore,
attentionNow: widget.attentionNow,
notifications: widget.notifications,
attention: widget.attention,
),
),
),
@@ -209,7 +209,10 @@ class _RunDetailTabsState extends State<RunDetailTabs> {
case RunSummarySection.output:
_outputSection.expand();
case null:
break;
// A hit that names no section must not leave a previously expanded
// one open; the Summary panel starts collapsed.
_inputSection.collapse();
_outputSection.collapse();
}
case RunVisitTarget(:final stageKey, :final timelineIndex):
if (detailVisitStepAt(widget.run, timelineIndex) == null) return;
@@ -177,6 +177,11 @@ class RunsController extends ChangeNotifier {
notifyListeners();
}
void setTimeRange(String value) {
timeRange = value;
notifyListeners();
}
void setSort(String value) {
sort = value;
notifyListeners();
+134 -9
View File
@@ -7,8 +7,8 @@ import 'runs_controller.dart';
/// The runs list's compact native filter/sort toolbar and applied-filter chips.
///
/// Mirrors the browser's run toolbar: one `Filter` menu carrying the status and
/// trigger facets, one `Sort:` menu, and a removable chip per applied facet.
/// Mirrors the browser's run toolbar: one `Filter` menu carrying its facets,
/// one `Sort:` menu, and a removable chip per applied facet.
/// The buttons sit in a single horizontally scrollable row so a phone at a
/// doubled text scale can still reach them without crushing the list.
class RunsFilters extends StatelessWidget {
@@ -58,6 +58,8 @@ class RunsFilters extends StatelessWidget {
checked: controller.sort == sort.$1,
child: Text(sort.$2),
),
const PopupMenuDivider(),
const PopupMenuItem(value: 'newest_first', child: Text('Reset')),
],
child: _materialButton(
Icons.sort,
@@ -79,6 +81,7 @@ class RunsFilters extends StatelessWidget {
);
List<PopupMenuEntry<_FilterChoice>> _materialMenuItems() => [
const PopupMenuItem(enabled: false, child: Text('Status')),
for (final status in runStates)
CheckedPopupMenuItem(
value: (kind: 'status', value: status),
@@ -86,6 +89,28 @@ class RunsFilters extends StatelessWidget {
child: Text(status),
),
const PopupMenuDivider(),
const PopupMenuItem(enabled: false, child: Text('Pipeline')),
CheckedPopupMenuItem(
value: (kind: 'pipeline', value: ''),
checked: controller.pipelineId == null,
child: const Text('Any pipeline'),
),
for (final pipeline in _pipelines(controller))
CheckedPopupMenuItem(
value: (kind: 'pipeline', value: '${pipeline.id}'),
checked: controller.pipelineId == pipeline.id,
child: Text(pipeline.name),
),
const PopupMenuDivider(),
const PopupMenuItem(enabled: false, child: Text('Time range')),
for (final range in _timeRanges)
CheckedPopupMenuItem(
value: (kind: 'time', value: range.$1),
checked: controller.timeRange == range.$1,
child: Text(range.$2),
),
const PopupMenuDivider(),
const PopupMenuItem(enabled: false, child: Text('Trigger')),
for (final schedule in _schedules)
CheckedPopupMenuItem(
value: (kind: 'schedule', value: schedule.$1),
@@ -99,6 +124,15 @@ class RunsFilters extends StatelessWidget {
child: Text('Clear filters'),
),
],
if (_hasUnclassifiedRuns(controller)) ...[
const PopupMenuDivider(),
const PopupMenuItem(
enabled: false,
child: Text(
'Some records have no scheduling provenance; they stay unclassified.',
),
),
],
];
void _apply(_FilterChoice choice) {
@@ -106,6 +140,12 @@ class RunsFilters extends StatelessWidget {
controller.setStatus(choice.value);
} else if (choice.kind == 'schedule') {
controller.setScheduled(choice.value);
} else if (choice.kind == 'pipeline') {
controller.setPipeline(
choice.value.isEmpty ? null : int.tryParse(choice.value),
);
} else if (choice.kind == 'time') {
controller.setTimeRange(choice.value);
} else {
controller.clearFilters();
}
@@ -127,7 +167,7 @@ class RunsFilters extends StatelessWidget {
onPressed: () => _choose(
context,
'Sort runs',
_sorts,
_sortChoices,
controller.sort,
controller.setSort,
),
@@ -148,6 +188,7 @@ class RunsFilters extends StatelessWidget {
builder: (context, _) => CupertinoActionSheet(
title: const Text('Filter runs'),
actions: [
_cupertinoSection('Status'),
for (final status in runStates)
CupertinoActionSheetAction(
onPressed: () => controller.setStatus(status),
@@ -155,6 +196,29 @@ class RunsFilters extends StatelessWidget {
'${controller.statuses.contains(status) ? '✓ ' : ''}$status',
),
),
_cupertinoSection('Pipeline'),
CupertinoActionSheetAction(
onPressed: () => controller.setPipeline(null),
child: Text(
'${controller.pipelineId == null ? '✓ ' : ''}Any pipeline',
),
),
for (final pipeline in _pipelines(controller))
CupertinoActionSheetAction(
onPressed: () => controller.setPipeline(pipeline.id),
child: Text(
'${controller.pipelineId == pipeline.id ? '✓ ' : ''}${pipeline.name}',
),
),
_cupertinoSection('Time range'),
for (final range in _timeRanges)
CupertinoActionSheetAction(
onPressed: () => controller.setTimeRange(range.$1),
child: Text(
'${controller.timeRange == range.$1 ? '✓ ' : ''}${range.$2}',
),
),
_cupertinoSection('Trigger'),
for (final schedule in _schedules)
CupertinoActionSheetAction(
onPressed: () => controller.setScheduled(schedule.$1),
@@ -163,6 +227,13 @@ class RunsFilters extends StatelessWidget {
'${schedule.$2}',
),
),
if (_hasUnclassifiedRuns(controller))
CupertinoActionSheetAction(
onPressed: () {},
child: const Text(
'Some records have no scheduling provenance; they stay unclassified.',
),
),
if (controller.activeFilterCount > 0)
CupertinoActionSheetAction(
onPressed: controller.clearFilters,
@@ -206,12 +277,16 @@ class RunsFilters extends StatelessWidget {
Widget _appliedFilters(BuildContext context) {
final applied = _applied();
return Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 4),
child: Wrap(
spacing: 8,
runSpacing: 4,
children: [for (final entry in applied) _appliedChip(context, entry)],
return Semantics(
container: true,
label: 'Applied run filters',
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 4),
child: Wrap(
spacing: 8,
runSpacing: 4,
children: [for (final entry in applied) _appliedChip(context, entry)],
),
),
);
}
@@ -225,6 +300,12 @@ class RunsFilters extends StatelessWidget {
for (final status in controller.statuses) {
applied.add((label: status, clear: () => controller.setStatus(status)));
}
if (controller.timeRange != 'any_time') {
applied.add((
label: _timeRangeLabel(controller.timeRange),
clear: () => controller.setTimeRange('any_time'),
));
}
if (controller.scheduled != 'any') {
applied.add((
label: _scheduleLabel(controller.scheduled),
@@ -288,14 +369,58 @@ typedef _FilterChoice = ({String kind, String value});
const _sorts = [
('newest_first', 'Newest first'),
('oldest_first', 'Oldest first'),
('longest_duration', 'Longest duration'),
('shortest_duration', 'Shortest duration'),
('pipeline_name', 'Pipeline name'),
('status', 'Status'),
];
const _sortChoices = [..._sorts, ('newest_first', 'Reset')];
const _schedules = [
('any', 'Any trigger'),
('scheduled', 'Scheduled runs'),
('unscheduled', 'Not scheduled'),
];
const _timeRanges = [
('any_time', 'Any time'),
('today', 'Today'),
('last_7_days', 'Last 7 days'),
('last_30_days', 'Last 30 days'),
];
List<({int id, String name})> _pipelines(RunsController controller) {
final names = <int, String>{};
final ids = <int>{};
for (final run in controller.runs) {
final id = run['pipeline_id'];
if (id is! int) continue;
ids.add(id);
final name = '${run['name'] ?? ''}'.trim();
if (name.isNotEmpty && !names.containsKey(id)) names[id] = name;
}
final options = ids
.map((id) => (id: id, name: names[id] ?? 'Pipeline $id'))
.toList();
options.sort((a, b) {
final nameOrder = a.name.toLowerCase().compareTo(b.name.toLowerCase());
return nameOrder != 0 ? nameOrder : a.id.compareTo(b.id);
});
return options;
}
bool _hasUnclassifiedRuns(RunsController controller) =>
controller.runs.any((run) {
final id = run['schedule_id'];
return run['scheduled'] is! bool && !(id is num && id > 0);
});
Widget _cupertinoSection(String title) => Padding(
padding: const EdgeInsetsDirectional.only(top: 8),
child: Text(title, style: const TextStyle(fontWeight: FontWeight.bold)),
);
String _timeRangeLabel(String value) => _timeRanges
.firstWhere((entry) => entry.$1 == value, orElse: () => _timeRanges.first)
.$2;
String _sortLabel(String value) =>
_sorts.firstWhere((e) => e.$1 == value, orElse: () => _sorts.first).$2;
String _scheduleLabel(String value) => _schedules
+32 -7
View File
@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/host.dart';
import '../../attention/notify/notification_controller.dart';
import '../../attention/runtime/attention_controller.dart';
import '../../attention/runtime/attention_store.dart';
import '../../attention/ui/needs_you_runs_heading.dart';
import '../domain/run_models.dart';
@@ -19,6 +20,7 @@ class RunsList extends StatelessWidget {
this.attentionStore = const SharedPreferencesAttentionStore(),
this.attentionNow,
this.notifications,
this.attention,
});
final RunsController controller;
@@ -37,6 +39,9 @@ class RunsList extends StatelessWidget {
/// App-level notification delivery; absent in list-only fixtures.
final NotificationController? notifications;
/// The app's shared attention controller; absent in list-only fixtures.
final AttentionController? attention;
@override
Widget build(BuildContext context) {
if (controller.loading && controller.runs.isEmpty) {
@@ -74,13 +79,7 @@ class RunsList extends StatelessWidget {
Expanded(
child: controller.visibleRuns.isEmpty
? const Center(child: Text('No runs found.'))
: ListView.separated(
itemCount: controller.visibleRuns.length,
separatorBuilder: (context, index) =>
const Divider(height: 1),
itemBuilder: (context, index) =>
_runTile(context, controller.visibleRuns[index]),
),
: _groupedRuns(context),
),
],
);
@@ -108,11 +107,37 @@ class RunsList extends StatelessWidget {
store: attentionStore,
now: attentionNow,
notifications: notifications,
attention: attention,
),
],
),
);
Widget _groupedRuns(BuildContext context) {
final groups = groupRunsByDay(controller.visibleRuns, DateTime.now());
final entries = <({String? label, JsonMap? run})>[];
for (final group in groups) {
entries.add((label: group.label, run: null));
entries.addAll(group.runs.map((run) => (label: null, run: run)));
}
return ListView.builder(
itemCount: entries.length,
itemBuilder: (context, index) {
final entry = entries[index];
if (entry.label case final label?) {
final style = usesCupertinoHost(context)
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.labelLarge;
return Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 4),
child: Semantics(header: true, child: Text(label, style: style)),
);
}
return _runTile(context, entry.run!);
},
);
}
Widget _emptyError(BuildContext context) => Center(
child: Column(
mainAxisSize: MainAxisSize.min,
+38 -6
View File
@@ -1,6 +1,7 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'attention_badge.dart';
import 'destination.dart';
class AdaptiveShell extends StatefulWidget {
@@ -11,6 +12,7 @@ class AdaptiveShell extends StatefulWidget {
this.destination,
this.onDestinationSelected,
this.onSearch,
this.attentionCount = 0,
});
final Map<AppDestination, WidgetBuilder> destinationBodies;
@@ -25,6 +27,10 @@ class AdaptiveShell extends StatefulWidget {
/// shell tests and compositions without routing keep their tab set only.
final VoidCallback? onSearch;
/// Runs needing the operator today, mirrored on the Runs tab in every mount
/// so it stays visible from any destination. Zero shows no badge.
final int attentionCount;
@override
State<AdaptiveShell> createState() => _AdaptiveShellState();
}
@@ -65,6 +71,17 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
List<T> _items<T>(T Function(AppDestination) build) =>
AppDestination.values.map(build).toList();
/// The destination's icon; only Runs carries the attention count.
Widget _icon(AppDestination destination, IconData data) {
final icon = Icon(data);
if (destination != AppDestination.runs) return icon;
return AttentionDestinationIcon(
count: widget.attentionCount,
cupertino: widget.cupertino,
child: icon,
);
}
@override
Widget build(BuildContext context) {
final index = AppDestination.values.indexOf(_selected);
@@ -108,6 +125,7 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
_CupertinoSidebar(
selected: _selected,
onSelected: _select,
attentionCount: widget.attentionCount,
),
Expanded(child: _destinationStack(contents, index)),
],
@@ -117,11 +135,12 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
Expanded(child: _destinationStack(contents, index)),
CupertinoTabBar(
currentIndex: index,
onTap: (value) => _select(AppDestination.values[value]),
onTap: (value) =>
_select(AppDestination.values[value]),
items: _items((destination) {
final item = destinationDetails(destination);
return BottomNavigationBarItem(
icon: Icon(item.cupertinoIcon),
icon: _icon(destination, item.cupertinoIcon),
label: item.label,
);
}),
@@ -155,7 +174,7 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
destinations: _items((destination) {
final item = destinationDetails(destination);
return NavigationRailDestination(
icon: Icon(item.icon),
icon: _icon(destination, item.icon),
label: Text(item.label),
);
}),
@@ -172,7 +191,7 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
destinations: _items((destination) {
final item = destinationDetails(destination);
return NavigationDestination(
icon: Icon(item.icon),
icon: _icon(destination, item.icon),
label: item.label,
);
}),
@@ -189,10 +208,15 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
/// The wide-window Cupertino destination list: the web's 200px rail with the
/// host's own grouped list controls.
class _CupertinoSidebar extends StatelessWidget {
const _CupertinoSidebar({required this.selected, required this.onSelected});
const _CupertinoSidebar({
required this.selected,
required this.onSelected,
this.attentionCount = 0,
});
final AppDestination selected;
final ValueChanged<AppDestination> onSelected;
final int attentionCount;
@override
Widget build(BuildContext context) {
@@ -215,7 +239,15 @@ class _CupertinoSidebar extends StatelessWidget {
for (final destination in AppDestination.values)
CupertinoListTile(
key: ValueKey('shell.destination.${destination.name}'),
leading: Icon(destinationDetails(destination).cupertinoIcon),
leading: destination == AppDestination.runs
? AttentionDestinationIcon(
count: attentionCount,
cupertino: true,
child: Icon(
destinationDetails(destination).cupertinoIcon,
),
)
: Icon(destinationDetails(destination).cupertinoIcon),
title: Text(destinationDetails(destination).label),
trailing: destination == selected
? Icon(
+82
View File
@@ -0,0 +1,82 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../features/attention/domain/attention_models.dart';
/// Mirrors the Runs-heading bell count onto the Runs destination icon.
///
/// The bell itself lives in the Runs heading, so without this the count would
/// be visible only on that destination; the web mirrors it on the rail and
/// dock tab. Material hosts use the framework [Badge]; Cupertino has no badge
/// control, so its tab bar and sidebar get the host's red count overlay. Zero
/// draws the bare icon, and a count labels the item exactly like the bell:
/// `Notifications, {n} needing attention`.
class AttentionDestinationIcon extends StatelessWidget {
const AttentionDestinationIcon({
super.key,
required this.count,
required this.cupertino,
required this.child,
});
final int count;
final bool cupertino;
final Widget child;
@override
Widget build(BuildContext context) {
final visible = count > 0;
final Widget icon = cupertino
? _CupertinoCountOverlay(count: count, visible: visible, child: child)
: Badge(label: Text('$count'), isLabelVisible: visible, child: child);
if (!visible) return icon;
// The number alone would read as a stray "3"; the item carries the bell's
// full label instead.
return Semantics(
label: attentionBadgeLabel(count),
child: ExcludeSemantics(child: icon),
);
}
}
/// The iOS tab-badge idiom: a red stadium with the count over the icon's
/// trailing corner. Content-driven size; only the overlap offset is fixed.
class _CupertinoCountOverlay extends StatelessWidget {
const _CupertinoCountOverlay({
required this.count,
required this.visible,
required this.child,
});
final int count;
final bool visible;
final Widget child;
@override
Widget build(BuildContext context) {
if (!visible) return child;
final style = CupertinoTheme.of(
context,
).textTheme.tabLabelTextStyle.copyWith(color: CupertinoColors.white);
return Stack(
clipBehavior: Clip.none,
children: [
child,
PositionedDirectional(
top: -6,
end: -10,
child: DecoratedBox(
decoration: ShapeDecoration(
color: CupertinoColors.systemRed.resolveFrom(context),
shape: const StadiumBorder(),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1),
child: Text('$count', style: style),
),
),
),
],
);
}
}
+71
View File
@@ -0,0 +1,71 @@
# Composer paste
Files and text can be pasted into the chat composer. Pasted files take the same
landed attachment draft path as the picker; text paste stays with the host field
and behaves exactly like typing.
## Files
- `lib/features/chat/domain/chat_clipboard_paste.dart` — the host seam
(`ChatClipboardPaste.listen(onFiles, canAccept, onError)`), the web client's
nameless-file name (`pasted-<n>.<mime subtype>`, `jpeg` → `jpg`, `bin`
fallback), and the running host's source.
- `lib/features/chat/domain/chat_clipboard_paste_web.dart` — a document-level
`paste` listener using `dart:js_interop` (JS and Wasm targets). It collects the
clipboard's file items synchronously, asks the composer whether it can take
them, consumes only that file paste (`preventDefault`), then reads the bytes
and hands back `ChatPickedFile`s. A text-only paste is never consumed.
Readable files are delivered before a partial read's failure, so the kept
files cannot clear the error line.
`DataTransferItemList` is indexed (`items[i]`), not a method list like
`FileList`; the first browser run caught the wrong `item()` call.
- `lib/features/chat/domain/chat_clipboard_paste_stub.dart` — non-web host: text
paste stays native, and the file-paste capability is reported as unsupported
instead of pretending it worked.
- `lib/features/chat/conversation/chat_composer_bar.dart` — subscribes once per
composer, unsubscribes on source replacement and dispose, and routes both
picker and paste files through `_addFiles`, so the landed
`ChatAttachmentDraft.add` owns the blank-name and 1 MiB decisions. Paste is
accepted only while this composer's field has focus and no prompt is in
flight, the same window as the attach control. No layout was changed.
## Checks run
- `flutter test test/features/chat` — 367 passed.
- `flutter test` — 1591 passed.
- `flutter test test/features/chat/conversation/chat_composer_paste_test.dart
test/features/chat/domain/chat_clipboard_paste_test.dart` — 14 passed.
- `flutter analyze` — no issues.
- `flutter build web` — built (the web seam compiles for the JS target; the
build also reports a successful Wasm dry run).
- `dart format` on touched Dart files — clean.
## Browser evidence
`tool/chat_paste_probe.mjs` builds the existing `tool/chat_composer_probe_entry.dart`
fixture, serves it on an OS-assigned loopback port, and drives real Chrome over
CDP. It dispatches native `ClipboardEvent`s carrying a `DataTransfer` at the
focused editing element. Result:
- a text-only paste is **not** intercepted (`defaultPrevented: false`);
- a file paste is consumed (`defaultPrevented: true`), shows a `shot.png` chip,
and leaves the typed draft `keep me` untouched;
- a 1 MiB + 1 byte file shows the exact draft refusal and adds no `huge.bin`
chip while the existing chip stays;
- a nameless `image/png` clipboard file shows as `pasted-1.png`.
Captures (in the run's shared artifacts, `public/paste-probe/`):
`paste-file-chip.png`, `paste-over-limit.png`, `paste-nameless-file.png`.
The synthetic browser paste cannot exercise Chrome's default text insertion, so
the text caret/selection/draft assertion is a widget test that sends the
platform's own editing update to the field. The browser check proves the listener
does not consume text-only pastes.
## Limits
- Web only, as required. Android/iOS/desktop were not built or tested; on those
hosts text paste stays native and pasted files remain unsupported until a
native clipboard-file seam exists.
- Attachments stay memory-only and are not restored with a draft, matching the
landed draft store and the web client.
+72
View File
@@ -0,0 +1,72 @@
# Next session prompt (written 2026-10-22 ~19:00)
Paste this as the opening message:
---
Continue the Flutter port in /Users/alan/repos/pipelines. Read app/AGENTS.md,
app/WORK.md (sections "Chat tasks landing and native builds" and "Open wave
handoff") and app/PARITY.md first. Main is at 88476800 with 1563 tests passing;
the preview on port 8098 serves the published app/build/web (rollback
web-before-chat-tasks-1792688535). Use the CLI
/private/var/folders/jp/q0qvjyg54fl_c5vhhk1ylz2m0000gn/T/opencode/pipelines-cli-inlinefix-c303756
(rebuild it if the server-build warning blocks a command). Never change,
restart or rebind the Pipelines server. Keep git history free of any Claude or
AI attribution: no Co-Authored-By trailers, ever.
State of the open wave (Task v6 lanes on openai/gpt-6-luna, one worktree each
under tmp/flutter-<name> on branch flutter/<name>):
- Landed on their branch, ready to merge: 146 report format
(flutter/run-report-format 6eb2a7b8), 147 recent directories
(flutter/run-directories b8d18bcb), 149 background question notices
(flutter/chat-question-notice 42808814).
- Still running when I stopped: 140 /stop + /help (flutter/chat-cmd-stop), 143
runs filter menu (flutter/runs-filter-menu), 144 runs day groups
(flutter/runs-day-groups), 145 runs pipeline URL filter
(flutter/runs-pipeline-url). `pipelines inspect <id> --json` first.
- Failed: 148 composer paste (flutter/chat-paste) and 152 chat create dialog
(flutter/chat-create-dialog): read the stage outputs, preserve any uncommitted
worktree changes as a WIP commit, then fix directly or rerun with the findings
addressed. 151 live New marks is a WIP commit faa5cc00 on flutter/chat-live-new
(needs the lint fix at chat_session_local.dart:59, focused tests and clearing
activeSessionId when the conversation is left). 141/142/150 (/new /close
/rename) blocked three times on Luna; a direct Claude agent was implementing it
on flutter/chat-cmd-session — check that branch for its commit before redoing.
- Direct agent branches (worktrees under .claude/worktrees/): shell Runs-tab
attention badge worktree-agent-ab5296d8f4132ba79 (eb800928), search selection
probe worktree-agent-a81e60797507d2317 (4f0d2aab); the chat task-bar/model
chooser probe and the graph pulse/session repair probe agents had not committed
yet — check their worktrees for uncommitted tool/ and notes/ files.
For each green branch: merge into main, `flutter test` + `flutter analyze` in
app/, fix fixture fallout yourself, `flutter build web --output build/web-next`
then publish by renaming (keep a web-before-<name>-<ts> rollback), one commit
per landing, then update the PARITY rows. After the wave, start the remaining
lanes listed under "Still to start" in WORK.md, keeping the lane contract (one
behaviour, small file budget, exact web wording in the prompt; the briefs with
that wording are in the session scratchpad briefs/ and in the run prompts of
140-152). Mobile: the Android testing APK is at
app/build/android-testing/pipelines-next-67045f25.apk; the phone still needs a
reachable endpoint, which is the operator's decision (a tailnet TLS-terminated
forward of 127.0.0.1:8080 gives wss:// with no manifest change). Keep answers
to a few sentences.
Late findings (after the prompt above was written):
- Shell Runs-tab attention badge is DONE on worktree-agent-ab5296d8f4132ba79
(eb800928, +454/-15, analyze clean, 239 focused tests green). Merge it first;
its pipelines_app.dart/runs_destination.dart/runs_list.dart/screen.dart hunks
are additive and will touch run 145's edits.
- Search selection probe is DONE on worktree-agent-a81e60797507d2317 (4f0d2aab,
22 captures in app/build/search-selection-probe/, note
app/notes/search-selection-probe.md). It found two lib defects to fix as
manager work: (1) a retired-field hit after a field hit leaves the earlier
Summary section expanded (`RunDetailTabs._selectSearchTarget` never collapses
on `section: null`, run_detail_tabs.dart); (2) a step hit opens the wrong visit,
off by one: `_openSearchResult` in pipelines_app.dart passes the server's
1-based `visit` into the zero-based `AppRoute.run.stage(visit:)`.
- Main now also carries 0acd7346 `feat(chat): add Claude Code chat backend` and
83d013f1 from another session; with it, three chat tests fail
(chat_model_picker_test, chat_screen_model_test, chat_thread_header_test: a
`chat-model` button appears where the fixture expects none, because
`supportsChatModels` now includes `claude`). Fix the fixtures or the rule
before trusting a full-suite run.
---
+140
View File
@@ -0,0 +1,140 @@
# Search result-target selection: browser probe
Real-Chrome evidence for the PARITY `Search` row's missing capture: a field hit
and an artifact hit select the recorded run Summary section or visit, and a
retired field / unknown visit falls back to the plain Summary.
## Files
- `app/tool/search_selection_probe_entry.dart` — the normal `PipelinesApp`
composition over the shared `PipelinesClient`, with the socket replaced by an
in-process channel that answers `search`, `get_run`, `list_runs`,
`list_pipelines`, `get_pipeline` and `ping` with server-shaped fixtures.
`subscribe`/`unsubscribe` are silent like the real server. A `search` body
that is not exactly `{query, kind, limit: 0}` is answered with an error
envelope, so a wrong request shape fails the captures instead of passing.
No live server; nothing is contacted over the network.
- `app/tool/search_selection_probe.mjs` — CDP driver (same shape as
`changes_probe.mjs`): loopback static server with index fallback for route
paths, headless Chrome, Flutter semantics enabled, exact-label clicks, PNGs.
Run from `app/`:
```
flutter build web --target tool/search_selection_probe_entry.dart --output build/probe-search-selection
node tool/search_selection_probe.mjs --root build/probe-search-selection --out build/search-selection-probe
```
Exit code 0 means every assertion held and no defect was recorded; exit code 2
means the assertions held but at least one recorded state differs from the
expected one (listed under `defects` in the JSON report). A thrown assertion
also writes `failure.png` next to the captures.
## Fixture
Run 7 "Release train run" (`name: release-train`), `input {prompt: "ship it"}`,
`output {result: "ok"}`, steps in recorded order plan seq 5, build seq 2
(artifact `release-report.txt`), plan seq 1 — the sequences are deliberately
not the row indexes, as in `test/features/runs/ui/run_search_selection_test.dart`.
Search replies (`truncated: false`, `scanned_steps 3`, `scanned_bytes 2048`,
`cap 50`, `scan_bound_bytes 1048576`):
| query | hits |
| --- | --- |
| `release` | `pipeline:24`, `pipeline:22:v6`, `run:7`, `run:7:5` (plan visit 2), `run:7:5:output`, `/artifacts/7/2/release-report.txt` |
| `retired` | `run:7:5:evidence` (retired field) |
| `missing` | `/artifacts/7/9/missing.log` (sequence 9 is not recorded) |
| `first` | `run:7:1` (plan visit 1) |
## Captures (`app/build/search-selection-probe/`)
Light scheme is pinned through `Emulation.setEmulatedMedia`; one dark pass is
included. Phone is 390×844, desktop 1280×800.
| capture | state |
| --- | --- |
| `search-selection-material-phone-results.png` | Search panel, `release`, one row per kind |
| `search-selection-material-phone-artifact-visit.png` | artifact hit → Timeline, `build · visit 2` pane |
| `search-selection-material-phone-retired-summary.png` | retired field after the open visit → plain Summary |
| `search-selection-material-phone-unknown-visit-summary.png` | unknown-visit artifact after an open visit → plain Summary |
| `search-selection-material-phone-field-summary.png` | field hit (`output`) → Summary, Output expanded, Input collapsed |
| `search-selection-material-phone-retired-after-field-summary.png` | retired field after that field hit (defect 1 evidence) |
| `search-selection-material-phone-step-visit.png` | step hit `plan visit 1` (defect 2 evidence) |
| `search-selection-material-desktop-results.png` | desktop results |
| `search-selection-material-desktop-artifact-visit.png` | desktop artifact visit |
| `search-selection-material-desktop-retired-summary.png` | desktop plain Summary |
| `search-selection-material-desktop-field-summary.png` | desktop field selection |
| `search-selection-material-phone-dark-results.png` | dark results |
| `search-selection-material-phone-dark-field-summary.png` | dark field selection |
| `search-selection-cupertino-phone-results.png` | Cupertino results (`Kind: All kinds` control) |
| `search-selection-cupertino-phone-artifact-visit.png` | Cupertino artifact visit |
| `search-selection-cupertino-phone-retired-summary.png` | Cupertino plain Summary after retired field |
| `search-selection-cupertino-phone-unknown-visit-summary.png` | Cupertino plain Summary after unknown visit |
| `search-selection-cupertino-phone-field-summary.png` | Cupertino field selection |
| `search-selection-cupertino-phone-retired-after-field-summary.png` | Cupertino retired-after-field (defect 1 evidence) |
| `search-selection-cupertino-desktop-results.png` | Cupertino desktop results |
| `search-selection-cupertino-desktop-artifact-visit.png` | Cupertino desktop artifact visit |
| `search-selection-cupertino-desktop-field-summary.png` | Cupertino desktop field selection |
## Asserted strings (Flutter semantics, exact)
- Results, every host/width: row titles `Release train`, `pipeline 22 · v6`,
`run #7 · Release train`, `run #7 · plan visit 2`, `run #7 · step 5 · output`,
`release-report.txt`; row meta `Pipeline`, `Pipeline version`, `Run`, `Step`,
`Field`, `Artifact`; snippet `ship the release`; bounds
`6 results · cap 50 · scanned 3 steps · 2.0 KiB scanned · scan limit 1.0 MiB`;
Cupertino also `Kind: All kinds`.
- Every hit: `location.pathname === '/runs/7'`, title `Release train run`,
and the Search page's text gone.
- Field hit: Summary tile `Output` announces `Expanded` and `Input` announces
`Collapsed` (first line of the tile's `aria-description`); no
`Back to timeline`, no `build · visit 2`.
- Artifact hit: `build · visit 2` and `Back to timeline` present;
`Original prompt` (Summary-only text) absent.
- Retired field / unknown visit: `Original prompt` present, `Input` and
`Output` both `Collapsed`, no visit pane text.
- One-shot: after an artifact hit, `Back to list` → row `Release train run`
reopens `/runs/7` on the Summary with no `build · visit 2`.
- Fixture-side: a `search` body other than `{query, kind, limit: 0}` and a
`get_run` for any run but 7 reply with an error envelope; both would have
failed the label assertions above (the JSON report has `pageErrors: []`).
Semantics limitation: Flutter web renders a read-only `SelectableText` /
read-only `CupertinoTextField` as a `<textarea>` whose `value` stays empty, so
the section JSON (`"result": "ok"`) is only visible in the PNGs; the probe
asserts the section state on the tile instead and scrolls the body so the
expanded JSON is inside the frame.
## Defects found (lib not changed)
1. A retired-field hit after a field hit keeps the earlier section expanded.
Flow on one mounted run 7: `run:7:5:output` → Output `Expanded`; then
`run:7:5:evidence` → `output: "Expanded", input: "Collapsed"`, expected both
`Collapsed` (report entries `material phone: a retired field hit after an
output field hit …` and the Cupertino twin). The widget tests only cover
retired-after-artifact, where nothing was expanded. Cause:
`RunDetailTabs._selectSearchTarget` handles `RunSummaryTarget(section: null)`
with `case null: break;` and never collapses `_inputSection`/`_outputSection`
(`app/lib/features/runs/ui/run_detail_tabs.dart`); only a different run
collapses them. The browser's `searchFieldTab` selects the exclusive
Summary tab, so a retired hit never shows the Output text there
(`web/src/search.js`). Evidence:
`search-selection-{material,cupertino}-phone-retired-after-field-summary.png`.
2. A step hit opens the wrong visit when the stage has more than one visit.
`run:7:1` (`step.visit: 1`, sequence 1, plan's first visit) navigated to
`/runs/7/stage/plan?visit=1` and opened `plan · visit 5` (plan's second
visit); expected `plan · visit 1`. `_openSearchResult` in
`app/lib/application/pipelines_app.dart` passes the server's 1-based
`visit` straight into `AppRoute.run.stage(..., visit:)`, which
`app_route.dart` documents as zero-based (and `RunDetailTabs` clamps). The
browser resolves a step target to the zero-based index within the stage
(`resolveRunTarget` in `web/src/search.js`). Evidence:
`search-selection-material-phone-step-visit.png`, report entry
`material phone: a step hit for plan visit 1 opens plan · visit 1`.
## Not verified
Web only; Android/iOS are unverified. The pipeline and version hits are listed
and the fixture answers `list_pipelines`/`get_pipeline`, but their navigation
is not captured here (it is covered by the existing search wiring probe).
@@ -0,0 +1,118 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart';
import '../core/transport/pipelines_client_test.dart' show FakeChannel;
import 'pipelines_app_test.dart' show pumpApp, replyList;
import 'pipelines_replies.dart';
/// The app lifts one attention controller above the destinations: the Runs
/// list seeds it when it loads and the app folds pushed `run_event` frames, so
/// the shell's Runs tab badge moves while another destination is shown.
void main() {
final needingAttention = RegExp('needing attention');
Finder badgeCount(String count) =>
find.descendant(of: find.byType(Badge), matching: find.text(count));
testWidgets(
'a run_event folded to waiting raises the Runs tab badge from Pipelines',
(tester) async {
final semantics = tester.ensureSemantics();
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(channelFactory: (_) => channel);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/runs')),
);
addTearDown(provider.dispose);
await pumpApp(
tester,
channel: channel,
client: client,
provider: provider,
);
await replyList(
tester,
channel,
runs: [
{
'id': 1,
'pipeline_id': 4,
'name': 'nightly',
'title': 'Nightly build',
'status': 'running',
'created_at': DateTime.now().toIso8601String(),
},
],
);
expect(find.text('Nightly build'), findsWidgets);
expect(tester.widget<Badge>(find.byType(Badge)).isLabelVisible, isFalse);
expect(find.bySemanticsLabel(needingAttention), findsNothing);
await tester.tap(find.text('Pipelines').last);
await tester.pump();
expect(provider.value.uri.path, '/pipelines');
await waitForRequest(tester, channel, 'list_pipelines');
expect(find.text('Nightly build'), findsNothing);
channel.incoming.add(
jsonEncode({'type': 'run_event', 'run_id': 1, 'status': 'waiting'}),
);
await tester.pump();
await tester.pump();
expect(provider.value.uri.path, '/pipelines');
expect(tester.widget<Badge>(find.byType(Badge)).isLabelVisible, isTrue);
expect(badgeCount('1'), findsOneWidget);
expect(
find.bySemanticsLabel(RegExp('Notifications, 1 needing attention')),
findsOneWidget,
);
// The decision taken elsewhere clears the badge the same way.
channel.incoming.add(
jsonEncode({'type': 'run_event', 'run_id': 1, 'status': 'succeeded'}),
);
await tester.pump();
await tester.pump();
expect(tester.widget<Badge>(find.byType(Badge)).isLabelVisible, isFalse);
expect(badgeCount('1'), findsNothing);
expect(find.bySemanticsLabel(needingAttention), findsNothing);
semantics.dispose();
},
);
testWidgets('a new waiting run pushed before any list read is counted', (
tester,
) async {
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(channelFactory: (_) => channel);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/settings')),
);
addTearDown(provider.dispose);
await pumpApp(tester, channel: channel, client: client, provider: provider);
expect(tester.widget<Badge>(find.byType(Badge)).isLabelVisible, isFalse);
channel.incoming.add(
jsonEncode({
'type': 'run_event',
'run_id': 9,
'pipeline_id': 4,
'name': 'nightly',
'title': 'Arrived while away',
'status': 'waiting',
'created_at': DateTime.now().toIso8601String(),
}),
);
await tester.pump();
await tester.pump();
expect(provider.value.uri.path, '/settings');
expect(badgeCount('1'), findsOneWidget);
});
}
@@ -97,6 +97,18 @@ void main() {
await tester.tap(find.byKey(runPipelineActionKey));
await tester.pumpAndSettle();
// The dialog asks for recent directories; answer it so the transport is
// free for the launch request this test asserts.
await waitForRequest(tester, channel, 'chat_directories');
final directories = pipelineRequest(channel, 'chat_directories')!;
channel.incoming.add(
jsonEncode({
'id': directories['id'],
'type': 'chat_directories',
'chat_directories': <dynamic>[],
}),
);
await tester.pump();
await tester.enterText(
find.byKey(runPipelinePromptKey),
'Review the change.',
@@ -21,7 +21,7 @@ Widget materialApp(
ServerEndpoint server, {
int? initialRunId,
ValueChanged<int>? onRunSelected,
VoidCallback? onBack,
ValueChanged<int?>? onBack,
}) => MaterialApp(
home: Scaffold(
body: RunsDestination(
@@ -0,0 +1,101 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/application/app_route.dart';
import 'package:pipelines_app/features/attention/notify/chat_question_notices.dart';
import 'notification_test_support.dart';
class _Gateway implements ApiGateway {
final controller = StreamController<JsonMap>.broadcast();
@override
Stream<JsonMap> get frames => controller.stream;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async => {};
}
Map<String, dynamic> _event({
String id = 'form-1',
String session = 'session_1',
String kind = 'question',
bool resolved = false,
bool cancelled = false,
}) => {
'type': 'chat_event',
'chat_event': {
'session_id': session,
'kind': 'form',
'form': {
'id': id,
'kind': kind,
'title': 'Choose an option',
'resolved': resolved,
'cancelled': cancelled,
},
},
};
void main() {
late _Gateway gateway;
late FakeNotificationBridge bridge;
late bool allowed;
late String? active;
late List<AppRoute> opened;
late ChatQuestionNotices notices;
setUp(() {
gateway = _Gateway();
bridge = FakeNotificationBridge(permission: 'granted');
allowed = true;
active = null;
opened = [];
notices = ChatQuestionNotices(
gateway: gateway,
canNotify: () => allowed,
activeChatSessionId: () => active,
sessionTitle: (id) async => id == 'session_1' ? ' Design chat ' : null,
openChat: (id) => opened.add(AppRoute.chatSession(id)),
bridge: bridge,
);
});
tearDown(() async {
notices.dispose();
await gateway.controller.close();
});
test('notifies titled and unknown sessions; tap opens the chat route', () async {
gateway.controller.add(_event());
await Future<void>.delayed(Duration.zero);
gateway.controller.add(_event(id: 'form-2', session: 'unknown'));
await Future<void>.delayed(Duration.zero);
expect(bridge.shown.map((message) => message.title), [
'Design chat needs your answer',
'Chat needs your answer',
]);
expect(bridge.shown.first.body, 'Choose an option');
expect(bridge.shown.first.tag, 'chat-question:form-1');
bridge.taps.first?.call();
expect(opened, [AppRoute.chatSession('session_1')]);
});
test('suppresses active, unavailable, resolved, cancelled and non-question frames', () async {
active = 'session_1';
gateway.controller.add(_event());
await Future<void>.delayed(Duration.zero);
active = null;
allowed = false;
gateway.controller.add(_event(id: 'form-2'));
await Future<void>.delayed(Duration.zero);
allowed = true;
gateway.controller.add(_event(id: 'form-3', resolved: true));
await Future<void>.delayed(Duration.zero);
gateway.controller.add(_event(id: 'form-4', cancelled: true));
await Future<void>.delayed(Duration.zero);
gateway.controller.add(_event(id: 'form-5', kind: 'approval'));
await Future<void>.delayed(Duration.zero);
expect(bridge.shown, isEmpty);
});
}
@@ -152,7 +152,7 @@ void main() {
(tester) async {
final gateway = _ScreenGateway()
..sessions = [
{'id': 's', 'title': 'Wire chat', 'backend': 'claude'},
{'id': 's', 'title': 'Wire chat', 'backend': 'other'},
];
await _pumpScreen(tester, gateway, initialSessionId: 's');
@@ -0,0 +1,340 @@
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
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_composer_bar.dart';
import 'package:pipelines_app/features/chat/conversation/chat_composer_controller.dart';
import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart';
import 'package:pipelines_app/features/chat/domain/chat_attachment_draft.dart';
import 'package:pipelines_app/features/chat/domain/chat_attachment_picker.dart';
import 'package:pipelines_app/features/chat/domain/chat_clipboard_paste.dart';
import 'chat_composer_bar_fixtures.dart';
/// A host paste source driven by the test. [paste] mirrors the web listener:
/// it asks [canAccept] before it hands files to the composer.
class _FakePaste {
ChatPasteFiles? onFiles;
ChatPasteCanAccept? canAccept;
ChatPasteFailed? onError;
int listens = 0;
int stops = 0;
ChatClipboardPaste get source => ChatClipboardPaste(
subscribe: (onFiles, canAccept, onError) {
listens += 1;
this.onFiles = onFiles;
this.canAccept = canAccept;
this.onError = onError;
return () {
stops += 1;
this.onFiles = null;
this.canAccept = null;
this.onError = null;
};
},
);
void paste(List<ChatPickedFile> files) {
final handler = onFiles;
if (handler == null) return;
if (!(canAccept?.call() ?? false)) return;
handler(files);
}
}
ChatPickedFile _file(
String name,
List<int> bytes, {
String mime = 'text/plain',
}) => ChatPickedFile(name: name, mime: mime, bytes: Uint8List.fromList(bytes));
Finder get _field => find.byKey(const Key('chat-composer-field'));
Finder get _chips => find.byKey(const Key('chat-composer-attachments'));
void main() {
late ComposerBarGateway gateway;
late ChatComposerController composer;
late List<ChatComposerController> controllers;
setUp(() {
gateway = ComposerBarGateway();
controllers = [];
});
tearDown(() {
for (final controller in controllers) {
controller.dispose();
}
gateway.close();
});
/// Rebuilds the same composer with a different paste source, so a test can
/// tell a replaced listener from a disposed one.
Future<void> pumpWith(
WidgetTester tester, {
ChatClipboardPaste? paste,
}) async {
await tester.pumpWidget(
materialHost(
ChatComposerBar(composer: composer, running: false, paste: paste),
),
);
await tester.pump();
}
Future<void> pumpBar(
WidgetTester tester, {
ChatClipboardPaste? paste,
ChatDraftStore? drafts,
}) async {
composer = ChatComposerController(
gateway,
's',
drafts: drafts ?? MemoryChatDraftStore(),
newOperationId: () => 'op/1',
);
controllers.add(composer);
await pumpWith(tester, paste: paste);
}
Future<void> focusField(WidgetTester tester) async {
await tester.showKeyboard(_field);
await tester.pump();
}
testWidgets('a pasted file makes the same chip as a picked file', (
tester,
) async {
final fake = _FakePaste();
await pumpBar(tester, paste: fake.source);
await focusField(tester);
fake.paste([
_file('shot.png', [1, 2, 3], mime: 'image/png'),
]);
await tester.pump();
expect(_chips, findsOneWidget);
expect(find.text('shot.png'), findsOneWidget);
expect(fake.listens, 1);
expect(fake.stops, 0);
});
testWidgets('pasting several files keeps clipboard order', (tester) async {
final fake = _FakePaste();
await pumpBar(tester, paste: fake.source);
await focusField(tester);
fake.paste([
_file('first.png', [1], mime: 'image/png'),
_file('second.txt', [2]),
]);
await tester.pump();
expect(find.text('first.png'), findsOneWidget);
expect(find.text('second.txt'), findsOneWidget);
expect(
tester.getTopLeft(find.text('first.png')).dx,
lessThan(tester.getTopLeft(find.text('second.txt')).dx),
);
});
testWidgets('an over-limit paste shows the draft refusal and adds nothing', (
tester,
) async {
final fake = _FakePaste();
await pumpBar(tester, paste: fake.source);
await focusField(tester);
fake.paste([
_file(
'huge.bin',
List<int>.filled(ChatAttachmentDraft.maxTotalBytes + 1, 0),
mime: 'application/octet-stream',
),
]);
await tester.pump();
expect(
find.text(ChatAttachmentRefusal.totalTooLarge.message),
findsOneWidget,
);
expect(_chips, findsNothing);
expect(find.text('huge.bin'), findsNothing);
});
testWidgets('a refused paste keeps the files already in the draft', (
tester,
) async {
final fake = _FakePaste();
await pumpBar(tester, paste: fake.source);
await focusField(tester);
fake.paste([
_file('kept.txt', [1]),
_file(
'huge.bin',
List<int>.filled(ChatAttachmentDraft.maxTotalBytes, 0),
mime: 'application/octet-stream',
),
]);
await tester.pump();
expect(find.text('kept.txt'), findsOneWidget);
expect(find.text('huge.bin'), findsNothing);
expect(
find.text(ChatAttachmentRefusal.totalTooLarge.message),
findsOneWidget,
);
});
testWidgets('a pasted attachment sends its exact name, type and bytes', (
tester,
) async {
final fake = _FakePaste();
await pumpBar(tester, paste: fake.source);
await focusField(tester);
fake.paste([
_file('shot.png', [9, 8, 7], mime: 'image/png'),
]);
await tester.pump();
await tester.enterText(_field, 'look');
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('chat-composer-primary')));
await tester.pumpAndSettle();
expect(gateway.promptBodies.single['attachments'], [
{
'name': 'shot.png',
'mime': 'image/png',
'data': base64Encode([9, 8, 7]),
},
]);
expect(_chips, findsNothing);
});
testWidgets('pasted text keeps its caret, selection and draft', (
tester,
) async {
final drafts = MemoryChatDraftStore();
final fake = _FakePaste();
await pumpBar(tester, paste: fake.source, drafts: drafts);
await focusField(tester);
await tester.enterText(_field, 'hello world');
await tester.pumpAndSettle();
final editable = tester.widget<EditableText>(
find.descendant(of: _field, matching: find.byType(EditableText)),
);
editable.controller.selection = const TextSelection.collapsed(offset: 5);
// The platform's text update for a paste between "hello" and " world".
tester.testTextInput.updateEditingValue(
const TextEditingValue(
text: 'hello there world',
selection: TextSelection.collapsed(offset: 11),
),
);
await tester.pumpAndSettle();
expect(editable.controller.text, 'hello there world');
expect(
editable.controller.selection,
const TextSelection.collapsed(offset: 11),
);
expect(composer.draft, 'hello there world');
expect(drafts.entries, {'s': 'hello there world'});
});
testWidgets('paste is only taken while this composer owns the field', (
tester,
) async {
final fake = _FakePaste();
await pumpBar(tester, paste: fake.source);
expect(fake.canAccept!(), isFalse);
await focusField(tester);
expect(fake.canAccept!(), isTrue);
tester.binding.focusManager.primaryFocus?.unfocus();
await tester.pump();
expect(fake.canAccept!(), isFalse);
});
testWidgets('a paste during an in-flight prompt adds nothing', (
tester,
) async {
final reply = Completer<JsonMap>();
gateway.prompt = (_, _) => reply.future;
final fake = _FakePaste();
await pumpBar(tester, paste: fake.source);
await focusField(tester);
await tester.enterText(_field, 'hello');
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('chat-composer-primary')));
await tester.pump();
expect(fake.canAccept!(), isFalse);
fake.paste([
_file('late.png', [1], mime: 'image/png'),
]);
await tester.pump();
expect(_chips, findsNothing);
reply.complete(const {});
await tester.pumpAndSettle();
});
testWidgets('an unreadable clipboard file is reported', (tester) async {
final fake = _FakePaste();
await pumpBar(tester, paste: fake.source);
await focusField(tester);
fake.onError!(StateError('clipboard read failed'));
await tester.pump();
expect(find.textContaining('clipboard read failed'), findsOneWidget);
});
testWidgets('a partial clipboard read shows its files and the failure', (
tester,
) async {
final fake = _FakePaste();
await pumpBar(tester, paste: fake.source);
await focusField(tester);
// The web source delivers readable files before a partial read's failure.
fake.paste([
_file('readable.png', [1], mime: 'image/png'),
]);
fake.onError!(StateError('second file failed'));
await tester.pump();
expect(find.text('readable.png'), findsOneWidget);
expect(find.textContaining('second file failed'), findsOneWidget);
});
testWidgets(
'a replaced source stops listening and dispose stops the new one',
(tester) async {
final first = _FakePaste();
await pumpBar(tester, paste: first.source);
expect(first.listens, 1);
final second = _FakePaste();
await pumpWith(tester, paste: second.source);
expect(first.stops, 1);
expect(second.listens, 1);
await tester.pumpWidget(const SizedBox());
expect(second.stops, 1);
},
);
}
@@ -380,7 +380,7 @@ void main() {
await _openThread(
tester,
gateway,
session: _withSession({'backend': 'claude'}),
session: _withSession({'backend': 'other'}),
);
expect(find.byKey(const Key('chat-model')), findsNothing);
@@ -110,7 +110,7 @@ void main() {
gateway: gateway,
sessionId: 's',
title: _title,
session: {..._session, 'backend': 'claude'},
session: {..._session, 'backend': 'other'},
onBack: () {},
),
cupertino: false,
@@ -0,0 +1,47 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/domain/chat_clipboard_paste.dart';
void main() {
test('a nameless clipboard file takes the web client name for its type', () {
expect(chatPastedAttachmentName('image/png', 1), 'pasted-1.png');
expect(chatPastedAttachmentName('image/jpeg', 2), 'pasted-2.jpg');
expect(
chatPastedAttachmentName('application/octet-stream', 3),
'pasted-3.octetstream',
);
expect(chatPastedAttachmentName('', 4), 'pasted-4.bin');
});
test('the unsupported host keeps text paste and reports the gap', () {
const paste = ChatClipboardPaste.unsupported('no files here');
expect(paste.isSupported, isFalse);
expect(
() =>
paste.listen(onFiles: (_) {}, canAccept: () => true, onError: (_) {}),
throwsUnsupportedError,
);
});
test('a supported host subscribes once and returns its unsubscribe', () {
var listens = 0;
var stops = 0;
final paste = ChatClipboardPaste(
subscribe: (onFiles, canAccept, onError) {
listens += 1;
return () => stops += 1;
},
);
final stop = paste.listen(
onFiles: (_) {},
canAccept: () => true,
onError: (_) {},
);
expect(paste.isSupported, isTrue);
expect(listens, 1);
stop();
expect(stops, 1);
});
}
@@ -86,6 +86,30 @@ void main() {
expect(find.text('Viewing v1 (latest v2).'), findsNothing);
});
testWidgets('detail Runs action names and opens that pipeline filter', (
tester,
) async {
final fixture = PipelineFixture();
final gateway = gatewayFor(fixture);
final opened = <int>[];
tester.view.physicalSize = const Size(1100, 900);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(
MaterialApp(
home: PipelinesScreen(gateway: gateway, onViewPipelineRuns: opened.add),
),
);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('pipeline-row-1')));
await tester.pumpAndSettle();
expect(find.bySemanticsLabel('View runs of Alpha review'), findsOneWidget);
await tester.tap(find.byKey(const Key('pipeline-view-runs')));
expect(opened, [1]);
});
testWidgets('refresh keeps the selected row and its detail', (tester) async {
final fixture = PipelineFixture();
final gateway = gatewayFor(fixture);
@@ -3,6 +3,7 @@ import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/transport/connection_state.dart';
import 'package:pipelines_app/features/pipelines/screen.dart';
@@ -28,6 +29,10 @@ FakeGateway launchGateway(
)!,
),
'list_schedules' => {'type': 'schedules', 'schedules': <dynamic>[]},
'chat_directories' => {
'type': 'chat_directories',
'chat_directories': ['/work/recent', 'relative', '/work/other'],
},
'run_pipeline' => onLaunch(fields),
'get_run' when onLookup != null => onLookup(fields),
_ => errorReply('unexpected $type'),
@@ -74,6 +79,45 @@ Future<void> fillFields(
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
SharedPreferences.setMockInitialValues({});
testWidgets(
'workspace directory suggestions load on open and selection is local',
(tester) async {
final fixture = PipelineFixture();
final gateway = launchGateway(fixture, onLaunch: (_) => acceptedRun(76));
await pumpScreen(tester, gateway, <int>[]);
await openDetail(tester);
await tester.tap(find.byKey(runPipelineActionKey));
await tester.pumpAndSettle();
expect(gateway.callsOf('chat_directories'), hasLength(1));
expect(find.text(runPipelineDirectoriesLoading), findsNothing);
expect(
tester
.widget<TextField>(find.byKey(runPipelineWorkspaceKey))
.controller
?.text,
'/work/recent',
);
await tester.tap(find.byKey(runPipelineWorkspaceSuggestionsKey));
await tester.pumpAndSettle();
expect(find.text('/work/other'), findsOneWidget);
expect(find.text('relative'), findsNothing);
await tester.tap(find.text('/work/other'));
await tester.pumpAndSettle();
expect(
tester
.widget<TextField>(find.byKey(runPipelineWorkspaceKey))
.controller
?.text,
'/work/other',
);
expect(gateway.callsOf('run_pipeline'), isEmpty);
expect(gateway.callsOf('chat_directories'), hasLength(1));
},
);
testWidgets('the detail Run action sends the web request for the pinned '
'version and opens only the reply run', (tester) async {
final fixture = PipelineFixture();
@@ -93,6 +137,8 @@ void main() {
expect(find.text(runPipelinePromptLabel), findsOneWidget);
expect(find.text(runPipelineWorkspaceLabel), findsOneWidget);
expect(find.text(runPipelineNotifyLabel), findsOneWidget);
expect(find.text(runPipelineOutputFormatLabel), findsOneWidget);
expect(find.text(runPipelineOutputFormatHelper), findsOneWidget);
expect(find.text(runPipelineCancelLabel), findsOneWidget);
expect(
find.descendant(
@@ -104,14 +150,15 @@ void main() {
expect(gateway.callsOf('run_pipeline'), isEmpty);
await fillFields(tester, prompt: ' Review the change. ');
await tester.enterText(
find.byKey(runPipelineWorkspaceKey),
'/work/alpha ',
);
await tester.enterText(find.byKey(runPipelineWorkspaceKey), '/work/alpha ');
await tester.tap(find.byKey(runPipelineNotifyKey));
await tester.pumpAndSettle();
await tester.tap(find.text('Silent').last);
await tester.pumpAndSettle();
await tester.tap(find.byKey(runPipelineOutputFormatKey));
await tester.pumpAndSettle();
await tester.tap(find.text('HTML report').last);
await tester.pumpAndSettle();
await tester.tap(find.byKey(runPipelineConfirmKey));
await tester.pumpAndSettle();
@@ -123,6 +170,7 @@ void main() {
'workspace': '/work/alpha',
'input': {'prompt': 'Review the change.'},
'notify_mode': 'off',
'output_format': 'html',
});
expect(fields['request_key'], startsWith('app-run-1-2-'));
expect('${fields['request_key']}'.length, lessThanOrEqualTo(128));
@@ -317,6 +365,12 @@ void main() {
// The fields stay locked while admission is unknown.
final prompt = tester.widget<TextField>(find.byKey(runPipelinePromptKey));
expect(prompt.enabled, isFalse);
expect(
tester.widget<DropdownButtonFormField<dynamic>>(
find.byKey(runPipelineOutputFormatKey),
).onChanged,
isNull,
);
await tester.tap(find.byKey(runPipelineConfirmKey));
await tester.pumpAndSettle();
@@ -495,13 +549,7 @@ void main() {
final helper = tester
.widget<Text>(find.text(runPipelineWorkspaceHelper))
.style;
expect(
helper?.color,
CupertinoColors.secondaryLabel.resolveFrom(context),
);
expect(
helper?.fontSize,
theme.textTheme.tabLabelTextStyle.fontSize,
);
expect(helper?.color, CupertinoColors.secondaryLabel.resolveFrom(context));
expect(helper?.fontSize, theme.textTheme.tabLabelTextStyle.fontSize);
});
}
@@ -0,0 +1,38 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/runs/domain/run_models.dart';
void main() {
group('run day grouping', () {
final today = DateTime(2026, 10, 22, 12);
test('labels local days and invalid dates', () {
expect(runDayLabel('2026-10-22T08:00:00', today), 'Today');
expect(runDayLabel('2026-10-21T08:00:00', today), 'Yesterday');
expect(runDayLabel('2026-10-17T08:00:00', today), '17 Oct 2026');
expect(runDayLabel('', today), 'Unknown date');
expect(localDayKey(DateTime(2026, 1, 2)), '2026-01-02');
});
test('retains encounter order and groups adjacent equal labels', () {
final runs = [
{'id': 3, 'created_at': '2026-10-22T09:00:00'},
{'id': 2, 'created_at': '2026-10-21T09:00:00'},
{'id': 1, 'created_at': '2026-10-21T08:00:00'},
{'id': 0, 'created_at': ''},
];
final groups = groupRunsByDay(runs, today);
expect(groups.map((group) => group.label), [
'Today',
'Yesterday',
'Unknown date',
]);
expect(groups.expand((group) => group.runs).map((run) => run['id']), [
3,
2,
1,
0,
]);
});
});
}
@@ -46,17 +46,21 @@ const _runs = [
Widget _materialScreen(
_Gateway gateway, {
int? initialRunId,
int? initialPipelineId,
int syncToken = 0,
ValueChanged<int>? onRunSelected,
VoidCallback? onBack,
ValueChanged<int?>? onBack,
ValueChanged<int?>? onPipelineFilterChanged,
}) => MaterialApp(
home: Scaffold(
body: RunsScreen(
gateway: gateway,
initialRunId: initialRunId,
initialPipelineId: initialPipelineId,
syncToken: syncToken,
onRunSelected: onRunSelected,
onBack: onBack,
onPipelineFilterChanged: onPipelineFilterChanged,
),
),
);
@@ -149,12 +153,12 @@ void main() {
tester,
) async {
int? selected;
var backs = 0;
int? backedPipeline;
await tester.pumpWidget(
_materialScreen(
gateway,
onRunSelected: (id) => selected = id,
onBack: () => backs++,
onBack: (id) => backedPipeline = id,
),
);
await _mountList(tester, gateway);
@@ -167,10 +171,60 @@ void main() {
await tester.tap(find.text('Back to list'));
await tester.pump();
expect(backs, 1);
expect(backedPipeline, isNull);
expect(find.text('Alpha run'), findsOneWidget);
});
testWidgets(
'pipeline route shows its chip and clearing reports the URL change',
(tester) async {
int? changedPipeline = 3;
await tester.pumpWidget(
_materialScreen(
gateway,
initialPipelineId: 3,
onPipelineFilterChanged: (id) => changedPipeline = id,
),
);
await _mountList(tester, gateway);
expect(find.text('Pipeline 3'), findsOneWidget);
expect(changedPipeline, 3);
await tester.tap(find.byTooltip('Clear filter: Pipeline 3'));
await tester.pump();
expect(changedPipeline, isNull);
expect(find.text('Pipeline 3'), findsNothing);
},
);
testWidgets('run detail keeps the pipeline filter for Back routing', (
tester,
) async {
int? backPipeline;
await tester.pumpWidget(
_materialScreen(
gateway,
initialPipelineId: 3,
onBack: (id) => backPipeline = id,
),
);
await _mountList(tester, gateway);
await tester.pumpWidget(
_materialScreen(
gateway,
initialRunId: 2,
onBack: (id) => backPipeline = id,
),
);
await tester.pump();
gateway.replyDetail(2, 0, {'id': 2, 'title': 'Beta run'});
await tester.pump();
await tester.tap(find.text('Back to list'));
await tester.pump();
expect(backPipeline, 3);
});
testWidgets('a route change opens and closes the named run', (tester) async {
await tester.pumpWidget(_materialScreen(gateway, initialRunId: 2));
await _mountList(tester, gateway);
@@ -38,8 +38,21 @@ void main() {
Future<void> mount(WidgetTester tester, {required bool cupertino}) async {
gateway.reply = {
'runs': [
{'id': 1, 'name': 'Alpha', 'status': 'running', 'scheduled': true},
{'id': 2, 'name': 'Beta', 'status': 'failed', 'scheduled': false},
{
'id': 1,
'pipeline_id': 9,
'name': 'Alpha',
'status': 'running',
'created_at': DateTime.now().toIso8601String(),
'scheduled': true,
},
{
'id': 2,
'pipeline_id': 10,
'name': 'Beta',
'status': 'failed',
'created_at': DateTime.now().toIso8601String(),
},
],
};
await controller.load();
@@ -68,8 +81,42 @@ void main() {
await tester.tap(find.text('Filter'));
await tester.pumpAndSettle();
expect(find.text('queued'), findsOneWidget);
expect(find.text('Pipeline'), findsOneWidget);
expect(find.text('Any pipeline'), findsOneWidget);
expect(find.text('Time range'), findsOneWidget);
expect(find.text('Last 7 days'), findsOneWidget);
expect(find.text('Any trigger'), findsOneWidget);
expect(
find.text(
'Some records have no scheduling provenance; they stay unclassified.',
),
findsOneWidget,
);
final pipelineItem = find.ancestor(
of: find.text('Alpha'),
matching: find.byWidgetPredicate((widget) => widget is PopupMenuItem),
);
await tester.ensureVisible(pipelineItem);
await tester.tap(pipelineItem);
await tester.pumpAndSettle();
expect(controller.pipelineId, 9);
await tester.tap(find.text('Filter (1)'));
await tester.pumpAndSettle();
final timeItem = find.ancestor(
of: find.text('Last 7 days'),
matching: find.byWidgetPredicate((widget) => widget is PopupMenuItem),
);
await tester.ensureVisible(timeItem);
await tester.tap(timeItem);
await tester.pumpAndSettle();
expect(controller.timeRange, 'last_7_days');
expect(find.text('Filter (2)'), findsOneWidget);
expect(find.byTooltip('Clear filter: Last 7 days'), findsOneWidget);
await tester.tap(find.text('Filter (2)'));
await tester.pumpAndSettle();
final failedItem = find.ancestor(
of: find.text('failed'),
matching: find.byWidgetPredicate((widget) => widget is PopupMenuItem),
@@ -77,11 +124,10 @@ void main() {
await tester.tap(failedItem);
await tester.pumpAndSettle();
expect(controller.statuses, {'failed'});
expect(find.text('Filter (1)'), findsOneWidget);
expect(find.byType(InputChip), findsOneWidget);
expect(find.text('Filter (3)'), findsOneWidget);
expect(find.byType(InputChip), findsNWidgets(3));
expect(find.text('failed'), findsWidgets);
expect(find.text('Alpha'), findsNothing);
expect(find.text('Beta'), findsOneWidget);
expect(controller.visibleRuns, isEmpty);
await tester.tap(find.textContaining('Sort:'));
await tester.pumpAndSettle();
@@ -97,6 +143,8 @@ void main() {
await tester.tap(find.byTooltip('Clear filter: failed'));
await tester.pumpAndSettle();
expect(controller.statuses, isEmpty);
controller.clearFilters();
await tester.pumpAndSettle();
expect(find.byType(InputChip), findsNothing);
expect(find.text('Filter'), findsOneWidget);
expect(find.text('Alpha'), findsOneWidget);
@@ -122,6 +170,8 @@ void main() {
await tester.pumpAndSettle();
expect(controller.statuses, {'failed'});
expect(find.text('✓ failed'), findsOneWidget);
expect(find.text('Pipeline'), findsOneWidget);
expect(find.text('Last 7 days'), findsOneWidget);
expect(find.text('Filter (1)'), findsOneWidget);
await tester.tap(find.text('Done'));
+106
View File
@@ -0,0 +1,106 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/shell/adaptive_shell.dart';
/// The Runs tab mirrors the attention count in every mount of both hosts:
/// Material rail and bottom bar, Cupertino sidebar and tab bar. Zero draws the
/// bare icon with no count and no attention semantics.
void main() {
final needingAttention = RegExp('Notifications, 3 needing attention');
final anyAttention = RegExp('needing attention');
Future<void> pumpShell(
WidgetTester tester, {
required double width,
required bool cupertino,
required int count,
}) async {
tester.view.physicalSize = Size(width, 900);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final shell = AdaptiveShell(cupertino: cupertino, attentionCount: count);
await tester.pumpWidget(
cupertino ? CupertinoApp(home: shell) : MaterialApp(home: shell),
);
}
for (final width in [390.0, 1000.0]) {
final mount = width < 600 ? 'bottom bar' : 'rail';
testWidgets('Material $mount shows the count on the Runs tab', (
tester,
) async {
final semantics = tester.ensureSemantics();
await pumpShell(tester, width: width, cupertino: false, count: 3);
expect(
find.byType(width < 600 ? NavigationBar : NavigationRail),
findsOneWidget,
);
final badge = find.byType(Badge);
expect(badge, findsOneWidget);
expect(tester.widget<Badge>(badge).isLabelVisible, isTrue);
expect(
find.descendant(of: badge, matching: find.text('3')),
findsOneWidget,
);
expect(find.bySemanticsLabel(needingAttention), findsOneWidget);
semantics.dispose();
});
testWidgets('Material $mount hides the badge at zero', (tester) async {
final semantics = tester.ensureSemantics();
await pumpShell(tester, width: width, cupertino: false, count: 0);
final badge = find.byType(Badge);
expect(badge, findsOneWidget);
expect(tester.widget<Badge>(badge).isLabelVisible, isFalse);
expect(
find.descendant(of: badge, matching: find.byType(Text)),
findsNothing,
);
expect(find.bySemanticsLabel(anyAttention), findsNothing);
semantics.dispose();
});
}
for (final width in [390.0, 1280.0]) {
final mount = width < 600 ? 'tab bar' : 'sidebar';
testWidgets('Cupertino $mount shows the count on the Runs item', (
tester,
) async {
final semantics = tester.ensureSemantics();
await pumpShell(tester, width: width, cupertino: true, count: 3);
expect(
find.byType(CupertinoTabBar),
width < 600 ? findsOneWidget : findsNothing,
);
expect(find.byType(Badge), findsNothing, reason: 'no Material badge');
expect(find.text('3'), findsOneWidget);
expect(find.bySemanticsLabel(needingAttention), findsOneWidget);
semantics.dispose();
});
testWidgets('Cupertino $mount hides the count at zero', (tester) async {
final semantics = tester.ensureSemantics();
await pumpShell(tester, width: width, cupertino: true, count: 0);
expect(find.text('0'), findsNothing);
expect(find.bySemanticsLabel(anyAttention), findsNothing);
semantics.dispose();
});
}
testWidgets('the badge stays visible from every destination', (tester) async {
await pumpShell(tester, width: 1000, cupertino: false, count: 2);
for (final label in ['Runs', 'Chat', 'Settings']) {
await tester.tap(find.text(label).last);
await tester.pumpAndSettle();
expect(
find.descendant(of: find.byType(Badge), matching: find.text('2')),
findsOneWidget,
reason: 'badge missing on $label',
);
}
});
}
+213
View File
@@ -0,0 +1,213 @@
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 Chrome acceptance for composer paste.
//
// Usage (from app/):
// flutter build web -t tool/chat_composer_probe_entry.dart -o build/composer_probe_paste
// OPENCODE_ARTIFACT_DIR=<dir> node tool/chat_paste_probe.mjs build/composer_probe_paste
//
// The fixture is served over loopback only. Flutter paints text on a canvas, so
// assertions read the semantics tree; the browser also reports whether the
// document paste listener called preventDefault. Captures are PNGs.
const artifactDir = process.env.OPENCODE_ARTIFACT_DIR;
if (!artifactDir) throw new Error('Set OPENCODE_ARTIFACT_DIR for the captures');
await mkdir(artifactDir, { recursive: true });
const root = resolve(process.argv[2] ?? join(process.cwd(), 'build/composer_probe_paste'));
const mime = {
'.html': 'text/html',
'.js': 'text/javascript',
'.json': 'application/json',
'.wasm': 'application/wasm',
'.png': 'image/png',
'.ico': 'image/x-icon',
'.ttf': 'font/ttf',
'.otf': 'font/otf',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
};
const server = createServer(async (req, res) => {
try {
const path = resolve(root, '.' + decodeURIComponent(new URL(req.url, 'http://localhost').pathname));
if (path !== root && !path.startsWith(root + sep)) return res.writeHead(403).end();
const filePath = path === root || path.endsWith('/') ? join(path, 'index.html') : path;
const file = await readFile(filePath);
res.writeHead(200, { 'content-type': mime[extname(filePath)] ?? 'application/octet-stream' }).end(file);
} catch {
res.writeHead(404).end('not found');
}
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const port = server.address().port;
const profile = await mkdtemp(join(tmpdir(), 'chat-paste-chrome-'));
const chrome = spawn('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', [
'--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu',
'--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank',
], { stdio: ['ignore', 'ignore', 'pipe'] });
let stderr = '';
chrome.stderr.on('data', data => { stderr += data; });
let ws;
try {
const 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}`);
};
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 msg = JSON.parse(event.data);
if (msg.method === 'Runtime.exceptionThrown') {
console.error('PAGE EXCEPTION', JSON.stringify(msg.params?.exceptionDetails?.exception?.description ?? msg.params?.exceptionDetails?.text));
}
if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); }
});
const send = (method, params = {}, sessionId) => new Promise(resolve => {
const callId = ++id;
pending.set(callId, resolve);
ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) }));
});
const created = await send('Target.createTarget', { url: 'about:blank' });
if (!created.result) throw new Error(`Target creation failed: ${JSON.stringify(created)}`);
const session = (await send('Target.attachToTarget', { targetId: created.result.targetId, flatten: true })).result.sessionId;
await send('Page.enable', {}, session);
await send('Runtime.enable', {}, session);
const navigation = await send('Page.navigate', { url: `http://127.0.0.1:${port}/` }, session);
if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation));
const evaluate = async expression => {
const response = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, session);
if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`);
return response.result?.result?.value;
};
for (let i = 0; i < 120; i++) {
if (await evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))")) break;
await delay(100);
}
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
await delay(1800);
const labels = async () =>
evaluate("[...document.querySelectorAll('flt-semantics')].map(x => x.getAttribute('aria-label') || x.innerText || '').filter(Boolean)");
const semanticText = async () => (await labels()).join('\n');
const assertSemantics = async (text, what) => {
const read = await semanticText();
if (!read.toLowerCase().replace(/\s+/g, ' ').includes(text.toLowerCase())) {
throw new Error(`${what}: semantics lacks ${JSON.stringify(text)}\n${read.slice(0, 2000)}`);
}
};
const assertMissing = async (text, what) => {
const read = await semanticText();
if (read.toLowerCase().replace(/\s+/g, ' ').includes(text.toLowerCase())) {
throw new Error(`${what}: semantics still has ${JSON.stringify(text)}\n${read.slice(0, 2000)}`);
}
};
const editingValue = async () => evaluate(`(() => {
const match = n => (n.getAttribute('aria-label') || n.getAttribute('placeholder') || '').includes('Message the agent');
const node = document.querySelector('input.flt-text-editing, textarea.flt-text-editing')
|| [...document.querySelectorAll('textarea, input')].find(match)
|| null;
return node ? { tag: node.tagName, value: node.value } : null;
})()`);
const focusField = async () => {
const focused = await evaluate(`(() => {
const needle = 'Message the agent';
const node = [...document.querySelectorAll('textarea, input')]
.find(n => (n.getAttribute('aria-label') || n.placeholder || '').includes(needle));
if (!node) return null;
node.focus();
return { tag: node.tagName };
})()`);
if (!focused) throw new Error('Composer field was not exposed to semantics');
await delay(500);
return focused;
};
const dispatchPaste = async ({ text = null, files = [] }) => evaluate(`(() => {
const data = new DataTransfer();
if (${JSON.stringify(text)} != null) data.setData('text/plain', ${JSON.stringify(text)});
const specs = ${JSON.stringify(files)};
for (const spec of specs) {
const bytes = new Uint8Array(spec.size).fill(7);
data.items.add(new File([bytes], spec.name, { type: spec.mime }));
}
const target = document.activeElement || document.body;
const event = new ClipboardEvent('paste', {
clipboardData: data, bubbles: true, cancelable: true,
});
target.dispatchEvent(event);
return event.defaultPrevented;
})()`);
const type = async text => { await send('Input.insertText', { text }, session); await delay(250); };
const capture = async name => {
const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data;
const file = `paste-${name}.png`;
await writeFile(`${artifactDir}/${file}`, Buffer.from(data, 'base64'));
return file;
};
const setSize = async (width, height, scale = 1) => {
await send('Emulation.setDeviceMetricsOverride', {
width, height, deviceScaleFactor: scale, mobile: width < 600,
}, session);
await delay(400);
};
const checks = [];
await setSize(390, 844);
await assertSemantics('Composer fixture', 'The fixture thread');
await focusField();
await type('keep me');
const textPrevented = await dispatchPaste({ text: ' clipboard words' });
if (textPrevented) throw new Error('A text-only paste was prevented');
checks.push({ check: 'a text-only paste is not intercepted', prevented: textPrevented });
const filePrevented = await dispatchPaste({
files: [{ name: 'shot.png', mime: 'image/png', size: 3 }],
});
if (!filePrevented) throw new Error('A file paste was not consumed');
await waitFor(async () => (await semanticText()).includes('shot.png'), 'the pasted chip');
const draftAfterFile = await editingValue();
if (draftAfterFile?.value !== 'keep me') {
throw new Error(`The paste changed the draft: ${JSON.stringify(draftAfterFile)}`);
}
await capture('file-chip');
checks.push({ check: 'a pasted file becomes a chip and leaves text alone', prevented: filePrevented, value: draftAfterFile.value });
const hugePrevented = await dispatchPaste({
files: [{ name: 'huge.bin', mime: 'application/octet-stream', size: 1048577 }],
});
await waitFor(
async () => (await semanticText()).includes('1 MiB total'),
'the over-limit refusal',
);
await assertSemantics('Attachments are too large for web chat (1 MiB total).', 'the over-limit refusal');
await assertMissing('huge.bin', 'the refused file');
await capture('over-limit');
checks.push({ check: 'an over-limit paste shows the refusal and adds no chip', prevented: hugePrevented });
await dispatchPaste({ files: [{ name: '', mime: 'image/png', size: 4 }] });
await waitFor(async () => (await semanticText()).includes('pasted-1.png'), 'the generated name');
await capture('nameless-file');
checks.push({ check: 'a nameless clipboard image takes the web pasted name' });
console.log(JSON.stringify({ checks }, 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 });
}
+646
View File
@@ -0,0 +1,646 @@
// Real-browser evidence for Search result-target selection.
//
// Usage (from app/):
// flutter build web --target tool/search_selection_probe_entry.dart \
// --output build/probe-search-selection
// node tool/search_selection_probe.mjs --root build/probe-search-selection \
// --out build/search-selection-probe
//
// Serves the fixture build over loopback (extension-less paths fall back to
// index.html so the app's real `/runs/7` and `/search` locations load), drives
// headless Chrome through the Chrome DevTools Protocol, enables Flutter
// semantics, types a query into the real search field, clicks result rows by
// their exact row title and asserts the run detail state the hit selects:
//
// field hit -> run Summary with the matched Output section expanded
// artifact hit -> the recorded visit pane (`build · visit 2`)
// retired field -> the plain Summary, no section expanded
// unknown visit -> the plain Summary, no visit pane
//
// Every reply comes from the in-app fixture channel in
// tool/search_selection_probe_entry.dart; no server is contacted.
import { createServer } from 'node:http';
import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
import { spawn } from 'node:child_process';
import { once } from 'node:events';
import { setTimeout as delay } from 'node:timers/promises';
import { extname, join, resolve, sep } from 'node:path';
import { tmpdir } from 'node:os';
const args = new Map();
for (let i = 2; i < process.argv.length; i++) {
const value = process.argv[i];
if (value.startsWith('--')) args.set(value.slice(2), process.argv[++i]);
}
const root = resolve(args.get('root') ?? 'build/probe-search-selection');
const out = resolve(args.get('out') ?? 'build/search-selection-probe');
const chromePath =
process.env.CHROME_PATH ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
await mkdir(out, { recursive: true });
const mime = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.wasm': 'application/wasm',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.ttf': 'font/ttf',
'.otf': 'font/otf',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.bin': 'application/octet-stream',
'.frag': 'application/octet-stream',
};
const server = createServer(async (req, res) => {
try {
const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);
let filePath = resolve(root, '.' + pathname);
if (filePath !== root && !filePath.startsWith(root + sep)) {
res.writeHead(403).end();
return;
}
// The app uses path URLs (`/runs/7`, `/search`); any route path without a
// file extension is the single page, as the Pipelines proxy serves it.
try {
if ((await stat(filePath)).isDirectory()) filePath = join(filePath, 'index.html');
} catch {
if (!extname(pathname)) filePath = join(root, 'index.html');
}
const file = await readFile(filePath);
const type = mime[extname(filePath)] ?? 'application/octet-stream';
res.writeHead(200, { 'content-type': type, 'cache-control': 'no-store' }).end(file);
} catch {
res.writeHead(404).end('not found');
}
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const port = server.address().port;
const origin = `http://127.0.0.1:${port}`;
const profile = await mkdtemp(join(tmpdir(), 'x1-search-selection-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, attempts = 120) => {
for (let i = 0; i < attempts; i++) {
const value = await fn();
if (value) return value;
await delay(100);
}
throw new Error(`Timed out waiting for ${what}: ${stderr.slice(-1500)}`);
};
// The exact row titles the fixture's six `release` hits render, one per kind,
// and the row meta each one announces (tool/search_selection_probe_entry.dart).
const RELEASE_ROWS = [
{ title: 'Release train', meta: 'Pipeline' },
{ title: 'pipeline 22 · v6', meta: 'Pipeline version' },
{ title: 'run #7 · Release train', meta: 'Run' },
{ title: 'run #7 · plan visit 2', meta: 'Step' },
{ title: 'run #7 · step 5 · output', meta: 'Field' },
{ title: 'release-report.txt', meta: 'Artifact' },
];
const RELEASE_BOUNDS = '6 results · cap 50 · scanned 3 steps · 2.0 KiB scanned · scan limit 1.0 MiB';
const BUILD_VISIT = 'build · visit 2';
// Flutter web renders a read-only SelectableText as a <textarea> whose value
// stays empty, so the section's JSON is pixels only; the section state itself
// is announced on the tile ("Expanded …" / "Collapsed …" aria-description).
const EXPANDED = 'Expanded';
const COLLAPSED = 'Collapsed';
let ws;
let send;
let session;
const evidence = { origin, captures: [], checks: [], defects: [] };
try {
const endpoint = await waitFor(
() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1],
'Chrome DevTools',
);
ws = new WebSocket(endpoint);
await once(ws, 'open');
let id = 0;
const pending = new Map();
const pageErrors = [];
ws.addEventListener('message', (event) => {
const message = JSON.parse(event.data);
if (message.method === 'Runtime.exceptionThrown') {
pageErrors.push(JSON.stringify(message.params?.exceptionDetails?.exception?.description ?? message.params));
}
if (message.id && pending.has(message.id)) {
pending.get(message.id)(message);
pending.delete(message.id);
}
});
send = (method, params = {}, sessionId) =>
new Promise((resolveCall) => {
const callId = ++id;
pending.set(callId, resolveCall);
ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) }));
});
const created = await send('Target.createTarget', { url: 'about:blank' });
if (!created.result) throw new Error(`Target creation failed: ${JSON.stringify(created)}`);
const target = created.result.targetId;
session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result
.sessionId;
await send('Page.enable', {}, session);
await send('Runtime.enable', {}, session);
// A headless target can stay unfocused, which makes the browser refuse the
// search field's autofocus rather than testing the app.
await send('Page.bringToFront', {}, 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(JSON.stringify(response.result.exceptionDetails));
}
return response.result?.result?.value;
};
const labels = () =>
evaluate(
"[...document.querySelectorAll('flt-semantics')].map(x => x.getAttribute('aria-label') || (x.innerText || '').trim()).filter(Boolean)",
);
// Everything the semantics tree announces: labels, leaf text, and the value
// of read-only text controls (the Cupertino Summary sections render their
// JSON in a read-only CupertinoTextField, which is an <input>/<textarea>).
const text = () =>
evaluate(`(() => {
const chunks = [];
for (const el of document.querySelectorAll('flt-semantics, [aria-label], input, textarea')) {
const label = el.getAttribute('aria-label');
if (label) chunks.push(label);
if (!el.children.length && el.innerText) chunks.push(el.innerText);
if ((el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') && el.value) chunks.push(el.value);
}
if (document.body?.innerText) chunks.push(document.body.innerText);
return [...new Set(chunks)].join('\\n');
})()`);
const path = () => evaluate('location.pathname');
const hasText = async (needle) => (await text()).includes(needle);
const assertText = async (needle, what = needle) => {
try {
await waitFor(async () => hasText(needle), `${what} (${JSON.stringify(needle)})`);
} catch (error) {
throw new Error(`${error.message}\n--- page text ---\n${await text()}`);
}
};
const assertNoText = async (needle, what = needle) => {
if (await hasText(needle)) {
throw new Error(`${what} unexpectedly present: ${JSON.stringify(needle)}`);
}
};
// Rows announce their title, then their meta and snippet lines; click the
// most specific (shortest) tappable node whose text starts with the title.
const clickPrefix = async (prefix) => {
const clicked = await evaluate(`(() => {
const wanted = ${JSON.stringify(prefix)};
const nodes = [...document.querySelectorAll('flt-semantics')];
const candidates = nodes.filter((x) =>
(x.getAttribute('aria-label') || '').startsWith(wanted)
|| (x.innerText || '').trim().startsWith(wanted));
if (candidates.length === 0) return false;
candidates.sort((a, b) => (a.innerText || a.getAttribute('aria-label') || '').length
- (b.innerText || b.getAttribute('aria-label') || '').length);
candidates[0].click();
return true;
})()`);
if (!clicked) throw new Error(`No semantics label starting ${JSON.stringify(prefix)}: ${JSON.stringify(await labels())}`);
await delay(450);
};
// The shell's Search action is a real button; a pointer event keeps user
// activation so the page may then focus the search field.
const tapExact = async (label) => {
const point = await evaluate(`(() => {
const wanted = ${JSON.stringify(label)};
const nodes = [...document.querySelectorAll('flt-semantics')];
const node = nodes.find(x => x.getAttribute('aria-label') === wanted)
|| nodes.find(x => (x.innerText || '').trim() === wanted);
if (!node) return null;
const rect = node.getBoundingClientRect();
return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
})()`);
if (!point) throw new Error(`No semantics node for ${JSON.stringify(label)}: ${JSON.stringify(await labels())}`);
for (const type of ['mousePressed', 'mouseReleased']) {
await send('Input.dispatchMouseEvent', { type, x: point.x, y: point.y, button: 'left', clickCount: 1 }, session);
}
await delay(450);
};
const activate = async () => {
await waitFor(
() => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"),
'Flutter semantics placeholder',
);
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
await delay(900);
};
let viewport = { width: 390, height: 844 };
const setSize = async (width, height, scale = 1) => {
viewport = { width, height };
await send('Emulation.setDeviceMetricsOverride', {
width,
height,
deviceScaleFactor: scale,
mobile: width < 600,
}, session);
await delay(500);
};
const navigate = async (url, width, height) => {
await setSize(width, height);
const navigation = await send('Page.navigate', { url }, session);
if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation));
await activate();
};
const capture = async (name) => {
await delay(350);
const data = (await send('Page.captureScreenshot', { format: 'png' }, session)).result.data;
const file = join(out, `${name}.png`);
await writeFile(file, Buffer.from(data, 'base64'));
evidence.captures.push(file);
return file;
};
// The Summary's Input/Output tiles: Material's ExpansionTile and the
// Cupertino expansion tile both announce their state as the first line of
// aria-description ("Expanded" / "Collapsed"); an expanded Cupertino tile
// merges with its read-only text child into one <textarea> node.
const tileState = (title) =>
evaluate(`(() => {
const wanted = ${JSON.stringify(title)};
const nodes = [...document.querySelectorAll('flt-semantics, textarea, input')];
const node = nodes.find((x) =>
(x.getAttribute('aria-label') || '').trim() === wanted
|| (x.children.length === 0 && (x.innerText || '').trim() === wanted));
if (!node) return null;
const description = node.getAttribute('aria-description') || '';
return description.split('\\n')[0].trim() || 'unknown';
})()`);
const waitForTile = async (title, state) => {
try {
await waitFor(async () => (await tileState(title)) === state, `the ${title} section to be ${state}`, 40);
} catch (error) {
throw new Error(`${error.message}\n--- tiles ---\nInput: ${await tileState('Input')}\nOutput: ${await tileState('Output')}\n--- page text ---\n${await text()}`);
}
};
// Scrolls the detail body to its end so an expanded section below the phone
// fold is inside the captured frame.
const scrollBodyToEnd = async () => {
for (let i = 0; i < 2; i++) {
await send('Input.dispatchMouseEvent', {
type: 'mouseWheel',
x: viewport.width / 2,
y: viewport.height * 0.6,
deltaX: 0,
deltaY: 3000,
}, session);
await delay(400);
}
};
const fieldFocused = () =>
evaluate(`(() => {
const active = document.activeElement;
return Boolean(active && (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA'));
})()`);
const typeQuery = async (value) => {
if (!(await fieldFocused())) {
const focused = await evaluate(`(() => {
const nodes = [...document.querySelectorAll('input.flt-text-editing, textarea.flt-text-editing, input, textarea')];
const node = nodes.find((el) => el.checkVisibility?.() ?? true) || nodes.at(-1);
if (!node) return false; node.focus(); return true;
})()`);
if (!focused) throw new Error('Search field not exposed as a semantics input');
await delay(300);
}
const inserted = await send('Input.insertText', { text: value }, session);
if (inserted.error) throw new Error(JSON.stringify(inserted));
// 250ms debounce plus the fixture channel's 120ms reply.
await delay(900);
};
// Search is a transient page above the shell: the action opens /search and
// the Cupertino host mounts the field after its page transition.
const openSearch = async () => {
await tapExact('Search');
await waitFor(async () => (await path()) === '/search', 'the /search route');
await waitFor(fieldFocused, 'the focused search field', 60).catch(() => {});
};
const searchFor = async (query, expectRow) => {
await openSearch();
await typeQuery(query);
await assertText(expectRow, `the ${JSON.stringify(query)} result row`);
};
const assertReleaseResults = async (host) => {
const body = await text();
const missing = [];
for (const row of RELEASE_ROWS) {
if (!body.includes(row.title)) missing.push(row.title);
if (!body.includes(row.meta)) missing.push(`meta ${row.meta}`);
}
if (!body.includes(RELEASE_BOUNDS)) missing.push(RELEASE_BOUNDS);
if (!body.includes('ship the release')) missing.push('field snippet "ship the release"');
if (!body.includes('Kind')) missing.push('Kind control');
evidence.checks.push({
check: `${host}: the search panel lists one hit per kind for "release"`,
rows: RELEASE_ROWS.map((row) => row.title),
bounds: RELEASE_BOUNDS,
missing,
});
if (missing.length) throw new Error(`Search results missing ${JSON.stringify(missing)}`);
};
const assertRun7 = async () => {
await waitFor(async () => (await path()) === '/runs/7', 'the /runs/7 route from search');
await assertText('Release train run', 'the run detail title');
if (await hasText('Kind: All kinds') || await hasText('Search pipelines, runs and artifacts')) {
throw new Error('Search stayed open above the run detail');
}
};
const assertFieldSummary = async (host) => {
await assertRun7();
await waitForTile('Output', EXPANDED);
await waitForTile('Input', COLLAPSED);
await assertNoText('Back to timeline', 'a visit pane');
await assertNoText(BUILD_VISIT, 'a visit pane');
evidence.checks.push({
check: `${host}: a field hit opens the Summary with only Output expanded`,
path: await path(),
output: await tileState('Output'),
input: await tileState('Input'),
visitPane: false,
});
await scrollBodyToEnd();
};
const assertArtifactVisit = async (host) => {
await assertRun7();
await assertText(BUILD_VISIT, 'the recorded build visit');
await assertText('Back to timeline', 'the visit pane');
// The visit pane has its own Input/Output section strip; the Summary's
// prompt block is the text that only the Summary tab shows.
await assertNoText('Original prompt', 'the Summary tab');
evidence.checks.push({
check: `${host}: an artifact hit opens the visit that recorded it`,
path: await path(),
visit: BUILD_VISIT,
summaryShown: false,
});
};
const assertPlainSummary = async (host, what) => {
await assertRun7();
await assertText('Original prompt', 'the plain Summary');
await waitForTile('Input', COLLAPSED);
await waitForTile('Output', COLLAPSED);
await assertNoText(BUILD_VISIT, 'a visit pane');
await assertNoText('Back to timeline', 'a visit pane');
evidence.checks.push({
check: `${host}: ${what} selects the plain Summary`,
path: await path(),
input: await tileState('Input'),
output: await tileState('Output'),
});
await scrollBodyToEnd();
};
// A retired field selects the plain Summary; after an earlier field hit on
// the same mounted run, a section that hit expanded must not stay open, or
// the "plain" Summary still shows the previous match's section. The state
// is recorded rather than asserted so the probe can still capture every
// required state; a carried-over section is reported as a defect.
const recordRetiredAfterField = async (host) => {
await assertRun7();
await assertText('Original prompt', 'the Summary');
await assertNoText('Back to timeline', 'a visit pane');
const state = { input: await tileState('Input'), output: await tileState('Output') };
const check = {
check: `${host}: a retired field hit after an output field hit selects the plain Summary`,
path: await path(),
...state,
expected: { input: COLLAPSED, output: COLLAPSED },
};
evidence.checks.push(check);
if (state.input !== COLLAPSED || state.output !== COLLAPSED) {
evidence.defects.push({
...check,
note: 'The earlier field hit\'s expanded section is kept when the retired hit resolves to the plain Summary on the same mounted detail.',
});
}
await scrollBodyToEnd();
};
// The app follows the system colour scheme; pin it so captures are
// deterministic (light first, one dark pass below).
const emulateScheme = (value) => send('Emulation.setEmulatedMedia', {
features: [{ name: 'prefers-color-scheme', value }],
}, session);
await emulateScheme('light');
await navigate(`${origin}/`, 390, 844);
const contentType = await evaluate("fetch('/').then(r => r.headers.get('content-type'))");
evidence.checks.push({ check: 'index content-type is text/html', value: contentType });
if (!String(contentType).toLowerCase().startsWith('text/html')) {
throw new Error(`Root index is not text/html: ${contentType}`);
}
const routeType = await evaluate("fetch('/runs/7').then(r => r.headers.get('content-type'))");
if (!String(routeType).toLowerCase().startsWith('text/html')) {
throw new Error(`Route path is not served as the page: ${routeType}`);
}
// ---- Material host, phone ------------------------------------------------
await navigate(`${origin}/runs`, 390, 844);
await assertText('Release train run', 'the Runs list');
await searchFor('release', 'run #7 · step 5 · output');
await assertReleaseResults('material phone');
await capture('search-selection-material-phone-results');
// An artifact hit opens the visit that recorded it.
await clickPrefix('release-report.txt');
await assertArtifactVisit('material phone');
await capture('search-selection-material-phone-artifact-visit');
// The retired field replaces the open visit with the plain Summary.
await searchFor('retired', 'run #7 · step 5 · evidence');
await clickPrefix('run #7 · step 5 · evidence');
await assertPlainSummary('material phone', 'a retired field hit');
await capture('search-selection-material-phone-retired-summary');
// An artifact whose recorded visit the run never recorded (sequence 9).
await searchFor('release', 'release-report.txt');
await clickPrefix('release-report.txt');
await assertArtifactVisit('material phone (reopened)');
await searchFor('missing', 'missing.log');
await clickPrefix('missing.log');
await assertPlainSummary('material phone', 'an unknown-visit artifact hit');
await capture('search-selection-material-phone-unknown-visit-summary');
// A field hit opens the Summary at its matched section.
await searchFor('release', 'run #7 · step 5 · output');
await clickPrefix('run #7 · step 5 · output');
await assertFieldSummary('material phone');
await capture('search-selection-material-phone-field-summary');
// A retired hit after that field hit, on the same mounted detail.
await searchFor('retired', 'run #7 · step 5 · evidence');
await clickPrefix('run #7 · step 5 · evidence');
await recordRetiredAfterField('material phone');
await capture('search-selection-material-phone-retired-after-field-summary');
// Reopening the run from its list is an ordinary visit: nothing replays.
await searchFor('release', 'release-report.txt');
await clickPrefix('release-report.txt');
await assertArtifactVisit('material phone (before reopen)');
await tapExact('Back to list');
await waitFor(async () => (await path()) === '/runs', 'the Runs list');
await clickPrefix('Release train run');
await waitFor(async () => (await path()) === '/runs/7', 'the reopened run');
await assertText('Original prompt', 'the reopened Summary');
await assertNoText(BUILD_VISIT, 'a replayed visit pane');
evidence.checks.push({ check: 'material phone: a consumed selection does not replay on reopen', path: await path() });
// A step hit names the run's recorded visit by stage and server visit
// number. plan visit 1 is sequence 1; the pane must say `plan · visit 1`.
await searchFor('first', 'run #7 · plan visit 1');
await clickPrefix('run #7 · plan visit 1');
await waitFor(async () => (await path()).startsWith('/runs/7'), 'the step route');
await delay(600);
const stepPath = await path();
const stepSearch = await evaluate('location.search');
const stepBody = await text();
const stepVisit = stepBody.match(/plan · visit (\d+)/)?.[0] ?? null;
const stepCheck = {
check: 'material phone: a step hit for plan visit 1 opens plan · visit 1',
route: `${stepPath}${stepSearch}`,
opened: stepVisit,
expected: 'plan · visit 1',
};
evidence.checks.push(stepCheck);
if (stepVisit !== 'plan · visit 1') {
evidence.defects.push({
...stepCheck,
note: 'The hit carries the server visit number (1-based); the route query is zero-based.',
});
}
await capture('search-selection-material-phone-step-visit');
// ---- Material host, desktop ----------------------------------------------
await navigate(`${origin}/runs`, 1280, 800);
await assertText('Release train run', 'the Runs list');
await searchFor('release', 'run #7 · step 5 · output');
await assertReleaseResults('material desktop');
await capture('search-selection-material-desktop-results');
await clickPrefix('release-report.txt');
await assertArtifactVisit('material desktop');
await capture('search-selection-material-desktop-artifact-visit');
await searchFor('retired', 'run #7 · step 5 · evidence');
await clickPrefix('run #7 · step 5 · evidence');
await assertPlainSummary('material desktop', 'a retired field hit');
await capture('search-selection-material-desktop-retired-summary');
await searchFor('release', 'run #7 · step 5 · output');
await clickPrefix('run #7 · step 5 · output');
await assertFieldSummary('material desktop');
await capture('search-selection-material-desktop-field-summary');
// Dark scheme is the host theme, not a fixture flag: the app follows the
// system scheme, so emulate it for one results and one selection capture.
await emulateScheme('dark');
await navigate(`${origin}/runs`, 390, 844);
await assertText('Release train run', 'the Runs list');
await searchFor('release', 'run #7 · step 5 · output');
await capture('search-selection-material-phone-dark-results');
await clickPrefix('run #7 · step 5 · output');
await assertFieldSummary('material phone dark');
await capture('search-selection-material-phone-dark-field-summary');
await emulateScheme('light');
// ---- Cupertino host, phone -----------------------------------------------
await navigate(`${origin}/runs?platform=cupertino`, 390, 844);
await assertText('Release train run', 'the Runs list');
await searchFor('release', 'run #7 · step 5 · output');
await assertReleaseResults('cupertino phone');
await assertText('Kind: All kinds', 'the Cupertino kind control');
await capture('search-selection-cupertino-phone-results');
await clickPrefix('release-report.txt');
await assertArtifactVisit('cupertino phone');
await capture('search-selection-cupertino-phone-artifact-visit');
await searchFor('retired', 'run #7 · step 5 · evidence');
await clickPrefix('run #7 · step 5 · evidence');
await assertPlainSummary('cupertino phone', 'a retired field hit');
await capture('search-selection-cupertino-phone-retired-summary');
await searchFor('release', 'release-report.txt');
await clickPrefix('release-report.txt');
await assertArtifactVisit('cupertino phone (reopened)');
await searchFor('missing', 'missing.log');
await clickPrefix('missing.log');
await assertPlainSummary('cupertino phone', 'an unknown-visit artifact hit');
await capture('search-selection-cupertino-phone-unknown-visit-summary');
await searchFor('release', 'run #7 · step 5 · output');
await clickPrefix('run #7 · step 5 · output');
await assertFieldSummary('cupertino phone');
await capture('search-selection-cupertino-phone-field-summary');
await searchFor('retired', 'run #7 · step 5 · evidence');
await clickPrefix('run #7 · step 5 · evidence');
await recordRetiredAfterField('cupertino phone');
await capture('search-selection-cupertino-phone-retired-after-field-summary');
// ---- Cupertino host, desktop ---------------------------------------------
await navigate(`${origin}/runs?platform=cupertino`, 1280, 800);
await assertText('Release train run', 'the Runs list');
await searchFor('release', 'run #7 · step 5 · output');
await assertReleaseResults('cupertino desktop');
await capture('search-selection-cupertino-desktop-results');
await clickPrefix('release-report.txt');
await assertArtifactVisit('cupertino desktop');
await capture('search-selection-cupertino-desktop-artifact-visit');
await searchFor('release', 'run #7 · step 5 · output');
await clickPrefix('run #7 · step 5 · output');
await assertFieldSummary('cupertino desktop');
await capture('search-selection-cupertino-desktop-field-summary');
evidence.pageErrors = pageErrors;
console.log(JSON.stringify(evidence, null, 2));
if (evidence.defects.length) process.exitCode = 2;
} catch (error) {
// Keep the failing frame beside the captures so the failure is inspectable.
try {
const data = (await send('Page.captureScreenshot', { format: 'png' }, session)).result.data;
await writeFile(join(out, 'failure.png'), Buffer.from(data, 'base64'));
} catch {
/* The failure is reported below either way. */
}
console.log(JSON.stringify({ ...evidence, failure: String(error.message) }, null, 2));
throw error;
} finally {
ws?.close();
chrome.kill('SIGTERM');
await Promise.race([once(chrome, 'exit'), delay(3000)]);
server.close();
await rm(profile, { recursive: true, force: true });
}
+469
View File
@@ -0,0 +1,469 @@
// Standalone fixture entry for real-browser Search result-selection evidence.
//
// Build and probe (from app/):
// flutter build web --target tool/search_selection_probe_entry.dart \
// --output build/probe-search-selection
// node tool/search_selection_probe.mjs --root build/probe-search-selection \
// --out build/search-selection-probe
//
// This is the normal application composition (`PipelinesApp`) over the shared
// transport, with the socket replaced by an in-process channel that answers
// the real `search`, `get_run`, `list_runs`, `list_pipelines`, `get_pipeline`
// and `ping` requests with server-shaped fixtures. Nothing here opens a
// network connection or touches a live server; the fixtures exist only so the
// shell's search → run-detail selection can be rendered and captured.
import 'dart:async';
import 'dart:convert';
import 'package:pipelines_app/application/app_url_strategy.dart';
import 'package:pipelines_app/application/pipelines_app.dart';
import 'package:pipelines_app/application/server_endpoint.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart';
import 'package:flutter/widgets.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
/// The run every run-scoped hit names. Its recorded sequences are deliberately
/// not its row indexes (plan 5, build 2, plan 1), exactly like the unit
/// fixture, so a selection has to resolve the recorded sequence.
JsonMap probeRunDetail() => {
'id': 7,
'title': 'Release train run',
'name': 'release-train',
'status': 'succeeded',
'created_at': '2026-10-20T08:12:00Z',
'finished_at': '2026-10-20T08:42:00Z',
'workspace': '/srv/probe/release',
'input': {'prompt': 'ship it'},
'output': {'result': 'ok'},
'steps': [
{
'stage': 'plan',
'sequence': 5,
'status': 'completed',
'outcome': 'success',
'target': '#success',
'started_at': '2026-10-20T08:30:00Z',
'finished_at': '2026-10-20T08:31:00Z',
'diagnostic': 'release plan accepted',
},
{
'stage': 'build',
'sequence': 2,
'status': 'completed',
'outcome': 'success',
'target': 'plan',
'started_at': '2026-10-20T08:16:00Z',
'finished_at': '2026-10-20T08:24:00Z',
'artifacts': [
{
'name': 'release-report.txt',
'content_type': 'text/plain',
'size_bytes': 12,
'url': '/artifacts/7/2/release-report.txt',
},
],
},
{
'stage': 'plan',
'sequence': 1,
'status': 'completed',
'outcome': 'success',
'target': 'build',
'started_at': '2026-10-20T08:12:00Z',
'finished_at': '2026-10-20T08:14:00Z',
},
],
};
List<JsonMap> probeRuns() => [
{
'id': 7,
'title': 'Release train run',
'name': 'release-train',
'status': 'succeeded',
'created_at': '2026-10-20T08:12:00Z',
'finished_at': '2026-10-20T08:42:00Z',
'pipeline_id': 24,
},
{
'id': 6,
'title': 'Nightly docs run',
'name': 'nightly-docs',
'status': 'failed',
'created_at': '2026-10-19T22:00:00Z',
'finished_at': '2026-10-19T22:03:00Z',
'pipeline_id': 22,
},
];
List<JsonMap> probePipelines() => [
{
'id': 24,
'name': 'Release train',
'version': 5,
'stages': 2,
'created_at': '2026-09-28T10:12:00',
'updated_at': '2026-10-20T09:18:00',
'scheduled': false,
'schedule_count': 0,
'enabled_schedule_count': 0,
},
{
'id': 22,
'name': 'Nightly documentation',
'version': 6,
'stages': 1,
'created_at': '2026-10-02T18:20:00',
'updated_at': '2026-10-18T16:05:00',
'scheduled': true,
'schedule_count': 1,
'enabled_schedule_count': 1,
},
];
const _releaseSource = 'name: Release train\n'
'stages:\n'
' plan:\n'
' type: model\n'
' output: plan\n'
' build:\n'
' type: model\n'
' output: release\n';
JsonMap probePipelineDetail(int id, int requestedVersion) {
final summary = probePipelines().firstWhere(
(pipeline) => pipeline['id'] == id,
orElse: () => probePipelines().first,
);
final latest = summary['version'] as int;
final version = requestedVersion > 0 ? requestedVersion : latest;
return {
...summary,
'version': version,
'latest_version': latest,
'version_created_at': '2026-10-18T16:05:00',
'content_hash': 'sha256:probe-$id-v$version',
'source': _releaseSource,
'versions': [
for (var v = 1; v <= latest; v++)
{'version': v, 'stages': summary['stages'], 'created_at': '2026-10-0${v}T10:00:00'},
],
};
}
/// One recorded hit per result kind, each with the text a server would have
/// matched (`haystack`). The payloads are server-shaped `search_results` rows:
/// the `target` tokens are the ones `internal/protocol/search.go` records.
///
/// `release` matches every kind once; `retired` matches only the retired-field
/// hit; `missing` matches only an artifact whose recorded visit (sequence 9)
/// the run never recorded; `first` matches only the plan visit 1 step hit.
const List<({String haystack, JsonMap hit})> probeHits = [
(
haystack: 'Release train pipeline definition',
hit: {
'kind': 'pipeline',
'target': 'pipeline:24',
'score': 3,
'recency': '2026-10-20T09:18:00Z',
'pipeline': {'id': 24, 'name': 'Release train', 'version': 5, 'stages': 2},
},
),
(
haystack: 'name: Nightly documentation release notes',
hit: {
'kind': 'version',
'target': 'pipeline:22:v6',
'score': 2,
'recency': '2026-10-18T16:05:00Z',
'version': {
'pipeline_id': 22,
'version': 6,
'content_hash': '9f2c1ad',
'created_at': '2026-10-18T16:05:00Z',
},
},
),
(
haystack: 'Release train run',
hit: {
'kind': 'run',
'target': 'run:7',
'score': 2,
'recency': '2026-10-20T08:42:00Z',
'run': {
'id': 7,
'pipeline_name': 'Release train',
'status': 'succeeded',
'workspace': '/srv/probe/release',
'created_at': '2026-10-20T08:12:00Z',
'finished_at': '2026-10-20T08:42:00Z',
},
},
),
(
haystack: 'release plan accepted',
hit: {
'kind': 'step',
'target': 'run:7:5',
'score': 1,
'recency': '2026-10-20T08:31:00Z',
'step': {
'run_id': 7,
'sequence': 5,
'stage': 'plan',
'visit': 2,
'outcome': 'success',
'target': '#success',
'diagnostic': 'release plan accepted',
},
},
),
(
haystack: 'ship the release',
hit: {
'kind': 'field',
'target': 'run:7:5:output',
'score': 1,
'matched_field': 'output',
'recency': '2026-10-20T08:31:00Z',
'field': {
'run_id': 7,
'sequence': 5,
'field': 'output',
'snippet': 'ship the release',
},
},
),
(
haystack: 'release-report.txt',
hit: {
'kind': 'artifact',
'target': '/artifacts/7/2/release-report.txt',
'score': 1,
'recency': '2026-10-20T08:24:00Z',
'artifact': {
'run_id': 7,
'sequence': 2,
'name': 'release-report.txt',
'content_type': 'text/plain',
'size_bytes': 12,
'url': '/artifacts/7/2/release-report.txt',
},
},
),
(
haystack: 'retired evidence note',
hit: {
'kind': 'field',
'target': 'run:7:5:evidence',
'score': 1,
'matched_field': 'evidence',
'recency': '2026-10-20T08:31:00Z',
'field': {
'run_id': 7,
'sequence': 5,
'field': 'evidence',
'snippet': 'retired evidence note',
},
},
),
(
haystack: 'missing.log',
hit: {
'kind': 'artifact',
'target': '/artifacts/7/9/missing.log',
'score': 1,
'recency': '2026-10-20T08:40:00Z',
'artifact': {
'run_id': 7,
'sequence': 9,
'name': 'missing.log',
'content_type': 'text/plain',
'size_bytes': 4096,
'url': '/artifacts/7/9/missing.log',
},
},
),
(
haystack: 'first plan visit',
hit: {
'kind': 'step',
'target': 'run:7:1',
'score': 1,
'recency': '2026-10-20T08:14:00Z',
'step': {
'run_id': 7,
'sequence': 1,
'stage': 'plan',
'visit': 1,
'outcome': 'success',
'target': 'build',
},
},
),
];
/// Answers one decoded request envelope with the server-shaped reply, or null
/// for a send-only request the real server does not acknowledge.
JsonMap? probeReply(JsonMap request) {
final id = request['id'];
final type = '${request['type']}';
JsonMap error(String message) => {'id': id, 'type': 'error', 'error': message};
switch (type) {
case 'subscribe':
case 'unsubscribe':
return null;
case 'ping':
return {
'id': id,
'type': 'pong',
'build': {'version': 'Search selection probe fixture'},
'time': '2026-10-20T09:00:00Z',
};
case 'list_runs':
return {'id': id, 'type': 'runs', 'runs': probeRuns(), 'usage': null};
case 'get_run':
if (request['run_id'] != 7) {
return error('Fixture run ${request['run_id']} is unavailable');
}
return {'id': id, 'type': 'run', 'run_detail': probeRunDetail()};
case 'list_pipelines':
return {'id': id, 'type': 'pipelines', 'pipelines': probePipelines()};
case 'get_pipeline':
final pipelineId = request['pipeline_id'];
if (pipelineId is! int ||
!probePipelines().any((pipeline) => pipeline['id'] == pipelineId)) {
return error('Fixture pipeline $pipelineId is unavailable');
}
final version = request['version'];
return {
'id': id,
'type': 'pipeline',
'detail': probePipelineDetail(pipelineId, version is int ? version : 0),
};
case 'search':
// The app must send exactly the browser's SearchRequest body; anything
// else is answered with a visible refusal so the capture cannot pass.
final search = request['search'];
if (search is! Map ||
search.length != 3 ||
search['query'] is! String ||
search['kind'] is! String ||
search['limit'] != 0) {
return error('Fixture refused a malformed search request: $search');
}
final query = (search['query'] as String).trim().toLowerCase();
final kind = search['kind'] as String;
final results = [
for (final entry in probeHits)
if ((kind.isEmpty || entry.hit['kind'] == kind) &&
(query.isEmpty || entry.haystack.toLowerCase().contains(query)))
entry.hit,
];
return {
'id': id,
'type': 'search_results',
'search_results': {
'query': search['query'],
'kind': kind,
'results': results,
'truncated': false,
'scanned_steps': 3,
'scanned_bytes': 2048,
'cap': 50,
'scan_bound_bytes': 1048576,
},
};
default:
return error('Fixture does not implement $type');
}
}
/// An in-process websocket channel: every frame the client sends is decoded
/// and answered asynchronously with [probeReply], as the server would over the
/// wire. `ready` completes at once so the shared client reports connected.
class _FixtureChannel implements WebSocketChannel {
_FixtureChannel();
final _incoming = StreamController<dynamic>();
late final _FixtureSink _sink = _FixtureSink(this);
@override
Stream<dynamic> get stream => _incoming.stream;
@override
WebSocketSink get sink => _sink;
@override
Future<void> get ready => Future<void>.value();
@override
String? get protocol => null;
@override
int? get closeCode => null;
@override
String? get closeReason => null;
void receive(dynamic data) {
if (data is! String) return;
final decoded = jsonDecode(data);
if (decoded is! Map<String, dynamic>) return;
final reply = probeReply(decoded);
if (reply == null) return;
Future<void>.delayed(const Duration(milliseconds: 120), () {
if (!_incoming.isClosed) _incoming.add(jsonEncode(reply));
});
}
Future<void> close() async {
if (!_incoming.isClosed) await _incoming.close();
}
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class _FixtureSink implements WebSocketSink {
_FixtureSink(this.channel);
final _FixtureChannel channel;
@override
void add(dynamic event) => channel.receive(event);
@override
void addError(Object error, [StackTrace? stackTrace]) => throw error;
@override
Future<void> addStream(Stream<dynamic> stream) async {
await for (final item in stream) {
add(item);
}
}
@override
Future<void> close([int? closeCode, String? closeReason]) => channel.close();
@override
Future<void> get done => channel._incoming.done;
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
void main() {
final params = Uri.base.queryParameters;
final cupertino = params['platform'] == 'cupertino';
useAppUrlStrategy();
runApp(
PipelinesApp(
server: ServerEndpoint.resolve(base: Uri.base, web: true),
client: PipelinesClient(channelFactory: (_) => _FixtureChannel()),
cupertino: cupertino,
),
);
}