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.

Terminal uploads: pace chunks by the daemon's acks; a stalled upload is given up and cancelled instead of freezing (#2305)

tony496s7cfb022f0ac8
diff --git a/desktop/lib/terminal/terminal_binary.dart b/desktop/lib/terminal/terminal_binary.dart
index b723f208f..455208800 100644
--- a/desktop/lib/terminal/terminal_binary.dart
+++ b/desktop/lib/terminal/terminal_binary.dart
@@ -290,3 +290,12 @@ TerminalBinaryFrame? decodeTerminalLocal(List<int> raw) {
/// spare). Every chunk but the last is exactly this size; `seq` is the chunk index. Mirrors the
/// harness CLI's `UPLOAD_CHUNK_BYTES` in terminalStreamManager.ts — keep the two in step.
const terminalUploadChunkBytes = 256 * 1024;
+
+/// Upload bytes allowed out ahead of the daemon's per-chunk acknowledgement
+/// (`terminal_chunked_upload_progress`). Sent back to back, a large image filled the P2P data
+/// channel's 2 MiB send buffer (`terminalP2pMaxBufferedBytes`) faster than a slow link drained it;
+/// the plugin then read the busy channel as a dead one and dropped the link with those chunks still
+/// in its buffer, and the upload stopped part way, its overlay frozen (2026-10-30). Four chunks keep
+/// that buffer, and the relay's own queue toward the machine, well below their limits. Every daemon
+/// that accepts a chunked upload acknowledges each chunk (both shipped together).
+const terminalUploadWindowBytes = 4 * terminalUploadChunkBytes;
diff --git a/desktop/lib/terminal/terminal_session.dart b/desktop/lib/terminal/terminal_session.dart
index cc601b1ef..4d4cf74a9 100644
--- a/desktop/lib/terminal/terminal_session.dart
+++ b/desktop/lib/terminal/terminal_session.dart
@@ -120,10 +120,33 @@ class UploadProgress {
/// Completers rather than one, since "the daemon accepted the announcement" and "the transfer is
/// over (however it ended)" are resolved at different points and by different frames.
class _ActiveUpload {
- final Completer<bool> beginAccepted = Completer<bool>();
+ Completer<bool> beginAccepted = Completer<bool>();
final Completer<bool> finished = Completer<bool>();
+
+ /// Why the daemon refused the last begin, as it said it.
+ String? refusal;
+
+ /// Bytes the daemon has confirmed holding (`terminal_chunked_upload_progress`).
+ int acked = 0;
+ Completer<void>? _ackWaiter;
+
+ void ack(int bytes) {
+ if (bytes <= acked) return;
+ acked = bytes;
+ final waiter = _ackWaiter;
+ _ackWaiter = null;
+ waiter?.complete();
+ }
+
+ /// Completes when the daemon next confirms more of the upload.
+ Future<void> nextAck() => (_ackWaiter ??= Completer<void>()).future;
}
+/// What a daemon answers a begin while it still holds an upload for the same pane. This pane runs
+/// one upload at a time, so that one is an upload it already gave up on.
+const _uploadAlreadyInProgress =
+ 'an upload is already in progress on this pane';
+
/// One controller stream for one remote Harness agent.
///
/// Sequence corruption is recovered with bounded resync retries and one clean
@@ -152,6 +175,13 @@ class TerminalSession extends ChangeNotifier {
final TerminalBinarySender sendBinary;
final Duration resyncTimeout;
+
+ /// How long an upload may wait for the daemon to confirm another chunk before it is taken as
+ /// lost on the way and given up (see [_uploadBytes]).
+ final Duration uploadStallTimeout;
+
+ /// The progress of the last upload given up because it stalled; null once another starts.
+ UploadProgress? lastStalledUpload;
final bool _readOnly;
bool get readOnly => _readOnly || _watchOnly;
String? _inputContext;
@@ -223,6 +253,7 @@ class TerminalSession extends ChangeNotifier {
String? inputContext,
bool watchOnly = false,
this.resyncTimeout = const Duration(seconds: 4),
+ this.uploadStallTimeout = const Duration(seconds: 30),
DateTime Function()? now,
}) : _now = now ?? DateTime.now,
// ignore: prefer_initializing_formals
@@ -651,6 +682,9 @@ class TerminalSession extends ChangeNotifier {
if (!_matchesStream(payload)) return true;
final accepted = payload['accepted'] == true;
if (_activeUpload?.beginAccepted.isCompleted == false) {
+ _activeUpload!.refusal = accepted
+ ? null
+ : payload['reason']?.toString();
_activeUpload!.beginAccepted.complete(accepted);
}
// Older daemons only sent this text. A vanished stream cannot accept input or upload
@@ -666,6 +700,7 @@ class TerminalSession extends ChangeNotifier {
if (!_matchesStream(payload)) return true;
final bytesWritten = (payload['bytesWritten'] as num?)?.toInt();
final totalBytes = (payload['totalBytes'] as num?)?.toInt();
+ if (bytesWritten != null) _activeUpload?.ack(bytesWritten);
if (bytesWritten != null &&
totalBytes != null &&
uploadProgress != null) {
@@ -1189,6 +1224,7 @@ class TerminalSession extends ChangeNotifier {
final upload = _activeUpload;
final currentStreamId = streamId;
if (upload == null) return;
+ if (!upload.beginAccepted.isCompleted) upload.beginAccepted.complete(false);
if (!upload.finished.isCompleted) upload.finished.complete(false);
_clearUpload();
if (currentStreamId != null) {
@@ -1211,6 +1247,13 @@ class TerminalSession extends ChangeNotifier {
/// philosophy (`autonomous-harness/cli/src/cable/fwPush.ts`). Only one upload runs at a time per
/// pane — a second call while one is active is refused immediately, matching the daemon's own
/// "an upload is already in progress" rejection.
+ ///
+ /// The same ACKs pace the chunks: at most [terminalUploadWindowBytes] go out ahead of them. A
+ /// chunk lost on the way (a P2P link dropped with chunks in its buffer, say) is never asked for
+ /// again, and the daemon waits for it for as long as the stream lives; without an ACK for
+ /// [uploadStallTimeout], the upload is given up rather than left showing its last percentage.
+ /// Every upload given up is cancelled on the daemon too: one it still held refused every later
+ /// upload on the pane.
Future<bool> _uploadBytes({
required String uploadKind,
required String? filename,
@@ -1227,6 +1270,7 @@ class TerminalSession extends ChangeNotifier {
bool current() =>
_isCurrent(generation) && identical(_activeUpload, upload);
_activeUpload = upload;
+ lastStalledUpload = null;
uploadProgress = UploadProgress(
label: filename ?? 'image',
bytesWritten: 0,
@@ -1234,24 +1278,40 @@ class TerminalSession extends ChangeNotifier {
);
notifyListeners();
- final sentBegin = await send('terminal_chunked_upload_begin', {
- 'streamId': currentStreamId,
- 'uploadKind': uploadKind,
- 'totalBytes': bytes.length,
- 'filename': ?filename,
- });
- if (!current()) return false;
- if (!sentBegin) {
- transportLost('Terminal upload request was not sent');
- _clearUpload();
- return false;
+ var accepted = false;
+ // A daemon may still hold an upload an older build gave up on without cancelling it. Cancel
+ // that one and ask once more.
+ for (var attempt = 0; attempt < 2 && !accepted; attempt++) {
+ if (attempt > 0) {
+ upload.beginAccepted = Completer<bool>();
+ await send('terminal_chunked_upload_cancel', {
+ 'streamId': currentStreamId,
+ });
+ if (!current()) return false;
+ }
+ final sentBegin = await send('terminal_chunked_upload_begin', {
+ 'streamId': currentStreamId,
+ 'uploadKind': uploadKind,
+ 'totalBytes': bytes.length,
+ 'filename': ?filename,
+ });
+ if (!current()) return false;
+ if (!sentBegin) {
+ transportLost('Terminal upload request was not sent');
+ _clearUpload();
+ return false;
+ }
+ accepted = await upload.beginAccepted.future.timeout(
+ const Duration(seconds: 10),
+ onTimeout: () => false,
+ );
+ if (!current()) return false;
+ // An unanswered begin may still have been accepted.
+ if (!accepted && !upload.beginAccepted.isCompleted) {
+ return _abandonUpload(currentStreamId);
+ }
+ if (upload.refusal != _uploadAlreadyInProgress) break;
}
-
- final accepted = await upload.beginAccepted.future.timeout(
- const Duration(seconds: 10),
- onTimeout: () => false,
- );
- if (!current()) return false;
if (!accepted) {
_clearUpload();
return false;
@@ -1259,7 +1319,14 @@ class TerminalSession extends ChangeNotifier {
var offset = 0;
var seq = 0;
- while (offset < bytes.length) {
+ while (offset < bytes.length && !upload.finished.isCompleted) {
+ while (offset - upload.acked >= terminalUploadWindowBytes &&
+ !upload.finished.isCompleted) {
+ final moved = await _awaitUploadAck(upload);
+ if (!current()) return false;
+ if (!moved) return _abandonUpload(currentStreamId, stalled: true);
+ }
+ if (upload.finished.isCompleted) break;
final end = min(offset + terminalUploadChunkBytes, bytes.length);
final frame = TerminalBinaryFrame(
kind: binaryKind,
@@ -1279,13 +1346,55 @@ class TerminalSession extends ChangeNotifier {
seq++;
}
+ while (upload.acked < bytes.length && !upload.finished.isCompleted) {
+ final moved = await _awaitUploadAck(upload);
+ if (!current()) return false;
+ if (!moved) return _abandonUpload(currentStreamId, stalled: true);
+ }
+ // Every byte is there: what remains is the daemon's own paste (a clipboard write, a file).
final finished = await upload.finished.future.timeout(
const Duration(minutes: 2),
onTimeout: () => false,
);
if (!current()) return false;
+ if (!finished) return _abandonUpload(currentStreamId);
_clearUpload();
- return finished;
+ return true;
+ }
+
+ /// True once the daemon confirms more of [upload] or it ends; false after [uploadStallTimeout]
+ /// with neither.
+ Future<bool> _awaitUploadAck(_ActiveUpload upload) async {
+ try {
+ await Future.any([upload.nextAck(), upload.finished.future])
+ .timeout(uploadStallTimeout);
+ return true;
+ } on TimeoutException {
+ return false;
+ }
+ }
+
+ /// Gives up the active upload here and on the daemon. The cancel is queued before the upload is
+ /// cleared, so it reaches the daemon ahead of any upload this pane starts next.
+ Future<bool> _abandonUpload(
+ String uploadStreamId, {
+ bool stalled = false,
+ }) async {
+ final progress = uploadProgress;
+ if (stalled) {
+ lastStalledUpload = progress;
+ appLog.warn(
+ 'terminal',
+ 'upload stalled machine=$machineId agent=$agentId '
+ 'confirmed=${progress?.bytesWritten}/${progress?.totalBytes}',
+ );
+ }
+ final cancelled = send('terminal_chunked_upload_cancel', {
+ 'streamId': uploadStreamId,
+ });
+ _clearUpload();
+ await cancelled;
+ return false;
}
void _clearUpload() {
diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dart
index ac9e093c0..fb24042b5 100644
--- a/desktop/lib/widgets/terminal_panel.dart
+++ b/desktop/lib/widgets/terminal_panel.dart
@@ -1847,7 +1847,18 @@ class _TerminalPanelState extends State<TerminalPanel>
if (imageBytes != null &&
imageBytes.isNotEmpty &&
imageBytes.length <= terminalLocalImagePasteMaxPayloadBytes) {
- await target.pasteImage(imageBytes);
+ final pasted = await target.pasteImage(imageBytes);
+ final stalled = target.lastStalledUpload;
+ if (!pasted && stalled != null && mounted) {
+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(
+ SnackBar(
+ content: Text(
+ 'The image upload stopped at ${(stalled.percent * 100).round()}%: '
+ 'part of it never reached the machine. Paste again to retry.',
+ ),
+ ),
+ );
+ }
return;
}
}
diff --git a/desktop/test/terminal_clipboard_test.dart b/desktop/test/terminal_clipboard_test.dart
index db5224d11..19d8ab0f9 100644
--- a/desktop/test/terminal_clipboard_test.dart
+++ b/desktop/test/terminal_clipboard_test.dart
@@ -286,6 +286,73 @@ void main() {
},
);
+ onPlatform(
+ TargetPlatform.windows,
+ 'an image upload the machine stops confirming is given up and says how far it got',
+ (tester) async {
+ final app = createApp();
+ app.stateOf('m')!.terminalImagePasteAvailable = true;
+ final frames = <TerminalBinaryFrame>[];
+ final controls = <String>[];
+ final session =
+ TerminalSession(
+ machineId: 'm',
+ agentId: 'a0',
+ agentName: 'a0',
+ engineId: 'claude',
+ uploadStallTimeout: const Duration(seconds: 1),
+ send: (type, _) async {
+ controls.add(type);
+ return true;
+ },
+ sendBinary: (frame) async {
+ frames.add(frame);
+ return true;
+ },
+ )
+ ..status = TerminalSessionStatus.controlling
+ ..streamId = 'stream-a0';
+ final png = Uint8List(terminalUploadChunkBytes * 2);
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(imageChannel, (_) async => png);
+ clipboard = null;
+ await mount(tester, app, session);
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.keyV);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.keyV);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
+ await tester.pump();
+ await session.handleFrame('terminal_chunked_upload_begin_result', {
+ 'streamId': session.streamId,
+ 'accepted': true,
+ });
+ await tester.pump();
+ expect(frames, hasLength(2));
+ await session.handleFrame('terminal_chunked_upload_progress', {
+ 'streamId': session.streamId,
+ 'bytesWritten': terminalUploadChunkBytes,
+ 'totalBytes': png.length,
+ });
+ await tester.pump();
+ expect(find.textContaining('stopped at'), findsNothing);
+
+ await tester.pump(const Duration(seconds: 2));
+ await tester.pump();
+ expect(
+ find.text(
+ 'The image upload stopped at 50%: part of it never reached the '
+ 'machine. Paste again to retry.',
+ ),
+ findsOneWidget,
+ );
+ expect(controls.last, 'terminal_chunked_upload_cancel');
+ expect(session.uploadProgress, isNull);
+ await tester.pumpWidget(const SizedBox());
+ session.dispose();
+ app.dispose();
+ },
+ );
+
for (final platform in [
TargetPlatform.macOS,
TargetPlatform.linux,
diff --git a/desktop/test/terminal_session_test.dart b/desktop/test/terminal_session_test.dart
index ca77812b4..43c6f5259 100644
--- a/desktop/test/terminal_session_test.dart
+++ b/desktop/test/terminal_session_test.dart
@@ -2,6 +2,7 @@ import 'dart:async';
import 'dart:convert';
import 'dart:io';
+import 'package:fake_async/fake_async.dart';
import 'package:harness/logging/app_log.dart';
import 'package:harness/terminal/terminal_session.dart';
import 'package:harness/terminal/terminal_binary.dart';
@@ -2043,7 +2044,7 @@ void main() {
await session.handleFrame('terminal_chunked_upload_begin_result', {
'streamId': streamId,
'accepted': false,
- 'reason': 'an upload is already in progress on this pane',
+ 'reason': 'exceeds the 8 MB limit',
});
expect(await future, isFalse);
@@ -2051,9 +2052,195 @@ void main() {
expect(session.uploadProgress, isNull);
expect(session.acceptsInput, isTrue);
expect(sent.where((frame) => frame.type == 'terminal_open'), isEmpty);
+ expect(
+ sent.where((frame) => frame.type == 'terminal_chunked_upload_cancel'),
+ isEmpty,
+ );
+ },
+ );
+
+ test('cancels an upload the daemon still holds for this pane, then begins again', () async {
+ await live();
+ final png = Uint8List.fromList(const [1, 2, 3]);
+
+ final future = session.pasteImage(png);
+ await pump();
+ await session.handleFrame('terminal_chunked_upload_begin_result', {
+ 'streamId': streamId,
+ 'accepted': false,
+ 'reason': 'an upload is already in progress on this pane',
+ });
+ await pump();
+ expect(sent.map((frame) => frame.type), [
+ 'terminal_chunked_upload_begin',
+ 'terminal_chunked_upload_cancel',
+ 'terminal_chunked_upload_begin',
+ ]);
+ expect(imagePastes(), isEmpty);
+
+ await session.handleFrame('terminal_chunked_upload_begin_result', {
+ 'streamId': streamId,
+ 'accepted': true,
+ });
+ await pump();
+ expect(imagePastes().single.bytes, png);
+ await session.handleFrame('terminal_paste_image_result', {
+ 'streamId': streamId,
+ 'outcome': 'clipboard',
+ });
+ expect(await future, isTrue);
+ });
+
+ test(
+ 'asks only once more when the daemon still says an upload is in progress',
+ () async {
+ await live();
+ final future = session.pasteImage(Uint8List.fromList(const [1]));
+ for (var answer = 0; answer < 2; answer++) {
+ await pump();
+ await session.handleFrame('terminal_chunked_upload_begin_result', {
+ 'streamId': streamId,
+ 'accepted': false,
+ 'reason': 'an upload is already in progress on this pane',
+ });
+ }
+ expect(await future, isFalse);
+ expect(
+ sent.where((frame) => frame.type == 'terminal_chunked_upload_begin'),
+ hasLength(2),
+ );
+ expect(imagePastes(), isEmpty);
+ expect(session.uploadProgress, isNull);
},
);
+ test('cancels on the daemon a begin it never answered', () {
+ fakeAsync((async) {
+ live();
+ async.flushMicrotasks();
+ bool? result;
+ session
+ .pasteImage(Uint8List.fromList(const [1, 2, 3]))
+ .then((value) => result = value);
+ async.flushMicrotasks();
+ expect(
+ sent.where((frame) => frame.type == 'terminal_chunked_upload_begin'),
+ hasLength(1),
+ );
+
+ async.elapse(const Duration(seconds: 9));
+ expect(result, isNull);
+ async.elapse(const Duration(seconds: 2));
+ expect(result, isFalse);
+ expect(
+ sent
+ .where((frame) => frame.type == 'terminal_chunked_upload_cancel')
+ .single
+ .payload['streamId'],
+ streamId,
+ );
+ expect(session.uploadProgress, isNull);
+ expect(imagePastes(), isEmpty);
+ });
+ });
+
+ test('keeps at most the window of unconfirmed bytes on the way', () async {
+ await live();
+ final chunks = terminalUploadWindowBytes ~/ terminalUploadChunkBytes;
+ final big = Uint8List(terminalUploadChunkBytes * (chunks + 2) + 10);
+
+ final future = session.pasteImage(big);
+ await acceptBegin();
+ await pump();
+ expect(imagePastes(), hasLength(chunks));
+
+ Future<void> confirm(int bytes) async {
+ await session.handleFrame('terminal_chunked_upload_progress', {
+ 'streamId': streamId,
+ 'bytesWritten': bytes,
+ 'totalBytes': big.length,
+ });
+ await pump();
+ }
+
+ await confirm(terminalUploadChunkBytes);
+ expect(imagePastes(), hasLength(chunks + 1));
+ // A repeated or older figure makes no room.
+ await confirm(terminalUploadChunkBytes);
+ expect(imagePastes(), hasLength(chunks + 1));
+ await confirm(terminalUploadChunkBytes * 3);
+ expect(imagePastes().map((frame) => frame.seq), [
+ for (var seq = 0; seq < chunks + 3; seq++) seq,
+ ]);
+ expect(imagePastes().last.bytes, hasLength(10));
+
+ await confirm(big.length);
+ await session.handleFrame('terminal_paste_image_result', {
+ 'streamId': streamId,
+ 'outcome': 'clipboard',
+ });
+ expect(await future, isTrue);
+ expect(
+ sent.where((frame) => frame.type == 'terminal_chunked_upload_cancel'),
+ isEmpty,
+ );
+ });
+
+ for (final waitingForRoom in [true, false]) {
+ test('gives up an upload the daemon stops confirming, here and on the daemon '
+ '(waiting for room in the window: $waitingForRoom)', () async {
+ session.dispose();
+ session = TerminalSession(
+ machineId: 'machine-1',
+ agentId: 'agent-1',
+ agentName: 'backend-api',
+ engineId: 'codex',
+ uploadStallTimeout: const Duration(milliseconds: 50),
+ send: (type, payload) async {
+ sent.add((type: type, payload: Map<String, dynamic>.from(payload)));
+ return true;
+ },
+ sendBinary: (frame) async {
+ binarySent.add(frame);
+ return true;
+ },
+ );
+ await live();
+ final chunks = waitingForRoom
+ ? terminalUploadWindowBytes ~/ terminalUploadChunkBytes + 3
+ : 3;
+ final image = Uint8List(terminalUploadChunkBytes * chunks);
+
+ final future = session.pasteImage(image);
+ await acceptBegin();
+ await pump();
+ // Part of the image arrives; the rest was lost on the way.
+ await session.handleFrame('terminal_chunked_upload_progress', {
+ 'streamId': streamId,
+ 'bytesWritten': terminalUploadChunkBytes,
+ 'totalBytes': image.length,
+ });
+
+ expect(await future, isFalse);
+ expect(imagePastes(), hasLength(waitingForRoom ? 5 : 3));
+ expect(session.uploadProgress, isNull);
+ expect(
+ session.lastStalledUpload!.bytesWritten,
+ terminalUploadChunkBytes,
+ );
+ expect(sent.last.type, 'terminal_chunked_upload_cancel');
+ expect(sent.last.payload['streamId'], streamId);
+ // The stream itself is fine: nothing reopens, and the next upload starts at once.
+ expect(session.status, TerminalSessionStatus.controlling);
+ expect(sent.where((frame) => frame.type == 'terminal_open'), isEmpty);
+ unawaited(session.pasteImage(Uint8List.fromList(const [1])));
+ await pump();
+ expect(sent.last.type, 'terminal_chunked_upload_begin');
+ expect(session.lastStalledUpload, isNull);
+ await session.cancelUpload();
+ });
+ }
+
for (final coded in [true, false]) {
test(
'a missing-stream upload rejection reopens once without replay (coded=$coded)',
@@ -2134,6 +2321,32 @@ void main() {
expect(session.uploadProgress, isNull);
});
+ test(
+ 'cancelUpload before the daemon answers the begin settles it at once',
+ () {
+ fakeAsync((async) {
+ live();
+ async.flushMicrotasks();
+ bool? result;
+ session
+ .pasteImage(Uint8List.fromList(const [1, 2, 3]))
+ .then((value) => result = value);
+ async.flushMicrotasks();
+
+ session.cancelUpload();
+ async.flushMicrotasks();
+
+ expect(result, isFalse);
+ expect(
+ sent.where(
+ (frame) => frame.type == 'terminal_chunked_upload_cancel',
+ ),
+ hasLength(1),
+ );
+ });
+ },
+ );
+
test('cancelUpload stops the transfer and tells the daemon', () async {
await live();
final png = Uint8List.fromList(const [1, 2, 3]);
diff --git a/mobile/lib/terminal/terminal_binary.dart b/mobile/lib/terminal/terminal_binary.dart
index ca57a3fac..4a935eb5d 100644
--- a/mobile/lib/terminal/terminal_binary.dart
+++ b/mobile/lib/terminal/terminal_binary.dart
@@ -295,3 +295,12 @@ TerminalBinaryFrame? decodeTerminalLocal(List<int> raw) {
/// spare). Every chunk but the last is exactly this size; `seq` is the chunk index. Mirrors the
/// harness CLI's `UPLOAD_CHUNK_BYTES` in terminalStreamManager.ts — keep the two in step.
const terminalUploadChunkBytes = 256 * 1024;
+
+/// Upload bytes allowed out ahead of the daemon's per-chunk acknowledgement
+/// (`terminal_chunked_upload_progress`). Sent back to back, a large image filled the P2P data
+/// channel's 2 MiB send buffer (`terminalP2pMaxBufferedBytes`) faster than a slow link drained it;
+/// the plugin then read the busy channel as a dead one and dropped the link with those chunks still
+/// in its buffer, and the upload stopped part way, its overlay frozen (2026-10-30). Four chunks keep
+/// that buffer, and the relay's own queue toward the machine, well below their limits. Every daemon
+/// that accepts a chunked upload acknowledges each chunk (both shipped together).
+const terminalUploadWindowBytes = 4 * terminalUploadChunkBytes;
diff --git a/mobile/lib/terminal/terminal_session.dart b/mobile/lib/terminal/terminal_session.dart
index 21a9e5763..33ecf228f 100644
--- a/mobile/lib/terminal/terminal_session.dart
+++ b/mobile/lib/terminal/terminal_session.dart
@@ -125,10 +125,33 @@ class UploadProgress {
/// Completers rather than one, since "the daemon accepted the announcement" and "the transfer is
/// over (however it ended)" are resolved at different points and by different frames.
class _ActiveUpload {
- final Completer<bool> beginAccepted = Completer<bool>();
+ Completer<bool> beginAccepted = Completer<bool>();
final Completer<bool> finished = Completer<bool>();
+
+ /// Why the daemon refused the last begin, as it said it.
+ String? refusal;
+
+ /// Bytes the daemon has confirmed holding (`terminal_chunked_upload_progress`).
+ int acked = 0;
+ Completer<void>? _ackWaiter;
+
+ void ack(int bytes) {
+ if (bytes <= acked) return;
+ acked = bytes;
+ final waiter = _ackWaiter;
+ _ackWaiter = null;
+ waiter?.complete();
+ }
+
+ /// Completes when the daemon next confirms more of the upload.
+ Future<void> nextAck() => (_ackWaiter ??= Completer<void>()).future;
}
+/// What a daemon answers a begin while it still holds an upload for the same pane. This pane runs
+/// one upload at a time, so that one is an upload it already gave up on.
+const _uploadAlreadyInProgress =
+ 'an upload is already in progress on this pane';
+
/// One controller stream for one remote Harness agent.
///
/// Sequence corruption is recovered with bounded resync retries and one clean
@@ -154,6 +177,13 @@ class TerminalSession extends ChangeNotifier {
final Duration resyncTimeout;
+ /// How long an upload may wait for the daemon to confirm another chunk before it is taken as
+ /// lost on the way and given up (see [_uploadBytes]).
+ final Duration uploadStallTimeout;
+
+ /// The progress of the last upload given up because it stalled; null once another starts.
+ UploadProgress? lastStalledUpload;
+
/// Forces a fresh transport dial (see `WsConn.forceReconnect`) — called once when the very first
/// `terminal_open` never gets a `terminal_ready` back within [resyncTimeout]. Covers the relay
/// going stale silently (the relayed machine's own Harness process restarted, dropping its E2EE
@@ -202,6 +232,7 @@ class TerminalSession extends ChangeNotifier {
this.lastHeardFromMachine,
this.onTransportSilent,
this.resyncTimeout = const Duration(seconds: 4),
+ this.uploadStallTimeout = const Duration(seconds: 30),
this.takeover = true,
this.scrollMemory,
}) {
@@ -900,6 +931,9 @@ class TerminalSession extends ChangeNotifier {
if (!_matchesStream(payload)) return true;
final accepted = payload['accepted'] == true;
if (_activeUpload?.beginAccepted.isCompleted == false) {
+ _activeUpload!.refusal = accepted
+ ? null
+ : payload['reason']?.toString();
_activeUpload!.beginAccepted.complete(accepted);
}
// A stream the daemon no longer has takes no input and no upload, and nothing else says
@@ -917,6 +951,7 @@ class TerminalSession extends ChangeNotifier {
if (!_matchesStream(payload)) return true;
final bytesWritten = (payload['bytesWritten'] as num?)?.toInt();
final totalBytes = (payload['totalBytes'] as num?)?.toInt();
+ if (bytesWritten != null) _activeUpload?.ack(bytesWritten);
if (bytesWritten != null &&
totalBytes != null &&
uploadProgress != null) {
@@ -1716,6 +1751,7 @@ class TerminalSession extends ChangeNotifier {
final upload = _activeUpload;
final currentStreamId = streamId;
if (upload == null) return;
+ if (!upload.beginAccepted.isCompleted) upload.beginAccepted.complete(false);
if (!upload.finished.isCompleted) upload.finished.complete(false);
_clearUpload();
if (currentStreamId != null) {
@@ -1738,6 +1774,13 @@ class TerminalSession extends ChangeNotifier {
/// philosophy (`autonomous-harness/cli/src/cable/fwPush.ts`). Only one upload runs at a time per
/// pane — a second call while one is active is refused immediately, matching the daemon's own
/// "an upload is already in progress" rejection.
+ ///
+ /// The same ACKs pace the chunks: at most [terminalUploadWindowBytes] go out ahead of them. A
+ /// chunk lost on the way (a P2P link dropped with chunks in its buffer, say) is never asked for
+ /// again, and the daemon waits for it for as long as the stream lives; without an ACK for
+ /// [uploadStallTimeout], the upload is given up rather than left showing its last percentage.
+ /// Every upload given up is cancelled on the daemon too: one it still held refused every later
+ /// upload on the pane.
Future<bool> _uploadBytes({
required String uploadKind,
required String? filename,
@@ -1754,6 +1797,7 @@ class TerminalSession extends ChangeNotifier {
bool current() =>
_isCurrent(generation) && identical(_activeUpload, upload);
_activeUpload = upload;
+ lastStalledUpload = null;
uploadProgress = UploadProgress(
label: filename ?? 'image',
bytesWritten: 0,
@@ -1761,24 +1805,40 @@ class TerminalSession extends ChangeNotifier {
);
notifyListeners();
- final sentBegin = await send('terminal_chunked_upload_begin', {
- 'streamId': currentStreamId,
- 'uploadKind': uploadKind,
- 'totalBytes': bytes.length,
- 'filename': ?filename,
- });
- if (!current()) return false;
- if (!sentBegin) {
- transportLost('Terminal upload request was not sent');
- _clearUpload();
- return false;
+ var accepted = false;
+ // A daemon may still hold an upload an older build gave up on without cancelling it. Cancel
+ // that one and ask once more.
+ for (var attempt = 0; attempt < 2 && !accepted; attempt++) {
+ if (attempt > 0) {
+ upload.beginAccepted = Completer<bool>();
+ await send('terminal_chunked_upload_cancel', {
+ 'streamId': currentStreamId,
+ });
+ if (!current()) return false;
+ }
+ final sentBegin = await send('terminal_chunked_upload_begin', {
+ 'streamId': currentStreamId,
+ 'uploadKind': uploadKind,
+ 'totalBytes': bytes.length,
+ 'filename': ?filename,
+ });
+ if (!current()) return false;
+ if (!sentBegin) {
+ transportLost('Terminal upload request was not sent');
+ _clearUpload();
+ return false;
+ }
+ accepted = await upload.beginAccepted.future.timeout(
+ const Duration(seconds: 10),
+ onTimeout: () => false,
+ );
+ if (!current()) return false;
+ // An unanswered begin may still have been accepted.
+ if (!accepted && !upload.beginAccepted.isCompleted) {
+ return _abandonUpload(currentStreamId);
+ }
+ if (upload.refusal != _uploadAlreadyInProgress) break;
}
-
- final accepted = await upload.beginAccepted.future.timeout(
- const Duration(seconds: 10),
- onTimeout: () => false,
- );
- if (!current()) return false;
if (!accepted) {
_clearUpload();
return false;
@@ -1786,7 +1846,14 @@ class TerminalSession extends ChangeNotifier {
var offset = 0;
var seq = 0;
- while (offset < bytes.length) {
+ while (offset < bytes.length && !upload.finished.isCompleted) {
+ while (offset - upload.acked >= terminalUploadWindowBytes &&
+ !upload.finished.isCompleted) {
+ final moved = await _awaitUploadAck(upload);
+ if (!current()) return false;
+ if (!moved) return _abandonUpload(currentStreamId, stalled: true);
+ }
+ if (upload.finished.isCompleted) break;
final end = min(offset + terminalUploadChunkBytes, bytes.length);
final frame = TerminalBinaryFrame(
kind: binaryKind,
@@ -1806,13 +1873,54 @@ class TerminalSession extends ChangeNotifier {
seq++;
}
+ while (upload.acked < bytes.length && !upload.finished.isCompleted) {
+ final moved = await _awaitUploadAck(upload);
+ if (!current()) return false;
+ if (!moved) return _abandonUpload(currentStreamId, stalled: true);
+ }
+ // Every byte is there: what remains is the daemon's own paste (a clipboard write, a file).
final finished = await upload.finished.future.timeout(
const Duration(minutes: 2),
onTimeout: () => false,
);
if (!current()) return false;
+ if (!finished) return _abandonUpload(currentStreamId);
_clearUpload();
- return finished;
+ return true;
+ }
+
+ /// True once the daemon confirms more of [upload] or it ends; false after [uploadStallTimeout]
+ /// with neither.
+ Future<bool> _awaitUploadAck(_ActiveUpload upload) async {
+ try {
+ await Future.any([upload.nextAck(), upload.finished.future])
+ .timeout(uploadStallTimeout);
+ return true;
+ } on TimeoutException {
+ return false;
+ }
+ }
+
+ /// Gives up the active upload here and on the daemon. The cancel is queued before the upload is
+ /// cleared, so it reaches the daemon ahead of any upload this pane starts next.
+ Future<bool> _abandonUpload(
+ String uploadStreamId, {
+ bool stalled = false,
+ }) async {
+ final progress = uploadProgress;
+ if (stalled) {
+ lastStalledUpload = progress;
+ debugPrint(
+ 'TerminalSession: upload stalled agent=$agentId '
+ 'confirmed=${progress?.bytesWritten}/${progress?.totalBytes}',
+ );
+ }
+ final cancelled = send('terminal_chunked_upload_cancel', {
+ 'streamId': uploadStreamId,
+ });
+ _clearUpload();
+ await cancelled;
+ return false;
}
void _clearUpload() {
diff --git a/mobile/test/terminal_session_protocol_test.dart b/mobile/test/terminal_session_protocol_test.dart
index 5d9ad4b4d..4f1b7c788 100644
--- a/mobile/test/terminal_session_protocol_test.dart
+++ b/mobile/test/terminal_session_protocol_test.dart
@@ -26,6 +26,7 @@ void main() {
DateTime? Function()? lastHeardFromMachine,
bool Function()? onTransportSilent,
Duration resync = const Duration(milliseconds: 40),
+ Duration uploadStall = const Duration(seconds: 30),
bool disposeAtEnd = true,
}) {
final built = TerminalSession(
@@ -40,6 +41,7 @@ void main() {
lastHeardFromMachine: lastHeardFromMachine,
onTransportSilent: onTransportSilent,
resyncTimeout: resync,
+ uploadStallTimeout: uploadStall,
takeover: takeover,
);
if (disposeAtEnd) addTearDown(built.dispose);
@@ -78,8 +80,9 @@ void main() {
String engine = 'claude',
String screen = 'prompt> ',
Duration resync = const Duration(milliseconds: 40),
+ Duration uploadStall = const Duration(seconds: 30),
}) async {
- final s = session(engine: engine, resync: resync);
+ final s = session(engine: engine, resync: resync, uploadStall: uploadStall);
await s.open();
final streamId = await ready(s);
await s.handleBinary(_keyframe(streamId, text: screen));
@@ -1677,6 +1680,33 @@ void main() {
expect(wire.of('terminal_chunked_upload_cancel'), hasLength(1));
});
+ test('cancelling before the daemon answers the announcement settles it at '
+ 'once', () {
+ fakeAsync((async) {
+ final s = session(disposeAtEnd: false);
+ s.open();
+ async.flushMicrotasks();
+ s.handleFrame('terminal_ready', {
+ 'requestId': wire.last('terminal_open')['requestId'],
+ 'agentId': 'a',
+ 'protocolVersion': TerminalSession.protocolVersion,
+ 'streamId': _streamId(),
+ });
+ s.handleBinary(_keyframe(s.streamId!));
+ async.flushMicrotasks();
+ bool? result;
+ s.pasteImage(Uint8List(3)).then((value) => result = value);
+ async.flushMicrotasks();
+
+ s.cancelUpload();
+ async.flushMicrotasks();
+
+ expect(result, isFalse);
+ expect(wire.of('terminal_chunked_upload_cancel'), hasLength(1));
+ s.dispose();
+ });
+ });
+
test('a stream lost mid-upload settles it at once', () async {
final (s, _) = await live();
@@ -1745,10 +1775,130 @@ void main() {
async.elapse(const Duration(seconds: 11));
expect(result, isFalse);
+ // It may have been accepted all the same: the daemon is told to drop it.
+ expect(wire.last('terminal_chunked_upload_cancel'), {
+ 'streamId': s.streamId,
+ });
s.dispose();
});
});
+ test(
+ 'chunks wait for the daemon to confirm: at most the window is on the way',
+ () async {
+ final (s, _) = await live();
+ final window = terminalUploadWindowBytes ~/ terminalUploadChunkBytes;
+ final image = Uint8List(terminalUploadChunkBytes * (window + 2) + 7);
+ List<int> sent() => [
+ for (final f in wire.binaries)
+ if (f.kind == TerminalBinaryKind.imagePaste) f.seq,
+ ];
+ Future<void> confirm(int bytes) async {
+ await answer(s, 'terminal_chunked_upload_progress', {
+ 'bytesWritten': bytes,
+ 'totalBytes': image.length,
+ });
+ await Future<void>.delayed(Duration.zero);
+ }
+
+ final pasting = s.pasteImage(image);
+ await Future<void>.delayed(Duration.zero);
+ await answer(s, 'terminal_chunked_upload_begin_result', {
+ 'accepted': true,
+ });
+ await Future<void>.delayed(Duration.zero);
+ expect(sent(), hasLength(window));
+
+ await confirm(terminalUploadChunkBytes);
+ expect(sent(), hasLength(window + 1));
+ await confirm(terminalUploadChunkBytes);
+ expect(sent(), hasLength(window + 1));
+ await confirm(terminalUploadChunkBytes * 3);
+ expect(sent(), [for (var seq = 0; seq < window + 3; seq++) seq]);
+
+ await confirm(image.length);
+ await answer(s, 'terminal_paste_image_result');
+ expect(await pasting, isTrue);
+ expect(wire.of('terminal_chunked_upload_cancel'), isEmpty);
+ },
+ );
+
+ for (final waitingForRoom in [true, false]) {
+ test('an upload the daemon stops confirming is given up, here and on the '
+ 'daemon (waiting for room: $waitingForRoom)', () async {
+ final (s, streamId) = await live(
+ uploadStall: const Duration(milliseconds: 50),
+ );
+ final window = terminalUploadWindowBytes ~/ terminalUploadChunkBytes;
+ final chunks = waitingForRoom ? window + 3 : 3;
+ final image = Uint8List(terminalUploadChunkBytes * chunks);
+
+ final pasting = s.pasteImage(image);
+ await Future<void>.delayed(Duration.zero);
+ await answer(s, 'terminal_chunked_upload_begin_result', {
+ 'accepted': true,
+ });
+ await Future<void>.delayed(Duration.zero);
+ // Part of the picture arrives; the rest was lost on the way.
+ await answer(s, 'terminal_chunked_upload_progress', {
+ 'bytesWritten': terminalUploadChunkBytes,
+ 'totalBytes': image.length,
+ });
+
+ expect(await pasting, isFalse);
+ expect(
+ wire.binaries.where((f) => f.kind == TerminalBinaryKind.imagePaste),
+ hasLength(waitingForRoom ? window + 1 : 3),
+ );
+ expect(s.uploadProgress, isNull);
+ expect(s.lastStalledUpload!.bytesWritten, terminalUploadChunkBytes);
+ expect(wire.last('terminal_chunked_upload_cancel'), {
+ 'streamId': streamId,
+ });
+ expect(s.status, TerminalSessionStatus.controlling);
+
+ final next = s.pasteImage(Uint8List(3));
+ await Future<void>.delayed(Duration.zero);
+ expect(wire.of('terminal_chunked_upload_begin'), hasLength(2));
+ expect(s.lastStalledUpload, isNull);
+ await s.cancelUpload();
+ expect(await next, isFalse);
+ });
+ }
+
+ test('an upload the daemon still holds for this pane is cancelled, and the '
+ 'announcement made once more', () async {
+ final (s, streamId) = await live();
+ const stale = {
+ 'accepted': false,
+ 'reason': 'an upload is already in progress on this pane',
+ };
+
+ final pasting = s.pasteImage(Uint8List(3));
+ await Future<void>.delayed(Duration.zero);
+ await answer(s, 'terminal_chunked_upload_begin_result', stale);
+ await Future<void>.delayed(Duration.zero);
+ expect(wire.of('terminal_chunked_upload_cancel'), [
+ {'streamId': streamId},
+ ]);
+ expect(wire.of('terminal_chunked_upload_begin'), hasLength(2));
+ await answer(s, 'terminal_chunked_upload_begin_result', {
+ 'accepted': true,
+ });
+ await Future<void>.delayed(Duration.zero);
+ await answer(s, 'terminal_paste_image_result');
+ expect(await pasting, isTrue);
+
+ // Only once: a daemon that refuses again ends it.
+ final again = s.pasteImage(Uint8List(3));
+ for (var i = 0; i < 2; i++) {
+ await Future<void>.delayed(Duration.zero);
+ await answer(s, 'terminal_chunked_upload_begin_result', stale);
+ }
+ expect(await again, isFalse);
+ expect(wire.of('terminal_chunked_upload_begin'), hasLength(4));
+ });
+
test('frames about an upload on another stream are ignored', () async {
final (s, _) = await live();
final other = _streamId();