feat(chat): files upload over HTTP before the prompt, up to 100 MiB each

This commit is contained in:
2026-10-23 21:25:41 +01:00
parent 39a68a00b3
commit e507f554c3
17 changed files with 634 additions and 74 deletions
@@ -6,6 +6,8 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../core/api_gateway.dart';
import '../../../core/transport/pipelines_client.dart';
import '../data/upload/chat_upload.dart';
import '../domain/chat_attachment_draft.dart';
import '../domain/chat_attachment_picker.dart';
import '../domain/chat_attachment_wire.dart';
@@ -101,6 +103,13 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
final List<Uint8List> _bytes = [];
String? _attachmentError;
/// True while the draft's files upload ahead of the prompt.
bool _uploading = false;
/// Upload names by attachment instance, so a retried send reuses the files
/// already stored instead of uploading them again.
final Expando<String> _uploaded = Expando();
/// The draft text whose palette the operator closed (Escape) or completed
/// (a row or Enter). The palette stays hidden while the draft still equals
/// it, so any further typing offers the commands again.
@@ -392,14 +401,39 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
/// accepted prompt clears them.
Future<void> _send() async {
final composer = widget.composer;
if (composer.sending || composer.draft.trim().isEmpty) return;
List<JsonMap> parts;
try {
parts = chatAttachmentParts(_attachments, read: _readAttachment);
} on ChatAttachmentWireException catch (error) {
setState(() => _attachmentError = error.message);
if (_uploading || composer.sending || composer.draft.trim().isEmpty) {
return;
}
List<JsonMap> parts;
final endpoint = configuredGatewayEndpoint(composer.gateway);
try {
if (endpoint.isEmpty || _attachments.isEmpty) {
parts = chatAttachmentParts(_attachments, read: _readAttachment);
} else {
// Each file goes to the server as its own request first; the prompt
// then names the stored files.
setState(() {
_uploading = true;
_attachmentError = null;
});
parts = await chatAttachmentUploadParts(
_attachments,
read: _readAttachment,
upload: (attachment, bytes) async => _uploaded[attachment] ??=
await uploadChatAttachment(endpoint, attachment, bytes),
);
}
} on ChatAttachmentWireException catch (error) {
if (mounted) {
setState(() {
_uploading = false;
_attachmentError = error.message;
});
}
return;
}
if (!mounted) return;
if (_uploading) setState(() => _uploading = false);
// Keep the caret in the field while the prompt is in flight, as before.
_focus.requestFocus();
final accepted = await composer.send(attachments: parts);
@@ -432,7 +466,7 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
/// Adds each file through the landed attachment draft. A refusal keeps every
/// attachment already in the draft and shows the draft's own words; the
/// refused file's bytes are never retained. Picking and pasting share this
/// path so both apply the same name and 1 MiB decisions.
/// path so both apply the same name and size decisions.
void _addFiles(List<ChatPickedFile> files) {
if (!mounted) return;
setState(() {
@@ -527,6 +561,15 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
),
),
if (!_attachments.isEmpty) _attachmentStrip(context, cupertino),
if (_uploading)
_notice(
context,
cupertino,
key: const Key('chat-composer-uploading'),
text: _attachments.attachments.length == 1
? 'Uploading 1 file…'
: 'Uploading ${_attachments.attachments.length} files…',
),
if (_attachmentError != null)
_notice(
context,
@@ -861,7 +904,7 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
final stop = widget.running;
final enabled = stop
? !composer.stopping
: !composer.sending && composer.draft.trim().isNotEmpty;
: !_uploading && !composer.sending && composer.draft.trim().isNotEmpty;
void press() {
if (stop) {
unawaited(composer.stop());
@@ -0,0 +1,81 @@
import 'dart:convert';
import 'dart:typed_data';
import '../../../../core/transport/server_url.dart';
import '../../domain/chat_attachment_draft.dart';
import '../../domain/chat_attachment_wire.dart';
import 'chat_upload_stub.dart'
if (dart.library.io) 'chat_upload_io.dart'
if (dart.library.js_interop) 'chat_upload_web.dart'
as platform;
/// The server's reply to one stored chat file.
typedef ChatUploadReply = ({int status, String body});
/// Posts one file to the server's `/chat-uploads`: the bytes travel as their
/// own HTTP request, outside the websocket frame, and the reply names the
/// stored file a prompt then references.
Future<ChatUploadReply> postChatUpload(
Uri uri, {
required String name,
required String mime,
required Uint8List bytes,
}) => platform.postChatUpload(uri, name: name, mime: mime, bytes: bytes);
/// The header that carries the file name; the server refuses a post without it.
const chatUploadNameHeader = 'X-Pipelines-Upload-Name';
/// Uploads [bytes] for [attachment] to the server behind [endpoint] and
/// returns the stored name a prompt references. Every failure is a
/// [ChatAttachmentWireException] in words the composer shows as they are.
Future<String> uploadChatAttachment(
String endpoint,
ChatAttachment attachment,
Uint8List bytes,
) async {
final uri = ServerUrl.resolveArtifactUrl(endpoint, '/chat-uploads');
if (uri == null) {
throw const ChatAttachmentWireException(
'No server is configured to upload files to.',
);
}
final ChatUploadReply reply;
try {
reply = await postChatUpload(
uri,
name: attachment.name.trim().isEmpty ? 'attachment' : attachment.name,
mime: attachment.mime.trim().isEmpty
? 'application/octet-stream'
: attachment.mime,
bytes: bytes,
);
} catch (error) {
throw ChatAttachmentWireException(
'"${attachment.name}" could not be uploaded: $error',
);
}
if (reply.status == 401) {
throw const ChatAttachmentWireException(
'Sign in to upload files (Settings → Sign in).',
);
}
if (reply.status != 200) {
final reason = reply.body.trim();
throw ChatAttachmentWireException(
reason.isEmpty
? '"${attachment.name}" could not be uploaded (HTTP ${reply.status}).'
: '"${attachment.name}" could not be uploaded: $reason',
);
}
try {
final decoded = jsonDecode(reply.body);
final upload = decoded is Map ? decoded['upload'] : null;
if (upload is String && upload.isNotEmpty) return upload;
} on FormatException {
// Reported below.
}
throw ChatAttachmentWireException(
'"${attachment.name}" upload returned no file name.',
);
}
@@ -0,0 +1,31 @@
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import '../../../../core/session/server_session.dart';
import 'chat_upload.dart';
Future<ChatUploadReply> postChatUpload(
Uri uri, {
required String name,
required String mime,
required Uint8List bytes,
}) async {
final client = HttpClient()..connectionTimeout = const Duration(seconds: 15);
try {
final request = await client.postUrl(uri);
request.followRedirects = false;
// A phone behind the web login carries its kept session.
ServerSession.headers.forEach(request.headers.set);
request.headers
..set(chatUploadNameHeader, Uri.encodeComponent(name))
..set(HttpHeaders.contentTypeHeader, mime)
..contentLength = bytes.length;
request.add(bytes);
final response = await request.close();
final body = await response.transform(utf8.decoder).join();
return (status: response.statusCode, body: body);
} finally {
client.close(force: true);
}
}
@@ -0,0 +1,10 @@
import 'dart:typed_data';
import 'chat_upload.dart';
Future<ChatUploadReply> postChatUpload(
Uri uri, {
required String name,
required String mime,
required Uint8List bytes,
}) => throw UnsupportedError('Uploads are not supported on this platform.');
@@ -0,0 +1,46 @@
import 'dart:js_interop';
import 'dart:typed_data';
import 'chat_upload.dart';
@JS('fetch')
external JSPromise<_Response> _fetch(JSString input, _Init init);
extension type _Init._(JSObject _) implements JSObject {
external factory _Init({
JSString method,
JSAny headers,
JSAny body,
JSString credentials,
});
}
extension type _Response._(JSObject _) implements JSObject {
external int get status;
external JSPromise<JSString> text();
}
/// The browser keeps the login cookie; `same-origin` sends it only to the
/// page's own server.
Future<ChatUploadReply> postChatUpload(
Uri uri, {
required String name,
required String mime,
required Uint8List bytes,
}) async {
final response = await _fetch(
uri.toString().toJS,
_Init(
method: 'POST'.toJS,
headers: {
chatUploadNameHeader: Uri.encodeComponent(name),
'Content-Type': mime,
}.jsify()!,
body: bytes.toJS,
credentials: 'same-origin'.toJS,
),
).toDart;
final body = (await response.text().toDart).toDart;
return (status: response.status, body: body);
}
@@ -39,7 +39,7 @@ enum ChatAttachmentRefusal {
/// Keeping this attachment would take the draft past
/// [ChatAttachmentDraft.maxTotalBytes]. The wording matches the web composer.
totalTooLarge('Attachments are too large for web chat (1 MiB total).');
totalTooLarge('Attachments are too large (100 MiB total).');
const ChatAttachmentRefusal(this.message);
@@ -48,13 +48,14 @@ enum ChatAttachmentRefusal {
/// The files attached to one conversation's next message.
///
/// Mirrors the web composer's 1 MiB total budget across attachments: an
/// Files upload to the server one request each (`/chat-uploads`, 100 MiB a
/// file), so the draft allows 100 MiB in total across attachments: an
/// attachment that would exceed it is refused with its own reason, and every
/// attachment already in the draft stays. Attachments are memory-only; nothing
/// here persists, reads file bytes or sends a prompt.
class ChatAttachmentDraft {
/// The largest total the web composer allows across all attachments.
static const int maxTotalBytes = 1 << 20;
static const int maxTotalBytes = 100 << 20;
final List<ChatAttachment> _attachments = [];
@@ -8,6 +8,10 @@ import 'chat_attachment_draft.dart';
/// server applies the same bound.
const int maxChatAttachmentCount = 8;
/// The inline route's budget: base64 bytes inside the 2 MiB websocket frame.
/// Uploaded files ([chatAttachmentUploadParts]) are not bound by it.
const int maxInlineAttachmentBytes = 1 << 20;
/// The web's fallback name when an attachment's recorded name is blank.
const String chatAttachmentFallbackName = 'attachment';
@@ -45,7 +49,7 @@ typedef ChatAttachmentBytes = Uint8List? Function(ChatAttachment attachment);
/// at all; the web omits it for a text-only prompt. The count and the actual
/// byte lengths are checked before any part is encoded: more than
/// [maxChatAttachmentCount] files, an unreadable file, or a total over
/// [ChatAttachmentDraft.maxTotalBytes] throws [ChatAttachmentWireException].
/// [maxInlineAttachmentBytes] throws [ChatAttachmentWireException].
/// Actual bytes are used, not the recorded size, matching the web reader.
List<JsonMap> chatAttachmentParts(
ChatAttachmentDraft draft, {
@@ -71,9 +75,9 @@ List<JsonMap> chatAttachmentParts(
);
}
total += bytes.length;
if (total > ChatAttachmentDraft.maxTotalBytes) {
if (total > maxInlineAttachmentBytes) {
throw const ChatAttachmentWireException(
'Attachments are too large for web chat (1 MiB total).',
'Attachments are too large to send without a server (1 MiB total).',
);
}
contents.add(bytes);
@@ -98,6 +102,43 @@ List<JsonMap> chatAttachmentParts(
/// history, so this reports no decoded bytes and its
/// [ChatAttachment.sizeBytes] is 0 (or the record's own numeric `size` when a
/// caller supplied one). Nothing here builds UI or keeps file contents.
/// Stores one file on the server and returns its upload name.
typedef ChatAttachmentUpload =
Future<String> Function(ChatAttachment attachment, Uint8List bytes);
/// The prompt parts for files sent ahead through [upload]: each part names the
/// stored file instead of carrying its bytes, so size is bound by the server's
/// upload limit, not the websocket frame. Throws [ChatAttachmentWireException]
/// for an unreadable file; [upload]'s own exceptions pass through.
Future<List<JsonMap>> chatAttachmentUploadParts(
ChatAttachmentDraft draft, {
required ChatAttachmentBytes read,
required ChatAttachmentUpload upload,
}) async {
final attachments = draft.attachments;
if (attachments.isEmpty) return const [];
if (attachments.length > maxChatAttachmentCount) {
throw const ChatAttachmentWireException(
'At most 8 attachments are allowed.',
);
}
final parts = <JsonMap>[];
for (final attachment in attachments) {
final bytes = read(attachment);
if (bytes == null) {
throw ChatAttachmentWireException(
'"${chatAttachmentDisplayName(attachment.name, '')}" could not be read.',
);
}
parts.add({
'name': _wireText(attachment.name, chatAttachmentFallbackName),
'mime': _wireText(attachment.mime, chatAttachmentFallbackMime),
'upload': await upload(attachment, bytes),
});
}
return parts;
}
ChatAttachment? chatAttachmentFromHistoryPart(Object? part) {
if (part is! Map) return null;
if ('${part['type'] ?? ''}'.trim() != 'file') return null;
@@ -50,7 +50,11 @@ ChatPickedFile _file(
String name,
List<int> bytes, {
String mime = 'text/plain',
}) => ChatPickedFile(name: name, mime: mime, bytes: Uint8List.fromList(bytes));
}) => ChatPickedFile(
name: name,
mime: mime,
bytes: bytes is Uint8List ? bytes : Uint8List.fromList(bytes),
);
Finder get _field => find.byKey(const Key('chat-composer-field'));
@@ -159,7 +163,7 @@ void main() {
fake.paste([
_file(
'huge.bin',
List<int>.filled(ChatAttachmentDraft.maxTotalBytes + 1, 0),
Uint8List(ChatAttachmentDraft.maxTotalBytes + 1),
mime: 'application/octet-stream',
),
]);
@@ -184,7 +188,7 @@ void main() {
_file('kept.txt', [1]),
_file(
'huge.bin',
List<int>.filled(ChatAttachmentDraft.maxTotalBytes, 0),
Uint8List(ChatAttachmentDraft.maxTotalBytes),
mime: 'application/octet-stream',
),
]);
@@ -42,10 +42,15 @@ void main() {
expect(draft.attachments, [second]);
});
test('accepts exactly 1 MiB in total', () {
test('accepts exactly 100 MiB in total', () {
final draft = ChatAttachmentDraft();
expect(draft.add(attachment('large.bin', 700000)), isNull);
expect(
draft.add(
attachment('large.bin', ChatAttachmentDraft.maxTotalBytes - 348576),
),
isNull,
);
expect(draft.add(attachment('rest.bin', 348576)), isNull);
expect(draft.totalBytes, ChatAttachmentDraft.maxTotalBytes);
expect(draft.attachments, hasLength(2));
@@ -59,10 +64,7 @@ void main() {
final refusal = draft.add(attachment('extra.bin', 1));
expect(refusal, ChatAttachmentRefusal.totalTooLarge);
expect(
refusal!.message,
'Attachments are too large for web chat (1 MiB total).',
);
expect(refusal!.message, 'Attachments are too large (100 MiB total).');
expect(draft.attachments, [kept]);
expect(draft.totalBytes, ChatAttachmentDraft.maxTotalBytes);
});
@@ -121,14 +121,14 @@ void main() {
draft,
read: (_) {
reads += 1;
return Uint8List(ChatAttachmentDraft.maxTotalBytes + 1);
return Uint8List(maxInlineAttachmentBytes + 1);
},
),
throwsA(
isA<ChatAttachmentWireException>().having(
(error) => error.message,
'message',
'Attachments are too large for web chat (1 MiB total).',
'Attachments are too large to send without a server (1 MiB total).',
),
),
);
@@ -190,4 +190,35 @@ void main() {
isNull,
);
});
test(
'uploaded files are named in their parts, not carried as bytes',
() async {
final draft = ChatAttachmentDraft();
final big = ChatAttachment(
name: 'photo.png',
mime: 'image/png',
sizeBytes: maxInlineAttachmentBytes + 1,
);
draft.add(big);
final uploaded = <String>[];
final parts = await chatAttachmentUploadParts(
draft,
read: (_) => Uint8List(maxInlineAttachmentBytes + 1),
upload: (attachment, bytes) async {
uploaded.add(attachment.name);
return 'up-0123-${attachment.name}';
},
);
expect(uploaded, ['photo.png']);
expect(parts, [
{
'name': 'photo.png',
'mime': 'image/png',
'upload': 'up-0123-photo.png',
},
]);
},
);
}
+1 -1
View File
@@ -123,7 +123,7 @@ export async function start({ root = resolve('build/web'), upstream = 'http://12
if (!['GET', 'HEAD', 'POST'].includes(req.method)) {
res.setHeader('Allow', 'GET, HEAD, POST'); return reply(res, 405);
}
if (pathname === '/login' || pathname === '/logout' || pathname.startsWith('/artifacts/')) return proxy(req, res, target);
if (pathname === '/login' || pathname === '/logout' || pathname === '/chat-uploads' || pathname.startsWith('/artifacts/')) return proxy(req, res, target);
if (req.method !== 'GET' && req.method !== 'HEAD') return reply(res, 405);
authCheck(req, target, (authenticated) => {
if (res.destroyed) return;