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
@@ -6,6 +6,7 @@ import '../../../core/api_gateway.dart';
import '../data/chat_repository.dart';
import '../domain/chat_account_usage.dart';
import '../domain/chat_sessions.dart';
import '../domain/chat_shown_items.dart';
import '../domain/chat_transcript.dart';
import '../domain/chat_turn_diffs.dart';
import 'chat_server_queue.dart';
@@ -73,6 +74,7 @@ class ChatThreadController extends ChangeNotifier {
void Function(JsonMap queue)? onQueue;
List<JsonMap> _messages = const [];
List<JsonMap> _shown = const [];
bool _running = false;
bool _loaded = false;
bool _loading = false;
@@ -116,6 +118,10 @@ class ChatThreadController extends ChangeNotifier {
List<JsonMap> get messages => _messages;
/// What the model showed through the Pipelines tools ([chatShownItemsOf]),
/// as the server retains it, oldest first.
List<JsonMap> get shown => _shown;
/// The prompts the server still holds for this session, in delivery order.
List<JsonMap> get queuedPrompts => _queue.prompts;
@@ -312,6 +318,7 @@ class ChatThreadController extends ChangeNotifier {
_subscribed = true;
_subscriptionError = null;
_applyQueue(reply['chat_queue']);
_applyShown(reply['chat_shown'], replace: true);
} catch (error) {
// History stays usable, but the UI must report that live updates failed.
if (_disposed) return;
@@ -340,8 +347,20 @@ class ChatThreadController extends ChangeNotifier {
_notify();
}
/// Adopts the subscribe reply's retained list, or one pushed item.
void _applyShown(Object? body, {bool replace = false}) {
final items = chatShownItemsOf(body, sessionId);
if (items == null) return;
_shown = mergeChatShownItems(_shown, items, replace: replace);
_notify();
}
void _onFrame(JsonMap envelope) {
if (_disposed) return;
if (envelope['type'] == 'chat_shown') {
_applyShown(envelope['chat_shown']);
return;
}
if (envelope['type'] == 'chat_queue') {
_applyQueue(envelope['chat_queue']);
return;
@@ -14,6 +14,9 @@ import '../domain/chat_activity_detail.dart';
import '../domain/chat_notice.dart';
import '../domain/chat_attachment_picker.dart';
import '../domain/chat_colors.dart';
import '../../../core/transport/pipelines_client.dart'
show configuredGatewayEndpoint;
import '../domain/chat_shown_items.dart';
import '../domain/chat_transcript.dart';
import '../domain/chat_turn_diffs.dart';
import '../ui/sessions/chat_adaptive.dart';
@@ -24,6 +27,7 @@ import '../ui/transcript/chat_markdown_view.dart';
import '../ui/transcript/chat_message_view.dart';
import '../ui/transcript/chat_transcript_selection.dart';
import '../ui/transcript/chat_injected_rows.dart';
import '../ui/transcript/shown/chat_shown_card.dart';
import '../ui/transcript/chat_task_notices_group.dart';
import '../ui/transcript/chat_turn_diff_chip.dart';
import '../../artifacts/actions/artifact_file_bridge.dart';
@@ -998,20 +1002,26 @@ class _ChatThreadViewState extends State<ChatThreadView> {
final allRows = attachChatTurnDiffs(
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,
withChatShownItems(
transcriptRows(
messages,
trailing: cards,
running:
_controller.running &&
!_reconnecting &&
!_staleTranscript &&
!cards.any(chatCardAwaitingOperator),
awaitingResponse:
_controller.awaitingResponse &&
!_reconnecting &&
!_staleTranscript &&
!cards.any(chatCardAwaitingOperator),
liveMessageId: _controller.liveAssistantMessageId,
),
// Placed only against a loaded transcript, so an entry never
// leads an empty one and then jumps down when history arrives.
_controller.loaded ? _controller.shown : const [],
hasMore: _controller.hasMore,
),
),
),
@@ -1482,6 +1492,12 @@ class _ChatThreadViewState extends State<ChatThreadView> {
runId: '${row['run_id']}',
);
}
if (kind == chatShownRowKind) {
return ChatShownCard(
row: row,
endpoint: configuredGatewayEndpoint(widget.gateway),
);
}
if (kind == 'task_notices') return ChatTaskNoticesGroup(row: row);
if (kind == 'questions') return ChatQuestionsRow(row: row);
if (kind == 'permission' || kind == 'question') {
@@ -0,0 +1,157 @@
import '../../../core/api_gateway.dart';
import 'chat_transcript.dart';
/// Entries a chat's model showed the operator through the Pipelines tools
/// (`show_file`, `show_image`, `show_html`, `notify`).
///
/// The server keeps them per chat, outside the harness transcript: the
/// `chat_subscribe` reply carries the retained list (oldest first) and a
/// pushed `chat_shown` frame carries each new or updated item. Items are keyed
/// by `id`; a later copy replaces the held one in place.
/// The four recorded kinds.
const chatShownKinds = {'file', 'image', 'html', 'notify'};
/// The transcript row kind an item is drawn as.
const String chatShownRowKind = 'shown';
/// The items of a `chat_shown` body for [sessionId], or null when the body is
/// absent, malformed or for another chat. Items of unknown kind or without an
/// id are dropped rather than drawn as something they are not.
List<JsonMap>? chatShownItemsOf(Object? body, String sessionId) {
if (body is! Map || '${body['session_id'] ?? ''}' != sessionId) return null;
final items = body['items'];
if (items is! List) return const [];
return [
for (final item in items.whereType<Map>())
if ('${item['id'] ?? ''}'.isNotEmpty &&
chatShownKinds.contains(item['kind']))
Map<String, dynamic>.from(item),
];
}
/// [held] with [incoming] merged by id: a known item is replaced where it is,
/// a new one is appended. [replace] adopts [incoming] as the whole list (the
/// subscribe reply is the server's complete retained set).
List<JsonMap> mergeChatShownItems(
List<JsonMap> held,
List<JsonMap> incoming, {
bool replace = false,
}) {
if (replace) return List<JsonMap>.unmodifiable(incoming);
final byId = {for (final item in incoming) '${item['id']}': item};
final merged = [
for (final item in held) byId.remove('${item['id']}') ?? item,
...byId.values,
];
return List<JsonMap>.unmodifiable(merged);
}
/// The tool names a harness reports for the Pipelines tools: Claude Code
/// `mcp__pipelines__show_file`, OpenCode `pipelines_show_file`, Codex
/// `pipelines/show_file`.
final RegExp _pipelinesTool = RegExp(
r'^(?:mcp__pipelines__|pipelines_|pipelines/)'
r'(?:show_file|show_image|show_html|notify)$',
);
/// Whether [part] is a call of a Pipelines tool whose result the transcript
/// draws as its own entry. A failed call stays a normal tool row: its error is
/// the only record of what went wrong.
bool chatPipelinesToolRepresented(JsonMap part) {
if ('${part['type'] ?? ''}' != 'tool') return false;
if (!_pipelinesTool.hasMatch('${part['name'] ?? ''}'.trim())) return false;
final state = part['state'];
return !(state is Map && '${state['status'] ?? ''}' == 'error');
}
int? _createdAt(JsonMap value) => chatMessageCreatedAt(value);
/// A transcript row's recorded time, or null for a row without one.
int? _rowTime(JsonMap row) {
final own = _createdAt(row);
if (own != null) return own;
final message = row['message'];
return message is Map ? _createdAt(Map<String, dynamic>.from(message)) : null;
}
/// [rows] (from [transcriptRows]) with the Pipelines tool calls removed from
/// answer turns and each shown item placed by its time.
///
/// An item goes before the first timed row recorded after it, else after the
/// last timed row (so it never follows the pending cards or the response
/// shell that come after the transcript). While older history pages remain
/// ([hasMore]), an item older than the oldest loaded row stays out until that
/// page loads, so it is never drawn above messages that precede it.
List<JsonMap> withChatShownItems(
List<JsonMap> rows,
List<JsonMap> items, {
required bool hasMore,
}) {
final out = <JsonMap>[];
for (final row in rows) {
final parts = row['parts'];
if (row['kind'] != 'assistant' || parts is! List) {
out.add(row);
continue;
}
final kept = [
for (final part in parts.whereType<Map>())
if (!chatPipelinesToolRepresented(Map<String, dynamic>.from(part)))
part,
];
if (kept.length == parts.length) {
out.add(row);
} else if (kept.isNotEmpty ||
row['streaming'] == true ||
row['activityRecords'] != null) {
out.add({...row, 'parts': kept});
}
}
if (items.isEmpty) return out;
final timed = [
for (final item in items)
if (_createdAt(item) != null) item,
]..sort((a, b) => _createdAt(a)!.compareTo(_createdAt(b)!));
int? oldest;
var lastTimed = -1;
for (var index = 0; index < out.length; index++) {
final time = _rowTime(out[index]);
if (time == null) continue;
oldest ??= time;
lastTimed = index;
}
final result = <JsonMap>[];
var next = 0;
JsonMap rowOf(JsonMap item) => {
'kind': chatShownRowKind,
'key': 'chat-shown-${item['id']}',
'messageIds': ['shown:${item['id']}'],
'item': item,
};
if (hasMore) {
while (next < timed.length &&
(oldest == null || _createdAt(timed[next])! < oldest)) {
next++;
}
}
for (var index = 0; index < out.length; index++) {
final time = _rowTime(out[index]);
if (time != null) {
while (next < timed.length && _createdAt(timed[next])! < time) {
result.add(rowOf(timed[next++]));
}
}
result.add(out[index]);
if (index == lastTimed) {
while (next < timed.length) {
result.add(rowOf(timed[next++]));
}
}
}
// A transcript with no timed row yet: the items lead.
if (lastTimed < 0) {
return [for (; next < timed.length; next++) rowOf(timed[next]), ...result];
}
return result;
}
@@ -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,
],
);
}
}