diff --git a/app/PARITY.md b/app/PARITY.md index 6f3fccf4..d1f4667f 100644 --- a/app/PARITY.md +++ b/app/PARITY.md @@ -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` | diff --git a/app/WORK.md b/app/WORK.md index c93041aa..f3b1535b 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -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:/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/`; 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. diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index 14ecb4f6..5778dd03 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -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 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? _attentionFrames; + int _attentionEpoch = 0; + + /// The count the shell's Runs tab shows; only a changed count rebuilds it. + final ValueNotifier _attentionCount = ValueNotifier(0); @override void initState() { @@ -115,6 +134,12 @@ class _PipelinesAppState extends State _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 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( routeInformationParser: const AppRouteParser(), routerDelegate: _delegate, @@ -137,7 +173,13 @@ class _PipelinesAppState extends State @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 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 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 setState(() => _pendingRunSearch = null); } + Future _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 _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( + 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 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 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( diff --git a/app/lib/application/pipelines_destination.dart b/app/lib/application/pipelines_destination.dart index e7c492e1..5720c3e6 100644 --- a/app/lib/application/pipelines_destination.dart +++ b/app/lib/application/pipelines_destination.dart @@ -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? onRunStarted; + final ValueChanged? 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, diff --git a/app/lib/application/runs_destination.dart b/app/lib/application/runs_destination.dart index 978faad1..005b2243 100644 --- a/app/lib/application/runs_destination.dart +++ b/app/lib/application/runs_destination.dart @@ -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? onRunSelected; - final VoidCallback? onBack; + final ValueChanged? onBack; + final ValueChanged? 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, ); } diff --git a/app/lib/features/attention/notify/chat_question_notices.dart b/app/lib/features/attention/notify/chat_question_notices.dart new file mode 100644 index 00000000..fc4b3fdb --- /dev/null +++ b/app/lib/features/attention/notify/chat_question_notices.dart @@ -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 Function(String sessionId) sessionTitle; + final void Function(String sessionId) openChat; + final NotificationBridge bridge; + late final StreamSubscription _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.from(form))); + } + + Future _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()); + } +} diff --git a/app/lib/features/attention/notify/notification_models.dart b/app/lib/features/attention/notify/notification_models.dart index f817c92e..a3d5af33 100644 --- a/app/lib/features/attention/notify/notification_models.dart +++ b/app/lib/features/attention/notify/notification_models.dart @@ -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; diff --git a/app/lib/features/attention/ui/needs_you_runs_heading.dart b/app/lib/features/attention/ui/needs_you_runs_heading.dart index ddd9966b..7e856574 100644 --- a/app/lib/features/attention/ui/needs_you_runs_heading.dart +++ b/app/lib/features/attention/ui/needs_you_runs_heading.dart @@ -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 createState() => _NeedsYouRunsHeadingState(); } class _NeedsYouRunsHeadingState extends State { - 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? _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 { @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 { @override void dispose() { unawaited(_frames?.cancel()); - _attention.dispose(); + if (_ownsController) { + _attention.dispose(); + } else { + _attention.removeListener(_publish); + } super.dispose(); } diff --git a/app/lib/features/chat/conversation/chat_composer_bar.dart b/app/lib/features/chat/conversation/chat_composer_bar.dart index ec871e00..a103aecb 100644 --- a/app/lib/features/chat/conversation/chat_composer_bar.dart +++ b/app/lib/features/chat/conversation/chat_composer_bar.dart @@ -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 createState() => _ChatComposerBarState(); } @@ -99,11 +106,15 @@ class _ChatComposerBarState extends State { 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 { 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 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 { 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 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 { @override void dispose() { + _stopListeningForPaste(); widget.composer.removeListener(_syncDraft); _text.dispose(); _focus.dispose(); diff --git a/app/lib/features/chat/domain/chat_clipboard_paste.dart b/app/lib/features/chat/domain/chat_clipboard_paste.dart new file mode 100644 index 00000000..3aa60707 --- /dev/null +++ b/app/lib/features/chat/domain/chat_clipboard_paste.dart @@ -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 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; diff --git a/app/lib/features/chat/domain/chat_clipboard_paste_stub.dart b/app/lib/features/chat/domain/chat_clipboard_paste_stub.dart new file mode 100644 index 00000000..3b390d00 --- /dev/null +++ b/app/lib/features/chat/domain/chat_clipboard_paste_stub.dart @@ -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); diff --git a/app/lib/features/chat/domain/chat_clipboard_paste_web.dart b/app/lib/features/chat/domain/chat_clipboard_paste_web.dart new file mode 100644 index 00000000..599c638a --- /dev/null +++ b/app/lib/features/chat/domain/chat_clipboard_paste_web.dart @@ -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 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('$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 _readFiles( + List<_ClipboardFile> files, + ChatPasteFiles onFiles, + ChatPasteFailed onError, + int Function() nextSequence, +) async { + final pasted = []; + final failures = []; + 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); + } +} diff --git a/app/lib/features/pipelines/run_pipeline_intent.dart b/app/lib/features/pipelines/run_pipeline_intent.dart index 5c1ca13a..ce66548d 100644 --- a/app/lib/features/pipelines/run_pipeline_intent.dart +++ b/app/lib/features/pipelines/run_pipeline_intent.dart @@ -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. diff --git a/app/lib/features/pipelines/screen.dart b/app/lib/features/pipelines/screen.dart index c7de8828..590281c5 100644 --- a/app/lib/features/pipelines/screen.dart +++ b/app/lib/features/pipelines/screen.dart @@ -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? onRunStarted; + final ValueChanged? onViewPipelineRuns; /// The pipeline a deep link names, opened after the list read starts. final int? initialPipelineId; @@ -170,6 +172,7 @@ class _PipelinesScreenState extends State { 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 { gateway: widget.gateway, showBack: false, onRunStarted: widget.onRunStarted, + onViewPipelineRuns: widget.onViewPipelineRuns, stageKey: stageKey, stagePipelineId: widget.initialPipelineId, stageVersion: widget.initialVersion, diff --git a/app/lib/features/pipelines/ui/run_pipeline_action.dart b/app/lib/features/pipelines/ui/run_pipeline_action.dart index 668cd6c5..7a58cde5 100644 --- a/app/lib/features/pipelines/ui/run_pipeline_action.dart +++ b/app/lib/features/pipelines/ui/run_pipeline_action.dart @@ -51,6 +51,7 @@ class _RunPipelineActionState extends State { 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 { workspace: intent.workspace, requestKey: intent.requestKey, notifyMode: intent.notifyMode.wireValue, + outputFormat: intent.outputFormat.wireValue, ); final accepted = _accept(run); if (accepted is RunPipelineAccepted) return accepted; diff --git a/app/lib/features/pipelines/ui/run_pipeline_dialog.dart b/app/lib/features/pipelines/ui/run_pipeline_dialog.dart index ec360f20..5bb650d0 100644 --- a/app/lib/features/pipelines/ui/run_pipeline_dialog.dart +++ b/app/lib/features/pipelines/ui/run_pipeline_dialog.dart @@ -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 showRunPipelineDialog({ required BuildContext context, required PipelineDetail detail, + required ApiGateway gateway, required RunPipelineIntent? pending, required Future Function(RunPipelineIntent intent) onSubmit, @@ -24,6 +26,7 @@ Future showRunPipelineDialog({ }) { final dialog = _RunPipelineDialog( detail: detail, + gateway: gateway, pending: pending, cupertino: usesCupertinoHost(context), onSubmit: onSubmit, @@ -46,6 +49,7 @@ Future 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 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 _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 _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().toList() + : []; + 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; + } } diff --git a/app/lib/features/pipelines/ui/run_pipeline_fields.dart b/app/lib/features/pipelines/ui/run_pipeline_fields.dart index c863ea54..bd77c202 100644 --- a/app/lib/features/pipelines/ui/run_pipeline_fields.dart +++ b/app/lib/features/pipelines/ui/run_pipeline_fields.dart @@ -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 directories; + final bool cupertino; + final ValueChanged onChooseDirectory; final RunNotifyMode notifyMode; + final RunOutputFormat outputFormat; final bool locked; final ValueChanged onNotifyChanged; + final ValueChanged 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( + 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 _chooseCupertinoDirectory(BuildContext context) async { + final chosen = await showCupertinoModalPopup( + 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( + 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 _chooseOutputFormat(BuildContext context) async { + final chosen = await showCupertinoModalPopup( + 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) { diff --git a/app/lib/features/pipelines/ui/run_pipeline_wording.dart b/app/lib/features/pipelines/ui/run_pipeline_wording.dart index 3cda4a28..531fba87 100644 --- a/app/lib/features/pipelines/ui/run_pipeline_wording.dart +++ b/app/lib/features/pipelines/ui/run_pipeline_wording.dart @@ -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( + '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('run-pipeline-action'); const runPipelinePromptKey = ValueKey('run-pipeline-prompt'); const runPipelineWorkspaceKey = ValueKey('run-pipeline-workspace'); const runPipelineNotifyKey = ValueKey('run-pipeline-notify'); +const runPipelineOutputFormatKey = ValueKey('run-pipeline-output-format'); const runPipelineCancelKey = ValueKey('run-pipeline-cancel'); const runPipelineConfirmKey = ValueKey('run-pipeline-confirm'); const runPipelineErrorKey = ValueKey('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.'); diff --git a/app/lib/features/pipelines/widgets/pipeline_detail_panel.dart b/app/lib/features/pipelines/widgets/pipeline_detail_panel.dart index 69014cad..351cea2c 100644 --- a/app/lib/features/pipelines/widgets/pipeline_detail_panel.dart +++ b/app/lib/features/pipelines/widgets/pipeline_detail_panel.dart @@ -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? onRunStarted; + final ValueChanged? 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 { 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'), + ), + ), + ), + ), ], ), ); diff --git a/app/lib/features/runs/domain/run_models.dart b/app/lib/features/runs/domain/run_models.dart index 0f0d4941..ddd1cdd7 100644 --- a/app/lib/features/runs/domain/run_models.dart +++ b/app/lib/features/runs/domain/run_models.dart @@ -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 runs})> groupRunsByDay( + List sortedRuns, + DateTime today, +) { + final groups = <({String label, List 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: [])); + } + groups.last.runs.add(run); + } + return groups; +} + ({String label, String? pipeline}) runIdentity(dynamic title, dynamic name) { final stored = '${title ?? ''}'.trim(); return ( diff --git a/app/lib/features/runs/screen.dart b/app/lib/features/runs/screen.dart index 3e8403e2..33ee84da 100644 --- a/app/lib/features/runs/screen.dart +++ b/app/lib/features/runs/screen.dart @@ -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? onRunSelected; - final VoidCallback? onBack; + final ValueChanged? onBack; + final ValueChanged? 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 createState() => _RunsScreenState(); } @@ -77,6 +86,8 @@ class RunsScreen extends StatefulWidget { class _RunsScreenState extends State { 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 { 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 { 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 { 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 { 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 { attentionStore: widget.attentionStore, attentionNow: widget.attentionNow, notifications: widget.notifications, + attention: widget.attention, ), ), ), diff --git a/app/lib/features/runs/ui/run_detail_tabs.dart b/app/lib/features/runs/ui/run_detail_tabs.dart index c7a1627e..1b2f2f70 100644 --- a/app/lib/features/runs/ui/run_detail_tabs.dart +++ b/app/lib/features/runs/ui/run_detail_tabs.dart @@ -209,7 +209,10 @@ class _RunDetailTabsState extends State { 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; diff --git a/app/lib/features/runs/ui/runs_controller.dart b/app/lib/features/runs/ui/runs_controller.dart index 60438c34..745dd8cb 100644 --- a/app/lib/features/runs/ui/runs_controller.dart +++ b/app/lib/features/runs/ui/runs_controller.dart @@ -177,6 +177,11 @@ class RunsController extends ChangeNotifier { notifyListeners(); } + void setTimeRange(String value) { + timeRange = value; + notifyListeners(); + } + void setSort(String value) { sort = value; notifyListeners(); diff --git a/app/lib/features/runs/ui/runs_filters.dart b/app/lib/features/runs/ui/runs_filters.dart index 7e756402..e6f89d30 100644 --- a/app/lib/features/runs/ui/runs_filters.dart +++ b/app/lib/features/runs/ui/runs_filters.dart @@ -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> _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 = {}; + final ids = {}; + 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 diff --git a/app/lib/features/runs/ui/runs_list.dart b/app/lib/features/runs/ui/runs_list.dart index 4c9bd7c1..3eafc210 100644 --- a/app/lib/features/runs/ui/runs_list.dart +++ b/app/lib/features/runs/ui/runs_list.dart @@ -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, diff --git a/app/lib/shell/adaptive_shell.dart b/app/lib/shell/adaptive_shell.dart index 007c6b9c..48c38b42 100644 --- a/app/lib/shell/adaptive_shell.dart +++ b/app/lib/shell/adaptive_shell.dart @@ -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 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 createState() => _AdaptiveShellState(); } @@ -65,6 +71,17 @@ class _AdaptiveShellState extends State { List _items(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 { _CupertinoSidebar( selected: _selected, onSelected: _select, + attentionCount: widget.attentionCount, ), Expanded(child: _destinationStack(contents, index)), ], @@ -117,11 +135,12 @@ class _AdaptiveShellState extends State { 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 { 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 { 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 { /// 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 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( diff --git a/app/lib/shell/attention_badge.dart b/app/lib/shell/attention_badge.dart new file mode 100644 index 00000000..6cf21f45 --- /dev/null +++ b/app/lib/shell/attention_badge.dart @@ -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), + ), + ), + ), + ], + ); + } +} diff --git a/app/notes/composer-paste.md b/app/notes/composer-paste.md new file mode 100644 index 00000000..a38d55b6 --- /dev/null +++ b/app/notes/composer-paste.md @@ -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-.`, `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. diff --git a/app/notes/next-session.md b/app/notes/next-session.md new file mode 100644 index 00000000..b36701d2 --- /dev/null +++ b/app/notes/next-session.md @@ -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- on branch flutter/): +- 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 --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-- 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. +--- diff --git a/app/notes/search-selection-probe.md b/app/notes/search-selection-probe.md new file mode 100644 index 00000000..2d219e84 --- /dev/null +++ b/app/notes/search-selection-probe.md @@ -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 `