Merge branch 'worktree-agent-aae8756320b8309f6'

# Conflicts:
#	app/lib/features/chat/conversation/chat_thread_view.dart
#	app/tool/perf/perf_fixture.dart
#	internal/protocol/message.go
#	internal/server/chat_hub.go
This commit is contained in:
2026-11-09 16:56:55 +00:00
54 changed files with 4192 additions and 22 deletions
@@ -0,0 +1,50 @@
import 'package:flutter/widgets.dart';
import '../../../../../core/api_gateway.dart';
import '../../../../artifacts/ui/artifact_html_view.dart';
import '../../../files/files_viewer.dart';
import 'chat_shown_file_card.dart';
import 'chat_shown_html_card.dart';
import 'chat_shown_link_image.dart';
import 'chat_shown_notify_row.dart';
/// One transcript row of kind `shown` ([withChatShownItems]): what the model
/// showed through a Pipelines tool, drawn by its recorded kind. [endpoint] is
/// the configured endpoint of the chat's own machine, so a file is read from
/// the machine that recorded it.
class ChatShownCard extends StatelessWidget {
const ChatShownCard({
super.key,
required this.row,
required this.endpoint,
this.viewer = const FilesViewer(),
this.htmlBuilder = defaultArtifactHtml,
});
final JsonMap row;
final String endpoint;
final FilesViewer viewer;
final ArtifactHtmlBuilder htmlBuilder;
@override
Widget build(BuildContext context) {
final raw = row['item'];
if (raw is! Map) return const SizedBox.shrink();
final item = Map<String, dynamic>.from(raw);
final path = '${item['path'] ?? ''}'.trim();
return switch ('${item['kind']}') {
'notify' => ChatShownNotifyRow(item: item),
'html' => ChatShownHtmlCard(item: item, htmlBuilder: htmlBuilder),
'image' when path.isEmpty => ChatShownLinkImage(
item: item,
openExternal: viewer.openExternal,
),
'file' || 'image' => ChatShownFileCard(
item: item,
endpoint: endpoint,
viewer: viewer,
),
_ => const SizedBox.shrink(),
};
}
}
@@ -0,0 +1,161 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../../../../../core/api_gateway.dart';
import '../../../../artifacts/domain/artifact_kind.dart';
import '../../../../artifacts/ui/artifact_viewer_fetch.dart';
import '../../../data/directory_listing.dart';
import '../../../files/files_icons.dart';
import '../../../files/files_models.dart';
import '../../../files/files_preview.dart';
import '../../../files/files_thumbnail_image.dart';
import '../../../files/files_urls.dart';
import '../../../files/files_viewer.dart';
import 'chat_shown_file_lines.dart';
import 'chat_shown_surface.dart';
/// The file a `file` (or path `image`) entry names on the chat's machine.
DirectoryEntry chatShownEntry(JsonMap item) {
final path = '${item['path'] ?? ''}';
var name = '${item['name'] ?? ''}'.trim();
if (name.isEmpty) {
name = path.split('/').lastWhere((s) => s.isNotEmpty, orElse: () => path);
}
final size = item['size'];
return DirectoryEntry(
name: name,
path: path,
isDir: false,
isGitRepo: false,
hidden: false,
size: size is num ? size.toInt() : null,
);
}
/// The largest logical height an inline shown image takes.
const double chatShownImageMaxHeight = 280;
/// A file the model showed: an image inline as a picture, any other file as a
/// card with its kind glyph, name and size, and the first lines of a text
/// document. Activating either opens the Files viewer (preview and download)
/// over the chat machine's `/files` endpoint ([endpoint]).
class ChatShownFileCard extends StatelessWidget {
const ChatShownFileCard({
super.key,
required this.item,
required this.endpoint,
this.viewer = const FilesViewer(),
});
final JsonMap item;
final String endpoint;
final FilesViewer viewer;
@override
Widget build(BuildContext context) {
final entry = chatShownEntry(item);
final urls = resolveFileUrls(endpoint, entry.path);
final image = isThumbnailFile(entry.name) && urls != null;
final kind = artifactKindLabel(
artifactKind(fileContentType(entry.name), entry.name),
);
final title = chatShownTitle(item, entry.name);
final subtitle = [
if (title != entry.name) entry.name,
kind,
fileSizeLabel(entry.size),
].join(' · ');
void open() => viewer.open(context, endpoint: endpoint, entry: entry);
final heading = Padding(
padding: const EdgeInsets.all(12),
child: ChatShownHeading(
title: title,
subtitle: subtitle,
leading: image
? null
: Icon(
fileIcon(entry),
size: 32,
color: chatShownSecondary(context),
),
),
);
final body = Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (image)
_ChatShownPicture(
view: urls.view,
name: entry.name,
fetch: viewer.fetch,
),
heading,
if (!image && urls != null)
ChatShownFileLines(
entry: entry,
view: urls.view,
fetch: viewer.fetch,
),
],
);
final cupertino = chatShownCupertino(context);
return ChatShownSurface(
label: image ? 'Shown image $title' : 'Shown file $title',
child: Semantics(
button: true,
onTap: open,
child: cupertino
? CupertinoButton(
padding: EdgeInsets.zero,
onPressed: open,
child: DefaultTextStyle.merge(
style: CupertinoTheme.of(context).textTheme.textStyle,
child: body,
),
)
: InkWell(onTap: open, child: body),
),
);
}
}
/// An image file's own bytes from the files endpoint, decoded at the width it
/// is drawn, with the image glyph while loading and when it fails.
class _ChatShownPicture extends StatelessWidget {
const _ChatShownPicture({
required this.view,
required this.name,
required this.fetch,
});
final Uri view;
final String name;
final ArtifactFetch fetch;
@override
Widget build(BuildContext context) {
final ratio = MediaQuery.devicePixelRatioOf(context).clamp(1, 3);
final ImageProvider source = kIsWeb
? NetworkImage(view.toString())
: FileThumbnailImage(view, fetch: fetch);
final glyph = SizedBox(
height: 96,
child: Center(
child: Icon(Icons.image_outlined, color: chatShownSecondary(context)),
),
);
return ConstrainedBox(
constraints: const BoxConstraints(maxHeight: chatShownImageMaxHeight),
child: Image(
image: ResizeImage.resizeIfNeeded((560 * ratio).round(), null, source),
fit: BoxFit.contain,
semanticLabel: name,
loadingBuilder: (_, child, progress) =>
progress == null ? child : glyph,
errorBuilder: (_, _, _) => glyph,
),
);
}
}
@@ -0,0 +1,105 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import '../../../../artifacts/domain/artifact_kind.dart';
import '../../../../artifacts/ui/artifact_viewer_fetch.dart';
import '../../../data/directory_listing.dart';
import '../../../files/files_preview.dart';
import 'chat_shown_surface.dart';
/// Text documents up to this size preview their first lines inline; larger
/// ones (and documents of unknown size) show only their card.
const int chatShownLinesMaxBytes = 256 << 10;
/// How many leading lines the inline preview shows.
const int chatShownPreviewLines = 6;
/// Whether [entry] is a text document the card previews by its first lines:
/// plain text, markdown and tables (the formats the Files viewer reads as
/// text).
bool chatShownPreviewsLines(DirectoryEntry entry) {
final size = entry.size;
if (size == null || size <= 0 || size > chatShownLinesMaxBytes) return false;
return switch (filePreviewFormat(fileContentType(entry.name), entry.name)) {
ArtifactPreviewFormat.text ||
ArtifactPreviewFormat.markdown ||
ArtifactPreviewFormat.table => true,
_ => false,
};
}
/// The first [chatShownPreviewLines] lines of a decoded document.
String chatShownLeadingLines(List<int> bytes) {
final text = utf8.decode(bytes, allowMalformed: true);
final lines = const LineSplitter().convert(text);
return lines.take(chatShownPreviewLines).join('\n').trimRight();
}
/// The first lines of a small text document, fetched once over the same
/// scoped fetch the viewer uses. Nothing is drawn for a document that is not
/// previewable or whose fetch fails: the card still names and opens it.
class ChatShownFileLines extends StatefulWidget {
const ChatShownFileLines({
super.key,
required this.entry,
required this.view,
required this.fetch,
});
final DirectoryEntry entry;
final Uri view;
final ArtifactFetch fetch;
@override
State<ChatShownFileLines> createState() => _ChatShownFileLinesState();
}
class _ChatShownFileLinesState extends State<ChatShownFileLines> {
Future<String?>? _lines;
@override
void initState() {
super.initState();
if (chatShownPreviewsLines(widget.entry)) _lines = _load();
}
Future<String?> _load() async {
try {
final result = await widget.fetch(widget.view);
if (!result.ok) return null;
final text = chatShownLeadingLines(result.bytes);
return text.isEmpty ? null : text;
} catch (_) {
return null;
}
}
@override
Widget build(BuildContext context) {
final lines = _lines;
if (lines == null) return const SizedBox.shrink();
return FutureBuilder<String?>(
future: lines,
builder: (context, snapshot) {
final text = snapshot.data;
if (text == null) return const SizedBox.shrink();
final style = Theme.of(context).textTheme.bodySmall?.copyWith(
fontFamily: 'monospace',
color: chatShownSecondary(context),
);
return Padding(
key: const Key('chat-shown-file-lines'),
padding: const EdgeInsetsDirectional.fromSTEB(12, 0, 12, 12),
child: Text(
text,
style: style,
maxLines: chatShownPreviewLines,
overflow: TextOverflow.ellipsis,
softWrap: false,
),
);
},
);
}
}
@@ -0,0 +1,188 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../../core/api_gateway.dart';
import '../../../../../ui/adaptive/host.dart';
import '../../../../artifacts/ui/artifact_fullscreen.dart';
import '../../../../artifacts/ui/artifact_html_view.dart';
import '../../../../artifacts/ui/artifact_viewer_scaffold.dart';
import '../../../files/files_models.dart';
import 'chat_shown_surface.dart';
/// The inline frame's height when the model gave no hint.
const double chatShownHtmlDefaultHeight = 320;
/// The inline frame's height: the model's hint held between 120 and 600.
double chatShownHtmlHeight(JsonMap item) {
final hint = item['height_hint'];
if (hint is! num || hint <= 0) return chatShownHtmlDefaultHeight;
return hint.toDouble().clamp(120, 600);
}
/// A view the model authored (HTML or SVG), drawn inline by the same inert
/// renderer as an HTML artifact preview: on the web an iframe whose sandbox
/// is only `allow-popups allow-popups-to-escape-sandbox` (no scripts, no
/// same origin, no forms, no navigation of the app); on Android and iOS a web
/// view with JavaScript off that refuses navigation. Open shows it full
/// screen. A body the server no longer retains says so instead.
class ChatShownHtmlCard extends StatelessWidget {
const ChatShownHtmlCard({
super.key,
required this.item,
this.htmlBuilder = defaultArtifactHtml,
});
final JsonMap item;
final ArtifactHtmlBuilder htmlBuilder;
@override
Widget build(BuildContext context) {
final title = chatShownTitle(item, 'View');
final html = '${item['html'] ?? ''}';
final expired = item['expired'] == true || html.isEmpty;
final bytes = item['html_bytes'];
final size = bytes is num ? fileSizeLabel(bytes.toInt()) : null;
final cupertino = chatShownCupertino(context);
final open = expired
? null
: () => Navigator.of(context, rootNavigator: true).push(
artifactFullscreenRoute(
cupertino: usesCupertinoHost(context),
builder: (_) => ChatShownHtmlPage(
title: title,
html: html,
htmlBuilder: htmlBuilder,
),
),
);
final action = open == null
? null
: cupertino
? CupertinoButton(
key: const Key('chat-shown-html-open'),
padding: const EdgeInsets.symmetric(horizontal: 8),
onPressed: open,
child: const Text('Open'),
)
: TextButton(
key: const Key('chat-shown-html-open'),
onPressed: open,
child: const Text('Open'),
);
final heading = Padding(
padding: const EdgeInsetsDirectional.fromSTEB(12, 8, 4, 8),
child: ChatShownHeading(
title: title,
subtitle: expired
? 'This view is no longer retained'
: ['View', ?size].join(' · '),
leading: Icon(
cupertino ? CupertinoIcons.chart_bar_square : Icons.web_asset,
color: chatShownSecondary(context),
),
trailing: action,
),
);
return ChatShownSurface(
label: 'Shown view $title',
maxWidth: 720,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
heading,
if (!expired)
// Inset from the card's edge: a web platform view is not clipped
// by the card's rounded outline and would draw over it.
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(8, 0, 8, 8),
child: SizedBox(
height: chatShownHtmlHeight(item),
child: MediaQuery.removePadding(
context: context,
removeTop: true,
removeBottom: true,
child: _SettledFrame(
builder: (context) => htmlBuilder(context, html),
),
),
),
),
],
),
);
}
}
/// Builds [builder] from the row's second frame on. The transcript's lazy
/// list can lay a row out and drop it within one frame; a platform view
/// (the web frame) laid out that way fails its post-frame position read, so
/// the frame is only created for a row that is still mounted a frame later.
class _SettledFrame extends StatefulWidget {
const _SettledFrame({required this.builder});
final WidgetBuilder builder;
@override
State<_SettledFrame> createState() => _SettledFrameState();
}
class _SettledFrameState extends State<_SettledFrame> {
bool _settled = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) setState(() => _settled = true);
});
}
@override
Widget build(BuildContext context) =>
_settled ? widget.builder(context) : const SizedBox.expand();
}
/// The full-screen view of a shown HTML entry: the platform's Close, the
/// title, and on the web the zoom actions the sandboxed frame needs.
class ChatShownHtmlPage extends StatefulWidget {
const ChatShownHtmlPage({
super.key,
required this.title,
required this.html,
this.htmlBuilder = defaultArtifactHtml,
});
final String title;
final String html;
final ArtifactHtmlBuilder htmlBuilder;
@override
State<ChatShownHtmlPage> createState() => _ChatShownHtmlPageState();
}
class _ChatShownHtmlPageState extends State<ChatShownHtmlPage> {
final ValueNotifier<double> _zoom = ValueNotifier<double>(1);
@override
void dispose() {
_zoom.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => ValueListenableBuilder<double>(
valueListenable: _zoom,
builder: (context, _, _) => ArtifactViewerScaffold(
title: widget.title,
subtitle: null,
actions: artifactHtmlZoomButtons ? artifactHtmlZoomActions(_zoom) : [],
body: ArtifactFullscreenScope(
htmlZoom: _zoom,
child: Builder(
builder: (context) => widget.htmlBuilder(context, widget.html),
),
),
),
);
}
@@ -0,0 +1,100 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../../core/api_gateway.dart';
import '../../../../artifacts/ui/artifact_external_open.dart';
import 'chat_shown_file_card.dart';
import 'chat_shown_surface.dart';
/// The https address of a web `image` entry, or null for any other scheme.
Uri? chatShownImageUrl(JsonMap item) {
final uri = Uri.tryParse('${item['url'] ?? ''}'.trim());
if (uri == null || uri.scheme != 'https' || uri.host.isEmpty) return null;
return uri;
}
/// A web image the model showed: the picture inline with its address under
/// it. The picture is fetched without credentials (the default network image
/// fetch; on the web that needs the host to allow cross-origin reads, and a
/// refused fetch shows the glyph and the link). Activating it opens the
/// address outside the app.
class ChatShownLinkImage extends StatelessWidget {
const ChatShownLinkImage({
super.key,
required this.item,
this.openExternal = openArtifactExternally,
});
final JsonMap item;
final ArtifactExternalOpen openExternal;
@override
Widget build(BuildContext context) {
final url = chatShownImageUrl(item);
final address = '${item['url'] ?? ''}'.trim();
final title = chatShownTitle(item, url?.host ?? 'Image');
final alt = '${item['alt'] ?? ''}'.trim();
final glyph = SizedBox(
height: 96,
child: Center(
child: Icon(
Icons.broken_image_outlined,
color: chatShownSecondary(context),
),
),
);
final picture = url == null
? glyph
: ConstrainedBox(
constraints: const BoxConstraints(
maxHeight: chatShownImageMaxHeight,
),
child: Image.network(
url.toString(),
fit: BoxFit.contain,
semanticLabel: alt.isEmpty ? title : alt,
loadingBuilder: (_, child, progress) =>
progress == null ? child : glyph,
errorBuilder: (_, _, _) => glyph,
),
);
final body = Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
picture,
Padding(
padding: const EdgeInsets.all(12),
child: ChatShownHeading(
title: title,
subtitle: url == null ? 'Not an https address: $address' : address,
),
),
],
);
void open() {
if (url != null) openExternal(url);
}
return ChatShownSurface(
label: 'Shown image $title',
child: url == null
? body
: Semantics(
button: true,
link: true,
onTap: open,
child: chatShownCupertino(context)
? CupertinoButton(
padding: EdgeInsets.zero,
onPressed: open,
child: DefaultTextStyle.merge(
style: CupertinoTheme.of(context).textTheme.textStyle,
child: body,
),
)
: InkWell(onTap: open, child: body),
),
);
}
}
@@ -0,0 +1,84 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../../core/api_gateway.dart';
import 'chat_shown_surface.dart';
/// What a `notify` entry says: the phone notification was accepted for
/// delivery, or why it was not sent.
String chatShownNotifyText(JsonMap item) {
final title = chatShownTitle(item, 'notification');
if (item['delivered'] == true) return 'Notified your phone: $title';
final detail = '${item['detail'] ?? ''}'.trim();
return detail.isEmpty
? 'Phone notification not sent: $title'
: 'Phone notification not sent: $title — $detail';
}
/// One secondary line in the agent's column for a `notify` entry, with the
/// notification's message under it.
class ChatShownNotifyRow extends StatelessWidget {
const ChatShownNotifyRow({super.key, required this.item});
final JsonMap item;
@override
Widget build(BuildContext context) {
final cupertino = chatShownCupertino(context);
final delivered = item['delivered'] == true;
final secondary = chatShownSecondary(context);
final color = delivered
? secondary
: (cupertino
? CupertinoColors.systemRed.resolveFrom(context)
: Theme.of(context).colorScheme.error);
final base = cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodySmall;
final text = chatShownNotifyText(item);
final message = '${item['message'] ?? ''}'.trim();
final icon = delivered
? (cupertino ? CupertinoIcons.bell : Icons.notifications_outlined)
: (cupertino
? CupertinoIcons.bell_slash
: Icons.notifications_off_outlined);
return Semantics(
container: true,
label: text,
value: message,
child: ExcludeSemantics(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsetsDirectional.only(end: 8),
child: Icon(
icon,
size: base?.fontSize == null ? 16 : base!.fontSize! * 1.2,
color: color,
),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(text, style: base?.copyWith(color: color)),
if (message.isNotEmpty)
Text(
message,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: base?.copyWith(color: secondary),
),
],
),
),
],
),
),
),
);
}
}
@@ -0,0 +1,142 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../../core/api_gateway.dart';
import '../../sessions/chat_adaptive.dart';
/// Whether the transcript draws Cupertino controls.
bool chatShownCupertino(BuildContext context) =>
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
/// The secondary text colour of either host.
Color chatShownSecondary(BuildContext context) => chatShownCupertino(context)
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
/// The item's title, else [fallback].
String chatShownTitle(JsonMap item, String fallback) {
final title = '${item['title'] ?? ''}'.trim();
return title.isEmpty ? fallback : title;
}
/// The outlined card a shown entry sits in, on the agent's side of the
/// transcript, at most [maxWidth] wide.
class ChatShownSurface extends StatelessWidget {
const ChatShownSurface({
super.key,
required this.label,
required this.child,
this.maxWidth = 560,
});
/// The entry's accessible name ("Shown file", "Shown view", ...).
final String label;
final Widget child;
final double maxWidth;
@override
Widget build(BuildContext context) {
final cupertino = chatShownCupertino(context);
const radius = BorderRadius.all(Radius.circular(12));
final card = cupertino
? DecoratedBox(
decoration: BoxDecoration(
color: CupertinoColors.secondarySystemGroupedBackground
.resolveFrom(context),
border: Border.all(
color: CupertinoColors.separator.resolveFrom(context),
),
borderRadius: radius,
),
child: ClipRRect(borderRadius: radius, child: child),
)
: Card.outlined(
margin: EdgeInsets.zero,
clipBehavior: Clip.antiAlias,
child: child,
);
return Semantics(
container: true,
explicitChildNodes: true,
label: label,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Align(
alignment: AlignmentDirectional.centerStart,
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: maxWidth),
child: card,
),
),
),
);
}
}
/// A title line with an optional subtitle, leading glyph and trailing action.
class ChatShownHeading extends StatelessWidget {
const ChatShownHeading({
super.key,
required this.title,
this.subtitle,
this.leading,
this.trailing,
});
final String title;
final String? subtitle;
final Widget? leading;
final Widget? trailing;
@override
Widget build(BuildContext context) {
final cupertino = chatShownCupertino(context);
final titleStyle = cupertino
? CupertinoTheme.of(
context,
).textTheme.textStyle.copyWith(fontWeight: FontWeight.w600)
: Theme.of(context).textTheme.titleSmall;
// Cupertino has no caption role; the body style at a smaller size keeps
// the line secondary while still following text scaling.
final cupertinoBody = CupertinoTheme.of(context).textTheme.textStyle;
final subtitleStyle =
(cupertino
? cupertinoBody.copyWith(
fontSize: (cupertinoBody.fontSize ?? 17) * 0.8,
)
: Theme.of(context).textTheme.bodySmall)
?.copyWith(color: chatShownSecondary(context));
final sub = subtitle;
return Row(
children: [
if (leading != null)
Padding(
padding: const EdgeInsetsDirectional.only(end: 12),
child: leading,
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
title,
style: titleStyle,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
if (sub != null && sub.isNotEmpty)
Text(
sub,
style: subtitleStyle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
),
?trailing,
],
);
}
}