feat(chat): show sent images as thumbnails with a full-screen viewer

Operator-attached images render as rounded thumbnails above the user
bubble and open a zoomable Material/Cupertino viewer. Inline data: URIs
decode locally; file:// attachment-store URIs load through the new
chat_attachment_image websocket request, which serves only regular image
files directly inside the private attachment store (os.Root, <= 4 MiB,
sniffed raster types). Missing files show an 'Image no longer available'
placeholder; other files keep the file row.
This commit is contained in:
2026-10-30 20:53:03 +00:00
parent 44b2cff347
commit 8c421952db
18 changed files with 1397 additions and 29 deletions
@@ -0,0 +1,57 @@
import 'package:flutter/widgets.dart';
import '../../../../core/api_gateway.dart';
import '../../data/chat_attachment_images.dart';
import '../../domain/chat_attachment_image.dart';
import 'chat_attachment_thumbnail.dart';
/// Whether a file part draws as a thumbnail: a raster image whose bytes the
/// client can reach (inline, the server's attachment store or a fresh upload).
bool chatPartIsThumbnail(JsonMap part) =>
chatPartImageMime(part) != null &&
chatImageSourceOf('${part['uri'] ?? ''}'.trim()) != null;
/// The operator's attached images above their message, end-aligned like the
/// turn itself, wrapping onto further lines on a narrow pane.
class ChatAttachmentGallery extends StatelessWidget {
const ChatAttachmentGallery({
super.key,
required this.parts,
required this.images,
required this.cupertino,
});
/// File parts for which [chatPartIsThumbnail] holds.
final List<JsonMap> parts;
final ChatAttachmentImages images;
final bool cupertino;
@override
Widget build(BuildContext context) => Wrap(
key: const Key('chat-attachment-gallery'),
alignment: WrapAlignment.end,
spacing: 8,
runSpacing: 8,
children: [
for (final (index, part) in parts.indexed)
ChatAttachmentThumbnail(
key: ValueKey<String>('chat-attachment-image-$index'),
name: chatAttachmentPartName(part),
uri: '${part['uri'] ?? ''}'.trim(),
images: images,
cupertino: cupertino,
),
],
);
}
/// The web's attachment name rule: its own name, else the URI basename, else
/// `file`. A `data:` URI has no useful basename, so it reads `image`.
String chatAttachmentPartName(JsonMap part) {
final name = '${part['name'] ?? ''}'.trim();
if (name.isNotEmpty) return name;
final uri = '${part['uri'] ?? ''}'.trim();
if (uri.startsWith('data:')) return 'image';
final basename = uri.split('/').last.trim();
return basename.isEmpty ? 'file' : basename;
}
@@ -0,0 +1,202 @@
import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../data/chat_attachment_images.dart';
import 'chat_image_viewer.dart';
/// The largest edge a sent image's thumbnail takes in the transcript.
const double chatThumbnailMaxWidth = 200;
const double chatThumbnailMaxHeight = 240;
const BorderRadius _radius = BorderRadius.all(Radius.circular(12));
/// One image the operator attached, drawn as a rounded thumbnail that opens
/// [ChatImageViewer]. Bytes load lazily through [images] and stay cached there;
/// a file the server no longer has becomes a small labelled placeholder.
class ChatAttachmentThumbnail extends StatefulWidget {
const ChatAttachmentThumbnail({
super.key,
required this.name,
required this.uri,
required this.images,
required this.cupertino,
});
final String name;
final String uri;
final ChatAttachmentImages images;
final bool cupertino;
@override
State<ChatAttachmentThumbnail> createState() =>
_ChatAttachmentThumbnailState();
}
class _ChatAttachmentThumbnailState extends State<ChatAttachmentThumbnail> {
Uint8List? _bytes;
String? _failure;
@override
void initState() {
super.initState();
_resolve();
}
@override
void didUpdateWidget(covariant ChatAttachmentThumbnail oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.uri != widget.uri || oldWidget.images != widget.images) {
_resolve();
}
}
void _resolve() {
final uri = widget.uri;
_bytes = widget.images.ready(uri);
_failure = widget.images.failure(uri);
if (_bytes != null || _failure != null) return;
widget.images
.load(uri)
.then(
(bytes) {
if (mounted && widget.uri == uri) setState(() => _bytes = bytes);
},
onError: (Object error) {
if (mounted && widget.uri == uri) {
setState(() => _failure = '$error');
}
},
);
}
@override
Widget build(BuildContext context) {
final bytes = _bytes;
if (bytes != null) return _thumbnail(context, bytes);
final failure = _failure;
if (failure != null) return _placeholder(context, failure);
return Semantics(
label: '${widget.name}, loading',
child: _pending(context),
);
}
/// A quiet surface square while loaded bytes decode, which is brief.
Widget _decoding(BuildContext context) => SizedBox.square(
dimension: 96,
child: ColoredBox(
color: widget.cupertino
? CupertinoColors.systemGrey5.resolveFrom(context)
: Theme.of(context).colorScheme.surfaceContainerHighest,
),
);
/// A square the thumbnail occupies while its bytes load from the server.
Widget _pending(BuildContext context) => SizedBox.square(
key: const Key('chat-attachment-thumbnail-loading'),
dimension: 96,
child: Center(
child: widget.cupertino
? const CupertinoActivityIndicator()
: const CircularProgressIndicator.adaptive(),
),
);
Widget _thumbnail(BuildContext context, Uint8List bytes) {
final ratio = MediaQuery.devicePixelRatioOf(context);
final image = ClipRRect(
borderRadius: _radius,
child: Image(
key: const Key('chat-attachment-thumbnail-image'),
// Decode at the thumbnail's size, not the photo's, while scrolling.
image: ResizeImage(
MemoryImage(bytes),
width: (chatThumbnailMaxWidth * ratio).round(),
height: (chatThumbnailMaxHeight * ratio).round(),
policy: ResizeImagePolicy.fit,
allowUpscaling: false,
),
fit: BoxFit.contain,
gaplessPlayback: true,
// Until the first frame decodes, hold the loading square's place so
// the row does not collapse and the control can still be tapped.
frameBuilder: (context, child, frame, synchronous) =>
frame == null && !synchronous ? _decoding(context) : child,
errorBuilder: (context, _, _) =>
_placeholder(context, 'Image could not be read'),
),
);
void open() => openChatImageViewer(
context,
name: widget.name,
bytes: bytes,
cupertino: widget.cupertino,
);
final constrained = ConstrainedBox(
constraints: const BoxConstraints(
maxWidth: chatThumbnailMaxWidth,
maxHeight: chatThumbnailMaxHeight,
),
child: image,
);
return Semantics(
button: true,
image: true,
label: widget.name,
excludeSemantics: true,
onTap: open,
child: widget.cupertino
? CupertinoButton(
key: const Key('chat-attachment-thumbnail'),
padding: EdgeInsets.zero,
minimumSize: Size.zero,
onPressed: open,
child: constrained,
)
: Material(
type: MaterialType.transparency,
child: InkWell(
key: const Key('chat-attachment-thumbnail'),
borderRadius: _radius,
onTap: open,
child: constrained,
),
),
);
}
Widget _placeholder(BuildContext context, String reason) {
final secondary = widget.cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
return Semantics(
key: const Key('chat-attachment-thumbnail-unavailable'),
label: '${widget.name}, $reason',
excludeSemantics: true,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: chatThumbnailMaxWidth),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
widget.cupertino
? CupertinoIcons.photo
: Icons.broken_image_outlined,
color: secondary,
),
const SizedBox(width: 8),
Flexible(
child: Text(
reason,
style: DefaultTextStyle.of(
context,
).style.copyWith(color: secondary),
),
),
],
),
),
);
}
}
@@ -0,0 +1,90 @@
import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
/// The accessible name and visible label of the viewer's close control.
const String chatImageViewerClose = 'Close';
/// One attached image full screen: pinch or scroll to zoom, drag to pan once
/// zoomed, and the host's own close control in the navigation bar.
class ChatImageViewer extends StatelessWidget {
const ChatImageViewer({
super.key,
required this.name,
required this.bytes,
required this.cupertino,
});
final String name;
final Uint8List bytes;
final bool cupertino;
@override
Widget build(BuildContext context) {
final body = SafeArea(
child: InteractiveViewer(
key: const Key('chat-image-viewer-zoom'),
maxScale: 8,
child: Center(
child: Semantics(
image: true,
label: name,
child: Image.memory(
bytes,
key: const Key('chat-image-viewer-image'),
fit: BoxFit.contain,
gaplessPlayback: true,
errorBuilder: (context, _, _) => Icon(
cupertino ? CupertinoIcons.photo : Icons.broken_image_outlined,
),
),
),
),
),
);
void close() => Navigator.of(context).maybePop();
if (cupertino) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
automaticallyImplyLeading: false,
middle: Text(name, overflow: TextOverflow.ellipsis),
leading: CupertinoButton(
key: const Key('chat-image-viewer-close'),
padding: EdgeInsets.zero,
onPressed: close,
child: const Text(chatImageViewerClose),
),
),
child: body,
);
}
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
leading: IconButton(
key: const Key('chat-image-viewer-close'),
tooltip: chatImageViewerClose,
onPressed: close,
icon: const Icon(Icons.close),
),
title: Text(name, overflow: TextOverflow.ellipsis),
),
body: body,
);
}
}
/// Pushes [ChatImageViewer] with the host's full-screen dialog transition.
Future<void> openChatImageViewer(
BuildContext context, {
required String name,
required Uint8List bytes,
required bool cupertino,
}) {
final page = ChatImageViewer(name: name, bytes: bytes, cupertino: cupertino);
final route = cupertino
? CupertinoPageRoute<void>(fullscreenDialog: true, builder: (_) => page)
: MaterialPageRoute<void>(fullscreenDialog: true, builder: (_) => page);
return Navigator.of(context).push(route);
}
@@ -4,7 +4,9 @@ import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../data/chat_attachment_images.dart';
import '../sessions/chat_adaptive.dart';
import 'chat_attachment_gallery.dart';
import '../../domain/chat_tool_calls.dart';
import 'chat_copy_button.dart';
import 'chat_message_bubble.dart';
@@ -22,11 +24,18 @@ class ChatMessageView extends StatelessWidget {
required this.row,
this.textBuilder,
this.footer = const [],
this.images,
});
final JsonMap row;
final ChatMessageTextBuilder? textBuilder;
/// Loads attached images for the operator's turn; without one, only images
/// the history carries inline can draw.
final ChatAttachmentImages? images;
static final ChatAttachmentImages _inlineImages = ChatAttachmentImages(null);
/// The turn's settled permissions, independent of passive activity details.
final List<Widget> footer;
@@ -69,7 +78,7 @@ class ChatMessageView extends StatelessWidget {
: 720,
),
child: user
? ChatUserBubble(cupertino: cupertino, child: body)
? _userTurn(cupertino, content, body)
: _agentTurn(
context,
content,
@@ -89,10 +98,38 @@ class ChatMessageView extends StatelessWidget {
bool _isCupertino(BuildContext context) =>
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
JsonMap get _userMessage => row['message'] is Map
? Map<String, dynamic>.from(row['message'] as Map)
: row;
/// Attached images sit above the operator's bubble, as their own thumbnails;
/// an images-only turn draws no empty bubble.
Widget _userTurn(bool cupertino, List<Widget> content, Widget body) {
final thumbnails = [
for (final part in _partsOf(_userMessage))
if (_isFile(part) && chatPartIsThumbnail(part)) part,
];
if (thumbnails.isEmpty) {
return ChatUserBubble(cupertino: cupertino, child: body);
}
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
ChatAttachmentGallery(
parts: thumbnails,
images: images ?? _inlineImages,
cupertino: cupertino,
),
if (content.isNotEmpty) const SizedBox(height: 6),
if (content.isNotEmpty)
ChatUserBubble(cupertino: cupertino, child: body),
],
);
}
List<Widget> _userParts(BuildContext context) {
final message = row['message'] is Map
? Map<String, dynamic>.from(row['message'] as Map)
: row;
final message = _userMessage;
final parts = _partsOf(message);
final text = parts
.where((part) => part['type'] == null || part['type'] == 'text')
@@ -100,7 +137,8 @@ class ChatMessageView extends StatelessWidget {
.join('\n');
final widgets = <Widget>[
if (text.trim().isNotEmpty) SelectableText(text),
for (final part in parts.where(_isFile)) _attachment(context, part),
for (final part in parts.where(_isFile))
if (!chatPartIsThumbnail(part)) _attachment(context, part),
for (final part in parts)
if (part['type'] != 'text' &&
!_isFile(part) &&
@@ -262,11 +300,7 @@ class ChatMessageView extends StatelessWidget {
padding: const EdgeInsets.only(right: 8),
child: Icon(cupertino ? CupertinoIcons.paperclip : Icons.attach_file),
),
Expanded(
child: SelectableText(
_attachmentDisplayName(part['name'], part['uri']),
),
),
Expanded(child: SelectableText(chatAttachmentPartName(part))),
],
);
}
@@ -288,11 +322,3 @@ List<JsonMap> _partsOf(Map<dynamic, dynamic> source) {
bool _isFile(JsonMap part) =>
part['type'] == 'file' &&
'${part['name'] ?? ''}${part['uri'] ?? ''}'.trim().isNotEmpty;
/// The web's attachment name rule: its own name, else the URI basename, else
/// `file`, so an attachment never shows an empty label.
String _attachmentDisplayName(Object? name, Object? uri) {
final shown = '${name ?? ''}'.trim();
final basename = '${uri ?? ''}'.split('/').last.trim();
return shown.isNotEmpty ? shown : (basename.isEmpty ? 'file' : basename);
}