Merge branch 'worktree-agent-ae487572986d7a387' into integrate/chat-ntfy-attachments

This commit is contained in:
2026-10-30 21:05:32 +00:00
18 changed files with 1397 additions and 29 deletions
@@ -9,6 +9,7 @@ import 'package:flutter/services.dart';
import '../../../core/api_gateway.dart';
import '../../../core/transport/pipelines_client.dart';
import '../data/chat_attachment_images.dart';
import '../data/upload/chat_upload.dart';
import '../domain/chat_attachment_draft.dart';
import '../domain/chat_attachment_picker.dart';
@@ -94,8 +95,13 @@ class ChatComposerBar extends StatefulWidget {
this.backgroundTasks,
this.placeholder = chatComposerPlaceholder,
this.enterSends,
this.images,
});
/// The transcript's image cache, told about uploaded files so the sent turn
/// shows them without a round trip.
final ChatAttachmentImages? images;
/// Overrides [chatEnterSends] for this composer; null follows the host.
final bool? enterSends;
@@ -472,8 +478,18 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
parts = await chatAttachmentUploadParts(
_attachments,
read: _readAttachment,
upload: (attachment, bytes) async => _uploaded[attachment] ??=
await uploadChatAttachment(endpoint, attachment, bytes),
upload: (attachment, bytes) async {
final stored = _uploaded[attachment] ??= await uploadChatAttachment(
endpoint,
attachment,
bytes,
);
// The sent turn draws these bytes instead of fetching them back.
if (attachment.mime.toLowerCase().startsWith('image/')) {
widget.images?.rememberUpload(stored, bytes);
}
return stored;
},
);
}
} on ChatAttachmentWireException catch (error) {
@@ -6,8 +6,10 @@ import 'package:flutter/rendering.dart';
import '../../../core/api_gateway.dart';
import '../../../shell/shell_bar.dart';
import '../data/chat_attachment_images.dart';
import '../data/chat_repository.dart';
import '../domain/chat_activity_detail.dart';
import '../domain/chat_attachment_image.dart';
import '../domain/chat_notice.dart';
import '../domain/chat_attachment_picker.dart';
import '../domain/chat_transcript.dart';
@@ -129,6 +131,9 @@ class _ChatThreadViewState extends State<ChatThreadView> {
late ChatComposerController _composer = _attachComposer();
late ChatRowKeys _rowKeys = ChatRowKeys();
/// Sent images' bytes for this server, cached across rebuilds and scrolling.
late ChatAttachmentImages _images = ChatAttachmentImages(widget.gateway);
/// Local notices the operator hid; cleared when the conversation or socket
/// changes so a reconnect never keeps a stale dismissal.
ChatNoticeDismissals _dismissals = ChatNoticeDismissals();
@@ -253,7 +258,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
{
'type': 'file',
'name': attachment['name'],
'uri': attachment['name'],
'uri': chatOptimisticAttachmentUri(attachment),
'mime': attachment['mime'],
},
],
@@ -352,6 +357,8 @@ class _ChatThreadViewState extends State<ChatThreadView> {
// A transcript from another server is not this one's to keep.
if (oldWidget.gateway == widget.gateway) {
_saveTranscript(oldWidget.transcripts, oldWidget.sessionId);
} else {
_images = ChatAttachmentImages(widget.gateway);
}
_controller.dispose();
_composer.dispose();
@@ -901,6 +908,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
running: _controller.running,
commands: _commandActions(),
picker: widget.attachmentPicker,
images: _images,
placeholder: chatComposerPlaceholderFor(
'${widget.session?['directory'] ?? ''}',
),
@@ -1026,6 +1034,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
row: row,
textBuilder: chatMarkdownText,
footer: chips,
images: _images,
);
}
@@ -0,0 +1,150 @@
import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:typed_data';
import '../../../core/api_gateway.dart';
import '../../../core/transport/connection_state.dart';
import '../domain/chat_attachment_image.dart';
/// Why a transcript image cannot be drawn, in words the placeholder shows.
class ChatAttachmentImageException implements Exception {
const ChatAttachmentImageException(this.message);
final String message;
@override
String toString() => message;
}
/// The placeholder's wording when the server no longer has the file.
const String chatImageGoneMessage = 'Image no longer available';
/// Loads and caches the bytes of images attached to sent chat messages, keyed
/// by the part's URI. A transcript row asks lazily when it builds; scrolling
/// back reuses the bytes instead of fetching again. Decoded bytes are bounded
/// by [maxCachedBytes], least recently used first out.
class ChatAttachmentImages {
ChatAttachmentImages(this.gateway, {this.maxCachedBytes = 48 << 20});
/// Null for a host with no server (only `data:` images draw).
final ApiGateway? gateway;
final int maxCachedBytes;
final LinkedHashMap<String, Uint8List> _ready = LinkedHashMap();
final Map<String, Future<Uint8List>> _pending = {};
final Map<String, String> _failed = {};
final Map<String, Uint8List> _uploads = {};
int _cachedBytes = 0;
/// Bytes already loaded for [uri], so a rebuilt row draws without a frame
/// of loading state.
Uint8List? ready(String uri) {
final bytes = _ready.remove(uri);
if (bytes != null) _ready[uri] = bytes;
return bytes;
}
/// The settled reason [uri] cannot be drawn, if a previous load failed.
String? failure(String uri) => _failed[uri];
/// Records the composer's own bytes for a file it uploaded ahead of a
/// prompt, so the sent turn draws them before and after the server echo.
void rememberUpload(String storedName, Uint8List bytes) {
if (storedName.isEmpty || bytes.isEmpty) return;
_uploads[storedName] = bytes;
while (_uploads.length > 16) {
_uploads.remove(_uploads.keys.first);
}
}
/// The image bytes behind [uri]. A server refusal is remembered; a transport
/// failure is not, so a later rebuild after reconnecting tries again.
Future<Uint8List> load(String uri) {
final bytes = ready(uri);
if (bytes != null) return Future.value(bytes);
final failed = _failed[uri];
if (failed != null) {
return Future.error(ChatAttachmentImageException(failed));
}
return _pending[uri] ??= _fetch(uri).then(
(bytes) {
_pending.remove(uri);
_store(uri, bytes);
return bytes;
},
onError: (Object error) {
_pending.remove(uri);
if (error is ChatAttachmentImageException) {
_failed[uri] = error.message;
throw error;
}
// Not connected, timed out: worth another try on a later build.
throw const ChatAttachmentImageException('Image unavailable');
},
);
}
Future<Uint8List> _fetch(String uri) async {
final local = _uploads[chatStoredFileName(uri)];
switch (chatImageSourceOf(uri)) {
case ChatImageSource.inline:
final bytes = chatDataUriBytes(uri);
if (bytes == null || bytes.isEmpty) {
throw const ChatAttachmentImageException('Image could not be read');
}
return bytes;
case ChatImageSource.upload:
if (local == null) {
throw const ChatAttachmentImageException(chatImageGoneMessage);
}
return local;
case ChatImageSource.stored:
if (local != null) return local;
return _request(uri);
case null:
throw const ChatAttachmentImageException('Image unavailable');
}
}
Future<Uint8List> _request(String uri) async {
final gateway = this.gateway;
if (gateway == null) {
throw const ChatAttachmentImageException('Image unavailable');
}
final JsonMap reply;
try {
reply = await gateway.call('chat_attachment_image', {
'chat_attachment_image_request': {'uri': uri},
});
} on ProtocolError catch (error) {
// The server's answer is settled; remember it rather than re-ask.
throw ChatAttachmentImageException(_wording(error.message));
}
final content = reply['chat_attachment_image'];
final data = content is Map ? content['data'] : null;
if (data is! String || data.isEmpty) {
throw const ChatAttachmentImageException('Image could not be read');
}
try {
return base64Decode(data);
} on FormatException {
throw const ChatAttachmentImageException('Image could not be read');
}
}
void _store(String uri, Uint8List bytes) {
_ready[uri] = bytes;
_cachedBytes += bytes.length;
while (_cachedBytes > maxCachedBytes && _ready.length > 1) {
final oldest = _ready.keys.first;
_cachedBytes -= _ready.remove(oldest)!.length;
}
}
static String _wording(String message) {
if (message.contains('no longer available')) return chatImageGoneMessage;
if (message.contains('too large')) return 'Image too large to preview';
return 'Image unavailable';
}
}
@@ -0,0 +1,107 @@
import 'dart:typed_data';
import '../../../core/api_gateway.dart';
/// Raster types the transcript can draw. SVG and unknown types stay file rows.
const Set<String> _imageMimes = {
'image/png',
'image/jpeg',
'image/jpg',
'image/gif',
'image/webp',
'image/bmp',
};
const Map<String, String> _imageExtensions = {
'png': 'image/png',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'gif': 'image/gif',
'webp': 'image/webp',
'bmp': 'image/bmp',
};
/// Where a transcript image's bytes come from.
enum ChatImageSource {
/// A `data:` URI the history already carries (Claude Code transcripts).
inline,
/// A server-local `file://` path read through `chat_attachment_image`.
stored,
/// A just-sent prompt's upload, known only by its stored name until the
/// server echoes the recorded turn.
upload,
}
/// The image type a file part names: its own MIME, else the type of a `data:`
/// URI, else its name or URI extension. Null when it is not a drawable image.
String? chatPartImageMime(JsonMap part) {
if (part['type'] != 'file') return null;
final mime = '${part['mime'] ?? ''}'.trim().toLowerCase();
if (mime.isNotEmpty && mime != 'application/octet-stream') {
return _imageMimes.contains(mime) ? mime : null;
}
final uri = '${part['uri'] ?? ''}'.trim();
if (uri.startsWith('data:')) {
final type = uri.substring(5).split(RegExp('[;,]')).first.toLowerCase();
return _imageMimes.contains(type) ? type : null;
}
for (final candidate in ['${part['name'] ?? ''}', uri]) {
final dot = candidate.lastIndexOf('.');
if (dot < 0) continue;
final type = _imageExtensions[candidate.substring(dot + 1).toLowerCase()];
if (type != null) return type;
}
return null;
}
/// How a drawable image part is loaded, or null when its URI is one the client
/// does not fetch (remote http(s) URLs stay plain file rows).
ChatImageSource? chatImageSourceOf(String uri) {
if (uri.startsWith('data:')) return ChatImageSource.inline;
if (uri.startsWith('file:///')) return ChatImageSource.stored;
if (uri.startsWith(chatUploadUriPrefix)) return ChatImageSource.upload;
return null;
}
/// The optimistic row's URI for a file the composer uploaded ahead of the
/// prompt; the loader resolves it from the composer's own bytes.
const String chatUploadUriPrefix = 'upload:';
/// The URI a just-sent turn's file part carries before the server records it:
/// an inline file's own `data:` URI, an uploaded file's `upload:` name, else
/// its name (drawn as a plain file row).
String chatOptimisticAttachmentUri(JsonMap wirePart) {
final name = '${wirePart['name'] ?? ''}';
final data = '${wirePart['data'] ?? ''}';
final upload = '${wirePart['upload'] ?? ''}';
if (upload.isNotEmpty) return '$chatUploadUriPrefix$upload';
if (data.isNotEmpty) {
final mime = '${wirePart['mime'] ?? ''}'.trim();
return 'data:${mime.isEmpty ? 'application/octet-stream' : mime};base64,$data';
}
return name;
}
/// The stored file name a `file://` or `upload:` URI ends in; the upload store
/// names files `up-<id>-<name>`, so the same bytes match before and after the
/// server records the turn.
String chatStoredFileName(String uri) {
if (uri.startsWith(chatUploadUriPrefix)) {
return uri.substring(chatUploadUriPrefix.length);
}
final path = Uri.tryParse(uri)?.pathSegments ?? const <String>[];
return path.isEmpty ? '' : path.last;
}
/// The bytes of a base64 `data:` image URI, or null when it is malformed.
Uint8List? chatDataUriBytes(String uri) {
try {
final data = UriData.parse(uri);
if (!data.isBase64) return null;
return data.contentAsBytes();
} on FormatException {
return null;
}
}
@@ -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);
}