Merge branch 'main' into worktree-agent-a35ac03e196ffae50

# Conflicts:
#	app/lib/features/runs/ui/run_detail_content.dart
#	app/lib/features/runs/ui/run_list_row.dart
#	app/tool/search_selection_probe_entry.dart
This commit is contained in:
2026-11-04 17:44:29 +00:00
296 changed files with 17727 additions and 3360 deletions
@@ -0,0 +1,50 @@
/// What following one link inside a recorded HTML document does.
enum ArtifactHtmlLinkAction {
/// A place in the same document (`#section`): the view scrolls to it.
inDocument,
/// An `http`, `https` or `mailto` address: it opens outside the artifact
/// (a new browser tab on the web, the system's handler on a phone), never
/// inside the document's view.
external,
/// Anything else (`javascript:`, `file:`, `data:`, a relative path the
/// document has no base for): the link stays inert.
blocked,
}
const _externalSchemes = {'http', 'https', 'mailto'};
/// The documents the views load the recorded HTML as: a web view's
/// `about:blank` and an iframe's `about:srcdoc`.
const _documentUrls = {'about:blank', 'about:srcdoc'};
/// Decides what a link in a recorded HTML document does, from the raw `href`
/// (the web view rewrites anchors before showing the document) or the url a
/// mobile web view resolved it to.
///
/// The document is loaded from a string, so it has no address of its own: a
/// relative link cannot resolve to the artifact's neighbours and stays inert
/// rather than reaching the app's own origin.
ArtifactHtmlLinkAction artifactHtmlLinkAction(String href) {
final link = href.trim();
if (link.isEmpty) return ArtifactHtmlLinkAction.blocked;
if (link.startsWith('#')) return ArtifactHtmlLinkAction.inDocument;
final uri = Uri.tryParse(link);
if (uri == null || !uri.hasScheme) return ArtifactHtmlLinkAction.blocked;
final scheme = uri.scheme.toLowerCase();
if (_externalSchemes.contains(scheme)) {
// `http:foo` with no host is not an address anyone can open.
if (scheme != 'mailto' && uri.host.isEmpty) {
return ArtifactHtmlLinkAction.blocked;
}
return ArtifactHtmlLinkAction.external;
}
if (scheme == 'about') {
final document = link.split('#').first.toLowerCase();
if (_documentUrls.contains(document)) {
return ArtifactHtmlLinkAction.inDocument;
}
}
return ArtifactHtmlLinkAction.blocked;
}
@@ -0,0 +1,116 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
/// Open, Copy and the file actions float over the top of the content: shown
/// when the page opens and whenever the content is touched, hidden again after
/// a few seconds without use, so nothing needs scrolling to reach them.
class ArtifactControlsOverlay extends StatefulWidget {
const ArtifactControlsOverlay({
super.key,
required this.controls,
required this.child,
this.hideAfter = const Duration(seconds: 3),
});
final List<Widget> controls;
final Widget child;
final Duration hideAfter;
@override
State<ArtifactControlsOverlay> createState() =>
_ArtifactControlsOverlayState();
}
class _ArtifactControlsOverlayState extends State<ArtifactControlsOverlay> {
bool _shown = true;
Timer? _hide;
@override
void initState() {
super.initState();
_schedule();
}
@override
void dispose() {
_hide?.cancel();
super.dispose();
}
void _schedule() {
_hide?.cancel();
_hide = Timer(widget.hideAfter, () {
if (mounted) setState(() => _shown = false);
});
}
void _show() {
if (!_shown) setState(() => _shown = true);
_schedule();
}
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
final surface = cupertino
? CupertinoColors.systemBackground
.resolveFrom(context)
.withValues(alpha: 0.92)
: Theme.of(
context,
).colorScheme.surfaceContainerHigh.withValues(alpha: 0.94);
return Stack(
children: [
// Any touch on the content brings the controls back.
Positioned.fill(
child: Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: (_) => _show(),
child: widget.child,
),
),
Positioned(
left: 8,
right: 8,
top: 8,
child: IgnorePointer(
ignoring: !_shown,
child: AnimatedOpacity(
key: const Key('artifact-viewer-controls'),
opacity: _shown ? 1 : 0,
duration: const Duration(milliseconds: 200),
child: Listener(
// Using a control keeps the bar up.
onPointerDown: (_) => _schedule(),
child: DecoratedBox(
decoration: BoxDecoration(
color: surface,
borderRadius: BorderRadius.circular(12),
boxShadow: const [
BoxShadow(color: Color(0x22000000), blurRadius: 6),
],
),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 4,
vertical: 2,
),
child: Wrap(
alignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
children: widget.controls,
),
),
),
),
),
),
),
],
);
}
}
@@ -0,0 +1,116 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/segmented_bar_overflow.dart';
import '../actions/artifact_file_actions.dart';
/// Marks a subtree as the artifact viewer's full-screen view, where an HTML
/// document takes every gesture over it (scroll, pan, pinch) instead of
/// sharing them with the viewer's page swipe, and follows [htmlZoom].
class ArtifactFullscreenScope extends InheritedWidget {
const ArtifactFullscreenScope({
super.key,
required this.htmlZoom,
required super.child,
});
/// The HTML document's zoom factor (1 is the document's own size), set by
/// [ArtifactHtmlZoomActions].
final ValueListenable<double> htmlZoom;
static ArtifactFullscreenScope? maybeOf(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<ArtifactFullscreenScope>();
@override
bool updateShouldNotify(ArtifactFullscreenScope oldWidget) =>
htmlZoom != oldWidget.htmlZoom;
}
/// The full-screen view's route, pushed on the root navigator so it covers
/// the shell's bars and list pane. A full-screen dialog route: its bar shows
/// the platform's Close, and the system back gesture leaves it.
Route<void> artifactFullscreenRoute({
required bool cupertino,
required WidgetBuilder builder,
}) => cupertino
? CupertinoPageRoute<void>(fullscreenDialog: true, builder: builder)
: MaterialPageRoute<void>(fullscreenDialog: true, builder: builder);
/// The zoom factors Zoom in and Zoom out step through.
const List<double> artifactHtmlZoomSteps = [
0.5, 0.67, 0.8, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4, //
];
/// The next zoom step from [current] in [direction] (+1 in, -1 out), held at
/// both ends.
double artifactHtmlZoomStep(double current, int direction) {
if (direction > 0) {
return artifactHtmlZoomSteps.firstWhere(
(step) => step > current + 0.001,
orElse: () => artifactHtmlZoomSteps.last,
);
}
return artifactHtmlZoomSteps.lastWhere(
(step) => step < current - 0.001,
orElse: () => artifactHtmlZoomSteps.first,
);
}
const artifactZoomOutKey = ValueKey<String>('artifact-zoom-out');
const artifactZoomResetKey = ValueKey<String>('artifact-zoom-reset');
const artifactZoomInKey = ValueKey<String>('artifact-zoom-in');
/// Zoom out, actual size and zoom in for an HTML document, as top-bar
/// actions (a narrow bar moves them into its More menu). Used where the
/// document cannot be pinched (the web's sandboxed frame): the frame keeps
/// scrolling the live document at the chosen size.
List<Widget> artifactHtmlZoomActions(ValueNotifier<double> zoom) {
void step(int direction) =>
zoom.value = artifactHtmlZoomStep(zoom.value, direction);
final percent = '${(zoom.value * 100).round()}%';
Widget action(
Key key,
String label,
IconData icon,
IconData cupertinoIcon,
VoidCallback? onPressed,
) => SegmentedOverflowAction(
key: key,
overflowEntry: SegmentedOverflowEntry(
label: label,
icon: icon,
onPressed: onPressed,
),
child: ArtifactIconAction(
label: label,
icon: icon,
cupertinoIcon: cupertinoIcon,
onPressed: onPressed,
),
);
final value = zoom.value;
return [
action(
artifactZoomOutKey,
'Zoom out',
Icons.zoom_out,
CupertinoIcons.zoom_out,
value > artifactHtmlZoomSteps.first + 0.001 ? () => step(-1) : null,
),
action(
artifactZoomResetKey,
'Actual size ($percent)',
Icons.restart_alt,
CupertinoIcons.arrow_counterclockwise,
(value - 1).abs() > 0.001 ? () => zoom.value = 1 : null,
),
action(
artifactZoomInKey,
'Zoom in',
Icons.zoom_in,
CupertinoIcons.zoom_in,
value < artifactHtmlZoomSteps.last - 0.001 ? () => step(1) : null,
),
];
}
@@ -0,0 +1,58 @@
import 'package:flutter/widgets.dart';
import '../../../ui/adaptive/host.dart';
import 'artifact_fullscreen.dart';
/// Lets a viewer page open its own content as the full-screen view.
///
/// The full-screen route lives on the root navigator, outside the page's
/// subtree, yet draws from the page's state: [buildFrame] builds either
/// presentation, and every [setState] redraws the full-screen route too, so
/// paging, loading and status messages show in both.
mixin ArtifactFullscreenHost<T extends StatefulWidget> on State<T> {
final ValueNotifier<int> _revision = ValueNotifier<int>(0);
/// The full-screen view's HTML zoom; each full-screen visit starts at 1.
final ValueNotifier<double> htmlZoom = ValueNotifier<double>(1);
Route<void>? _fullscreen;
/// The page's scaffold, inline or as the full-screen view.
Widget buildFrame(BuildContext context, {required bool fullscreen});
@override
void setState(VoidCallback fn) {
super.setState(fn);
_revision.value++;
}
@override
void dispose() {
// The full-screen route closes with the page, once the tree unlocks.
final route = _fullscreen;
if (route != null) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (route.isActive) route.navigator?.removeRoute(route);
});
}
super.dispose();
}
/// Opens the full-screen view; it returns when the view closes.
Future<void> enterFullscreen() async {
if (_fullscreen != null) return;
htmlZoom.value = 1;
final route = artifactFullscreenRoute(
cupertino: usesCupertinoHost(context),
builder: (_) => ArtifactFullscreenScope(
htmlZoom: htmlZoom,
child: ListenableBuilder(
listenable: Listenable.merge([_revision, htmlZoom]),
builder: (context, _) => buildFrame(context, fullscreen: true),
),
),
);
_fullscreen = route;
await Navigator.of(context, rootNavigator: true).push(route);
_fullscreen = null;
}
}
@@ -370,7 +370,7 @@ class _ArtifactGalleryPageState extends State<ArtifactGalleryPage> {
CupertinoDialogAction(
isDefaultAction: true,
onPressed: () => _open(resolved, dialogContext),
child: const Text('Open'),
child: const Text('Open in browser'),
),
],
),
@@ -394,7 +394,7 @@ class _ArtifactGalleryPageState extends State<ArtifactGalleryPage> {
if (resolved != null)
TextButton(
onPressed: () => _open(resolved, dialogContext),
child: const Text('Open'),
child: const Text('Open in browser'),
),
],
),
@@ -0,0 +1,52 @@
import 'dart:js_interop';
import 'package:web/web.dart' as web;
import '../domain/artifact_html_links.dart';
/// The iframe's sandbox: no script, no same-origin access, no forms and no
/// navigation of the app, but a link may open a new tab that is itself
/// unsandboxed (an ordinary website, as if typed into the address bar).
const String artifactHtmlSandbox =
'allow-popups allow-popups-to-escape-sandbox';
/// [html] with every link's behaviour fixed before the frame shows it
/// ([artifactHtmlLinkAction]): a `#place` stays in the frame and scrolls
/// there, an http(s)/mailto address opens a new tab (no opener, no
/// referrer), and every other link loses its `href`, so it is inert text.
/// A document's own `<base>` is dropped: the frame is not at the artifact's
/// address, and a relative link must not reach the app's origin.
///
/// The browser's `DOMParser` builds an inert document: nothing in it runs or
/// loads while it is rewritten.
String artifactHtmlWithInertLinks(String html) {
final doc = web.DOMParser().parseFromString(html.toJS, 'text/html');
final bases = doc.querySelectorAll('base');
for (var i = bases.length - 1; i >= 0; i--) {
(bases.item(i) as web.Element?)?.remove();
}
final links = doc.querySelectorAll('a[href], area[href]');
for (var i = 0; i < links.length; i++) {
final link = links.item(i) as web.Element?;
if (link == null) continue;
final href = link.getAttribute('href') ?? '';
switch (artifactHtmlLinkAction(href)) {
case ArtifactHtmlLinkAction.inDocument:
// A srcdoc document's base is the app page, so a bare `#place` would
// navigate the frame to the app; the document's own address keeps it
// a same-document jump.
final hash = href.indexOf('#');
final place = hash < 0 ? '' : href.substring(hash);
link.setAttribute('href', 'about:srcdoc$place');
link.setAttribute('target', '_self');
case ArtifactHtmlLinkAction.external:
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener noreferrer');
case ArtifactHtmlLinkAction.blocked:
link.removeAttribute('href');
link.removeAttribute('target');
}
}
final doctype = doc.doctype == null ? '' : '<!DOCTYPE html>';
return '$doctype${doc.documentElement?.outerHTML ?? ''}';
}
@@ -1,5 +1,6 @@
import 'package:flutter/widgets.dart';
import 'artifact_fullscreen.dart';
import 'artifact_html_view_native.dart'
if (dart.library.js_interop) 'artifact_html_view_web.dart'
as impl;
@@ -9,6 +10,12 @@ import 'artifact_html_view_native.dart'
typedef ArtifactHtmlBuilder =
Widget Function(BuildContext context, String html);
/// Whether the full-screen view offers zoom buttons for HTML: on the web the
/// sandboxed frame cannot be pinched (the page's viewport is not scalable and
/// a frame's document has no pinch zoom of its own), so the buttons scale the
/// live frame. The mobile web views pinch natively and offer none.
const bool artifactHtmlZoomButtons = impl.inertHtmlZoomButtons;
/// Renders a recorded HTML document inertly: on the web in an iframe whose
/// empty `sandbox` blocks scripts, forms, popups and navigation; on Android and
/// iOS in a web view with JavaScript disabled and navigation refused. The
@@ -18,13 +25,22 @@ typedef ArtifactHtmlBuilder =
/// the web the iframe is a platform view that takes every click over its
/// area, even where a bar is drawn on top, which left the viewer's actions
/// and pager unclickable.
///
/// Inside an [ArtifactFullscreenScope] the document takes every gesture over
/// it and follows the scope's zoom; inline it shares them with the viewer's
/// page swipe.
Widget defaultArtifactHtml(BuildContext context, String html) {
final padding = MediaQuery.paddingOf(context);
final fullscreen = ArtifactFullscreenScope.maybeOf(context);
return Padding(
padding: EdgeInsets.only(top: padding.top, bottom: padding.bottom),
child: SizedBox.expand(
key: const Key('artifact-html-preview'),
child: impl.InertHtmlView(html: html),
child: impl.InertHtmlView(
html: html,
interactive: fullscreen != null,
zoom: fullscreen?.htmlZoom,
),
),
);
}
@@ -1,36 +1,105 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/widgets.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../domain/artifact_html_links.dart';
import 'artifact_external_open.dart';
/// The mobile web views pinch-zoom natively (Android's built-in zoom, which
/// the plugin turns on with its display controls hidden; WKWebView's own), so
/// the full-screen view needs no zoom buttons.
const bool inertHtmlZoomButtons = false;
/// A web view with JavaScript disabled that refuses every navigation after the
/// recorded document itself loads.
///
/// A platform view only receives the pointers of gestures that its
/// [WebViewWidget.gestureRecognizers] win in Flutter's gesture arena. With
/// none it got a drag only after every other recognizer gave up, which the
/// viewer's page swipe never does before the finger lifts: the document never
/// scrolled or pinched. Inline it claims vertical drags (scrolling the
/// document) and leaves horizontal ones to the page swipe; [interactive] (the
/// full-screen view) claims every pointer at once, so scroll, pan and pinch
/// all reach the document.
class InertHtmlView extends StatefulWidget {
const InertHtmlView({super.key, required this.html});
const InertHtmlView({
super.key,
required this.html,
this.interactive = false,
this.zoom,
this.openExternal = openArtifactExternally,
});
final String html;
/// Opens a link's http(s)/mailto address outside the artifact.
final ArtifactExternalOpen openExternal;
final bool interactive;
/// Unused: the mobile web views pinch instead ([inertHtmlZoomButtons]).
final ValueListenable<double>? zoom;
@override
State<InertHtmlView> createState() => _InertHtmlViewState();
}
final _inlineGestures = <Factory<OneSequenceGestureRecognizer>>{
Factory<VerticalDragGestureRecognizer>(VerticalDragGestureRecognizer.new),
};
final _allGestures = <Factory<OneSequenceGestureRecognizer>>{
Factory<EagerGestureRecognizer>(EagerGestureRecognizer.new),
};
class _InertHtmlViewState extends State<InertHtmlView> {
/// Until the recorded document finishes loading, the view may load it (an
/// `about:` or `data:` document); afterwards only links are followed.
bool _loaded = false;
late final WebViewController _controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.disabled)
..enableZoom(true)
..setNavigationDelegate(
NavigationDelegate(
onNavigationRequest: (request) =>
request.url.startsWith('about:') || request.url.startsWith('data:')
? NavigationDecision.navigate
: NavigationDecision.prevent,
onPageFinished: (_) => _loaded = true,
onNavigationRequest: _decide,
),
)
..loadHtmlString(widget.html);
@override
void didUpdateWidget(covariant InertHtmlView oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.html != widget.html) _controller.loadHtmlString(widget.html);
/// Links: a place in the document scrolls there; an http(s)/mailto address
/// opens in the system's handler, never inside this view; anything else
/// (scripts, files, other schemes, relative paths) stays inert.
NavigationDecision _decide(NavigationRequest request) {
if (!_loaded &&
(request.url.startsWith('about:') || request.url.startsWith('data:'))) {
return NavigationDecision.navigate;
}
switch (artifactHtmlLinkAction(request.url)) {
case ArtifactHtmlLinkAction.inDocument:
return NavigationDecision.navigate;
case ArtifactHtmlLinkAction.external:
final uri = Uri.tryParse(request.url.trim());
if (uri != null) widget.openExternal(uri);
return NavigationDecision.prevent;
case ArtifactHtmlLinkAction.blocked:
return NavigationDecision.prevent;
}
}
@override
Widget build(BuildContext context) => WebViewWidget(controller: _controller);
void didUpdateWidget(covariant InertHtmlView oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.html != widget.html) {
_loaded = false;
_controller.loadHtmlString(widget.html);
}
}
@override
Widget build(BuildContext context) => WebViewWidget(
controller: _controller,
gestureRecognizers: widget.interactive ? _allGestures : _inlineGestures,
);
}
@@ -1,28 +1,109 @@
import 'dart:js_interop';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:web/web.dart' as web;
/// A sandboxed iframe: the empty `sandbox` attribute applies every
/// restriction, so the document cannot run script or leave the frame.
class InertHtmlView extends StatelessWidget {
const InertHtmlView({super.key, required this.html});
import 'artifact_html_links_web.dart';
/// The frame's document cannot be pinched: a pinch over it is a page zoom,
/// which the app's viewport (`user-scalable=no`) refuses, and the sandbox
/// keeps the document out of the app's reach. The full-screen view zooms
/// the live frame with buttons instead.
const bool inertHtmlZoomButtons = true;
/// A sandboxed iframe ([artifactHtmlSandbox]): the document cannot run
/// script, reach the app's origin, submit forms or navigate the app. Its
/// links are fixed first ([artifactHtmlWithInertLinks]): a `#place` scrolls
/// the frame, a web or mail address opens a new tab, anything else is inert.
///
/// The frame scrolls its document itself, by wheel, trackpad and touch.
/// [zoom] scales the live frame as a browser's page zoom would: the frame is
/// laid out 1/zoom as wide and tall and scaled back to fill its box, so the
/// document reflows and still scrolls inside it. In the app, Chrome returns
/// the frame's document to its top when a zoom step resizes it.
///
/// While another route covers this one (a menu, a sheet) the frame stops
/// taking pointers: a platform view takes every click over its area, even
/// where Flutter draws that menu on top.
class InertHtmlView extends StatefulWidget {
const InertHtmlView({
super.key,
required this.html,
this.interactive = false,
this.zoom,
});
final String html;
/// The full-screen view's frame. Pointers already reach the frame directly
/// on the web, inline as in full screen.
final bool interactive;
final ValueListenable<double>? zoom;
@override
Widget build(BuildContext context) => HtmlElementView.fromTagName(
key: ValueKey<int>(html.hashCode),
tagName: 'iframe',
onElementCreated: (element) {
final frame = element as web.HTMLIFrameElement;
frame.setAttribute('sandbox', '');
frame.srcdoc = html.toJS;
frame.style
..border = 'none'
..width = '100%'
..height = '100%'
..backgroundColor = 'white';
},
);
State<InertHtmlView> createState() => _InertHtmlViewState();
}
class _InertHtmlViewState extends State<InertHtmlView> {
web.HTMLIFrameElement? _frame;
bool _covered = false;
@override
void initState() {
super.initState();
widget.zoom?.addListener(_style);
}
@override
void didUpdateWidget(covariant InertHtmlView oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.zoom != widget.zoom) {
oldWidget.zoom?.removeListener(_style);
widget.zoom?.addListener(_style);
_style();
}
}
@override
void dispose() {
widget.zoom?.removeListener(_style);
super.dispose();
}
void _style() {
final frame = _frame;
if (frame == null) return;
final zoom = widget.zoom?.value ?? 1;
final size = '${100 / zoom}%';
frame.style
..width = size
..height = size
..transformOrigin = '0 0'
..transform = zoom == 1 ? '' : 'scale($zoom)'
..pointerEvents = _covered ? 'none' : '';
}
@override
Widget build(BuildContext context) {
final covered = !(ModalRoute.of(context)?.isCurrent ?? true);
if (covered != _covered) {
_covered = covered;
_style();
}
return HtmlElementView.fromTagName(
key: ValueKey<int>(widget.html.hashCode),
tagName: 'iframe',
onElementCreated: (element) {
final frame = element as web.HTMLIFrameElement;
frame.setAttribute('sandbox', artifactHtmlSandbox);
frame.srcdoc = artifactHtmlWithInertLinks(widget.html).toJS;
frame.style
..border = 'none'
..backgroundColor = 'white';
_frame = frame;
_style();
},
);
}
}
@@ -0,0 +1,158 @@
import 'dart:math' as math;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/glass_bar.dart';
import '../../../ui/adaptive/host.dart';
import '../../../ui/navigation/chevron_pager.dart';
import '../actions/artifact_file_actions.dart';
import '../actions/artifact_file_bridge.dart';
import '../domain/artifact_url.dart';
import '../domain/gallery_navigation.dart';
import 'artifact_viewer_fetch.dart';
const artifactPreviousKey = ValueKey<String>('artifact-previous');
const artifactNextKey = ValueKey<String>('artifact-next');
const artifactFullscreenKey = ValueKey<String>('artifact-fullscreen');
/// The viewer's bottom controls: file transfer, Open, Copy link, Full screen
/// and the pager, in one glass bar above the bottom safe area.
///
/// The inline viewer and the full-screen view draw this same bar; in full
/// screen the Full screen control reads Exit full screen and leaves it.
class ArtifactViewerBar extends StatelessWidget {
const ArtifactViewerBar({
super.key,
required this.page,
required this.resolved,
required this.index,
required this.count,
required this.fetch,
required this.fileBridge,
required this.onOpen,
required this.onCopy,
required this.onPrevious,
required this.onNext,
this.fullscreen = false,
this.onFullscreen,
});
final PagedArtifact page;
final ResolvedArtifactUrl? resolved;
final int index;
final int count;
final ArtifactFetch fetch;
final ArtifactFileBridge fileBridge;
final VoidCallback onOpen;
final VoidCallback onCopy;
final VoidCallback onPrevious;
final VoidCallback onNext;
/// Whether this bar is the full-screen view's.
final bool fullscreen;
/// Enters (inline) or leaves (in full screen) the full-screen view; absent,
/// the control is not drawn.
final VoidCallback? onFullscreen;
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
final actions = _actions(resolved, onFullscreen);
final pagerMin = count > 1
? 2 * GlassBarMetrics.controlExtent(cupertino)
: 0.0;
final pager = ChevronPager(
index: index,
count: count,
previousLabel: 'Previous artifact',
nextLabel: 'Next artifact',
previousKey: artifactPreviousKey,
nextKey: artifactNextKey,
onPrevious: pagedIndex(index, -1, count) != index ? onPrevious : null,
onNext: pagedIndex(index, 1, count) != index ? onNext : null,
);
return SafeArea(
// The SafeArea already lifts the bar by the inherited bottom inset (a
// shell bar below the pane); adding that clearance again floated the
// bar far above it.
top: false,
minimum: const EdgeInsets.all(8),
// Without a pager the bar is as wide as its actions, so its last
// control keeps the same gap from the bar's end as the first.
child: Align(
alignment: AlignmentDirectional.centerStart,
heightFactor: 1,
child: GlassControlBar(
cupertino: cupertino,
child: LayoutBuilder(
builder: (context, constraints) => Row(
key: const Key('artifact-viewer-actions'),
mainAxisSize: count > 1 ? MainAxisSize.max : MainAxisSize.min,
children: [
// On a narrow window or at large text the actions scroll
// sideways, so the chevrons beside them stay whole.
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: math.max(0, constraints.maxWidth - pagerMin),
),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
mainAxisSize: MainAxisSize.min,
children: actions,
),
),
),
if (count > 1) Expanded(child: pager),
],
),
),
),
),
);
}
List<Widget> _actions(ResolvedArtifactUrl? resolved, VoidCallback? toggle) =>
[
if (resolved != null && !resolved.external)
ArtifactFileActions(
key: ValueKey<String>(
'viewer-files-${page.group.stageKey}\u0000'
'${page.group.visit}\u0000${page.artifact.url}',
),
artifact: page.artifact,
resolved: resolved,
fetch: fetch,
bridge: fileBridge,
compact: true,
),
if (resolved != null) ...[
ArtifactIconAction(
key: const Key('artifact-open'),
label: 'Open in browser',
icon: Icons.open_in_new,
cupertinoIcon: CupertinoIcons.arrow_up_right_square,
onPressed: onOpen,
),
ArtifactIconAction(
key: const Key('artifact-copy-link'),
label: 'Copy link',
icon: Icons.link,
cupertinoIcon: CupertinoIcons.link,
onPressed: onCopy,
),
],
if (toggle != null)
ArtifactIconAction(
key: artifactFullscreenKey,
label: fullscreen ? 'Exit full screen' : 'Full screen',
icon: fullscreen ? Icons.fullscreen_exit : Icons.fullscreen,
cupertinoIcon: fullscreen
? CupertinoIcons.fullscreen_exit
: CupertinoIcons.fullscreen,
onPressed: toggle,
),
];
}
@@ -1,5 +1,3 @@
import 'dart:async';
import '../../../ui/navigation/chevron_pager.dart';
import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
@@ -7,15 +5,19 @@ import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import '../../../ui/adaptive/floating_bar_layout.dart';
import '../../../ui/adaptive/glass_bar.dart';
import '../actions/artifact_file_actions.dart';
import '../actions/artifact_file_bridge.dart';
import '../domain/artifact_preview.dart';
import '../domain/artifact_url.dart';
import '../domain/gallery_navigation.dart';
import 'artifact_html_view.dart';
import 'artifact_viewer_bar.dart';
import 'artifact_viewer_content.dart';
import 'artifact_viewer_fetch.dart';
export 'artifact_controls_overlay.dart';
export 'artifact_viewer_bar.dart'
show artifactFullscreenKey, artifactNextKey, artifactPreviousKey;
/// One viewer page: the recorded facts, position, live status, preview surface,
/// file transfer actions, external actions and paging controls.
///
@@ -42,8 +44,20 @@ class ArtifactViewerBody extends StatelessWidget {
this.error,
this.status,
this.onRetry,
this.htmlBuilder = defaultArtifactHtml,
this.fullscreen = false,
this.onFullscreen,
});
/// The inert HTML renderer; tests inject a plain stand-in.
final ArtifactHtmlBuilder htmlBuilder;
/// Whether this body is the full-screen view's ([ArtifactViewerBar]).
final bool fullscreen;
/// Enters or leaves the full-screen view.
final VoidCallback? onFullscreen;
/// Loads the current page's preview again after a failure.
final VoidCallback? onRetry;
@@ -79,6 +93,7 @@ class ArtifactViewerBody extends StatelessWidget {
bytes: bytes,
error: error,
onRetry: onRetry,
htmlBuilder: htmlBuilder,
),
),
],
@@ -116,233 +131,25 @@ class ArtifactViewerBody extends StatelessWidget {
// no empty glass bar, and no bottom clearance reserved for one.
if (resolved == null && count <= 1) return swipe;
return FloatingBarOverlay(
// The SafeArea already lifts the bar by the inherited bottom inset (a
// shell bar below the pane); adding that clearance again floated the
// bar far above it.
bar: SafeArea(
top: false,
minimum: const EdgeInsets.all(8),
// Without a pager the bar is as wide as its actions, so its last
// control keeps the same gap from the bar's end as the first.
child: Align(
alignment: AlignmentDirectional.centerStart,
heightFactor: 1,
child: GlassControlBar(
cupertino: usesCupertinoHost(context),
child: Row(
key: const Key('artifact-viewer-actions'),
mainAxisSize: count > 1 ? MainAxisSize.max : MainAxisSize.min,
children: [
if (resolved != null && !resolved.external)
ArtifactFileActions(
key: ValueKey<String>(
'viewer-files-${page.group.stageKey}\u0000'
'${page.group.visit}\u0000${page.artifact.url}',
),
artifact: page.artifact,
resolved: resolved,
fetch: fetch,
bridge: fileBridge,
compact: true,
),
if (resolved != null)
_Actions(resolved: resolved, onOpen: onOpen, onCopy: onCopy),
if (count > 1)
Expanded(
child: _Pager(
index: index,
count: count,
onPrevious: onPrevious,
onNext: onNext,
),
),
],
),
),
),
bar: ArtifactViewerBar(
page: page,
resolved: resolved,
index: index,
count: count,
fetch: fetch,
fileBridge: fileBridge,
onOpen: onOpen,
onCopy: onCopy,
onPrevious: onPrevious,
onNext: onNext,
fullscreen: fullscreen,
onFullscreen: onFullscreen,
),
child: swipe,
);
}
}
/// Open, Copy and the file actions float over the top of the content: shown
/// when the page opens and whenever the content is touched, hidden again after
/// a few seconds without use, so nothing needs scrolling to reach them.
class ArtifactControlsOverlay extends StatefulWidget {
const ArtifactControlsOverlay({
super.key,
required this.controls,
required this.child,
this.hideAfter = const Duration(seconds: 3),
});
final List<Widget> controls;
final Widget child;
final Duration hideAfter;
@override
State<ArtifactControlsOverlay> createState() =>
_ArtifactControlsOverlayState();
}
class _ArtifactControlsOverlayState extends State<ArtifactControlsOverlay> {
bool _shown = true;
Timer? _hide;
@override
void initState() {
super.initState();
_schedule();
}
@override
void dispose() {
_hide?.cancel();
super.dispose();
}
void _schedule() {
_hide?.cancel();
_hide = Timer(widget.hideAfter, () {
if (mounted) setState(() => _shown = false);
});
}
void _show() {
if (!_shown) setState(() => _shown = true);
_schedule();
}
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
final surface = cupertino
? CupertinoColors.systemBackground
.resolveFrom(context)
.withValues(alpha: 0.92)
: Theme.of(
context,
).colorScheme.surfaceContainerHigh.withValues(alpha: 0.94);
return Stack(
children: [
// Any touch on the content brings the controls back.
Positioned.fill(
child: Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: (_) => _show(),
child: widget.child,
),
),
Positioned(
left: 8,
right: 8,
top: 8,
child: IgnorePointer(
ignoring: !_shown,
child: AnimatedOpacity(
key: const Key('artifact-viewer-controls'),
opacity: _shown ? 1 : 0,
duration: const Duration(milliseconds: 200),
child: Listener(
// Using a control keeps the bar up.
onPointerDown: (_) => _schedule(),
child: DecoratedBox(
decoration: BoxDecoration(
color: surface,
borderRadius: BorderRadius.circular(12),
boxShadow: const [
BoxShadow(color: Color(0x22000000), blurRadius: 6),
],
),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 4,
vertical: 2,
),
child: Wrap(
alignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
children: widget.controls,
),
),
),
),
),
),
),
],
);
}
}
class _Actions extends StatelessWidget {
const _Actions({
required this.resolved,
required this.onOpen,
required this.onCopy,
});
final ResolvedArtifactUrl resolved;
final VoidCallback onOpen;
final VoidCallback onCopy;
@override
Widget build(BuildContext context) => Row(
mainAxisSize: MainAxisSize.min,
children: [
ArtifactIconAction(
key: const Key('artifact-open'),
label: 'Open',
icon: Icons.open_in_new,
cupertinoIcon: CupertinoIcons.arrow_up_right_square,
onPressed: onOpen,
),
ArtifactIconAction(
key: const Key('artifact-copy-link'),
label: 'Copy link',
icon: Icons.link,
cupertinoIcon: CupertinoIcons.link,
onPressed: onCopy,
),
],
);
}
const artifactPreviousKey = ValueKey<String>('artifact-previous');
const artifactNextKey = ValueKey<String>('artifact-next');
class _Pager extends StatelessWidget {
const _Pager({
required this.index,
required this.count,
required this.onPrevious,
required this.onNext,
});
final int index;
final int count;
final VoidCallback onPrevious;
final VoidCallback onNext;
@override
Widget build(BuildContext context) {
if (count <= 1) return const SizedBox.shrink();
final hasPrevious = pagedIndex(index, -1, count) != index;
final hasNext = pagedIndex(index, 1, count) != index;
return ChevronPager(
index: index,
count: count,
previousLabel: 'Previous artifact',
nextLabel: 'Next artifact',
previousKey: artifactPreviousKey,
nextKey: artifactNextKey,
onPrevious: hasPrevious ? onPrevious : null,
onNext: hasNext ? onNext : null,
);
}
}
/// The viewer's top edge: where this artifact sits in the list, and an
/// information button for its recorded facts.
class ArtifactViewerInfoAction extends StatelessWidget {
@@ -1,13 +1,9 @@
import '../../../ui/adaptive/segmented_bar.dart';
import '../../../ui/theme/app_theme.dart';
import '../../../ui/input/arrow_key_pager.dart';
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../ui/adaptive/host.dart';
import '../../../ui/input/arrow_key_pager.dart';
import 'artifact_selection_facts.dart';
import '../actions/artifact_file_bridge.dart';
import '../domain/artifact_groups.dart';
@@ -16,9 +12,13 @@ import '../domain/artifact_preview_failure.dart';
import '../domain/artifact_url.dart';
import '../domain/gallery_navigation.dart';
import 'artifact_external_open.dart';
import 'artifact_fullscreen.dart';
import 'artifact_fullscreen_host.dart';
import 'artifact_html_view.dart';
import 'artifact_viewer_body.dart';
import 'artifact_viewer_content.dart';
import 'artifact_viewer_fetch.dart';
import 'artifact_viewer_scaffold.dart';
import 'artifact_visit_list.dart';
/// The full-screen viewer's title, matching the web client's wording.
@@ -47,6 +47,7 @@ class ArtifactViewerPage extends StatefulWidget {
this.markdownBuilder = defaultArtifactMarkdown,
this.openExternal = openArtifactExternally,
this.fileBridge = const ArtifactFileBridge(),
this.htmlBuilder = defaultArtifactHtml,
});
final List<ArtifactGroup> groups;
@@ -64,6 +65,9 @@ class ArtifactViewerPage extends StatefulWidget {
final ArtifactExternalOpen openExternal;
final ArtifactFileBridge fileBridge;
/// The inert HTML renderer; tests inject a plain stand-in.
final ArtifactHtmlBuilder htmlBuilder;
@override
State<ArtifactViewerPage> createState() => _ArtifactViewerPageState();
}
@@ -75,7 +79,8 @@ class _FetchedPreview {
final Uint8List? bytes;
}
class _ArtifactViewerPageState extends State<ArtifactViewerPage> {
class _ArtifactViewerPageState extends State<ArtifactViewerPage>
with ArtifactFullscreenHost<ArtifactViewerPage> {
late final List<PagedArtifact> _pages = pagedArtifacts(
widget.groups,
includeExternalDocuments: widget.includeExternalDocuments,
@@ -117,47 +122,31 @@ class _ArtifactViewerPageState extends State<ArtifactViewerPage> {
void _beginLoad({bool initial = false}) {
final generation = ++_generation;
final plan = _plan;
// The first load runs in initState, before there is anything to redraw.
void update(VoidCallback change) => initial ? change() : setState(change);
if (plan == null || !plan.canFetch) {
void clear() {
update(() {
_loading = false;
_error = null;
_fetched = null;
}
if (initial) {
clear();
} else {
setState(clear);
}
});
return;
}
final key = plan.resolved!.url;
final cached = _cache[key];
if (cached != null) {
void apply() {
update(() {
_loading = false;
_error = null;
_fetched = cached;
}
if (initial) {
apply();
} else {
setState(apply);
}
});
return;
}
void start() {
update(() {
_loading = true;
_error = null;
_fetched = null;
}
if (initial) {
start();
} else {
setState(start);
}
});
widget
.fetch(plan.resolved!.uri)
.then(
@@ -226,7 +215,13 @@ class _ArtifactViewerPageState extends State<ArtifactViewerPage> {
}
@override
Widget build(BuildContext context) {
Widget build(BuildContext context) => buildFrame(context, fullscreen: false);
/// The viewer's scaffold, inline or as the full-screen view: the same top
/// bar, preview and bottom actions; full screen adds HTML zoom on the web
/// and gives the preview every gesture over it.
@override
Widget buildFrame(BuildContext context, {required bool fullscreen}) {
final page = _page;
final plan = _plan;
final title = page == null
@@ -242,6 +237,11 @@ class _ArtifactViewerPageState extends State<ArtifactViewerPage> {
final info = page == null || plan == null
? const <Widget>[]
: <Widget>[
if (fullscreen &&
artifactHtmlZoomButtons &&
plan.kind == ArtifactPreviewKind.html &&
_fetched?.text != null)
...artifactHtmlZoomActions(htmlZoom),
ArtifactViewerInfoAction(
facts: ArtifactSelectionFacts(
group: page.group,
@@ -251,7 +251,7 @@ class _ArtifactViewerPageState extends State<ArtifactViewerPage> {
),
),
];
Widget body = page == null || plan == null
final body = page == null || plan == null
? const Center(child: Text('No previewable artifacts recorded.'))
: ArtifactViewerBody(
page: page,
@@ -272,36 +272,26 @@ class _ArtifactViewerPageState extends State<ArtifactViewerPage> {
onRetry: _beginLoad,
onOpen: plan.resolved == null ? () {} : () => _open(plan.resolved!),
onCopy: plan.resolved == null ? () {} : () => _copy(plan.resolved!),
htmlBuilder: widget.htmlBuilder,
fullscreen: fullscreen,
onFullscreen: fullscreen
? () => Navigator.of(context).maybePop()
: enterFullscreen,
);
// Left/right arrows walk the same list as the Previous/Next buttons.
body = ArrowKeyPager(
// Left/right arrows walk the same list as the Previous/Next buttons,
// wherever focus is on the page, its top bar's controls included.
return ArrowKeyPager(
onPrevious: () => _step(-1),
onNext: () => _step(1),
// Escape closes the viewer, like the web's overlay.
// Escape closes the viewer (or leaves full screen), like the web's
// overlay.
onEscape: () => Navigator.of(context).maybePop(),
child: body,
);
if (usesCupertinoHost(context)) {
return CupertinoPageScaffold(
backgroundColor: AppColors.groupedBackground,
navigationBar: SegmentedBar(
cupertino: true,
title: title,
subtitle: subtitle,
actions: info,
),
child: body,
);
}
return Scaffold(
extendBodyBehindAppBar: true,
appBar: SegmentedBar(
cupertino: false,
child: ArtifactViewerScaffold(
title: title,
subtitle: subtitle,
actions: info,
body: body,
),
body: body,
);
}
}
@@ -0,0 +1,42 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import '../../../ui/adaptive/segmented_bar.dart';
import '../../../ui/theme/app_theme.dart';
/// The viewer's page structure on either host: its [SegmentedBar] (the
/// platform's Back, or Close on the full-screen route) over [body].
class ArtifactViewerScaffold extends StatelessWidget {
const ArtifactViewerScaffold({
super.key,
required this.title,
required this.subtitle,
required this.actions,
required this.body,
});
final String title;
final String? subtitle;
final List<Widget> actions;
final Widget body;
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
final bar = SegmentedBar(
cupertino: cupertino,
title: title,
subtitle: subtitle,
actions: actions,
);
if (cupertino) {
return CupertinoPageScaffold(
backgroundColor: AppColors.groupedBackground,
navigationBar: bar,
child: body,
);
}
return Scaffold(extendBodyBehindAppBar: true, appBar: bar, body: body);
}
}
@@ -100,8 +100,31 @@ String noChangeDetail(RunChanges changes) {
return emptyCaptureDetail;
}
/// The message for the server's `no_patch_reason`, or null when it sent none
/// or one this client does not know (the generic wording then applies).
String? noPatchReasonMessage(String? reason) => switch (reason) {
'binary' => 'Binary file; only its metadata was recorded.',
'file_size' => 'This file is over 1 MiB, so no diff text was recorded.',
'budget' =>
'The workspace snapshot ran out of text budget, so no diff text was '
'recorded.',
'lines' => 'The change is over 5,000 lines, so no diff text was recorded.',
'evidence_size' =>
"This visit's recorded changes reached their size limit, so this patch "
'was dropped.',
'git_status' =>
"This change was seen only in Git status, so the file's contents weren't "
'compared.',
'baseline' =>
"The file's content at stage start couldn't be recovered from Git, so no "
'diff was recorded.',
_ => null,
};
/// Why a file has no patch to render, in the entry's own recorded terms.
String patchUnavailableReason(FileChange file) {
final reason = noPatchReasonMessage(file.noPatchReason);
if (reason != null) return reason;
if (file.truncated) {
return "The server truncated this file's patch at its capture limit; no "
'diff text was recorded.';
@@ -12,12 +12,14 @@ class FileChange {
String? patch,
this.binary = false,
this.truncated = false,
String? noPatchReason,
String? beforeMode,
String? afterMode,
this.steps = const [],
ParsedPatch? parsedPatch,
}) : patch = _nonBlank(patch),
beforeMode = _nonBlank(beforeMode),
noPatchReason = _nonBlank(noPatchReason),
afterMode = _nonBlank(afterMode),
// Aggregate copies pass their already-parsed patch through instead of
// re-parsing the same recorded bytes for every stage that touched a path.
@@ -32,6 +34,11 @@ class FileChange {
final String? patch;
final bool binary;
final bool truncated;
/// Why the server recorded no (complete) patch: `binary`, `file_size`,
/// `budget`, `lines`, `evidence_size`, `git_status` or `baseline`. Null from
/// an older server or when a patch was recorded.
final String? noPatchReason;
final String? beforeMode;
final String? afterMode;
@@ -68,6 +75,7 @@ class FileChange {
patch: patch,
binary: binary,
truncated: truncated,
noPatchReason: noPatchReason,
beforeMode: beforeMode,
afterMode: afterMode,
steps: List.unmodifiable(value),
@@ -88,6 +96,9 @@ class FileChange {
patch: json['patch'] is String ? json['patch'] as String : null,
binary: json['binary'] == true,
truncated: json['truncated'] == true,
noPatchReason: json['no_patch_reason'] is String
? json['no_patch_reason'] as String
: null,
beforeMode: _textOrNull(json['before_mode']),
afterMode: _textOrNull(json['after_mode']),
);
@@ -211,7 +211,11 @@ class _FileDiffViewerState extends State<FileDiffViewer> {
Widget _body(BuildContext context, TextStyle mono) {
final file = widget.file;
if (file.binary) return _message(context, binaryDiffMessage);
// A recorded reason is more specific than the generic binary message.
final reason = noPatchReasonMessage(file.noPatchReason);
if (file.binary && reason == null) {
return _message(context, binaryDiffMessage);
}
if (!file.hasPatch) {
return _message(context, patchUnavailableReason(file));
}
@@ -215,11 +215,7 @@ class _ChatQuestionCardState extends State<ChatQuestionCard> {
String _statusLine() {
if (_pending) return chatQuestionWaiting;
if (widget.form['cancelled'] == true) return chatQuestionExpired;
final answers = widget.form['answers'];
return answers is Map && answers.isNotEmpty
? chatQuestionAnswered
: chatQuestionClosed;
return chatQuestionSettledStatus(widget.form);
}
String get _submitLabel {
@@ -132,6 +132,15 @@ String chatQuestionOptionLabel(JsonMap option) {
bool chatFormPending(JsonMap form) =>
form['resolved'] != true && form['cancelled'] != true;
/// How a settled form ended: expired, answered, or closed without an answer.
String chatQuestionSettledStatus(JsonMap form) {
if (form['cancelled'] == true) return chatQuestionExpired;
final answers = form['answers'];
return answers is Map && answers.isNotEmpty
? chatQuestionAnswered
: chatQuestionClosed;
}
/// True when an external form URL is one this app can safely show. Mirrors the
/// web's `safeFormURL`: an absolute HTTP(S) URL with a real host and no spaces.
bool chatExternalUrlIsSafe(String raw) {
@@ -145,21 +154,34 @@ bool chatExternalUrlIsSafe(String raw) {
/// Fold one `form` frame into the retained forms, keyed by id. A resolved or
/// cancelled update keeps the recorded answers so the card can show them
/// read-only instead of dropping evidence.
///
/// [raisedIn] is recorded as [chatQuestionRaisedIn] only on the form's first
/// frame: a later resolution arrives during another message and must not move
/// the question.
Map<String, JsonMap> chatFoldQuestionFrame(
Map<String, JsonMap> current,
JsonMap? form,
) {
JsonMap? form, {
String? raisedIn,
}) {
if (form == null) return current;
final id = _text(form['id']);
if (id.isEmpty) return current;
final existing = current[id];
final next = <String, JsonMap>{...current};
final anchor = _text(raisedIn);
next[id] = existing == null
? Map<String, dynamic>.from(form)
? {
...Map<String, dynamic>.from(form),
if (anchor.isNotEmpty) chatQuestionRaisedIn: anchor,
}
: {...existing, ...Map<String, dynamic>.from(form)};
return next;
}
/// Client-only form key: the agent message id the question was raised during.
/// The server never sends it, so folding a frame never overwrites it.
const chatQuestionRaisedIn = 'raised_in_message_id';
/// A stable id for one confirmed answer action on a form. Reusing the same id
/// across a retry lets the send gate recognise a double tap.
String chatQuestionReplyId(String formId, {String action = ''}) =>
@@ -0,0 +1,211 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../ui/sessions/chat_adaptive.dart';
import '../ui/transcript/chat_turn_chip.dart';
import 'chat_card_styles.dart';
import 'chat_question_card_model.dart';
import 'chat_question_recorded_answers.dart';
/// The settled form of [row], a question card row; null while it still needs
/// the operator or its last answer was refused.
JsonMap? _settled(JsonMap row) {
if (row['kind'] != 'question') return null;
if ('${row['error'] ?? ''}'.trim().isNotEmpty) return null;
final form = row['form'];
if (form is! Map) return null;
final converted = Map<String, dynamic>.from(form);
return chatFormPending(converted) ? null : converted;
}
/// Folds answered and expired question cards out of the card list, the way a
/// turn's tool calls fold into one chip.
///
/// A settled question joins the agent turn it was raised during (the
/// [chatQuestionRaisedIn] message id) as that row's `questions`. Questions
/// naming no turn in view share one `questions` row where the first stood.
/// Pending questions, and ones whose answer was refused, stay full cards.
List<JsonMap> groupSettledQuestions(List<JsonMap> rows) {
final result = <JsonMap>[];
final attached = <int, List<JsonMap>>{};
final loose = <JsonMap>[];
int? looseAt;
for (final row in rows) {
final form = _settled(row);
if (form == null) {
result.add(row);
continue;
}
final turn = _turnOf(result, '${form[chatQuestionRaisedIn] ?? ''}'.trim());
if (turn != null) {
attached.putIfAbsent(turn, () => []).add(form);
} else {
looseAt ??= result.length;
loose.add(form);
}
}
for (final entry in attached.entries) {
result[entry.key] = {...result[entry.key], 'questions': entry.value};
}
if (looseAt != null) {
result.insert(looseAt, {
'kind': 'questions',
'key': 'chat-questions-${loose.first['id']}',
'questions': loose,
});
}
return result;
}
int? _turnOf(List<JsonMap> rows, String messageId) {
if (messageId.isEmpty) return null;
for (var index = rows.length - 1; index >= 0; index--) {
final row = rows[index];
final ids = row['messageIds'];
if (row['kind'] == 'assistant' && ids is List && ids.contains(messageId)) {
return index;
}
}
return null;
}
/// The settled forms a row carries (a turn's or a loose `questions` row's).
List<JsonMap> chatRowQuestions(JsonMap row) {
final questions = row['questions'];
if (questions is! List) return const [];
return [
for (final form in questions)
if (form is Map) Map<String, dynamic>.from(form),
];
}
/// The collapsed line for one settled question: the question and its outcome,
/// `Which database? · Postgres`, `… · +1 more` when several were answered.
String chatQuestionSummary(JsonMap form) {
final fields = chatFormFields(form);
final answers = form['answers'] is Map
? Map<String, dynamic>.from(form['answers'] as Map)
: <String, dynamic>{};
final title = '${form['title'] ?? ''}'.trim();
String question = title.isEmpty ? 'Question' : title;
if (fields.isNotEmpty) {
question = chatQuestionFieldLabel(
fields.first,
'${fields.first['key'] ?? ''}'.trim(),
);
}
if (form['cancelled'] == true) return '$question · Expired';
final answered = [
for (final field in fields)
if (answers.containsKey('${field['key'] ?? ''}'.trim())) field,
];
if (answered.isEmpty) {
return answers.isEmpty ? '$question · Closed' : '$question · Answered';
}
final first = answered.first;
final key = '${first['key'] ?? ''}'.trim();
final more = answers.length - 1;
return [
chatQuestionFieldLabel(first, key),
chatQuestionAnswerText(first, answers[key]),
if (more > 0) '+$more more',
].join(' · ');
}
/// One settled question as the quiet chip a turn's tools use. It opens a
/// native sheet with the full question and the recorded answers.
class ChatQuestionChip extends StatelessWidget {
const ChatQuestionChip({super.key, required this.form});
final JsonMap form;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final color = cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
final label = chatQuestionSummary(form);
return ChatTurnChip(
chipKey: ValueKey<String>('chat-question-chip-${form['id']}'),
leading: Icon(
cupertino ? CupertinoIcons.question_circle : Icons.help_outline,
size: 14,
color: color,
),
label: label,
color: color,
ellipsizeLabel: true,
semanticsLabel: 'Question: $label, expand for details',
sheet: _QuestionSheet(form: form),
);
}
}
/// The chips for [row]'s settled questions, one per question.
List<Widget> chatQuestionChips(JsonMap row) => [
for (final form in chatRowQuestions(row)) ChatQuestionChip(form: form),
];
/// A loose `questions` row: its chips on the agent's side.
class ChatQuestionsRow extends StatelessWidget {
const ChatQuestionsRow({super.key, required this.row});
final JsonMap row;
@override
Widget build(BuildContext context) => Align(
alignment: AlignmentDirectional.centerStart,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: chatQuestionChips(row),
),
);
}
class _QuestionSheet extends StatelessWidget {
const _QuestionSheet({required this.form});
final JsonMap form;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final style = cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodyMedium;
final title = '${form['title'] ?? ''}'.trim();
return DefaultTextStyle.merge(
style: style,
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.sizeOf(context).height * 0.8,
),
child: ListView(
key: const Key('chat-question-sheet'),
shrinkWrap: true,
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
children: [
Text(
title.isEmpty ? 'Question' : title,
style: chatCardTitleStyle(context, cupertino),
),
Text(
chatQuestionSettledStatus(form),
style: chatCardSecondaryStyle(context, cupertino),
),
...chatQuestionRecordedAnswers(
context: context,
form: form,
cupertino: cupertino,
),
],
),
),
);
}
}
@@ -24,8 +24,8 @@ List<Widget> chatQuestionRecordedAnswers({
widgets.add(
_recorded(
context,
_fieldLabel(field, key),
_answerText(field, answers[key]),
chatQuestionFieldLabel(field, key),
chatQuestionAnswerText(field, answers[key]),
cupertino,
),
);
@@ -33,7 +33,12 @@ List<Widget> chatQuestionRecordedAnswers({
for (final entry in answers.entries) {
if (shown.contains(entry.key)) continue;
widgets.add(
_recorded(context, entry.key, _answerText(null, entry.value), cupertino),
_recorded(
context,
entry.key,
chatQuestionAnswerText(null, entry.value),
cupertino,
),
);
}
if (widgets.isEmpty) {
@@ -49,7 +54,7 @@ List<Widget> chatQuestionRecordedAnswers({
/// The field's display label, falling back past blank recorded strings the same
/// way the pending field does.
String _fieldLabel(JsonMap field, String key) {
String chatQuestionFieldLabel(JsonMap field, String key) {
for (final candidate in [field['title'], field['description']]) {
final text = '${candidate ?? ''}'.trim();
if (text.isNotEmpty) return text;
@@ -74,7 +79,8 @@ Widget _recorded(
),
);
String _answerText(JsonMap? field, Object? value) {
/// A recorded answer as display text: option labels, Yes/No, list joined.
String chatQuestionAnswerText(JsonMap? field, Object? value) {
final values = value is List ? value : [value];
final boolean = field != null && '${field['type'] ?? ''}' == 'boolean';
return values
@@ -10,7 +10,8 @@ import 'chat_question_card_model.dart';
/// gates, so the controller itself stays about messages and live turn state.
///
/// The web drops an approval or form once it is resolved. This app keeps the
/// latest settled cards as read-only evidence, which is an intentional addition;
/// latest settled cards as read-only evidence, collapsed into their turn like
/// tool calls (see `chat_permission_group.dart`, `chat_question_group.dart`);
/// [settledLimit] bounds that history so a long session cannot grow without
/// limit while pending cards are never dropped.
class ChatThreadCards {
@@ -136,11 +137,12 @@ class ChatThreadCards {
}
/// Fold one `form` event. A folded update keeps a settled form's recorded
/// answers for the read-only card.
void foldForm(JsonMap form) {
/// answers for the collapsed row. [raisedIn] is the agent message the first
/// frame arrived during; it places the answered question in its turn.
void foldForm(JsonMap form, {String? raisedIn}) {
final id = '${form['id'] ?? ''}'.trim();
if (id.isEmpty) return;
final next = chatFoldQuestionFrame(_forms, form);
final next = chatFoldQuestionFrame(_forms, form, raisedIn: raisedIn);
if (identical(next, _forms)) return;
_forms
..clear()
@@ -369,7 +369,10 @@ class ChatThreadController extends ChangeNotifier {
if (body['kind'] == 'form') {
final form = body['form'];
if (form is! Map) return;
_cards.foldForm(Map<String, dynamic>.from(form));
_cards.foldForm(
Map<String, dynamic>.from(form),
raisedIn: _answeringMessageId(),
);
return;
}
final current = _thread;
@@ -415,6 +418,21 @@ class ChatThreadController extends ChangeNotifier {
].any((key) => usage[key] != null);
}
/// The agent message a question frame arrives during: the streamed reply,
/// else the last answer when it is the agent's. A question raised before the
/// reply starts names none rather than an older turn.
String? _answeringMessageId() {
final live = _liveAssistantMessageId;
if (live != null && live.isNotEmpty) return live;
for (final message in _messages.reversed) {
if (chatInjectedKind(message) != null) continue;
if (message['role'] != 'assistant') return null;
final id = '${message['id'] ?? ''}'.trim();
return id.isEmpty ? null : id;
}
return null;
}
/// The pushed envelope body, or null for another message type. The server
/// wraps `chat_event` in the typed envelope; domain code never sees the
/// transport fields.
@@ -52,6 +52,7 @@ import 'chat_transcript_cache.dart';
import 'chat_transcript_scroll_view.dart';
import 'chat_permission_card_model.dart';
import 'chat_permission_group.dart';
import 'chat_question_group.dart';
import 'chat_transcript_card.dart';
/// One read-only conversation: the controller's transcript in the order the
@@ -851,22 +852,25 @@ class _ChatThreadViewState extends State<ChatThreadView> {
permissionErrorFor: _controller.permissionErrorFor,
formErrorFor: _controller.questionErrorFor,
);
// Answered approvals fold into their turn's chips, like tool calls.
final allRows = groupSettledPermissions(
transcriptRows(
messages,
trailing: cards,
running:
_controller.running &&
!_reconnecting &&
!_staleTranscript &&
!cards.any(chatCardAwaitingOperator),
awaitingResponse:
_controller.awaitingResponse &&
!_reconnecting &&
!_staleTranscript &&
!cards.any(chatCardAwaitingOperator),
liveMessageId: _controller.liveAssistantMessageId,
// Answered approvals and questions fold into their turn's chips, like
// tool calls; only cards still waiting on the operator stay full cards.
final allRows = groupSettledQuestions(
groupSettledPermissions(
transcriptRows(
messages,
trailing: cards,
running:
_controller.running &&
!_reconnecting &&
!_staleTranscript &&
!cards.any(chatCardAwaitingOperator),
awaitingResponse:
_controller.awaitingResponse &&
!_reconnecting &&
!_staleTranscript &&
!cards.any(chatCardAwaitingOperator),
liveMessageId: _controller.liveAssistantMessageId,
),
),
);
// A transcript held from before a socket gap may still say a compaction is
@@ -1262,6 +1266,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
}
if (kind == 'system_notice') return ChatSystemNoticeLine(row: row);
if (kind == 'task_notices') return ChatTaskNoticesGroup(row: row);
if (kind == 'questions') return ChatQuestionsRow(row: row);
if (kind == 'permission' || kind == 'question') {
return ChatTranscriptCard(
row: row,
@@ -1273,6 +1278,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
final chips = [
if (permissions is List<ChatPermissionCardData> && permissions.isNotEmpty)
ChatPermissionsChip(permissions: permissions),
...chatQuestionChips(row),
];
if (kind == 'permissions') {
return Align(
@@ -0,0 +1,43 @@
import '../../../core/api_gateway.dart';
/// One chat's live activity as the server observes it: a turn in flight and
/// how many background tasks (shells, background commands, subagents) still
/// run. It rides on each `chat_sessions` row as `activity` and is pushed to
/// every connection as `chat_activity` on each change. [seq] orders one
/// chat's snapshots across the list and the pushes; the larger one is newer.
typedef ChatListActivity = ({
String sessionId,
bool turnRunning,
int backgroundTasks,
int seq,
});
/// Reads an `activity` row field or a `chat_activity` body. [sessionId] names
/// the row when the body omits it. Anything malformed is null, so an older
/// server (which sends neither) leaves the list exactly as before.
ChatListActivity? chatListActivityOf(Object? value, {String? sessionId}) {
if (value is! Map) return null;
final named = value['session_id'];
final id = sessionId ?? (named is String ? named : '');
if (id.isEmpty) return null;
final tasks = value['background_tasks'];
final seq = value['seq'];
return (
sessionId: id,
turnRunning: value['turn_running'] == true,
backgroundTasks: tasks is num && tasks > 0 ? tasks.toInt() : 0,
seq: seq is num ? seq.toInt() : 0,
);
}
/// The row keys the list controller derives from the activity.
JsonMap chatListActivityRowFields(ChatListActivity activity) => {
'running': activity.turnRunning,
'background_tasks': activity.backgroundTasks,
};
/// Running background tasks of a list row; 0 when unknown.
int chatSessionBackgroundTasks(JsonMap session) {
final tasks = session['background_tasks'];
return tasks is int && tasks > 0 ? tasks : 0;
}
@@ -8,6 +8,7 @@ import '../../../../core/servers/server_scope.dart';
import '../../../../core/transport/connection_state.dart';
import '../../../attention/runtime/attention_ack_sync.dart';
import '../../data/chat_repository.dart';
import '../../domain/chat_list_activity.dart';
import '../../domain/chat_sessions.dart';
import 'chat_session_local.dart';
import 'session_attention.dart';
@@ -65,6 +66,9 @@ class ChatSessionsController extends ChangeNotifier {
Future<void> _persistTail = Future<void>.value();
int _runningRevision = 0;
final Map<String, ({int revision, bool running})> _runningFrames = {};
// The newest server activity applied per chat (list row or push), so an
// older snapshot that arrives later never replaces it.
final Map<String, ChatListActivity> _activity = {};
StreamSubscription<JsonMap>? _frameSubscription;
String? activeSessionId;
@@ -75,6 +79,9 @@ class ChatSessionsController extends ChangeNotifier {
void _onFrame(JsonMap frame) {
if (frame['type'] == 'chat_session_changed') return _sessionChanged(frame);
if (frame['type'] == 'chat_activity') {
return _activityChanged(frame['chat_activity']);
}
final effect = chatSessionFrameEffect(frame);
if (effect == null) return;
final id = effect.sessionId;
@@ -130,6 +137,58 @@ class ChatSessionsController extends ChangeNotifier {
if (found) _notify();
}
/// The server pushed a chat's turn state and background-task count. It
/// reaches every connection, so every listed chat's spinner and
/// background-task badge follow it, not only the chat open here. A push
/// older than the snapshot already applied is ignored.
void _activityChanged(Object? body) {
final activity = chatListActivityOf(body);
if (activity == null || _disposed) return;
final id = activity.sessionId;
if (activity.seq <= (_activity[id]?.seq ?? 0)) return;
_activity[id] = activity;
_runningFrames[id] = (
revision: ++_runningRevision,
running: activity.turnRunning,
);
final fields = chatListActivityRowFields(activity);
var changed = false;
_sessions = [
for (final row in _sessions)
if ('${row['id'] ?? ''}' == id &&
(row['running'] != fields['running'] ||
row['background_tasks'] != fields['background_tasks']))
() {
changed = true;
return {...row, ...fields};
}()
else
row,
];
if (changed) _notify();
}
/// A listed row with the newest activity known for it: the row's own
/// `activity` unless a newer push was already applied, then a turn frame
/// this connection saw during the read. An older server sends no
/// `activity`, so only the turn frames apply, as before.
JsonMap _withActivity(JsonMap row, int runningRevision) {
final id = '${row['id'] ?? ''}';
var next = row;
final listed = chatListActivityOf(row['activity'], sessionId: id);
if (listed != null) {
final known = _activity[id];
final activity = known != null && known.seq > listed.seq ? known : listed;
_activity[id] = activity;
next = {...row, ...chatListActivityRowFields(activity)};
}
final frame = _runningFrames[id];
if ((frame?.revision ?? 0) > runningRevision) {
next = {...next, 'running': frame!.running};
}
return next;
}
void _bindAckSync(AttentionAckSync? sync) {
if (identical(sync, _ackSync)) return;
_ackSync?.removeListener(_ackChanged);
@@ -246,6 +305,7 @@ class ChatSessionsController extends ChangeNotifier {
if (identical(next.gateway, repository.gateway)) return;
repository = next;
_runningFrames.clear();
_activity.clear();
_listenFrames();
_bindAckSync(attentionAckSyncOf(next.gateway) ?? _ackSync);
refresh();
@@ -265,12 +325,7 @@ class ChatSessionsController extends ChangeNotifier {
final sessions = await repository.sessions();
if (generation != _generation) return;
_sessions = [
for (final row in sessions)
if ((_runningFrames['${row['id'] ?? ''}']?.revision ?? 0) >
runningRevision)
{...row, 'running': _runningFrames['${row['id'] ?? ''}']!.running}
else
row,
for (final row in sessions) _withActivity(row, runningRevision),
];
_seedLocal();
_loading = false;
@@ -0,0 +1,93 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
/// The corner badge a chat's avatar wears for its live activity: the
/// platform's activity indicator while a turn runs; otherwise, while
/// background tasks still run, a quiet muted glyph (never a second spinner).
/// Null when the chat is idle.
Widget? chatSessionActivityBadge({
required bool cupertino,
required bool running,
required int backgroundTasks,
}) {
if (running) {
return Semantics(
key: const Key('chat-row-working'),
label: 'Chat is working',
child: _WorkingBadge(cupertino: cupertino),
);
}
if (backgroundTasks <= 0) return null;
final label = 'Background tasks running ($backgroundTasks)';
// Hover shows the tooltip on a pointer device; a touch long press stays the
// row's own gesture.
return Tooltip(
key: const Key('chat-row-background'),
message: label,
triggerMode: TooltipTriggerMode.manual,
excludeFromSemantics: true,
child: Semantics(
label: label,
child: _BackgroundBadge(cupertino: cupertino),
),
);
}
/// The badge's own disc in the surface colour, so it reads over any avatar.
class _BadgeDisc extends StatelessWidget {
const _BadgeDisc({required this.cupertino, required this.child});
final bool cupertino;
final Widget child;
@override
Widget build(BuildContext context) {
final background = cupertino
? CupertinoColors.systemBackground.resolveFrom(context)
: Theme.of(context).colorScheme.surface;
return DecoratedBox(
decoration: BoxDecoration(color: background, shape: BoxShape.circle),
child: Padding(padding: const EdgeInsets.all(2), child: child),
);
}
}
class _WorkingBadge extends StatelessWidget {
const _WorkingBadge({required this.cupertino});
final bool cupertino;
@override
Widget build(BuildContext context) {
return _BadgeDisc(
cupertino: cupertino,
child: cupertino
? const CupertinoActivityIndicator(radius: 6)
: const SizedBox.square(
dimension: 12,
child: CircularProgressIndicator(strokeWidth: 2),
),
);
}
}
class _BackgroundBadge extends StatelessWidget {
const _BackgroundBadge({required this.cupertino});
final bool cupertino;
@override
Widget build(BuildContext context) {
final color = cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
return _BadgeDisc(
cupertino: cupertino,
child: Icon(
cupertino ? CupertinoIcons.ellipsis_circle_fill : Icons.pending,
size: 12,
color: color,
),
);
}
}
@@ -18,23 +18,20 @@ ChatSessionFrameEffect? chatSessionFrameEffect(JsonMap frame) {
if (event is! Map) return null;
id = event['session_id'] is String ? event['session_id'] as String : null;
final kind = event['kind'];
// A badge means content to read, not transport/activity churn: assistant
// text, another client's user message, a returned tool result, or a pending
// form. Reasoning, starts, steps, shells, compaction and usage are not unread.
// A badge means the agent said something to read or is waiting on the
// operator: visible assistant reply text or a pending form. Tool calls and
// their results, harness notices and agent reports (`message_kind`), the
// operator's own prompts from any device, reasoning, steps, shells,
// compaction and usage are turn activity, never unread.
if (kind == 'text') {
attention = '${event['delta'] ?? ''}'.isNotEmpty;
} else if (kind == 'user') {
attention = true;
attention =
'${event['delta'] ?? ''}'.trim().isNotEmpty &&
'${event['message_kind'] ?? ''}'.isEmpty;
} else if (kind == 'tool') {
final part = event['part'];
final state = part is Map ? part['state'] : null;
if (state is Map) {
final status = state['status'];
attention =
(status == 'completed' || status == 'error') &&
((state['content'] is List &&
(state['content'] as List).isNotEmpty) ||
state['error'] != null);
if (status == 'running' || status == 'streaming') running = true;
}
} else if (kind == 'form') {
@@ -6,10 +6,12 @@ import '../../../../ui/layout/app_list_avatar.dart';
import '../../../../ui/layout/app_list_row.dart';
import '../../../../ui/text/relative_time_label.dart';
import '../../domain/chat_colors.dart';
import '../../domain/chat_list_activity.dart';
import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart';
import 'chat_color_palette.dart';
import 'session_actions.dart';
import 'session_activity_badge.dart';
import 'session_harness_icon.dart';
import 'session_row_style.dart';
@@ -68,6 +70,9 @@ class ChatSessionRow extends StatelessWidget {
leading: ChatSessionAvatar(
session: session,
running: session['running'] == true && !unseen,
backgroundTasks: session['running'] == true
? 0
: chatSessionBackgroundTasks(session),
selected: selected,
),
// The star rides in the title's own text, so a narrow row ellipsises
@@ -149,17 +154,20 @@ class _Star extends StatelessWidget {
/// The chat's harness mark in a filled circle, like a contact avatar. A
/// running chat carries a small activity badge on the avatar's corner instead
/// of a line of its own; a selected chat's avatar takes the accent fill.
/// of a line of its own, and an idle chat whose background tasks still run a
/// quieter one; a selected chat's avatar takes the accent fill.
class ChatSessionAvatar extends StatelessWidget {
const ChatSessionAvatar({
super.key,
required this.session,
this.running = false,
this.backgroundTasks = 0,
this.selected = false,
});
final JsonMap session;
final bool running;
final int backgroundTasks;
final bool selected;
@override
@@ -192,39 +200,12 @@ class ChatSessionAvatar extends StatelessWidget {
return AppListAvatar(
foreground: mark,
background: fill,
badge: running
? Semantics(
key: const Key('chat-row-working'),
label: 'Chat is working',
child: _WorkingBadge(cupertino: cupertino),
)
: null,
badge: chatSessionActivityBadge(
cupertino: cupertino,
running: running,
backgroundTasks: backgroundTasks,
),
child: SessionHarnessIcon(session: session, color: mark),
);
}
}
class _WorkingBadge extends StatelessWidget {
const _WorkingBadge({required this.cupertino});
final bool cupertino;
@override
Widget build(BuildContext context) {
final background = cupertino
? CupertinoColors.systemBackground.resolveFrom(context)
: Theme.of(context).colorScheme.surface;
return DecoratedBox(
decoration: BoxDecoration(color: background, shape: BoxShape.circle),
child: Padding(
padding: const EdgeInsets.all(2),
child: cupertino
? const CupertinoActivityIndicator(radius: 6)
: const SizedBox.square(
dimension: 12,
child: CircularProgressIndicator(strokeWidth: 2),
),
),
);
}
}
@@ -7,6 +7,25 @@ import '../../../../ui/adaptive/host.dart';
import 'chat_link_browser_menu.dart';
import 'chat_links.dart';
/// A link's tap recognizer. A primary mouse press on a link belongs to the
/// link, as a press on a web page's anchor does: otherwise the selection area
/// claims the press as a selection drag once the pointer moves
/// [kPrecisePointerPanSlop] (2 px), so an ordinary click with a little hand or
/// trackpad movement opened nothing. The click still cancels past the tap
/// slop, and a selection drag that starts on plain text still crosses links.
/// Touch, stylus and secondary presses keep competing in the arena, so a long
/// press still selects and offers Copy link.
class _LinkTapRecognizer extends TapGestureRecognizer {
@override
void addAllowedPointer(PointerDownEvent event) {
super.addAllowedPointer(event);
if (event.kind == PointerDeviceKind.mouse &&
event.buttons == kPrimaryMouseButton) {
resolve(GestureDisposition.accepted);
}
}
}
/// The link spans of one selectable text block, and the selection area that
/// hosts them. A tap opens the link. A long press (or a native right-click)
/// shows the selection menu with "Copy link" added; on the web, where the
@@ -24,7 +43,7 @@ class ChatLinkSpans {
static bool? debugOwnsSecondaryClick;
final VoidCallback onChanged;
final Map<String, TapGestureRecognizer> _recognizers = {};
final Map<String, _LinkTapRecognizer> _recognizers = {};
final ContextMenuController _linkMenu = ContextMenuController();
String? _hovered;
String? _pressed;
@@ -45,7 +64,7 @@ class ChatLinkSpans {
final uri = chatLinkUri(target);
if (uri == null) return TextSpan(children: label);
final url = uri.toString();
final recognizer = _recognizers.putIfAbsent(url, TapGestureRecognizer.new)
final recognizer = _recognizers.putIfAbsent(url, _LinkTapRecognizer.new)
..onTapDown = (_) {
_pressed = url;
}
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
import '../../../../ui/layout/wheel_scroll_forwarding.dart';
import '../../../../ui/text/monospace.dart';
import '../sessions/chat_adaptive.dart';
import 'chat_link_launcher.dart';
import 'chat_link_spans.dart';
@@ -209,7 +210,12 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
decoration: BoxDecoration(color: _codeFill(context, cupertino)),
child: Padding(
padding: const EdgeInsets.all(12),
child: HorizontalScrollView(child: Text(code)),
child: HorizontalScrollView(
child: Text(
code,
style: const TextStyle(fontFamily: appMonospaceFamily),
),
),
),
),
],
@@ -262,9 +268,12 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
MarkdownPlain(text: final text) => TextSpan(text: text),
MarkdownInlineCode(text: final text) => TextSpan(
text: text,
// The same host-theme surface as a fenced block marks the run as
// code without a font, size or literal colour override.
style: TextStyle(backgroundColor: _codeFill(context, cupertino)),
// The same host-theme surface and monospace family as a fenced
// block mark the run as code; the size stays the surrounding text's.
style: TextStyle(
fontFamily: appMonospaceFamily,
backgroundColor: _codeFill(context, cupertino),
),
),
MarkdownStrong(spans: final inner) => TextSpan(
style: const TextStyle(fontWeight: FontWeight.bold),
@@ -14,6 +14,7 @@ class ChatTurnChip extends StatelessWidget {
required this.color,
required this.semanticsLabel,
required this.sheet,
this.ellipsizeLabel = false,
});
final Key chipKey;
@@ -23,6 +24,10 @@ class ChatTurnChip extends StatelessWidget {
final String semanticsLabel;
final Widget sheet;
/// Shrink a long label to one ellipsized line. Only for a chip whose parent
/// bounds its width (a turn footer's Wrap, an aligned row).
final bool ellipsizeLabel;
@override
Widget build(BuildContext context) {
final cupertino =
@@ -32,7 +37,10 @@ class ChatTurnChip extends StatelessWidget {
children: [
leading,
const SizedBox(width: 6),
Text(label, style: TextStyle(color: color, fontSize: 13)),
if (ellipsizeLabel)
Flexible(child: _label(maxLines: 1, overflow: TextOverflow.ellipsis))
else
_label(),
Icon(
cupertino ? CupertinoIcons.chevron_up : Icons.expand_less,
size: 14,
@@ -73,6 +81,13 @@ class ChatTurnChip extends StatelessWidget {
);
}
Text _label({int? maxLines, TextOverflow? overflow}) => Text(
label,
maxLines: maxLines,
overflow: overflow,
style: TextStyle(color: color, fontSize: 13),
);
Future<void> _open(BuildContext context, bool cupertino) {
if (cupertino) {
return showCupertinoModalPopup<void>(
@@ -1,5 +1,6 @@
import '../../pipelines/pipeline_format.dart';
import '../../../core/api_gateway.dart';
import 'run_tokens.dart';
const runStates = [
'queued',
@@ -268,6 +269,19 @@ List<JsonMap> sortRuns(List<JsonMap> runs, {String sort = 'newest_first'}) {
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
}
break;
case 'most_tokens':
// Runs with no reported tokens (older servers, no model stage) sort
// after every reported total; a partial total sorts by what was
// reported.
final ta = runTokenUsage(a)?.total, tb = runTokenUsage(b)?.total;
primary = cmp(ta == null ? 1 : 0, tb == null ? 1 : 0);
if (primary == 0 && ta != null && tb != null) {
primary = tb.compareTo(ta);
}
if (primary == 0) {
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
}
break;
case 'pipeline_name':
primary = '${a['name'] ?? ''}'.toLowerCase().compareTo(
'${b['name'] ?? ''}'.toLowerCase(),
@@ -0,0 +1,182 @@
import '../../../core/api_gateway.dart';
/// Reported token and cost usage of a run or one stage. No widgets here.
///
/// Every figure is what the server recorded from the harness: nothing is
/// estimated. A run total is partial when some stages that recorded usage
/// reported no token count, and it is then labelled as a lower bound (`≥`).
class TokenUsage {
const TokenUsage({
required this.total,
required this.partial,
this.input,
this.output,
this.cacheRead,
this.cost,
this.costPartial = false,
this.stages,
this.tokenStages,
});
/// The summed reported total.
final int total;
/// Some stages that recorded usage reported no token count.
final bool partial;
/// The input/output split, only when every counted stage reported it.
final int? input;
final int? output;
/// The cache-read share of [total], only when every counted stage reported
/// its cache components. Older rows never recorded them, so they have none.
final int? cacheRead;
/// The tokens that were not cache reads, when [cacheRead] is known.
int? get fresh => cacheRead == null ? null : total - cacheRead!;
/// The reported cost in USD, only when a positive cost was reported. Some
/// providers (subscription models) report a cost of zero or none at all;
/// that is "not reported", never a known zero.
final double? cost;
/// Some stages reported no cost, so [cost] is a lower bound.
final bool costPartial;
/// Run totals only: the stages that recorded usage, and those of them that
/// reported tokens.
final int? stages;
final int? tokenStages;
}
/// The run's reported token usage from its `usage` total, or null when the
/// server sent none (an older server's list, or a run with no model usage) or
/// no stage reported a token count.
TokenUsage? runTokenUsage(JsonMap run) {
final raw = run['usage'];
if (raw is! Map) return null;
final stages = _int(raw['stages']);
final tokenStages = _int(raw['tokens_known_stages']) ?? 0;
final total = _int(raw['tokens_total']);
if (tokenStages <= 0 || total == null) return null;
final costStages = _int(raw['cost_known_stages']) ?? 0;
final split = raw['split_known'] == true;
final cost = costStages > 0 ? _positive(raw['cost_usd']) : null;
return TokenUsage(
total: total,
partial: stages != null && tokenStages < stages,
// The server omits a zero in/out, so a known split makes absence zero.
input: split ? _int(raw['tokens_in']) ?? 0 : null,
output: split ? _int(raw['tokens_out']) ?? 0 : null,
cacheRead: _cacheRead(raw, total),
cost: cost,
costPartial: cost != null && stages != null && costStages < stages,
stages: stages,
tokenStages: tokenStages,
);
}
/// One stage's reported token usage from its step `usage`, or null when the
/// stage reported no token count.
TokenUsage? stageTokenUsage(JsonMap step) {
final raw = step['usage'];
if (raw is! Map || raw['tokens_known'] != true) return null;
final total = _int(raw['tokens_total']);
if (total == null) return null;
final split = raw['split_known'] == true;
return TokenUsage(
total: total,
partial: false,
input: split ? _int(raw['tokens_in']) ?? 0 : null,
output: split ? _int(raw['tokens_out']) ?? 0 : null,
cacheRead: _cacheRead(raw, total),
cost: raw['cost_known'] == true ? _positive(raw['cost_usd']) : null,
);
}
/// A compact token count: `950`, `1.2K`, `340K`, `22.4M`, `1.3B`.
///
/// Decimal multiples, one decimal below a hundred units, whole units above.
String formatTokenCount(int tokens) {
if (tokens < 1000) return '$tokens';
const units = ['K', 'M', 'B', 'T'];
var value = tokens / 1000;
var unit = 0;
while (value >= 1000 && unit < units.length - 1) {
value /= 1000;
unit++;
}
// Rounding 999.6K up would print "1000K"; promote it instead.
if (value >= 999.5 && unit < units.length - 1) {
value /= 1000;
unit++;
}
final text = value < 99.95
? value.toStringAsFixed(1).replaceFirst(RegExp(r'\.0$'), '')
: value.round().toString();
return '$text${units[unit]}';
}
/// The list row's compact label: `22.4M tokens`, or `≥22.4M tokens` when some
/// stages did not report a count.
String tokenUsageLabel(TokenUsage usage) =>
'${usage.partial ? '≥' : ''}${formatTokenCount(usage.total)} tokens';
/// A stage row's compact label: the total, the cached share when the stage
/// recorded its cache split, and the cost when a positive one was reported.
/// `20.1M tokens · 95% cached · $0.42`. A missing figure is omitted, never
/// shown as zero.
String stageTokenRowLabel(TokenUsage usage) {
final cacheRead = usage.cacheRead;
final cost = usage.cost;
return [
tokenUsageLabel(usage),
if (cacheRead != null && usage.total > 0)
'${(cacheRead * 100 / usage.total).round()}% cached',
if (cost != null) cost < 0.005 ? '<\$0.01' : '\$${cost.toStringAsFixed(2)}',
].join(' · ');
}
/// The detail's token value: the compact total, then fresh versus cached
/// when every stage reported its cache components, the in/out split when
/// reported, and how many stages reported when the total is partial.
/// `22.4M · 1.1M fresh, 21.3M cached · 900K in, 150K out`,
/// `≥9 · 1 of 2 stages reported`.
String tokenUsageDetail(TokenUsage usage) => [
'${usage.partial ? '≥' : ''}${formatTokenCount(usage.total)}',
if (usage.fresh != null)
'${formatTokenCount(usage.fresh!)} fresh, '
'${formatTokenCount(usage.cacheRead!)} cached',
if (usage.input != null && usage.output != null)
'${formatTokenCount(usage.input!)} in, '
'${formatTokenCount(usage.output!)} out',
if (usage.partial && usage.stages != null)
'${usage.tokenStages} of ${usage.stages} stages reported',
].join(' · ');
/// The wording for a cost no stage reported as a positive amount.
const costNotReported = 'Not reported';
/// The reported cost: `$1.75`, `$0.10`, `$0.0042` (four places below a cent),
/// `≥$0.10` when some stages reported no cost, and [costNotReported] when no
/// positive cost was reported.
String tokenUsageCost(TokenUsage usage) {
final cost = usage.cost;
if (cost == null) return costNotReported;
final text = cost >= 0.01 ? cost.toStringAsFixed(2) : cost.toStringAsFixed(4);
return '${usage.costPartial ? '≥' : ''}\$$text';
}
int? _int(dynamic value) =>
value is num && value.isFinite && value >= 0 ? value.round() : null;
double? _positive(dynamic value) =>
value is num && value.isFinite && value > 0 ? value.toDouble() : null;
/// The cache reads, only when the server marked the cache split complete and
/// the count fits inside the total.
int? _cacheRead(Map raw, int total) {
if (raw['cache_known'] != true) return null;
final read = _int(raw['cache_read']) ?? 0;
return read <= total ? read : null;
}
@@ -3,6 +3,7 @@ import 'dart:convert';
import '../../../core/api_gateway.dart';
import '../../pipelines/pipeline_format.dart' show formatDuration;
import '../domain/run_models.dart';
import '../domain/run_tokens.dart';
/// One labelled value in the run detail's metrics block.
typedef DetailMetric = ({String label, String value});
@@ -24,6 +25,7 @@ typedef DetailVisit = ({
String target,
String? duration,
DateTime? runningSince,
String? tokens,
});
/// The run's primary label: the stored title, else the pipeline name, and only
@@ -75,6 +77,7 @@ List<DetailMetric> detailUsageMetrics(dynamic raw) {
final tokenStages = _int(usage['tokens_known_stages']) ?? 0;
final costStages = _int(usage['cost_known_stages']) ?? 0;
final totalTokens = _int(usage['tokens_total']);
final cost = usage['cost_usd'] is num ? usage['cost_usd'] as num : null;
final splitKnown = usage['split_known'] == true && tokenStages > 0;
final rows = <DetailMetric>[
if (stages != null) (label: 'Stages', value: '$stages'),
@@ -94,11 +97,11 @@ List<DetailMetric> detailUsageMetrics(dynamic raw) {
),
(
label: 'Reported cost',
// cost_usd is omitted by the server when zero, so a known stage count
// makes an absent value a real $0.000000 rather than an unknown cost.
value: costStages == 0
? 'Unavailable'
: '\$${((usage['cost_usd'] as num?) ?? 0).toStringAsFixed(6)}',
// A cost of zero (or none) is what subscription models report even
// with a "known" cost: it is not reported, never a measured zero.
value: costStages == 0 || cost == null || cost <= 0
? 'Not reported'
: '\$${cost.toStringAsFixed(6)}',
),
];
if (stages != null && tokenStages < stages) {
@@ -151,6 +154,10 @@ List<DetailVisit> detailTimeline(dynamic steps) {
target: '${step['target'] ?? ''}'.trim(),
duration: _visitDuration(step),
runningSince: _visitRunningSince(step),
tokens: switch (stageTokenUsage(JsonMap.from(step))) {
final usage? => stageTokenRowLabel(usage),
null => null,
},
);
}(),
];
@@ -1,5 +1,7 @@
import '../../../core/api_gateway.dart';
import '../../pipelines/pipeline_format.dart';
import '../domain/run_deletion.dart' show formatByteSize, runSizeBytes;
import '../domain/run_tokens.dart';
import 'run_detail_visit_facts.dart';
/// One recorded Summary row: the web run summary's key/value shape.
@@ -14,9 +16,9 @@ typedef DetailSummaryRow = ({
bool block,
});
/// The run Summary's rows, in the web summary's order: Pipeline, Stage,
/// Workspace, Content hash, Started, Finished, Duration, Retry of and the
/// Diagnostic block.
/// The run Summary's rows: Pipeline, Stage, Workspace, Content hash, Started,
/// Finished, Duration, Size on disk, Tokens, Cost, Retry of and the Diagnostic
/// block.
///
/// Only values the server actually recorded are rows: a blank field is omitted
/// rather than drawn as an empty or invented placeholder, exactly as
@@ -56,6 +58,16 @@ List<DetailSummaryRow> detailSummaryRows(JsonMap run, {DateTime? now}) {
? now?.difference(since).inSeconds
: durationSeconds(_text(run['created_at']), _text(run['finished_at']));
if (seconds != null) add('Duration', formatDuration(seconds));
// What the run occupies on disk and what it spent, as the server measured
// and the harness reported; an unmeasured size or unreported usage has no
// row.
final bytes = runSizeBytes(run);
if (bytes != null) add('Size on disk', formatByteSize(bytes));
final usage = runTokenUsage(run);
if (usage != null) {
add('Tokens', tokenUsageDetail(usage));
add('Cost', tokenUsageCost(usage));
}
final retryOf = _number(run['retry_of'])?.toInt() ?? 0;
if (retryOf > 0) add('Retry of', 'run $retryOf');
// A diagnostic is a recorded document: its own whitespace is preserved, but a
@@ -17,7 +17,7 @@ import '../../../ui/adaptive/floating_bar_layout.dart';
/// the stored original prompt with its copy control and the collapsible Input
/// and Output sections.
///
/// The web run detail has no usage block, so no metrics are drawn here. A fact
/// The run's size and reported token usage are facts like the others. A fact
/// the server did not record is omitted rather than shown as an invented or
/// `Unavailable` row; only the Input/Output empty sentences remain, and only
/// when that section recorded nothing.
@@ -137,8 +137,8 @@ class RunTimelineRow extends StatelessWidget {
@override
Widget build(BuildContext context) {
final state = _state;
// The outcome chip leads the second line, then where the visit went; the
// duration is the row's time.
// The outcome chip leads the second line, then where the visit went and
// the tokens it reported; the duration is the row's time.
return AppListRow(
cupertino: cupertino,
selected: selected,
@@ -163,7 +163,14 @@ class RunTimelineRow extends StatelessWidget {
),
),
subtitleLeading: _outcome(context),
subtitle: visit.target.isEmpty ? null : Text('→ ${visit.target}'),
subtitle: visit.target.isEmpty && visit.tokens == null
? null
: Text(
[
if (visit.target.isNotEmpty) '→ ${visit.target}',
?visit.tokens,
].join(' · '),
),
);
}
}
@@ -1,6 +1,7 @@
import '../../../core/api_gateway.dart';
import '../../graph/domain/stage_definition.dart';
import '../../pipelines/pipeline_format.dart';
import '../domain/run_tokens.dart';
import 'run_detail_content.dart';
/// The exact empty wording for a visit's recorded Input and Output. They are
@@ -80,6 +81,11 @@ List<VisitFact> detailVisitFacts(JsonMap step) {
if (duration != null) facts.add((label: 'Duration', value: duration));
final model = detailVisitProviderModel(step);
if (model != null) facts.add((label: 'Provider/model', value: model));
final usage = stageTokenUsage(step);
if (usage != null) {
facts.add((label: 'Tokens', value: tokenUsageDetail(usage)));
facts.add((label: 'Cost', value: tokenUsageCost(usage)));
}
final target = _text(step['target']);
if (target != null) facts.add((label: 'Target', value: target));
return facts;
@@ -10,6 +10,7 @@ import '../../../ui/text/live_elapsed_builder.dart';
import '../../../ui/text/relative_time_label.dart';
import '../domain/run_deletion.dart';
import '../domain/run_models.dart';
import '../domain/run_tokens.dart';
import 'run_more_menu.dart';
/// One run in the list: a status avatar, title/time, and one muted fact
@@ -77,6 +78,9 @@ class RunListRow extends StatelessWidget {
final scheduled = run['scheduled'] == true;
final bytes = runSizeBytes(run);
final size = bytes == null ? null : formatByteSize(bytes);
// Reported tokens sit beside the size; an older server sends none.
final usage = runTokenUsage(run);
final tokens = usage == null ? null : tokenUsageLabel(usage);
final createdAt = DateTime.tryParse('${run['created_at'] ?? ''}');
String subtitle(DateTime now) {
final facts = runRowFacts(run, now);
@@ -86,6 +90,7 @@ class RunListRow extends StatelessWidget {
?facts.duration,
?facts.progress,
?size,
?tokens,
].join(' · ');
}
@@ -99,6 +104,7 @@ class RunListRow extends StatelessWidget {
if (run['executing'] == true && facts.progress != null) facts.progress!,
if (pipelineLabel == null && facts.duration != null) facts.duration!,
?size,
?tokens,
].join(' · ');
}
@@ -162,14 +162,7 @@ class RunsController extends ChangeNotifier {
// A cancel/decision reply changes lifecycle fields as well as title.
// Keep sparse/unknown summary fields, without copying bulky detail-only
// payloads into the held list or inventing missing values.
const detailOnly = {
'steps',
'input',
'output',
'graph',
'usage',
'notifications',
};
const detailOnly = {'steps', 'input', 'output', 'graph', 'notifications'};
runs = [...runs]
..[index] = {
...runs[index],
@@ -7,6 +7,7 @@ const runSorts = [
('newest_first', 'Newest first'),
('oldest_first', 'Oldest first'),
('largest_first', 'Largest first'),
('most_tokens', 'Most tokens'),
('longest_duration', 'Longest duration'),
('shortest_duration', 'Shortest duration'),
('pipeline_name', 'Pipeline name'),
@@ -25,8 +26,8 @@ const runTimeRanges = [
];
/// Sorts that list runs flat instead of under day headings: an order by
/// size has no meaningful day grouping.
const flatRunSorts = {'largest_first'};
/// size or token count has no meaningful day grouping.
const flatRunSorts = {'largest_first', 'most_tokens'};
/// The pipelines the loaded runs belong to, by name then id.
List<({int id, String name})> runFilterPipelines(RunsController controller) {
@@ -0,0 +1,139 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../ui/theme/app_font.dart';
import '../../ui/theme/app_font_controller.dart';
import 'settings_group.dart';
import 'settings_row.dart';
import 'settings_theme.dart';
const fontSectionTitle = 'Font';
const fontSectionFooter =
'Saved on this device only. Code keeps its monospace font.';
const fontLoadingText = 'Loading…';
const fontLoadFailedText = 'Could not load this font.';
const fontSaveFailedText = 'Not saved on this device; it applies until reload.';
ValueKey<String> settingsFontKey(AppFont font) =>
ValueKey<String>('settings-font-${font.id}');
/// The device's interface font: one row per option, each named in its own
/// face. Material rows are radio tiles, Cupertino rows carry the checkmark.
/// A choice is stored locally and applies as soon as its files load.
class SettingsFontSection extends StatefulWidget {
const SettingsFontSection({super.key, required this.controller});
final AppFontController controller;
@override
State<SettingsFontSection> createState() => _SettingsFontSectionState();
}
class _SettingsFontSectionState extends State<SettingsFontSection> {
@override
void initState() {
super.initState();
_preview();
}
@override
void didUpdateWidget(SettingsFontSection oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.controller != widget.controller) _preview();
}
/// Only the regular weight of each option, only once Settings is shown.
void _preview() {
for (final font in AppFont.values) {
unawaited(widget.controller.preview(font));
}
}
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: widget.controller,
builder: (context, _) => _group(context),
);
Widget _group(BuildContext context) {
final controller = widget.controller;
final cupertino = usesCupertinoControls(context);
final group = SettingsGroup(
title: fontSectionTitle,
footer: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
const Text(fontSectionFooter),
if (controller.saveFailed)
Text(
fontSaveFailedText,
style: TextStyle(color: settingsErrorColor(context)),
),
],
),
children: <Widget>[
for (final font in AppFont.values)
cupertino
? _cupertinoRow(context, font)
: RadioListTile<AppFont>(
key: settingsFontKey(font),
value: font,
title: _name(context, font),
subtitle: _status(context, font),
),
],
);
if (cupertino) return group;
return RadioGroup<AppFont>(
groupValue: controller.selected,
onChanged: (font) {
if (font != null) unawaited(controller.select(font));
},
child: group,
);
}
Widget _cupertinoRow(BuildContext context, AppFont font) => SettingsRow(
key: settingsFontKey(font),
title: _name(context, font),
subtitle: _status(context, font),
trailing: widget.controller.selected == font
? Icon(
CupertinoIcons.check_mark,
color: CupertinoTheme.of(context).primaryColor,
)
: null,
onTap: () => unawaited(widget.controller.select(font)),
);
/// The option's name in its own face once its regular weight has loaded;
/// the system face until then (and always for the system option).
Widget _name(BuildContext context, AppFont font) {
final family = widget.controller.canPreview(font)
? font.family ?? _systemFamily(context)
: _systemFamily(context);
return Text(font.label, style: TextStyle(fontFamily: family));
}
Widget? _status(BuildContext context, AppFont font) {
final controller = widget.controller;
if (controller.selected != font) return null;
if (controller.loadFailed == font) {
return Text(
fontLoadFailedText,
style: TextStyle(color: settingsErrorColor(context)),
);
}
return controller.loading ? const Text(fontLoadingText) : null;
}
}
/// The platform's own interface family (Roboto, or the Cupertino system
/// face), independent of the font the theme currently applies.
String? _systemFamily(BuildContext context) => usesCupertinoControls(context)
? const CupertinoTextThemeData().textStyle.fontFamily
: Typography.material2021(
platform: Theme.of(context).platform,
).black.bodyLarge?.fontFamily;
@@ -10,6 +10,8 @@ import '../attention/notify/notification_controller.dart';
import 'default_endpoint.dart';
import 'settings_controller.dart';
import 'settings_controls.dart';
import 'settings_font_section.dart';
import '../../ui/theme/app_font_controller.dart';
import 'settings_group.dart';
import 'settings_page_body.dart';
import 'settings_notifications_section.dart';
@@ -53,8 +55,12 @@ class SettingsScreen extends StatefulWidget {
this.servers,
this.deliveryService,
this.deliveryServiceController,
this.fonts,
});
/// The device's interface font; defaults to the app's shared controller.
final AppFontController? fonts;
/// Android background delivery; hidden when absent or unsupported.
final NotificationServiceBridge? deliveryService;
final NotificationServiceController? deliveryServiceController;
@@ -190,6 +196,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
controller: _controller,
workspaceField: _workspaceField,
),
// A device-local choice: a browser and a phone keep their own.
SettingsFontSection(
controller: widget.fonts ?? AppFontController.instance,
),
if (widget.notifications case final notifications?)
SettingsNotificationsSection(controller: notifications),
if (widget.deliveryService case final service? when service.supported)