Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Open chat text files in an in-app viewer (#1599)

0xken159880ade35ef1
diff --git a/desktop/lib/super_tabs/attachment_chips.dart b/desktop/lib/super_tabs/attachment_chips.dart
index a6e4161fd..a61ab10f0 100644
--- a/desktop/lib/super_tabs/attachment_chips.dart
+++ b/desktop/lib/super_tabs/attachment_chips.dart
@@ -6,11 +6,12 @@ import '../shared/widgets/app_dialog.dart';
import '../widgets/desktop_chrome.dart';
import '../widgets/update_notice.dart' show formatDownloadSize;
import 'attachment_upload.dart';
+import 'attachment_viewer.dart';
import 'model.dart';
/// The files a message carries, one chip each. The chat never loads a file by
-/// itself: a chip only names it, and a click opens it — an image in a viewer
-/// that fetches it then, anything else in the browser.
+/// itself: a chip only names it, and a click opens it — an image or a text
+/// file in a viewer that fetches it then, anything else in the browser.
class SuperTabAttachmentChips extends StatelessWidget {
const SuperTabAttachmentChips(this.attachments, {super.key});
@@ -46,6 +47,11 @@ class _AttachmentChip extends StatelessWidget {
context: context,
builder: (_) => _ImageViewer(file: file, url: url),
);
+ } else if (opensAsText(file)) {
+ await showAppDialog<void>(
+ context: context,
+ builder: (_) => AttachmentTextViewer(file: file, url: url),
+ );
} else {
await openInBrowser(url);
}
@@ -135,19 +141,7 @@ class _ImageViewer extends StatelessWidget {
),
),
const SizedBox(height: 12),
- Row(
- mainAxisAlignment: MainAxisAlignment.end,
- children: [
- TextButton(
- onPressed: () => openInBrowser(url),
- child: const Text('Open in browser'),
- ),
- TextButton(
- onPressed: () => Navigator.pop(context),
- child: const Text('Close'),
- ),
- ],
- ),
+ AttachmentViewerActions(file: file, url: url),
],
),
),
diff --git a/desktop/lib/super_tabs/attachment_viewer.dart b/desktop/lib/super_tabs/attachment_viewer.dart
new file mode 100644
index 000000000..91420282a
--- /dev/null
+++ b/desktop/lib/super_tabs/attachment_viewer.dart
@@ -0,0 +1,284 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:math' as math;
+import 'dart:typed_data';
+
+import 'package:dio/dio.dart';
+import 'package:file_selector/file_selector.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+import 'package:re_editor/re_editor.dart';
+
+import '../core/open_in_browser.dart';
+import '../finder/finder_file_kind.dart';
+import '../finder/finder_language.dart';
+import '../finder/finder_text_format.dart';
+import '../finder/widgets/finder_code_editor.dart';
+import '../finder/widgets/finder_markdown_view.dart';
+import '../shared/theme/app_icons.dart';
+import '../shared/widgets/app_icon_button.dart';
+import '../shared/widgets/empty_state.dart';
+import '../shared/widgets/skeleton.dart';
+import '../widgets/desktop_chrome.dart';
+import 'model.dart';
+
+/// The largest file read into the chat's text viewer; a bigger one opens in
+/// the browser. Specs and logs sit well under it, and the backend takes 10 MB.
+const kAttachmentTextMaxBytes = 2 * 1024 * 1024;
+
+/// Reads a file off the attachments host, when a person asks for it.
+@visibleForTesting
+Future<Uint8List> Function(Uri url, {int? maxBytes}) attachmentFetcher =
+ fetchAttachment;
+
+/// A file past the text viewer's limit; it opens in the browser instead.
+class AttachmentTooLarge implements Exception {
+ const AttachmentTooLarge();
+}
+
+/// The file at [url], or [AttachmentTooLarge] once it passes [maxBytes]:
+/// read as it arrives, so a file larger than it says is cut off, not read
+/// whole. A redirect is refused, since it could lead off the attachments
+/// host.
+Future<Uint8List> fetchAttachment(Uri url, {int? maxBytes}) async {
+ final dio = Dio();
+ try {
+ final answer = await dio.getUri<ResponseBody>(
+ url,
+ options: Options(
+ responseType: ResponseType.stream,
+ followRedirects: false,
+ validateStatus: (status) => status == 200,
+ ),
+ );
+ final body = answer.data!;
+ final bytes = BytesBuilder(copy: false);
+ await for (final chunk in body.stream) {
+ bytes.add(chunk);
+ if (maxBytes != null && bytes.length > maxBytes) {
+ throw const AttachmentTooLarge();
+ }
+ }
+ return bytes.takeBytes();
+ } finally {
+ // Hangs up a body read only in part, rather than leaving it open.
+ dio.close(force: true);
+ }
+}
+
+/// Whether [file] opens in the text viewer: text by its name, as Finder tells
+/// it, and small enough to read in place. Never in a browser, whose fetch
+/// follows redirects and loads a body whole before the page sees it; there
+/// the file opens in a new tab.
+bool opensAsText(SuperTabAttachment file) =>
+ !kIsWeb &&
+ file.size <= kAttachmentTextMaxBytes &&
+ switch (finderFileKind(file.name)) {
+ FinderFileKind.text || FinderFileKind.markdown => true,
+ _ => false,
+ };
+
+/// Asks where to save [file], then fetches it from [url] into that place.
+/// False when the person cancelled.
+Future<bool> downloadAttachment(SuperTabAttachment file, Uri url) async {
+ final where = await getSaveLocation(suggestedName: file.name);
+ if (where == null) return false;
+ await File(where.path).writeAsBytes(await attachmentFetcher(url));
+ return true;
+}
+
+/// A text file from the chat, read only: Markdown rendered with its source a
+/// click away, anything else in Finder's editor. Fetched when this opens.
+class AttachmentTextViewer extends StatefulWidget {
+ const AttachmentTextViewer({
+ super.key,
+ required this.file,
+ required this.url,
+ });
+
+ final SuperTabAttachment file;
+ final Uri url;
+
+ @override
+ State<AttachmentTextViewer> createState() => _AttachmentTextViewerState();
+}
+
+class _AttachmentTextViewerState extends State<AttachmentTextViewer> {
+ late final Future<Uint8List> _bytes = attachmentFetcher(
+ widget.url,
+ maxBytes: kAttachmentTextMaxBytes,
+ );
+
+ @override
+ void initState() {
+ super.initState();
+ // Larger than its size said: read it in the browser, as a large file is.
+ _bytes.then<void>(
+ (_) {},
+ onError: (Object error) {
+ if (error is! AttachmentTooLarge || !mounted) return;
+ Navigator.pop(context);
+ openInBrowser(widget.url);
+ },
+ );
+ }
+
+ CodeLineEditingController? _text;
+ bool _source = false;
+
+ bool get _markdown =>
+ finderFileKind(widget.file.name) == FinderFileKind.markdown;
+
+ @override
+ void dispose() {
+ _text?.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final screen = MediaQuery.sizeOf(context);
+ return Dialog(
+ child: SizedBox(
+ width: math.min(960, screen.width * .9),
+ height: screen.height * .85,
+ child: FutureBuilder(
+ future: _bytes,
+ builder: (context, read) => Padding(
+ padding: const EdgeInsets.all(16),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ children: [
+ Expanded(
+ child: Text(
+ widget.file.name,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(medium: true),
+ ),
+ ),
+ if (_markdown && _textOf(read) != null)
+ AppIconButton(
+ icon: _source ? AppIcons.eye : AppIcons.code,
+ tooltip: _source ? 'Show preview' : 'Show source',
+ onPressed: () => setState(() => _source = !_source),
+ ),
+ ],
+ ),
+ const SizedBox(height: 12),
+ Expanded(child: _body(read)),
+ const SizedBox(height: 12),
+ AttachmentViewerActions(file: widget.file, url: widget.url),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ /// The file's text once it has arrived and reads as text; null otherwise.
+ CodeLineEditingController? _textOf(AsyncSnapshot<Uint8List> read) {
+ final bytes = read.data;
+ if (bytes == null || !looksLikeText(bytes)) {
+ return null;
+ }
+ return _text ??= () {
+ final text = utf8.decode(bytes, allowMalformed: true);
+ return CodeLineEditingController.fromText(text, detectTextFormat(text));
+ }();
+ }
+
+ Widget _body(AsyncSnapshot<Uint8List> read) {
+ if (read.hasError) {
+ return const EmptyState(
+ icon: AppIcons.circleAlert,
+ title: 'Can’t open this file',
+ message: 'It couldn’t be downloaded. Try again in the browser.',
+ compact: true,
+ );
+ }
+ if (read.connectionState != ConnectionState.done) {
+ return const SkeletonList(rows: 12);
+ }
+ final text = _textOf(read);
+ if (text == null) {
+ return const EmptyState(
+ icon: AppIcons.file,
+ title: 'No preview',
+ message: 'This file isn’t text that can be shown here.',
+ compact: true,
+ );
+ }
+ if (_markdown && !_source) return FinderMarkdownView(text.text);
+ return FinderCodeEditor(
+ controller: text,
+ language: finderLanguageOf(widget.file.name),
+ readOnly: true,
+ onSave: () {},
+ );
+ }
+}
+
+/// A viewer's buttons: save the file, open it in the browser, or close.
+class AttachmentViewerActions extends StatefulWidget {
+ const AttachmentViewerActions({
+ super.key,
+ required this.file,
+ required this.url,
+ });
+
+ final SuperTabAttachment file;
+ final Uri url;
+
+ @override
+ State<AttachmentViewerActions> createState() =>
+ _AttachmentViewerActionsState();
+}
+
+class _AttachmentViewerActionsState extends State<AttachmentViewerActions> {
+ bool _saving = false;
+ String? _outcome;
+
+ Future<void> _download() async {
+ setState(() {
+ _saving = true;
+ _outcome = null;
+ });
+ String? outcome;
+ try {
+ if (await downloadAttachment(widget.file, widget.url)) outcome = 'Saved';
+ } catch (_) {
+ outcome = 'Couldn’t save this file.';
+ }
+ if (!mounted) return;
+ setState(() {
+ _saving = false;
+ _outcome = outcome;
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) => Row(
+ children: [
+ if (_outcome != null) Text(_outcome!, style: DesktopChrome.metadata()),
+ const Spacer(),
+ // A browser cannot write to a chosen path; Open in browser saves there.
+ if (!kIsWeb)
+ TextButton(
+ onPressed: _saving ? null : _download,
+ child: const Text('Download'),
+ ),
+ TextButton(
+ onPressed: () => openInBrowser(widget.url),
+ child: const Text('Open in browser'),
+ ),
+ TextButton(
+ onPressed: () => Navigator.pop(context),
+ child: const Text('Close'),
+ ),
+ ],
+ );
+}
diff --git a/desktop/test/super_tab_attachment_fetch_test.dart b/desktop/test/super_tab_attachment_fetch_test.dart
new file mode 100644
index 000000000..4b9096366
--- /dev/null
+++ b/desktop/test/super_tab_attachment_fetch_test.dart
@@ -0,0 +1,77 @@
+// The chat's file fetch against a real server: it never follows a redirect
+// off the attachments host, and it stops reading at the text viewer's limit.
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+import 'dart:typed_data';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/attachment_viewer.dart';
+
+void main() {
+ late HttpServer server, elsewhere;
+ late int elsewhereHits;
+ late Future<void> Function(HttpResponse) answer;
+
+ Uri link(String path) => Uri.parse('http://127.0.0.1:${server.port}$path');
+
+ setUp(() async {
+ elsewhereHits = 0;
+ elsewhere = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ elsewhere.listen((request) {
+ elsewhereHits++;
+ request.response
+ ..write('from another host')
+ ..close();
+ });
+ server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ server.listen((request) => answer(request.response));
+ });
+ tearDown(() async {
+ await server.close(force: true);
+ await elsewhere.close(force: true);
+ });
+
+ test('reads the file', () async {
+ answer = (response) => (response..write('hello')).close();
+
+ expect(
+ await fetchAttachment(link('/a')),
+ Uint8List.fromList('hello'.codeUnits),
+ );
+ });
+
+ test('a redirect is refused, never followed', () async {
+ answer = (response) =>
+ response.redirect(Uri.parse('http://127.0.0.1:${elsewhere.port}/b'));
+
+ await expectLater(fetchAttachment(link('/a')), throwsA(anything));
+ expect(elsewhereHits, 0);
+ });
+
+ test('stops reading past the limit and hangs up', () async {
+ // A raw socket, because only it sees the reader hang up: more than the
+ // limit, with no length and no end, so only a reader that stops at the
+ // limit gets an answer.
+ final raw = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
+ addTearDown(raw.close);
+ final hungUp = Completer<void>();
+ raw.listen((socket) {
+ socket.listen((_) {}, onDone: hungUp.complete, onError: (_) {});
+ socket
+ ..add(
+ utf8.encode('HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\n\r\n'),
+ )
+ ..add(Uint8List(1536 * 1024));
+ });
+
+ await expectLater(
+ fetchAttachment(
+ Uri.parse('http://127.0.0.1:${raw.port}/a'),
+ maxBytes: 1024 * 1024,
+ ),
+ throwsA(isA<AttachmentTooLarge>()),
+ );
+ await hungUp.future.timeout(const Duration(seconds: 10));
+ });
+}
diff --git a/desktop/test/super_tab_attachments_test.dart b/desktop/test/super_tab_attachments_test.dart
index 7a651eb00..3dbbb45f8 100644
--- a/desktop/test/super_tab_attachments_test.dart
+++ b/desktop/test/super_tab_attachments_test.dart
@@ -12,7 +12,10 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/open_in_browser.dart';
+import 'package:harness/finder/widgets/finder_code_editor.dart';
+import 'package:harness/finder/widgets/finder_markdown_view.dart';
import 'package:harness/super_tabs/attachment_upload.dart';
+import 'package:harness/super_tabs/attachment_viewer.dart';
import 'package:harness/super_tabs/controller.dart';
import 'package:harness/super_tabs/model.dart';
import 'package:harness/super_tabs/view.dart';
@@ -51,6 +54,22 @@ class _Picker extends FileSelectorPlatform {
}) async => files;
}
+/// A save dialog that answers with [path], or cancels when it is null.
+class _SaveTo extends FileSelectorPlatform {
+ _SaveTo(this.path);
+ final String? path;
+ final suggested = <String?>[];
+
+ @override
+ Future<FileSaveLocation?> getSaveLocation({
+ List<XTypeGroup>? acceptedTypeGroups,
+ SaveDialogOptions options = const SaveDialogOptions(),
+ }) async {
+ suggested.add(options.suggestedName);
+ return path == null ? null : FileSaveLocation(path!);
+ }
+}
+
void main() {
final composer = find.byKey(const ValueKey('super-message-composer'));
final send = find.byTooltip('Send message');
@@ -533,6 +552,55 @@ void main() {
);
});
+ group('download', () {
+ final file = SuperTabAttachment.fromJson({
+ 'id': 'a1',
+ 'name': 'spec.md',
+ 'mime': 'text/markdown',
+ 'size': 5,
+ 'url': 'https://cdn.harness.autonomous.ai/a1/spec.md',
+ });
+ final url = Uri.parse(file.url);
+ late Directory dir;
+ late FileSelectorPlatform picker;
+ final fetched = <Uri>[];
+ late Future<Uint8List> Function(Uri, {int? maxBytes}) fetcher;
+
+ setUp(() {
+ dir = Directory.systemTemp.createTempSync('attachment-download');
+ picker = FileSelectorPlatform.instance;
+ fetcher = attachmentFetcher;
+ fetched.clear();
+ attachmentFetcher = (url, {maxBytes}) async {
+ fetched.add(url);
+ return Uint8List.fromList(utf8.encode('hello'));
+ };
+ });
+ tearDown(() {
+ FileSelectorPlatform.instance = picker;
+ attachmentFetcher = fetcher;
+ dir.deleteSync(recursive: true);
+ });
+
+ test('asks where, then saves the fetched file there', () async {
+ final target = '${dir.path}/saved.md';
+ final dialog = _SaveTo(target);
+ FileSelectorPlatform.instance = dialog;
+
+ expect(await downloadAttachment(file, url), isTrue);
+ expect(dialog.suggested, ['spec.md']);
+ expect(fetched, [url]);
+ expect(File(target).readAsStringSync(), 'hello');
+ });
+
+ test('a cancelled save dialog fetches nothing', () async {
+ FileSelectorPlatform.instance = _SaveTo(null);
+
+ expect(await downloadAttachment(file, url), isFalse);
+ expect(fetched, isEmpty);
+ });
+ });
+
group('messages', () {
testWidgets('show chips and load nothing until a click', (tester) async {
final server = ConversationServer()
@@ -667,6 +735,235 @@ void main() {
await close(tester, controller);
});
+ /// A message carrying [rows], mounted, with the browser and the file
+ /// fetch recorded; a fetch answers with [served] by file name.
+ Future<(SuperTabController, List<Uri>, List<Uri>)> showFiles(
+ WidgetTester tester,
+ List<Map<String, dynamic>> rows, {
+ Map<String, List<int>> served = const {},
+ }) async {
+ final server = ConversationServer()..append('Here', attachments: rows);
+ final controller = server.controller();
+ await controller.refresh();
+ await mount(tester, controller);
+ final opened = <Uri>[], fetched = <Uri>[];
+ final browser = browserOpener, fetcher = attachmentFetcher;
+ browserOpener = (url) async {
+ opened.add(url);
+ return true;
+ };
+ attachmentFetcher = (url, {maxBytes}) async {
+ fetched.add(url);
+ return Uint8List.fromList(served[url.pathSegments.last]!);
+ };
+ addTearDown(() {
+ browserOpener = browser;
+ attachmentFetcher = fetcher;
+ });
+ return (controller, opened, fetched);
+ }
+
+ Map<String, dynamic> row(String id, String name, String mime, int size) => {
+ 'id': id,
+ 'name': name,
+ 'mime': mime,
+ 'size': size,
+ 'url': 'https://cdn.harness.autonomous.ai/$id/$name',
+ };
+
+ String shownText(WidgetTester tester) => tester
+ .widget<FinderCodeEditor>(find.byType(FinderCodeEditor))
+ .controller
+ .text;
+
+ testWidgets('a Markdown file opens rendered, its source a click away', (
+ tester,
+ ) async {
+ final (controller, opened, fetched) = await showFiles(
+ tester,
+ [row('a1', 'spec.md', 'text/markdown', 40)],
+ served: {'spec.md': utf8.encode('# The spec\n\nRead **this**.')},
+ );
+
+ await tester.tap(find.byKey(const ValueKey('super-attachment:a1')));
+ await tester.pumpAndSettle();
+ expect(fetched, [
+ Uri.parse('https://cdn.harness.autonomous.ai/a1/spec.md'),
+ ]);
+ expect(find.byType(FinderMarkdownView), findsOneWidget);
+ expect(find.text('The spec'), findsOneWidget);
+ expect(find.byType(FinderCodeEditor), findsNothing);
+
+ await tester.tap(find.byTooltip('Show source'));
+ await tester.pumpAndSettle();
+ expect(find.byType(FinderMarkdownView), findsNothing);
+ final editor = tester.widget<FinderCodeEditor>(
+ find.byType(FinderCodeEditor),
+ );
+ expect(editor.readOnly, isTrue);
+ expect(editor.controller.text, '# The spec\n\nRead **this**.');
+
+ await tester.tap(find.byTooltip('Show preview'));
+ await tester.pumpAndSettle();
+ expect(find.byType(FinderMarkdownView), findsOneWidget);
+ expect(find.text('Download'), findsOneWidget);
+ expect(find.text('Open in browser'), findsOneWidget);
+ expect(opened, isEmpty);
+ await tester.tap(find.text('Close'));
+ await tester.pumpAndSettle();
+ await close(tester, controller);
+ });
+
+ testWidgets('a log and a JSON file open as text', (tester) async {
+ final (controller, opened, _) = await showFiles(
+ tester,
+ [
+ row('a1', 'run.log', 'text/plain', 20),
+ row('a2', 'data.json', 'application/json', 20),
+ ],
+ served: {
+ 'run.log': utf8.encode('line one\nline two'),
+ 'data.json': utf8.encode('{"ok": true}'),
+ },
+ );
+
+ await tester.tap(find.byKey(const ValueKey('super-attachment:a1')));
+ await tester.pumpAndSettle();
+ expect(shownText(tester), 'line one\nline two');
+ expect(find.byTooltip('Show source'), findsNothing);
+ await tester.tap(find.text('Close'));
+ await tester.pumpAndSettle();
+
+ await tester.tap(find.byKey(const ValueKey('super-attachment:a2')));
+ await tester.pumpAndSettle();
+ expect(shownText(tester), '{"ok": true}');
+ expect(opened, isEmpty);
+ await tester.tap(find.text('Close'));
+ await tester.pumpAndSettle();
+ await close(tester, controller);
+ });
+
+ testWidgets('a file too large or not text opens in the browser unread', (
+ tester,
+ ) async {
+ final (controller, opened, fetched) = await showFiles(tester, [
+ row('a1', 'huge.log', 'text/plain', kAttachmentTextMaxBytes + 1),
+ row('a2', 'bundle.zip', 'application/zip', 100),
+ ]);
+
+ await tester.tap(find.byKey(const ValueKey('super-attachment:a1')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('super-attachment:a2')));
+ await tester.pumpAndSettle();
+ expect(opened, [
+ Uri.parse('https://cdn.harness.autonomous.ai/a1/huge.log'),
+ Uri.parse('https://cdn.harness.autonomous.ai/a2/bundle.zip'),
+ ]);
+ expect(fetched, isEmpty);
+ await close(tester, controller);
+ });
+
+ testWidgets(
+ 'a file that runs past the limit while read opens the browser',
+ (tester) async {
+ final (controller, opened, _) = await showFiles(tester, [
+ row('a1', 'small-on-paper.log', 'text/plain', 10),
+ ]);
+ final limits = <int?>[];
+ attachmentFetcher = (url, {maxBytes}) async {
+ limits.add(maxBytes);
+ throw const AttachmentTooLarge();
+ };
+
+ await tester.tap(find.byKey(const ValueKey('super-attachment:a1')));
+ await tester.pumpAndSettle();
+ expect(limits, [kAttachmentTextMaxBytes]);
+ expect(opened, [
+ Uri.parse('https://cdn.harness.autonomous.ai/a1/small-on-paper.log'),
+ ]);
+ expect(find.text('Close'), findsNothing);
+ await close(tester, controller);
+ },
+ );
+
+ testWidgets('a text name over binary bytes shows no preview', (
+ tester,
+ ) async {
+ final (controller, _, _) = await showFiles(
+ tester,
+ [row('a1', 'notes.txt', 'text/plain', 4)],
+ served: {
+ 'notes.txt': [0, 1, 2, 3],
+ },
+ );
+
+ await tester.tap(find.byKey(const ValueKey('super-attachment:a1')));
+ await tester.pumpAndSettle();
+ expect(find.text('No preview'), findsOneWidget);
+ expect(find.byType(FinderCodeEditor), findsNothing);
+ await tester.tap(find.text('Close'));
+ await tester.pumpAndSettle();
+ await close(tester, controller);
+ });
+
+ testWidgets('the picture viewer offers Download', (tester) async {
+ final (controller, _, _) = await showFiles(tester, [
+ row('a1', 'shot.png', 'image/png', 2048),
+ ]);
+
+ await tester.tap(find.byKey(const ValueKey('super-attachment:a1')));
+ await tester.pumpAndSettle();
+ expect(
+ find.byKey(const ValueKey('super-attachment-image:a1')),
+ findsOneWidget,
+ );
+ expect(find.text('Download'), findsOneWidget);
+ expect(find.text('Open in browser'), findsOneWidget);
+ await tester.tap(find.text('Close'));
+ await tester.pumpAndSettle();
+ await close(tester, controller);
+ });
+
+ testWidgets('a text file off the attachments host is never fetched', (
+ tester,
+ ) async {
+ final server = ConversationServer()
+ ..append(
+ 'Here',
+ attachments: [
+ {
+ 'id': 'a1',
+ 'name': 'notes.md',
+ 'mime': 'text/markdown',
+ 'size': 10,
+ 'url': 'https://evil.example/a1/notes.md',
+ },
+ ],
+ );
+ final controller = server.controller();
+ await controller.refresh();
+ await mount(tester, controller);
+ final fetched = <Uri>[];
+ final original = attachmentFetcher;
+ attachmentFetcher = (url, {maxBytes}) async {
+ fetched.add(url);
+ return Uint8List(0);
+ };
+ addTearDown(() => attachmentFetcher = original);
+
+ await tester.tap(find.byKey(const ValueKey('super-attachment:a1')));
+ await tester.pump();
+ expect(
+ find.text(
+ 'This file isn’t on Harness’s file storage, so it wasn’t opened.',
+ ),
+ findsOneWidget,
+ );
+ expect(fetched, isEmpty);
+ expect(find.byType(FinderMarkdownView), findsNothing);
+ await close(tester, controller);
+ });
+
testWidgets('a malformed attachment row is left out, not the page', (
tester,
) async {
diff --git a/desktop/test/web/attachment_viewer_web_test.dart b/desktop/test/web/attachment_viewer_web_test.dart
new file mode 100644
index 000000000..92c7d7013
--- /dev/null
+++ b/desktop/test/web/attachment_viewer_web_test.dart
@@ -0,0 +1,72 @@
+@TestOn('browser')
+library;
+
+// In a browser a chat file is the browser's: a text file opens in a new tab
+// rather than being fetched into a popup (a page cannot refuse a redirect or
+// stop a download part way), and a viewer offers no Download, since a page
+// cannot write a chosen path.
+import 'dart:typed_data';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/open_in_browser.dart';
+import 'package:harness/super_tabs/attachment_chips.dart';
+import 'package:harness/super_tabs/attachment_viewer.dart';
+import 'package:harness/super_tabs/model.dart';
+
+void main() {
+ testWidgets('a text file opens in the browser, not fetched in the page', (
+ tester,
+ ) async {
+ final opened = <Uri>[], fetched = <Uri>[];
+ final browser = browserOpener, fetcher = attachmentFetcher;
+ browserOpener = (url) async {
+ opened.add(url);
+ return true;
+ };
+ attachmentFetcher = (url, {maxBytes}) async {
+ fetched.add(url);
+ return Uint8List(0);
+ };
+ addTearDown(() {
+ browserOpener = browser;
+ attachmentFetcher = fetcher;
+ });
+ final file = SuperTabAttachment.fromJson({
+ 'id': 'a1',
+ 'name': 'spec.md',
+ 'mime': 'text/markdown',
+ 'size': 5,
+ 'url': 'https://cdn.harness.autonomous.ai/a1/spec.md',
+ });
+ await tester.pumpWidget(
+ MaterialApp(home: Scaffold(body: SuperTabAttachmentChips([file]))),
+ );
+
+ await tester.tap(find.byKey(const ValueKey('super-attachment:a1')));
+ await tester.pumpAndSettle();
+ expect(opened, [Uri.parse(file.url)]);
+ expect(fetched, isEmpty);
+ expect(find.byType(AttachmentTextViewer), findsNothing);
+ });
+
+ testWidgets('a viewer in the browser has no Download', (tester) async {
+ final file = SuperTabAttachment.fromJson({
+ 'id': 'a1',
+ 'name': 'spec.md',
+ 'mime': 'text/markdown',
+ 'size': 5,
+ 'url': 'https://cdn.harness.autonomous.ai/a1/spec.md',
+ });
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: AttachmentViewerActions(file: file, url: Uri.parse(file.url)),
+ ),
+ ),
+ );
+
+ expect(find.text('Open in browser'), findsOneWidget);
+ expect(find.text('Download'), findsNothing);
+ });
+}