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.

Merge the dead-code pass into phone-overnight-polish

dee87140c85d11f
diff --cc mobile/lib/core/snapshot_store.dart
index cfa7990ef,2701fe0f4..8ba750acf
--- a/mobile/lib/core/snapshot_store.dart
+++ b/mobile/lib/core/snapshot_store.dart
@@@ -82,22 -82,3 +82,22 @@@ class FileSnapshotStore implements Snap
}
}
}
+
- /// The same contract with no disk under it — for tests, and for a build that
- /// deliberately keeps nothing.
++/// In memory — what every test passes, for the reason at the top of this file: a widget test that
++/// reached a real file store would hang rather than fail.
+class MemorySnapshotStore implements SnapshotStore {
+ MemorySnapshotStore([this.contents]);
+
+ String? contents;
+
+ bool get isEmpty => contents == null;
+
+ @override
+ Future<String?> read() async => contents;
+
+ @override
+ Future<void> write(String value) async => contents = value;
+
+ @override
+ Future<void> clear() async => contents = null;
+}
diff --cc mobile/lib/phone/phone_search_field.dart
index 4f0144cfe,4035070ca..39d394db9
--- a/mobile/lib/phone/phone_search_field.dart
+++ b/mobile/lib/phone/phone_search_field.dart
@@@ -428,21 -113,10 +113,20 @@@ class _QueryInput extends StatelessWidg
// — and a capital forced onto the first letter of one is a wrong query.
textCapitalization: TextCapitalization.none,
// With the decoration's padding zeroed below, the field is exactly one line
- // tall inside its box (44pt on the page, 36 in the sheet); this is what
- // centres that line on the chevron or magnifier beside it instead of
- // letting it sit on the box's top edge.
+ // tall inside its 44pt box; this is what centres that line in the box
+ // instead of letting it sit on the box's top edge.
textAlignVertical: TextAlignVertical.center,
- style: TextStyle(color: AppPalette.textPrimary, fontSize: 16),
+ // ⚠️ The face the placeholder and every row under it are in — the terminal's. Left to
+ // TextField, what is typed took the theme's sans and the query changed typeface the moment
+ // the first key landed.
+ style: TextStyle(
+ fontFamily: DefaultTextStyle.of(context).style.fontFamily,
+ fontFamilyFallback: DefaultTextStyle.of(context)
+ .style
+ .fontFamilyFallback,
+ color: AppPalette.textPrimary,
+ fontSize: 16,
+ ),
cursorColor: AppPalette.accentOnSurface,
decoration: InputDecoration(
isDense: true,
diff --cc mobile/lib/phone/terminal_page.dart
index deb75bac0,f458dd03e..751f104bd
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@@ -1999,10 -1858,11 +1894,9 @@@ class _TerminalPageState extends State<
),
),
onLineTap: _onLineTap,
- showHeader: false,
- // tmux's copy-mode position while
- // reading back — see [_CopyModePosition].
+ // Where the reader is in the history —
+ // what holds the view still under them.
scrollback: _scrollback,
- jumpToEndRequest:
- _jumpToEnd,
// No composer, and so no grip above it: the
// page hands the pane its full height and the
// software keyboard drives the terminal
@@@ -3232,51 -3052,45 +3069,6 @@@ class _SkeletonTurn
final double? meta;
}
- /// The longest agent name the header will print before it cuts.
- ///
- /// An agent's name is usually a filename, and the header row has to hold three
- /// controls beside it. Left to the width alone, a long name pushed right up
- /// against `+` with no gap; cutting by COUNT keeps a fixed, predictable stretch
- /// of chrome whatever the name and whatever the screen.
- const int _titleMaxChars = 20;
-/// tmux's copy-mode position — `[42/1380]` on tmux's yellow, top right — while the reader is up in
-/// the history: 42 lines above the end, of 1380. The view holds still as output arrives, and the
-/// first number counts it. One tap is back at the end, following the stream.
-class _CopyModePosition extends StatelessWidget {
- const _CopyModePosition({
- required this.above,
- required this.total,
- required this.onTap,
- });
--
- /// The name as the header prints it: cut to [_titleMaxChars] with an ellipsis
- /// when it is longer.
- ///
- /// ⚠️ Counts runes, not code units. `String.length` counts UTF-16 units, so an
- /// emoji or a decomposed Vietnamese vowel costs two and a name cuts early —
- /// short of the 20 the design asks for, and at a different point per name.
- ///
- /// ⚠️ The header's own width ellipsis stays as well. This one bounds the
- /// string; that one still catches a 20-character name on a narrow screen, and
- /// neither makes the other redundant.
- ///
- /// ⚠️ **Nothing calls it** — [TerminalHeader] ellipses the name on width alone,
- /// beside the machine. Kept because a count cut may be wanted there again, and
- /// this is the rune-correct one it would want.
- // ignore: unused_element
- String _clipTitle(String name) {
- final runes = name.runes.toList();
- if (runes.length <= _titleMaxChars) return name;
- // Trailing space before the ellipsis reads as a typo, so it goes.
- return '${String.fromCharCodes(runes.take(_titleMaxChars)).trimRight()}…';
- }
- final int above;
- final int total;
- final VoidCallback onTap;
--
- /// One of the header's trailing controls, padded so the three sit evenly.
- ///
- /// ⚠️ The padding is what makes the row look right, and the reason is that
- /// [AppIconButton] is a fixed 24px box for every glyph size. A 22px glyph fills
- /// that box to its edges while a 20px one floats inside it, so equal gaps
- /// BETWEEN the boxes read as unequal gaps between the marks. Giving every
- /// action the same glyph size and the same padding puts the marks on an even
- /// pitch.
- ///
- /// ⚠️ It does NOT widen the tap target. [AppIconButton] takes its tap on a
- /// 24px `GestureDetector` with no `HitTestBehavior.opaque`, so the padding is
- /// dead space either side and the three stay 24px each — under the 44 iOS asks
- /// for. Fixing that belongs in the shared button, where every screen's header
- /// would get it, not in a wrapper one page defines.
- @override
- Widget build(BuildContext context) {
- final tty = Tty.of(context);
- return Semantics(
- button: true,
- label: '$above lines above the end. Back to the latest output',
- child: GestureDetector(
- behavior: HitTestBehavior.opaque,
- onTap: onTap,
- child: Padding(
- // A full touch target around a one-line tag.
- padding: const EdgeInsets.all(8),
- child: ColoredBox(
- color: tty.yellow,
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 4),
- child: TtyText('[$above/$total]', color: tty.theme.black),
- ),
- ),
- ),
- ),
- );
- }
-}
--
/// Slides the title off the top as [progress] runs 0 → 1, fading it as it goes.
class _SlideAway extends StatelessWidget {
const _SlideAway({required this.progress, required this.child});
diff --cc mobile/test/api/api_client_test.dart
index b9aea740b,000000000..ff7a2a9e7
mode 100644,000000..100644
--- a/mobile/test/api/api_client_test.dart
+++ b/mobile/test/api/api_client_test.dart
@@@ -1,404 -1,0 +1,396 @@@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:typed_data';
+
+import 'package:dio/dio.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+import 'package:harness_mobile/api/access_token_source.dart';
+import 'package:harness_mobile/api/api_client.dart';
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/viewer/direct_auth.dart';
+import 'package:harness_mobile/viewer/direct_auth_api.dart';
+import 'package:harness_mobile/viewer/email_code_api.dart';
+
+import '../viewer/fake_http.dart';
+import '../voice_fakes.dart' show MemoryKeyValueStore;
+
+/// The backend on loopback — nothing leaves the process. Each request is recorded, and answered
+/// by [answer] with a status and a JSON body.
+class _Backend {
+ _Backend._(this.server);
+
+ final HttpServer server;
+ final requests =
+ <
+ ({
+ String method,
+ String path,
+ Map<String, String> query,
+ HttpHeaders headers,
+ List<int> body,
+ })
+ >[];
+ ({int status, Object? body}) Function(HttpRequest request, int index) answer =
+ (_, _) =>
+ (status: 200, body: {'success': true, 'data': <String, Object?>{}});
+
+ String get url => 'http://127.0.0.1:${server.port}';
+
+ static Future<_Backend> start() async {
+ final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ final backend = _Backend._(server);
+ server.listen((request) async {
+ final body = await request.fold<List<int>>(
+ [],
+ (all, chunk) => all..addAll(chunk),
+ );
+ final index = backend.requests.length;
+ backend.requests.add((
+ method: request.method,
+ path: request.uri.path,
+ query: request.uri.queryParameters,
+ headers: request.headers,
+ body: body,
+ ));
+ final reply = backend.answer(request, index);
+ request.response
+ ..statusCode = reply.status
+ ..headers.contentType = ContentType.json
+ ..write(jsonEncode(reply.body));
+ await request.response.close();
+ });
+ return backend;
+ }
+}
+
+/// Hands out tokens as told, and counts what it was asked.
+class _Tokens implements AccessTokenSource {
+ _Tokens(this.tokens);
+
+ final List<String> tokens;
+ int index = 0;
+ final asks = <({bool force, String? failedToken})>[];
+ Object? failWith;
+
+ @override
+ Future<String> accessToken({bool force = false, String? failedToken}) async {
+ asks.add((force: force, failedToken: failedToken));
+ final error = failWith;
+ if (error != null) throw error;
+ if (force) index++;
+ return tokens[index.clamp(0, tokens.length - 1)];
+ }
+}
+
+void main() {
+ late _Backend backend;
+ setUp(() async => backend = await _Backend.start());
+ tearDown(() async => backend.server.close(force: true));
+
+ ApiClient client(AccessTokenSource auth) => ApiClient(
+ config: AppConfig(apiBaseUrl: backend.url, autonomousEnv: 'stag'),
+ session: AuthSession(storage: MemoryKeyValueStore()),
+ auth: auth,
+ );
+
+ Map<String, Object?> ok(Object? data) => {'success': true, 'data': data};
+
+ group('signing', () {
+ test('every call carries the bearer and the environment', () async {
+ backend.answer = (_, _) => (status: 200, body: ok({'email': '[email protected]'}));
+ final me = await client(_Tokens(['t1'])).me();
+ expect(me, {'email': '[email protected]'});
+ final sent = backend.requests.single;
+ expect(sent.path, '/api/auth/me');
+ expect(sent.headers.value('authorization'), 'Bearer t1');
+ expect(sent.headers.value('x-autonomous-env'), 'stag');
+ });
+
+ test(
+ 'a 401 is retried once, with a token renewed past the refused one',
+ () async {
+ backend.answer = (_, index) => index == 0
+ ? (status: 401, body: {'success': false})
+ : (status: 200, body: ok({'machines': <Object>[]}));
+ final tokens = _Tokens(['old', 'new']);
+ expect(await client(tokens).machines(), isEmpty);
+ expect(backend.requests.map((r) => r.headers.value('authorization')), [
+ 'Bearer old',
+ 'Bearer new',
+ ]);
+ expect(tokens.asks.where((a) => a.force).single.failedToken, 'old');
+ },
+ );
+
+ test('a second 401 is the answer: no loop', () async {
+ backend.answer = (_, _) => (
+ status: 401,
+ body: {
+ 'success': false,
+ 'error': {'message': 'Unauthorized'},
+ },
+ );
+ await expectLater(
+ client(_Tokens(['a', 'b', 'c'])).me(),
+ throwsA(
+ isA<ApiException>()
+ .having((e) => e.status, 'status', 401)
+ .having((e) => e.message, 'message', 'Unauthorized'),
+ ),
+ );
+ expect(backend.requests, hasLength(2));
+ });
+
+ test('a refresh that fails hands back the 401 itself', () async {
+ final tokens = _Tokens(['old']);
+ backend.answer = (_, _) {
+ tokens.failWith = const DirectAuthException('offline');
+ return (status: 401, body: {'success': false});
+ };
+ final error = await client(tokens)
+ .me()
+ .then<Object?>((_) => null, onError: (Object e) => e);
- expect(isUnauthorizedError(error!), isTrue);
++ // A 401 that survived the one retry reaches the caller as one.
++ expect(
++ (error is ApiException && error.status == 401) ||
++ (error is DioException && error.response?.statusCode == 401),
++ isTrue,
++ reason: '$error',
++ );
+ expect(backend.requests, hasLength(1));
+ });
+
+ test('no session: the call fails before anything is sent', () async {
+ final tokens = _Tokens(['x'])
+ ..failWith = const DirectAuthException(
+ 'Not signed in.',
+ signedOut: true,
+ );
+ final error = await client(tokens)
+ .me()
+ .then<Object?>((_) => null, onError: (Object e) => e);
+ expect(error, isA<DioException>());
+ expect((error as DioException).error, isA<DirectAuthException>());
+ expect(backend.requests, isEmpty);
+ });
+
+ // Every call on screen can hit a lapsed token at once — the machine list, the desk, the
+ // profile — and each 401 asks for a renewal. They must share ONE refresh: a refresh token
+ // spent twice is, on a server that rotates them, a session thrown away.
+ test('many 401s at once share one refresh', () async {
+ final refreshes = FakeHttp({
+ '/api/auth/refresh': (
+ status: 200,
+ body: ok({'token': 'renewed', 'expiresIn': 3600}),
+ ),
+ });
+ final session = AuthSession(storage: MemoryKeyValueStore());
+ final auth = DirectAuth(
+ session: session,
+ api: DirectAuthApi(
+ config: const AppConfig(apiBaseUrl: 'https://h.invalid'),
+ dio: refreshes.dio(),
+ ),
+ emailCodes: EmailCodeApi(
+ config: const AppConfig(apiBaseUrl: 'https://h.invalid'),
+ dio: FakeHttp({}).dio(),
+ ),
+ );
+ await auth.signIn(const IssuedTokens(token: 'lapsed', refreshToken: 'r'));
+ backend.answer = (request, _) =>
+ request.headers.value('authorization') == 'Bearer renewed'
+ ? (status: 200, body: ok({'machines': <Object>[]}))
+ : (status: 401, body: {'success': false});
+
+ final api = client(auth);
+ await Future.wait([api.machines(), api.machines(), api.machines()]);
+ expect(refreshes.sent, hasLength(1));
+ expect(await session.accessToken(), 'renewed');
+ });
+ });
+
+ group('the calls', () {
+ test('machines are read from their envelope', () async {
+ backend.answer = (_, _) => (
+ status: 200,
+ body: ok({
+ 'machines': [
+ {'machineId': 'm1', 'name': 'Studio', 'status': 'running'},
+ ],
+ }),
+ );
+ final machines = await client(_Tokens(['t'])).machines();
+ expect(machines.single.machineId, 'm1');
+ expect(machines.single.name, 'Studio');
+ });
+
+ test('rename and delete are marked as the app\'s own', () async {
+ backend.answer = (request, _) => request.method == 'PATCH'
+ ? (status: 200, body: ok({'name': 'Renamed'}))
+ : (status: 200, body: ok(null));
+ final api = client(_Tokens(['t']));
+ expect(
+ await api.renameMachine(machineId: 'm1', name: 'Renamed'),
+ 'Renamed',
+ );
+ await api.deleteMachine(machineId: 'm1');
+ expect(backend.requests.map((r) => '${r.method} ${r.path}'), [
+ 'PATCH /api/machines/m1',
+ 'DELETE /api/machines/m1',
+ ]);
+ expect(jsonDecode(utf8.decode(backend.requests.first.body)), {
+ 'name': 'Renamed',
+ });
+ for (final request in backend.requests) {
+ expect(request.headers.value('x-adapter-local'), '1');
+ }
+ });
+
+ test(
+ 'the desk is null where the backend has none or will not say',
+ () async {
+ final api = client(_Tokens(['t']));
+ for (final status in [404, 401]) {
+ backend.answer = (_, _) => (status: status, body: {'success': false});
+ expect(await api.desk(), isNull, reason: '$status');
+ expect(
+ await api.deskOps([
+ {'op': 'noop'},
+ ]),
+ isNull,
+ reason: '$status',
+ );
+ }
+ backend.answer = (_, _) =>
+ (status: 200, body: ok({'revision': 3, 'tabs': <Object>[]}));
+ expect((await api.desk())!['revision'], 3);
+ expect(
+ (await api.deskOps([
+ {'op': 'noop'},
+ ]))!['revision'],
+ 3,
+ );
+ expect(jsonDecode(utf8.decode(backend.requests.last.body)), {
+ 'ops': [
+ {'op': 'noop'},
+ ],
+ });
+ },
+ );
+
+ test('a failure without the envelope still reads as a failure', () async {
+ backend.answer = (_, _) => (status: 502, body: 'Bad Gateway');
+ await expectLater(
+ client(_Tokens(['t'])).desk(),
+ throwsA(
+ isA<ApiException>()
+ .having((e) => e.status, 'status', 502)
+ .having((e) => '$e', 'text', 'Request failed (502)'),
+ ),
+ );
+ });
+
+ test(
+ 'a recording goes up as one multipart file, in its language',
+ () async {
+ backend.answer = (_, _) =>
+ (status: 200, body: ok({'transcript': ' hello there \n'}));
+ final wav = Uint8List.fromList(List.generate(64, (i) => i));
+ final text = await client(_Tokens(['t']))
+ .transcribeVoice(wav, lang: 'de');
+ expect(text, 'hello there');
+ final sent = backend.requests.single;
+ expect(sent.path, '/api/voice/stt');
+ expect(sent.query, {'lang': 'de'});
+ expect(sent.headers.contentType!.mimeType, 'multipart/form-data');
+ expect(latin1.decode(sent.body), contains('filename="voice.wav"'));
+ },
+ );
+
+ test(
+ 'a recording retried after a 401 goes up whole the second time',
+ () async {
+ backend.answer = (_, index) => index == 0
+ ? (status: 401, body: {'success': false})
+ : (status: 200, body: ok({'transcript': 'ok'}));
+ final wav = Uint8List.fromList(List.filled(128, 7));
+ expect(
+ await client(_Tokens(['a', 'b'])).transcribeVoice(wav, lang: 'en'),
+ 'ok',
+ );
+ expect(backend.requests[1].body, backend.requests[0].body);
+ },
+ );
+
+ test('no transcript is an empty one', () async {
+ backend.answer = (_, _) => (status: 200, body: ok(<String, Object?>{}));
+ expect(
+ await client(_Tokens(['t'])).transcribeVoice(Uint8List(4), lang: 'en'),
+ '',
+ );
+ });
+ });
+
+ group('describing a failure', () {
+ DioException dio(DioExceptionType type, {int? status}) => DioException(
+ requestOptions: RequestOptions(
+ receiveTimeout: const Duration(seconds: 30),
+ ),
+ type: type,
+ response: status == null
+ ? null
+ : Response(requestOptions: RequestOptions(), statusCode: status),
+ message: type == DioExceptionType.unknown ? 'boom' : null,
+ );
+
+ test('says which leg failed, in words', () {
+ expect(describeApiError(ApiException('nope')), 'nope');
+ expect(
+ describeApiError(dio(DioExceptionType.connectionError)),
+ contains('not answering'),
+ );
+ expect(
+ describeApiError(dio(DioExceptionType.receiveTimeout)),
+ contains('within 30s'),
+ );
+ expect(
+ describeApiError(dio(DioExceptionType.connectionTimeout)),
+ contains('did not answer'),
+ );
+ expect(
+ describeApiError(dio(DioExceptionType.sendTimeout)),
+ contains('did not answer'),
+ );
+ expect(
+ describeApiError(dio(DioExceptionType.badResponse, status: 503)),
+ contains('503'),
+ );
+ expect(
+ describeApiError(dio(DioExceptionType.badResponse)),
+ contains('with an error'),
+ );
+ expect(describeApiError(dio(DioExceptionType.unknown)), 'boom');
+ expect(
+ describeApiError(
+ DioException(
+ requestOptions: RequestOptions(),
+ type: DioExceptionType.cancel,
+ ),
+ ),
+ 'request failed',
+ );
+ expect(describeApiError(StateError('x')), 'Bad state: x');
+ expect(
+ describeApiError(
+ DioException(
+ requestOptions: RequestOptions(),
+ type: DioExceptionType.receiveTimeout,
+ ),
+ ),
+ isNot(contains('within')),
+ );
+ });
-
- test('only a 401 is unauthorized', () {
- expect(isUnauthorizedError(ApiException('x', status: 401)), isTrue);
- expect(isUnauthorizedError(ApiException('x', status: 403)), isFalse);
- expect(
- isUnauthorizedError(dio(DioExceptionType.badResponse, status: 401)),
- isTrue,
- );
- expect(
- isUnauthorizedError(dio(DioExceptionType.badResponse, status: 500)),
- isFalse,
- );
- expect(isUnauthorizedError(StateError('401')), isFalse);
- });
+ });
+}
diff --cc mobile/test/core_units_test.dart
index 9d1ca6e03,000000000..10fc80282
mode 100644,000000..100644
--- a/mobile/test/core_units_test.dart
+++ b/mobile/test/core_units_test.dart
@@@ -1,973 -1,0 +1,969 @@@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:math';
+
+import 'package:fake_async/fake_async.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/core/agent_output_stats.dart';
+import 'package:harness_mobile/core/device_name.dart';
+import 'package:harness_mobile/core/fuzzy_match.dart';
+import 'package:harness_mobile/core/git_project.dart';
+import 'package:harness_mobile/core/harness_file_store.dart';
+import 'package:harness_mobile/core/local_key_value_store.dart';
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/core/phone_search_history.dart';
+import 'package:harness_mobile/core/project_folder.dart';
+import 'package:harness_mobile/core/project_history.dart';
+import 'package:harness_mobile/state/external_session.dart';
+import 'package:harness_mobile/state/search_when.dart';
+import 'package:harness_mobile/state/session_content_search.dart';
+
+import 'voice_fakes.dart' show MemoryKeyValueStore;
+
+/// The parts of `core/` the phone's screens stand on: what a machine's answers
+/// are read into, what a new agent's Git choices become, how the search ranks,
+/// and what is kept on disk between launches.
+void main() {
+ group('Git choices', () {
+ GitProjectInfo repo({
+ String? branch = 'main',
+ String? defaultRef = 'refs/remotes/origin/main',
+ List<GitBranch> branches = const [
+ GitBranch('refs/heads/main', 'main'),
+ GitBranch('refs/heads/feature', 'feature'),
+ GitBranch('refs/heads/busy', 'busy', worktree: '/w/busy'),
+ GitBranch('refs/remotes/origin/main', 'origin/main', remote: true),
+ GitBranch('refs/remotes/origin/only-remote', 'x', remote: true),
+ ],
+ }) => GitProjectInfo(
+ isGit: true,
+ branch: branch,
+ defaultRef: defaultRef,
+ branches: branches,
+ );
+
+ test('a machine\'s answer is read, and what it cannot mean is dropped', () {
+ final info = GitProjectInfo.fromJson({
+ 'isGit': true,
+ 'branch': 'main',
+ 'mainFolder': 'relative/path',
+ 'mainBranch': 'main',
+ 'defaultRef': 'refs/tags/v1',
+ 'root': '/w/app',
+ 'branches': [
+ {'ref': 'refs/heads/main', 'name': 'main', 'harness': true},
+ {'ref': 'refs/heads/x', 'name': 'x', 'worktree': '/w/x'},
+ {'ref': 3},
+ 'junk',
+ ],
+ });
+
+ expect(info.isGit, isTrue);
+ expect(info.mainFolder, isNull, reason: 'not an absolute path');
+ expect(info.defaultRef, isNull, reason: 'not a branch ref');
+ expect(info.root, '/w/app');
+ expect(info.branches.map((b) => b.name), ['main', 'x']);
+ expect(info.branches.first.harness, isTrue);
+ expect(info.branches.last.worktree, '/w/x');
+ expect(info.unavailable, isFalse);
+ expect(
+ GitProjectInfo.fromJson({'error': 'UNAVAILABLE'}).unavailable,
+ isTrue,
+ );
+ });
+
+ test('where Start begins with nothing chosen', () {
+ final info = repo();
+
+ expect(currentBranchRef(info), 'refs/heads/main');
+ expect(currentBranchRef(repo(branch: 'gone')), isNull);
+ expect(worktreeByDefault(info), isTrue);
+ expect(worktreeByDefault(const GitProjectInfo(isGit: true)), isFalse);
+ expect(defaultBranchRef(info, worktree: false), 'refs/heads/main');
+ expect(defaultBranchRef(info, worktree: true), 'refs/heads/main');
+ expect(
+ defaultBranchRef(
+ repo(defaultRef: 'refs/remotes/origin/dev'),
+ worktree: true,
+ ),
+ 'refs/remotes/origin/dev',
+ reason: 'no local branch of that name: the remote itself',
+ );
+ expect(
+ defaultBranchRef(repo(defaultRef: null), worktree: true),
+ 'refs/heads/main',
+ );
+ });
+
+ test('a worktree plan for every kind of base and name', () {
+ final info = repo();
+ WorktreePlan plan({String? base, String? name}) =>
+ planWorktree(info, base: base, name: name, placeholder: 'calm-otter');
+
+ // Typed names.
+ expect(plan(name: 'new-thing').kind, WorktreeStart.newBranch);
+ expect(plan(name: 'new-thing').branch, 'new-thing');
+ expect(plan(name: 'main').kind, WorktreeStart.unavailable);
+ expect(plan(name: 'feature').kind, WorktreeStart.existingBranch);
+ expect(plan(name: 'busy').kind, WorktreeStart.openWorktree);
+ expect(plan(name: 'busy').worktree, '/w/busy');
+
+ // Nothing typed.
+ expect(plan().branch, 'calm-otter');
+ expect(plan(base: 'refs/remotes/origin/main').branch, 'calm-otter');
+ expect(plan(base: 'refs/heads/main').branch, 'calm-otter');
+ expect(
+ plan(base: 'refs/heads/feature').kind,
+ WorktreeStart.existingBranch,
+ );
+ expect(plan(base: 'refs/heads/missing').branch, 'calm-otter');
+ expect(
+ plan(base: 'refs/remotes/origin/feature').kind,
+ WorktreeStart.existingBranch,
+ );
+
+ final tracking = plan(base: 'refs/remotes/origin/only-remote');
+ expect(tracking.kind, WorktreeStart.newBranch);
+ expect(tracking.branch, 'only-remote');
+ expect(tracking.tracks, isTrue);
+ expect(plan(name: 'x', base: 'refs/heads/main').tracks, isFalse);
+
+ // The folder's own branch, picked from the list, starts a new branch.
+ final own = planWorktree(
+ repo(defaultRef: null),
+ base: 'refs/heads/main',
+ name: null,
+ placeholder: 'calm-otter',
+ );
+ expect(own.kind, WorktreeStart.newBranch);
+ expect(own.branch, 'calm-otter');
+ });
+
+ test('what the machine is asked to do with the folder', () {
+ final info = repo();
+ ProjectFolderRequest? request({
+ bool worktree = true,
+ String? ref,
+ String? name,
+ }) => gitFolderRequest(
+ '/w/app',
+ info,
+ worktree: worktree,
+ branchRef: ref,
+ branchName: name,
+ placeholder: 'calm-otter',
+ );
+
+ expect(request(worktree: false)!.payload, {
+ 'projectSource': 'branch',
+ 'gitSource': '/w/app',
+ 'branchRef': 'refs/heads/main',
+ });
+ expect(request(worktree: false, name: 'fresh')!.payload, {
+ 'projectSource': 'branch',
+ 'gitSource': '/w/app',
+ 'branchRef': 'refs/heads/fresh',
+ 'branchName': 'fresh',
+ });
+ expect(
+ gitFolderRequest(
+ '/w/app',
+ repo(branch: null),
+ worktree: false,
+ branchRef: null,
+ branchName: null,
+ placeholder: 'p',
+ ),
+ isNull,
+ );
+ expect(request()!.payload, {
+ 'projectSource': 'worktree',
+ 'gitSource': '/w/app',
+ 'branchRef': 'refs/heads/main',
+ 'branchName': 'calm-otter',
+ 'branchMode': 'placeholder',
+ });
+ expect(request(name: 'feature')!.payload['branchMode'], 'existing');
+ expect(request(name: 'busy')!.payload, {
+ 'projectSource': 'branch',
+ 'gitSource': '/w/app',
+ 'branchRef': 'refs/heads/busy',
+ });
+ expect(
+ request(name: 'typed')!.payload.containsKey('branchMode'),
+ isFalse,
+ );
+ });
+
+ test('with Worktree off, only a name no branch has is a new one', () {
+ final info = repo();
+
+ expect(newBranchHere(info, null), isNull);
+ expect(newBranchHere(info, ' '), isNull);
+ expect(newBranchHere(info, 'feature'), isNull);
+ expect(newBranchHere(info, ' fresh '), 'fresh');
+ });
+
+ test('a placeholder branch is two words none of the taken ones use', () {
+ final taken = <String>{};
+ final random = Random(1);
+ for (var i = 0; i < 50; i++) {
+ final name = placeholderBranch(taken, random: random);
+ expect(taken, isNot(contains(name)));
+ expect(name, matches(RegExp(r'^[a-z]+-[a-z]+(-\d+)?$')));
+ taken.add(name);
+ }
+ // Every name taken: a suffix.
+ final all = {
+ for (final a in kPlaceholderAdjectives)
+ for (final n in kPlaceholderNouns) 'refs/heads/$a-$n',
+ };
+ expect(placeholderBranch(all), matches(RegExp(r'-\d+$')));
+ });
+
+ test('a typed name becomes a branch git accepts', () {
+ expect(branchNameFrom(' fix the login '), 'fix-the-login');
+ expect(branchNameFrom('a..b~c^d:e?f*g[h\\i'), 'a.bcdefghi');
+ expect(branchNameFrom('-/.lead'), 'lead');
+ expect(branchNameFrom('x//y/.z'), 'x/y/z');
+ expect(branchNameFrom('name.lock'), 'name');
+ expect(branchNameFrom('ends/.'), 'ends');
+ expect(branchNameFrom('a@{b'), 'a@b');
+ expect(branchNameFrom('@'), '');
+ expect(branchNameFrom('a---b'), 'a-b');
+
+ expect(plausibleBranchName('ok/name'), isTrue);
+ expect(plausibleBranchName(''), isFalse);
+ expect(plausibleBranchName('-x'), isFalse);
+ expect(plausibleBranchName('has space'), isFalse);
+ expect(plausibleBranchName('x' * 256), isFalse);
+ expect(validGitPath('/abs'), isTrue);
+ expect(validGitPath('rel'), isFalse);
+ expect(validGitPath('/a\u0001b'), isFalse);
+ expect(validGitRef('refs/heads/x'), isTrue);
+ expect(validGitRef('refs/tags/x'), isFalse);
+ });
+ });
+
+ group('fuzzy matching', () {
+ test('a subsequence, its spread, and where each letter landed', () {
+ final at = <(int, int)>[];
+
+ expect(subsequenceSpread('harness', ''), 0);
+ expect(
+ subsequenceSpread('harness', 'hns', onMatch: (s, e) => at.add((s, e))),
+ 5,
+ );
+ expect(at, [(0, 1), (3, 4), (5, 6)]);
+ expect(subsequenceSpread('harness', 'z'), isNull);
+ expect(subsequenceSpread('harness', 'h', from: 1), isNull);
+ });
+
+ test('a word starts after anything that is not a letter or digit', () {
+ expect(startsWord('fix-auth', 0), isTrue);
+ expect(startsWord('fix-auth', 4), isTrue);
+ expect(startsWord('fix-auth', 5), isFalse);
+ expect(startsWord('a9', 1), isFalse);
+ expect(startsWord('a\u00a0b', 2), isTrue);
+ expect(startsWord('a·b', 2), isTrue);
+ expect(startsWord('a—b', 2), isTrue);
+ expect(startsWord('é b', 1), isFalse);
+ expect(startsWord('éb', 1), isFalse);
+ expect(startsWord('中b', 1), isFalse);
+ expect(startsWord('🙂b', 2), isTrue);
+ });
+
+ test('a term found only where it begins a word', () {
+ expect(wordStartIndexOf('windows port', 'port'), 8);
+ expect(wordStartIndexOf('support', 'port'), -1);
+ expect(wordStartIndexOf('abc', '', 5), 3);
+ });
+
+ test('scattered letters stay close and start on a word', () {
+ final at = <(int, int)>[];
+
+ expect(
+ wordSubsequenceSpread(
+ 'fix authentication',
+ 'ath',
+ onMatch: (s, e) => at.add((s, e)),
+ ),
+ isNotNull,
+ );
+ expect(at.first.$1, 4);
+ expect(wordSubsequenceSpread('command', 'cmd'), isNotNull);
+ expect(wordSubsequenceSpread('x', ''), 0);
+ expect(wordSubsequenceSpread('autonomous-harness', 'auth'), isNull);
+ expect(wordSubsequenceSpread('abc', 'xyz'), isNull);
+ // Two letters count only as initials.
+ expect(wordSubsequenceSpread('new split', 'ns'), isNotNull);
+ expect(wordSubsequenceSpread('harness', 'hn'), isNull);
+ final initials = <(int, int)>[];
+ wordSubsequenceSpread(
+ 'new split',
+ 'ns',
+ onMatch: (s, e) => initials.add((s, e)),
+ );
+ expect(initials, [(0, 1), (4, 5)]);
+ // Too far apart to count.
+ expect(wordSubsequenceSpread('a${' ' * 40}bc', 'abc'), isNull);
+ // A later start that finds the tightest spread wins.
+ expect(wordSubsequenceSpread('dxxxxxial dial', 'dial'), 3);
+ });
+ });
+
+ group('models off the wire', () {
+ test('the account\'s profile, and what it cannot be', () {
+ expect(
+ () => CurrentUserProfile.fromMe({'user': 'x'}),
+ throwsFormatException,
+ );
+ expect(
+ () => CurrentUserProfile.fromMe({
+ 'user': {'email': ' '},
+ }),
+ throwsFormatException,
+ );
+ final pat = CurrentUserProfile.fromMe({
+ 'user': {'id': 'u', 'email': ' [email protected] ', 'name': ' Pat Lee '},
+ 'avatarUrl': ' https://a/b.png ',
+ });
+ expect(pat.email, '[email protected]');
+ expect(pat.displayName, 'Pat Lee');
+ expect(pat.initials, 'PL');
+ expect(pat.avatarUrl, 'https://a/b.png');
+ final bare = CurrentUserProfile.fromMe({
+ 'user': {'email': '[email protected]', 'name': ''},
+ });
+ expect(bare.displayName, '[email protected]');
+ expect(bare.initials, 'Q');
+ expect(const CurrentUserProfile(email: ' ').initials, '?');
+ expect(const CurrentUserProfile.local().isLocalSession, isTrue);
+ });
+
+ test('a machine with no name is called by its id', () {
+ const long = Machine(
+ machineId: 'abcdef0123456789',
+ authMode: MachineAuthMode.remote,
+ );
+ const short = Machine(machineId: 'abc', authMode: MachineAuthMode.remote);
+
+ expect(long.displayName, 'machine-abcdef01');
+ expect(short.displayName, 'machine-abc');
+ expect(long.copyWith(name: 'Mac').displayName, 'Mac');
+ expect(
+ Machine.fromJson({'machineId': 'm', 'authMode': 'weird'}).authMode,
+ MachineAuthMode.managed,
+ );
+ });
+
+ test('an agent reads only what it can trust', () {
+ final agent = Agent.fromJson({
+ 'id': 'a',
+ 'engine': 'codex',
+ 'codexHome': 'relative',
+ 'launch': {'state': 'failed', 'error': 'E', 'detail': 'bad\u0000thing'},
+ 'terminal': {
+ 'runtimes': [
+ {'backend': 'tmux'},
+ ],
+ },
+ 'tokenUsage': {'totalTokens': -1},
+ 'resumeMode': 'nonsense',
+ });
+
+ expect(agent.name, 'agent');
+ expect(agent.codexHome, isNull);
+ expect(agent.launchDetail, 'bad thing');
+ expect(agent.terminalAvailable, isTrue, reason: 'a tmux runtime');
+ expect(agent.tokensUsed, isNull);
+ expect(agent.resumeMode, isNull);
+ expect(
+ Agent.fromJson({'id': 'a', 'engine': 'bad engine!'}).engine,
+ isNull,
+ );
+ expect(
+ Agent.fromJson({
+ 'id': 'a',
+ 'launch': {'state': 'failed', 'detail': ' '},
+ }).launchDetail,
+ isNull,
+ );
+ expect(
+ Agent.fromJson({
+ 'id': 'a',
+ 'launch': {'state': 'failed', 'detail': 'x' * 600},
+ }).launchDetail!.length,
+ 500,
+ );
+ });
+
+ test(
+ 'a name somebody chose is kept; a made-up one gives way to the title',
+ () {
+ const chosen = Agent(id: 'a', name: 'api work');
+ const made = Agent(id: 'a', name: 'harness-3', title: 'Fix the dial');
+ const untitled = Agent(id: 'a', name: 'harness-3');
+
+ expect(chosen.displayName, 'api work');
+ expect(made.displayName, 'Fix the dial');
+ expect(untitled.displayName, kUntitledPane);
+ expect(isAutomaticHarnessName('Claude harness 9-23 13:52'), isTrue);
+ },
+ );
+
+ test('the last use is the later of activity and opening', () {
+ final early = DateTime(2026, 9, 1);
+ final late = DateTime(2026, 9, 2);
+
+ expect(Agent(id: 'a', name: 'a', updatedAt: early).lastUsedAt, early);
+ expect(Agent(id: 'a', name: 'a', lastOpenedAt: late).lastUsedAt, late);
+ expect(
+ Agent(
+ id: 'a',
+ name: 'a',
+ updatedAt: late,
+ lastOpenedAt: early,
+ ).lastUsedAt,
+ late,
+ );
+ expect(
+ Agent(
+ id: 'a',
+ name: 'a',
+ updatedAt: early,
+ lastOpenedAt: late,
+ ).lastUsedAt,
+ late,
+ );
+ });
+
+ test('a project is labelled as the person chose it', () {
+ const plain = AgentProject(name: 'work', cwd: '/work');
+ const sub = AgentProject(
+ name: 'repo',
+ cwd: '/w/repo/packages/app/',
+ root: '/w/repo',
+ branch: ' Detached 6528156 ',
+ );
+ const same = AgentProject(name: 'repo', cwd: '/w/repo/', root: '/w/repo');
+ const pending = AgentProject(
+ name: 'r',
+ cwd: '/r',
+ branch: 'main',
+ branchPending: true,
+ );
+
+ expect(plain.label, 'work');
+ expect(sub.label, 'app');
+ expect(same.label, 'repo');
+ expect(sub.detached, isTrue);
+ expect(sub.shownBranch, isNull);
+ expect(sub.branchDetail, 'No branch: on commit 6528156');
+ expect(pending.shownBranch, isNull);
+ expect(pending.branchDetail, 'Branch: main');
+ expect(plain.branchDetail, isNull);
+ expect(
+ const AgentProject(name: 'r', cwd: '/r', branch: ' ').branchLabel,
+ isNull,
+ );
+ expect(plain.identity('m'), 'folder:m:/work');
+ expect(
+ const AgentProject(name: 'r', cwd: '/r', remote: 'git@x').identity('m'),
+ 'repo:git@x',
+ );
+ expect(plain, const AgentProject(name: 'work', cwd: '/work'));
+ expect(
+ plain.hashCode,
+ const AgentProject(name: 'work', cwd: '/work').hashCode,
+ );
+ expect(AgentProject.fromJson({'name': 'n', 'cwd': 'a\u0001'}), isNull);
+ });
+
+ test('grid answers: web search, sections and who may run locally', () {
+ expect(GridWebSearch.on.sentence, isNull);
+ expect(GridWebSearch.unsupported.sentence, contains('not supported'));
+ expect(GridWebSearch.fromWire('new-word'), isNull);
+ expect(GridCli.parse('path'), GridCli.path);
+ expect(GridCli.parse('missing'), GridCli.missing);
+
+ const own = GridModels(
+ gridName: 'mine',
+ models: [GridModel(id: 'q', node: 'mac')],
+ );
+ expect(own.sections.single.own, isTrue);
+ expect(const GridModels(gridName: null, models: []).sections, isEmpty);
+ expect(own.canRunLocally('anything'), isTrue);
+ const limited = GridModels(
+ gridName: 'mine',
+ models: [],
+ localModelEngines: {'codex'},
+ );
+ expect(limited.canRunLocally(' Codex '), isTrue);
+ expect(limited.canRunLocally('claude'), isFalse);
+ expect(limited.canRunLocally(null), isFalse);
+ expect(const GridModels.unreachable().reachable, isFalse);
+ });
+
+ test('output stats keep an edit pair whole, or not at all', () {
+ expect(AgentOutputStats.fromJson('x'), isNull);
+ expect(AgentOutputStats.fromJson({'linesAdded': 3}), isNull);
+ final stats = AgentOutputStats.fromJson({
+ 'linesAdded': 3,
+ 'linesRemoved': 1,
+ 'pullRequestsCreated': 2,
+ 'updatedAt': '2026-09-27T10:00:00Z',
+ })!;
+ expect(stats.hasEdits, isTrue);
+ expect(
+ stats,
+ AgentOutputStats.fromJson({
+ 'linesAdded': 3,
+ 'linesRemoved': 1,
+ 'pullRequestsCreated': 2,
+ 'updatedAt': '2026-09-27T10:00:00Z',
+ }),
+ );
+ expect(stats.hashCode, isA<int>());
+ expect(wireCount(-1), isNull);
+ expect(wireCount(1.5), isNull);
- expect(formatCount(980), '980');
- expect(formatCount(12300), '12.3k');
- expect(formatCount(4500000), '4.5M');
- expect(formatCount(2000000000), '2.0B');
+ });
+
+ test('a project folder request says what the machine should make', () {
+ expect(const ProjectFolderRequest.newProject().payload, {
+ 'projectSource': 'new',
+ });
+ expect(
+ const ProjectFolderRequest.branch(
+ '/w',
+ 'refs/heads/x',
+ newBranch: 'x',
+ ).payload,
+ {
+ 'projectSource': 'branch',
+ 'gitSource': '/w',
+ 'branchRef': 'refs/heads/x',
+ 'branchName': 'x',
+ },
+ );
+ });
+ });
+
+ group('what search reads', () {
+ test('a conversation Harness did not start, as a person says it', () {
+ const ext = ExternalSessionRef(
+ sessionId: 's',
+ engine: 'codex',
+ cwd: '/w/app/',
+ origin: 'codex-app',
+ );
+
+ expect(ext.originLabel, 'Codex app');
+ expect(ext.engineLabel, 'Codex');
+ expect(ext.folderName, 'app');
+ expect(
+ const ExternalSessionRef(
+ sessionId: 's',
+ engine: 'gemini',
+ cwd: '/',
+ origin: 'editor',
+ ).engineLabel,
+ 'gemini',
+ );
+ expect(
+ const ExternalSessionRef(
+ sessionId: 's',
+ engine: 'claude',
+ cwd: '/',
+ origin: 'claude-app',
+ ).originLabel,
+ 'Claude app',
+ );
+ expect(
+ const ExternalSessionRef(
+ sessionId: 's',
+ engine: 'claude',
+ cwd: '/',
+ origin: 'editor',
+ ).originLabel,
+ 'editor',
+ );
+ expect(externalDestinationId('m', 's'), 'external:m:s');
+ });
+
+ test(
+ 'a hit on a conversation Harness did not start, and a long snippet',
+ () {
+ final hits = SessionContentHit.listFromReply('m', {
+ 'hits': [
+ {
+ 'agentId': '',
+ 'sessionId': 's-ext',
+ 'engine': 'claude',
+ 'snippet': 'x' * 700,
+ 'lastAt': 1790000000000,
+ 'external': {'cwd': '/w/app', 'title': 'Fix', 'open': true},
+ },
+ {
+ 'agentId': '',
+ 'sessionId': 's-bad',
+ 'engine': 'claude',
+ 'external': {'cwd': 'relative'},
+ },
+ ],
+ });
+
+ final hit = hits.single;
+ expect(hit.snippet.length, 600);
+ expect(hit.lastAt, DateTime.fromMillisecondsSinceEpoch(1790000000000));
+ expect(hit.external!.origin, 'terminal');
+ expect(hit.external!.open, isTrue);
+ expect(hit.destinationId, 'external:m:s-ext');
+ expect(SessionContentHit.listFromReply('m', {'error': 'OLD'}), isEmpty);
+ },
+ );
+
+ test('an earlier answer vouches only where a word begins', () async {
+ final search = SessionContentSearch(
+ machines: () => ['m'],
+ debounce: Duration.zero,
+ ask: (_, query, _) async => query == 'po'
+ ? [
+ SessionContentHit(
+ machineId: 'm',
+ agentId: 'a',
+ sessionId: 's',
+ field: 'ask',
+ snippet: 'support the port',
+ together: true,
+ score: 1,
+ ),
+ ]
+ : null,
+ );
+ addTearDown(search.dispose);
+ search.search('po');
+ await Future<void>.delayed(const Duration(milliseconds: 20));
+
+ search.search('port');
+ expect(search.hitsFor('port'), hasLength(1));
+ });
+
+ test('a later, closer conversation of one harness wins its row', () async {
+ SessionContentHit hit(int position, {bool together = false}) =>
+ SessionContentHit(
+ machineId: 'm',
+ agentId: 'a',
+ sessionId: 's$position',
+ field: 'ask',
+ snippet: 'dial',
+ together: together,
+ score: 1,
+ position: position,
+ );
+ final search = SessionContentSearch(
+ machines: () => ['m', 'n'],
+ debounce: Duration.zero,
+ ask: (machine, _, _) async =>
+ machine == 'm' ? [hit(3), hit(1)] : [hit(5, together: true)],
+ );
+ addTearDown(search.dispose);
+
+ search.search('dial');
+ await Future<void>.delayed(const Duration(milliseconds: 20));
+
+ expect(search.hits.values.single.together, isTrue);
+ });
+
+ test('"this month" runs from the first to now', () {
+ final now = DateTime(2026, 9, 27, 12);
+
+ final read = parseSearchWhen('dial this month', now);
+
+ expect(read.words, 'dial');
+ expect(read.when!.from, DateTime(2026, 9));
+ expect(read.when!.to, now);
+ });
+ });
+
+ group('kept between launches', () {
+ test('recent folders, per machine, newest first and valid only', () async {
+ final storage = MemoryKeyValueStore()
+ ..values['new_agent_projects_v1'] = jsonEncode({
+ 'm': {
+ 'selected': '/w/b',
+ 'recent': ['/w/b', '/w/a', 'relative', 3, '/w/a'],
+ },
+ 'n': {'selected': 'relative', 'recent': 'nope'},
+ '': 7,
+ });
+ final history = ProjectHistory(storage);
+
+ await history.load();
+ expect(history.recent('m'), ['/w/b', '/w/a']);
+ expect(history.selected('m'), '/w/b');
+ expect(history.hasSelection('n'), isFalse);
+
+ await history.select('m', '/w/c');
+ await history.select('m', 'relative');
+ expect(history.recent('m'), ['/w/c', '/w/b', '/w/a']);
+
+ final again = ProjectHistory(storage);
+ await again.load();
+ expect(again.recent('m'), ['/w/c', '/w/b', '/w/a']);
+ await again.select('m', null);
+ expect(again.selected('m'), isNull);
+ expect(again.hasSelection('m'), isTrue);
+ });
+
+ test(
+ 'recent folders survive a store that cannot be read or written',
+ () async {
+ final history = ProjectHistory(_Broken());
+
+ await history.select('m', '/w/a');
+
+ expect(history.recent('m'), ['/w/a']);
+ expect(ProjectHistory(null).recent('m'), isEmpty);
+ final garbled = ProjectHistory(
+ MemoryKeyValueStore()..values['new_agent_projects_v1'] = '[1]',
+ );
+ await garbled.load();
+ expect(garbled.recent('m'), isEmpty);
+ },
+ );
+
+ test('search visits, most recent first, written once they settle', () {
+ fakeAsync((async) {
+ final storage = MemoryKeyValueStore()
+ ..values['phone_recent_agents_v1'] = jsonEncode([
+ 'agent:m:a',
+ 'not-an-agent',
+ 'agent:m:a',
+ 7,
+ ])
+ ..values['phone_recent_commands_v1'] = '{broken';
+ final history = PhoneSearchHistory(storage);
+
+ history.load();
+ async.flushMicrotasks();
+ expect(history.recent, ['agent:m:a']);
+ expect(history.recentCommands, isEmpty);
+
+ history.remember('agent:m:b');
+ history.remember('agent:m:b');
+ history.rememberCommand('cmd:new');
+ async.elapse(const Duration(milliseconds: 300));
+ expect(storage.values['phone_recent_agents_v1'], contains('agent:m:a'));
+ expect(jsonDecode(storage.values['phone_recent_agents_v1']!), [
+ 'agent:m:a',
+ 'not-an-agent',
+ 'agent:m:a',
+ 7,
+ ], reason: 'not yet: visits come in bursts');
+
+ async.elapse(const Duration(milliseconds: 400));
+ expect(jsonDecode(storage.values['phone_recent_agents_v1']!), [
+ 'agent:m:b',
+ 'agent:m:a',
+ ]);
+ expect(jsonDecode(storage.values['phone_recent_commands_v1']!), [
+ 'cmd:new',
+ ]);
+
+ for (var i = 0; i < 40; i++) {
+ history.remember('agent:m:$i');
+ }
+ expect(history.recent, hasLength(32));
+ history.dispose();
+ async.elapse(const Duration(seconds: 1));
+ });
+ });
+
+ test('search visits with nowhere to keep them, or a store that fails', () {
+ fakeAsync((async) {
+ final memory = PhoneSearchHistory(null)..remember('agent:m:a');
+ expect(memory.recent, ['agent:m:a']);
+
+ final broken = PhoneSearchHistory(_Broken());
+ broken.load();
+ broken.remember('agent:m:a');
+ async.elapse(const Duration(seconds: 1));
+ expect(broken.recent, ['agent:m:a']);
+ });
+ });
+ });
+
+ group('the state file', () {
+ late Directory dir;
+
+ setUp(() => dir = Directory.systemTemp.createTempSync('harness_store'));
+ tearDown(() => dir.deleteSync(recursive: true));
+
+ test('keys round-trip, alone and together, and deletes stick', () async {
+ final store = HarnessFileStore(directory: dir);
+
+ await store.write('a', '1');
+ await store.write('b', '2');
+ expect(await store.read('a'), '1');
+ expect(await store.readMany(['a', 'b', 'c']), {
+ 'a': '1',
+ 'b': '2',
+ 'c': null,
+ });
+ expect(await store.readMany(const []), isEmpty);
+
+ await store.delete('a');
+ await store.delete('never-there');
+ expect(await HarnessFileStore(directory: dir).read('a'), isNull);
+ expect(await HarnessFileStore(directory: dir).read('b'), '2');
+ });
+
+ test('a corrupt file is moved aside and read as empty', () async {
+ final store = HarnessFileStore(directory: dir);
+ store.stateFile.writeAsStringSync('{not json');
+
+ expect(await store.read('a'), isNull);
+
+ expect(
+ dir.listSync().map((f) => f.path.split('/').last),
+ contains(startsWith('state.corrupt-')),
+ );
+ });
+
+ test('every wrong shape is corruption', () async {
+ final store = HarnessFileStore(directory: dir);
+ for (final document in [
+ '[]',
+ '{"version": 1}',
+ '{"version": 0, "values": {}}',
+ '{"version": 1, "values": {"a": 3}}',
+ ]) {
+ store.stateFile.writeAsStringSync(document);
+ expect(await store.read('a'), isNull, reason: document);
+ }
+ expect(
+ dir.listSync().where((f) => f.path.contains('state.corrupt-')),
+ hasLength(4),
+ );
+ });
+
+ test(
+ 'a newer build\'s file is refused, and left exactly as it was',
+ () async {
+ final store = HarnessFileStore(directory: dir);
+ const newer = '{"version": 99, "values": {"a": "1"}}';
+ store.stateFile.writeAsStringSync(newer);
+
+ await expectLater(
+ store.read('a'),
+ throwsA(isA<UnsupportedStateVersionException>()),
+ );
+ await expectLater(store.write('a', '2'), throwsA(anything));
+ expect(store.stateFile.readAsStringSync(), newer);
+ expect(
+ const UnsupportedStateVersionException(99).toString(),
+ contains('refusing to overwrite'),
+ );
+ },
+ );
+
+ test(
+ 'on a phone the document is held, and a failed write drops it',
+ () async {
+ final store = HarnessFileStore(directory: dir, cacheableForTest: true);
+ final outside = HarnessFileStore(directory: dir);
+ await store.write('a', '1');
+
+ // Changed behind its back: the held copy answers, as it may where it is
+ // the only writer.
+ await outside.write('a', 'outside');
+ expect(await store.read('a'), '1');
+ expect(await store.readMany(['a']), {'a': '1'});
+
+ // A write that cannot land: its rename meets a directory.
+ store.stateFile.deleteSync();
+ Directory('${store.stateFile.path}/blocker')
+ .createSync(recursive: true);
+ await expectLater(store.write('b', '2'), throwsA(anything));
+ Directory(store.stateFile.path).deleteSync(recursive: true);
+ await outside.write('a', 'on disk');
+
+ // Forgotten, so the next read goes and looks.
+ expect(await store.read('a'), 'on disk');
+ },
+ );
+
+ test('a home is required, and the sibling is named', () {
+ expect(
+ HarnessFileStore.defaultDirectoryPath(
+ environment: {'HOME': '/Users/pat'},
+ name: 'machines',
+ ),
+ '/Users/pat/.harness/machines',
+ );
+ expect(
+ () => HarnessFileStore.defaultDirectoryPath(environment: const {}),
+ throwsStateError,
+ );
+ });
+ });
+
+ group('the phone\'s own name', () {
+ const channel = MethodChannel('harness/device_name');
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ tearDown(() {
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(channel, null);
+ NativeDeviceInfo.setForTest(null);
+ });
+
+ test('is asked of the OS once, and kept', () async {
+ var asked = 0;
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(channel, (call) async {
+ asked++;
+ return {'name': "Pat's iPhone", 'modelCode': 'iPhone16,1'};
+ });
+
+ final first = NativeDeviceInfo.describe();
+ final second = NativeDeviceInfo.describe();
+ expect((await first)?.name, "Pat's iPhone");
+ await second;
+ await NativeDeviceInfo.describe();
+
+ expect(asked, 1);
+ expect(NativeDeviceInfo.cached?.modelCode, 'iPhone16,1');
+ });
+
+ test('a platform with no answer, or a failing one, has no name', () async {
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(
+ channel,
+ (call) async => throw PlatformException(code: 'nope'),
+ );
+
+ expect(await NativeDeviceInfo.describe(), isNull);
+
+ NativeDeviceInfo.setForTest(null);
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(channel, null);
+ expect(await NativeDeviceInfo.describe(), isNull);
+ expect(DeviceInfo.fromMap('junk'), isNull);
+ });
+ });
+}
+
+class _Broken implements LocalKeyValueStore {
+ @override
+ Future<String?> read(String key) async => throw StateError('locked');
+
+ @override
+ Future<void> write(String key, String value) async =>
+ throw StateError('locked');
+
+ @override
+ Future<void> delete(String key) async => throw StateError('locked');
+}
diff --cc mobile/test/terminal_session_protocol_test.dart
index 415402659,000000000..41b881804
mode 100644,000000..100644
--- a/mobile/test/terminal_session_protocol_test.dart
+++ b/mobile/test/terminal_session_protocol_test.dart
@@@ -1,1572 -1,0 +1,1566 @@@
+import 'dart:convert';
+import 'dart:io' show ZLibEncoder;
+import 'dart:typed_data';
+
+import 'package:fake_async/fake_async.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/terminal/terminal_binary.dart';
+import 'package:harness_mobile/terminal/terminal_session.dart';
+import 'package:harness_mobile/terminal/terminal_viewport.dart';
+
+/// The terminal stream protocol a phone speaks with a machine's daemon, frame
+/// by frame: an open and its answer, a screen and the output after it, gaps
+/// and the resync that repairs them, a stream closed or taken, and everything
+/// typed, pasted and uploaded back.
+void main() {
+ late _Wire wire;
+
+ setUp(() => wire = _Wire());
+
+ /// [disposeAtEnd] false for a test that disposes the session itself.
+ TerminalSession session({
+ String engine = 'claude',
+ bool takeover = true,
+ Future<bool> Function()? onOpenStalled,
+ Duration resync = const Duration(milliseconds: 40),
+ bool disposeAtEnd = true,
+ }) {
+ final built = TerminalSession(
+ machineId: 'm',
+ agentId: 'a',
+ agentName: 'a',
+ engineId: engine,
+ send: wire.send,
+ sendBinary: wire.sendBinary,
+ client: const TerminalClientDescriptor(kind: 'phone', name: 'Pat'),
+ onOpenStalled: onOpenStalled,
+ resyncTimeout: resync,
+ takeover: takeover,
+ );
+ if (disposeAtEnd) addTearDown(built.dispose);
+ return built;
+ }
+
+ /// Real time passing until [done], in small steps — for a ladder of timers
+ /// whose exact rungs a test wants to stop between.
+ Future<void> until(bool Function() done) async {
+ for (var i = 0; i < 200 && !done(); i++) {
+ await Future<void>.delayed(const Duration(milliseconds: 2));
+ }
+ expect(done(), isTrue, reason: 'never got there');
+ }
+
+ /// The daemon answering the last open: a stream id.
+ Future<String> ready(
+ TerminalSession s, {
+ bool readOnly = false,
+ Map<String, dynamic>? heldBy,
+ }) async {
+ final streamId = _streamId();
+ await s.handleFrame('terminal_ready', {
+ 'requestId': wire.last('terminal_open')['requestId'],
+ 'agentId': 'a',
+ 'protocolVersion': TerminalSession.protocolVersion,
+ 'streamId': streamId,
+ if (readOnly) 'readOnly': true,
+ 'heldBy': ?heldBy,
+ });
+ return streamId;
+ }
+
+ /// A session with a stream and its first screen.
+ Future<(TerminalSession, String)> live({
+ String engine = 'claude',
+ String screen = 'prompt> ',
+ Duration resync = const Duration(milliseconds: 40),
+ }) async {
+ final s = session(engine: engine, resync: resync);
+ await s.open();
+ final streamId = await ready(s);
+ await s.handleBinary(_keyframe(streamId, text: screen));
+ return (s, streamId);
+ }
+
+ group('the open', () {
+ test(
+ 'asks for the agent at a size the daemon will accept, and says who asks',
+ () async {
+ final s = session();
+
+ await s.open(initialCols: 10, initialRows: 500);
+
+ final open = wire.last('terminal_open');
+ expect(open['protocolVersion'], TerminalSession.protocolVersion);
+ expect(open['agentId'], 'a');
+ expect(open['cols'], TerminalSession.minCols);
+ expect(open['rows'], TerminalSession.maxRows);
+ expect(open['compression'], ['zlib', 'none']);
+ expect(open['client'], {'kind': 'phone', 'name': 'Pat'});
+ expect(open.containsKey('takeover'), isFalse);
+ expect(s.status, TerminalSessionStatus.opening);
+ expect(s.holdsTerminal, isTrue);
+ expect(s.hasRenderedFrame, isFalse);
+ },
+ );
+
+ test('a polite open says so', () async {
+ final s = session(takeover: false);
+
+ await s.open();
+
+ expect(wire.last('terminal_open')['takeover'], isFalse);
+ });
+
+ test('waits for the panel\'s own measurement', () async {
+ final s = session();
+
+ final opening = s.open(waitForViewportSize: true);
+ await Future<void>.delayed(Duration.zero);
+ expect(wire.of('terminal_open'), isEmpty);
+ s.reportViewport(120, 40);
+ s.reportViewport(10, 10);
+ await opening;
+
+ expect(wire.last('terminal_open')['cols'], 120);
+ expect(wire.last('terminal_open')['rows'], 40);
+ });
+
+ test('opens at the fallback size when the panel never measures', () {
+ fakeAsync((async) {
+ final s = session(disposeAtEnd: false);
+ s.open(waitForViewportSize: true);
+ async.elapse(const Duration(seconds: 3));
+
+ expect(wire.last('terminal_open')['cols'], 80);
+ expect(wire.last('terminal_open')['rows'], 24);
+ s.dispose();
+ });
+ });
+
+ test(
+ 'an open that cannot be sent, with nothing to recover it, fails',
+ () async {
+ wire.sends = false;
+ final s = session();
+
+ await s.open();
+
+ expect(s.status, TerminalSessionStatus.error);
+ expect(s.errorMessage, 'Could not send terminal_open');
+ },
+ );
+
+ test(
+ 'an open that cannot be sent redials once and sends it again',
+ () async {
+ var redials = 0;
+ final s = session(
+ onOpenStalled: () async {
+ redials++;
+ wire.sends = true;
+ return true;
+ },
+ );
+ wire.sends = false;
+
+ await s.open();
+
+ expect(redials, 1);
+ expect(s.status, TerminalSessionStatus.opening);
+ expect(wire.of('terminal_open'), hasLength(2));
+ expect(
+ wire.of('terminal_open').last['requestId'],
+ wire.of('terminal_open').first['requestId'],
+ );
+ },
+ );
+
+ test('a redial that throws still started one, and is polled', () async {
+ final s = session(
+ onOpenStalled: () async {
+ wire.sends = true;
+ throw StateError('socket closed mid-redial');
+ },
+ );
+ wire.sends = false;
+
+ await s.open();
+
+ expect(s.status, TerminalSessionStatus.opening);
+ });
+
+ test(
+ 'a transport that declines the redial keeps its one recovery',
+ () async {
+ var asked = 0;
+ final s = session(
+ onOpenStalled: () async {
+ asked++;
+ return false;
+ },
+ );
+ wire.sends = false;
+
+ await s.open();
+ expect(s.status, TerminalSessionStatus.error);
+
+ // Declined, so not spent: the next open that stalls may still redial.
+ await s.reopen();
+ expect(asked, 2);
+ },
+ );
+
+ test('silence after the open redials, resends, then gives up', () async {
+ var redials = 0;
+ final s = session(
+ onOpenStalled: () async {
+ redials++;
+ return true;
+ },
+ resync: const Duration(milliseconds: 20),
+ );
+
+ await s.open();
+ await Future<void>.delayed(const Duration(milliseconds: 120));
+
+ expect(redials, 1, reason: 'one forced redial per open');
+ expect(wire.of('terminal_open').length, greaterThanOrEqualTo(2));
+ expect(s.status, TerminalSessionStatus.error);
+ expect(s.errorCode, 'TERMINAL_RESYNC_TIMEOUT');
+ expect(s.errorMessage, contains('did not respond'));
+ });
+
+ test('a resend that cannot be sent either gives up at once', () {
+ fakeAsync((async) {
+ final s = session(
+ disposeAtEnd: false,
+ onOpenStalled: () async {
+ wire.sends = false;
+ return true;
+ },
+ );
+ s.open();
+ async.flushMicrotasks();
+ async.elapse(const Duration(seconds: 5));
+
+ expect(s.status, TerminalSessionStatus.error);
+ expect(s.errorCode, 'TERMINAL_RESYNC_TIMEOUT');
+ s.dispose();
+ });
+ });
+ });
+
+ group('terminal_ready', () {
+ test(
+ 'an answer to another open, agent or protocol is not this one\'s',
+ () async {
+ final s = session();
+ await s.open();
+ final requestId = wire.last('terminal_open')['requestId'];
+
+ for (final payload in [
+ {'requestId': 'other', 'agentId': 'a', 'protocolVersion': 3},
+ {'requestId': requestId, 'agentId': 'b', 'protocolVersion': 3},
+ {'requestId': requestId, 'agentId': 'a', 'protocolVersion': 2},
+ ]) {
+ expect(
+ await s.handleFrame('terminal_ready', {
+ ...payload,
+ 'streamId': _streamId(),
+ }),
+ isTrue,
+ );
+ }
+
+ expect(s.streamId, isNull);
+ expect(s.status, TerminalSessionStatus.opening);
+ },
+ );
+
+ test('a ready with no stream is a failure', () async {
+ final s = session();
+ await s.open();
+
+ await s.handleFrame('terminal_ready', {
+ 'requestId': wire.last('terminal_open')['requestId'],
+ 'agentId': 'a',
+ 'protocolVersion': TerminalSession.protocolVersion,
+ });
+
+ expect(s.status, TerminalSessionStatus.error);
+ expect(s.errorCode, 'TERMINAL_READY_INVALID');
+ });
+
+ test('an answered takeover is spent', () async {
+ final s = session();
+ await s.open();
+ expect(s.takeover, isTrue);
+
+ await ready(s);
+
+ expect(s.takeover, isFalse);
+ });
+
+ test(
+ 'a read-only answer watches, names the holder and types nothing',
+ () async {
+ final s = session();
+ await s.open();
+
+ final streamId = await ready(
+ s,
+ readOnly: true,
+ heldBy: {'kind': 'desktop', 'name': 'Studio'},
+ );
+ await s.handleBinary(_keyframe(streamId));
+ s.terminal.textInput('x');
+ await Future<void>.delayed(Duration.zero);
+
+ expect(s.watching, isTrue);
+ expect(s.heldBy?.name, 'Studio');
+ expect(
+ s.takeover,
+ isTrue,
+ reason: 'nothing was won, so nothing is spent',
+ );
+ expect(s.acceptsInput, isFalse);
+ expect(wire.binaries, isEmpty);
+ },
+ );
+
+ test(
+ 'a second answer to the same open leaves one heartbeat, and none after',
+ () {
+ fakeAsync((async) {
+ final s = session(disposeAtEnd: false);
+ s.open();
+ async.flushMicrotasks();
+ final requestId = wire.last('terminal_open')['requestId'];
+ Map<String, dynamic> answer(String streamId) => {
+ 'requestId': requestId,
+ 'agentId': 'a',
+ 'protocolVersion': TerminalSession.protocolVersion,
+ 'streamId': streamId,
+ };
+ // The original reply, late, and the reply to the SAME open resent
+ // after the watchdog gave up on it — both match, and both land before
+ // the first screen.
+ s.handleFrame('terminal_ready', answer(_streamId()));
+ final second = _streamId();
+ s.handleFrame('terminal_ready', answer(second));
+ s.handleBinary(_keyframe(second));
+ async.flushMicrotasks();
+
+ async.elapse(const Duration(seconds: 5));
+ expect(wire.of('terminal_alive'), hasLength(1));
+
+ s.dispose();
+ async.elapse(const Duration(seconds: 20));
+ expect(
+ wire.of('terminal_alive'),
+ hasLength(1),
+ reason: 'a disposed session sends nothing',
+ );
+ });
+ },
+ );
+
+ test(
+ 'heartbeats keep a live stream alive, and a failed one is a lost stream',
+ () {
+ 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();
+
+ async.elapse(const Duration(seconds: 10));
+ expect(wire.of('terminal_alive'), hasLength(2));
+
+ wire.sends = false;
+ async.elapse(const Duration(seconds: 5));
+ expect(s.status, TerminalSessionStatus.error);
+ expect(s.errorMessage, 'Terminal heartbeat was not sent');
+ s.dispose();
+ });
+ },
+ );
+ });
+
+ group('the screen and the output after it', () {
+ test('a keyframe before its stream is ready is dropped, and the watchdog asks again', () async {
+ final s = session();
+ await s.open();
+ final streamId = _streamId();
+
+ // The screen overtakes its own ready.
+ await s.handleBinary(_keyframe(streamId));
+ expect(s.hasRenderedFrame, isFalse);
+
+ await s.handleFrame('terminal_ready', {
+ 'requestId': wire.last('terminal_open')['requestId'],
+ 'agentId': 'a',
+ 'protocolVersion': TerminalSession.protocolVersion,
+ 'streamId': streamId,
+ });
+ await Future<void>.delayed(const Duration(milliseconds: 60));
+
+ expect(s.status, TerminalSessionStatus.resyncing);
+ expect(wire.last('terminal_resync'), {
+ 'streamId': streamId,
+ 'attempt': 1,
+ 'reason': 'TERMINAL_KEYFRAME_TIMEOUT',
+ });
+
+ await s.handleBinary(_keyframe(streamId, seq: 5));
+ expect(s.status, TerminalSessionStatus.controlling);
+ expect(s.hasRenderedFrame, isTrue);
+ });
+
+ test('a frame for another stream is not drawn', () async {
+ final (s, _) = await live();
+ final ticks = s.outputTicks.value;
+
+ await s.handleBinary(_output(_streamId(), 1, 'stray'));
+
+ expect(s.outputTicks.value, ticks);
+ expect(s.status, TerminalSessionStatus.controlling);
+ });
+
+ test('output in order is drawn and acknowledged', () async {
+ final (s, streamId) = await live();
+
+ await s.handleBinary(_output(streamId, 1, 'hello '));
+ await s.handleBinary(_output(streamId, 2, 'world'));
+ await Future<void>.delayed(const Duration(milliseconds: 40));
+
+ expect(_screen(s), contains('hello world'));
+ expect(wire.last('terminal_ack'), {'streamId': streamId, 'lastSeq': 2});
+ });
+
+ test('a scalar split across two frames is drawn whole', () async {
+ final (s, streamId) = await live(screen: '');
+ final bytes = utf8.encode('é');
+
+ await s.handleBinary(
+ _output(streamId, 1, null, bytes: bytes.sublist(0, 1)),
+ );
+ await s.handleBinary(_output(streamId, 2, null, bytes: bytes.sublist(1)));
+
+ expect(_screen(s), contains('é'));
+ });
+
+ test(
+ 'a gap is repaired by a resync, and output meanwhile is dropped',
+ () async {
+ final (s, streamId) = await live(resync: const Duration(seconds: 5));
+
+ await s.handleBinary(_output(streamId, 3, 'skipped ahead'));
+ expect(s.status, TerminalSessionStatus.resyncing);
+ expect(s.errorCode, 'TERMINAL_SEQUENCE_GAP');
+ expect(wire.last('terminal_resync')['attempt'], 1);
+ expect(s.acceptsInput, isFalse);
+
+ await s.handleBinary(_output(streamId, 4, 'more'));
+ await s.handleBinary(_sync(streamId, 5));
+ expect(_screen(s), isNot(contains('more')));
+
+ await s.handleBinary(_keyframe(streamId, seq: 9, text: 'repaired'));
+ expect(s.status, TerminalSessionStatus.controlling);
+ expect(s.errorCode, isNull);
+ expect(_screen(s), contains('repaired'));
+
+ await s.handleBinary(_output(streamId, 10, ' next'));
+ expect(_screen(s), contains('repaired next'));
+ },
+ );
+
+ test(
+ 'a sync frame moves the sequence on; one out of order is a gap',
+ () async {
+ final (s, streamId) = await live(resync: const Duration(seconds: 5));
+
+ await s.handleBinary(_sync(streamId, 1));
+ await s.handleBinary(_output(streamId, 2, 'after sync'));
+ expect(_screen(s), contains('after sync'));
+
+ await s.handleBinary(_sync(streamId, 9));
+ expect(s.status, TerminalSessionStatus.resyncing);
+ },
+ );
+
+ test('a sync or output before any screen asks for one', () async {
+ for (final frame in [
+ _sync,
+ (String id, int seq) => _output(id, seq, 'x'),
+ ]) {
+ final s = session(resync: const Duration(seconds: 5));
+ await s.open();
+ final streamId = await ready(s);
+
+ await s.handleBinary(frame(streamId, 0));
+
+ expect(s.status, TerminalSessionStatus.resyncing);
+ }
+ });
+
+ test(
+ 'three unanswered resyncs, then one reopen, then it says so',
+ () async {
+ final (s, streamId) = await live(
+ resync: const Duration(milliseconds: 20),
+ );
+
+ await s.handleBinary(_output(streamId, 7, 'gap'));
+ await until(() => wire.of('terminal_open').length == 2);
+
+ expect(
+ [for (final r in wire.of('terminal_resync')) r['attempt']],
+ [1, 2, 3],
+ );
+ expect(wire.last('terminal_close'), {'streamId': streamId});
+ expect(s.status, TerminalSessionStatus.opening);
+ expect(
+ _screen(s),
+ contains('prompt>'),
+ reason: 'kept through the reopen',
+ );
+
+ // The reopened stream answers, and never draws.
+ await ready(s);
+ await until(() => s.status == TerminalSessionStatus.error);
+
+ expect(
+ s.errorMessage,
+ 'Terminal did not recover after resync and reopen.',
+ );
+ },
+ );
+
+ test('a reopen nobody answers says the reopen failed', () async {
+ final (s, streamId) = await live(
+ resync: const Duration(milliseconds: 20),
+ );
+
+ await s.handleBinary(_output(streamId, 7, 'gap'));
+ await until(() => wire.of('terminal_open').length == 2);
+ await until(() => s.status == TerminalSessionStatus.error);
+
+ expect(s.errorCode, 'TERMINAL_RESYNC_TIMEOUT');
+ expect(s.errorMessage, 'Terminal did not reopen after resync failed.');
+ });
+
+ test('a screen after the reopen resets the ladder', () async {
+ final (s, streamId) = await live(
+ resync: const Duration(milliseconds: 20),
+ );
+ await s.handleBinary(_output(streamId, 7, 'gap'));
+ await until(() => wire.of('terminal_open').length == 2);
+
+ final second = await ready(s);
+ await s.handleBinary(_keyframe(second));
+ await s.handleBinary(_output(second, 1, 'fine'));
+ expect(s.status, TerminalSessionStatus.controlling);
+ expect(_screen(s), contains('fine'));
+
+ // A second gap climbs the whole ladder again, reopen included.
+ await s.handleBinary(_output(second, 9, 'gap'));
+ await until(() => wire.of('terminal_open').length == 3);
+ expect(s.status, TerminalSessionStatus.opening);
+ });
+
+ test('a resync that cannot be sent is a lost stream', () async {
+ final (s, streamId) = await live();
+ wire.sends = false;
+
+ await s.handleBinary(_output(streamId, 5, 'gap'));
+
+ expect(s.status, TerminalSessionStatus.error);
+ expect(s.errorMessage, 'Could not request terminal resync');
+ });
+
+ test(
+ 'a compressed screen is inflated; a corrupt one is asked for again',
+ () async {
+ final s = session(resync: const Duration(seconds: 5));
+ await s.open();
+ final streamId = await ready(s);
+
+ await s.handleBinary(
+ _keyframe(
+ streamId,
+ bytes: ZLibEncoder().convert(utf8.encode('zipped')),
+ compressed: true,
+ ),
+ );
+ expect(_screen(s), contains('zipped'));
+
+ await s.handleBinary(
+ _output(streamId, 1, null, bytes: [1, 2, 3], compressed: true),
+ );
+ expect(s.status, TerminalSessionStatus.resyncing);
+ expect(s.errorCode, 'TERMINAL_BINARY_DECODE_FAILED');
+ },
+ );
+
+ test('a screen with no size is asked for again', () async {
+ final s = session(resync: const Duration(seconds: 5));
+ await s.open();
+ final streamId = await ready(s);
+
+ await s.handleBinary(
+ TerminalBinaryFrame(
+ kind: TerminalBinaryKind.keyframe,
+ streamId: streamId,
+ seq: 0,
+ bytes: Uint8List(0),
+ compressed: false,
+ ),
+ );
+
+ expect(s.errorCode, 'TERMINAL_KEYFRAME_INVALID');
+ });
+
+ test(
+ 'a renderer that throws is repaired by a resync, not a dead tile',
+ () async {
+ final (s, _) = await live(resync: const Duration(seconds: 5));
+
+ await s.onRendererFailure();
+
+ expect(s.status, TerminalSessionStatus.resyncing);
+ expect(s.errorCode, 'TERMINAL_RENDERER_FAILED');
+ },
+ );
+
+ test('a resync with no stream to ask on is a failure', () async {
+ final s = session();
+
+ await s.onRendererFailure();
+
+ expect(s.status, TerminalSessionStatus.error);
+ });
+
+ test('Grok is drawn in the alternate buffer, reset or not', () async {
+ for (final screen in ['\x1bcgrok', 'grok']) {
+ final (s, _) = await live(engine: 'grok', screen: screen);
+
+ expect(s.terminal.isUsingAltBuffer, isTrue);
+ expect(s.scrollViaTmuxCopyMode, isTrue);
+ }
+ });
+
+ test('bulk data sent as JSON is refused', () async {
+ final (s, _) = await live();
+
+ expect(await s.handleFrame('terminal_output', {}), isTrue);
+
+ expect(s.status, TerminalSessionStatus.error);
+ expect(s.errorCode, 'TERMINAL_BINARY_REQUIRED');
+ });
+
+ test('a kept screen stands in until the first real one', () async {
+ final (first, _) = await live(screen: 'last time');
+ final s = session();
+
+ s.seedScreen(first.terminal);
+ expect(s.showingKeptScreen, isTrue);
+ expect(s.hasScreen, isTrue);
+ final opening = s.open(waitForViewportSize: true);
+ expect(_screen(s), contains('last time'), reason: 'through the open');
+ s.reportViewport(100, 30);
+ await opening;
+ expect(_screen(s), contains('last time'));
+ final streamId = await ready(s);
+ expect(_screen(s), contains('last time'), reason: 'until a screen lands');
+ await s.handleBinary(_keyframe(streamId, text: 'now'));
+
+ expect(s.showingKeptScreen, isFalse);
+ expect(_screen(s), contains('now'));
+ s.seedScreen(first.terminal);
+ expect(s.showingKeptScreen, isFalse, reason: 'too late to stand in');
+ });
+ });
+
+ group('a stream closed, taken or refused', () {
+ test('closed for another stream is not this one\'s', () async {
+ final (s, _) = await live();
+
+ await s.handleFrame('terminal_closed', {'streamId': _streamId()});
+
+ expect(s.status, TerminalSessionStatus.controlling);
+ });
+
+ test('closed by the machine, with its reason', () async {
+ final (s, streamId) = await live();
+
+ await s.handleFrame('terminal_closed', {
+ 'streamId': streamId,
+ 'reason': 'pane exited',
+ });
+
+ expect(s.status, TerminalSessionStatus.closed);
+ expect(s.errorMessage, 'pane exited');
+ expect(s.errorCode, isNull);
+ expect(s.streamId, isNull);
+ });
+
+ test('taken, by someone named or not', () async {
+ final (s, streamId) = await live();
+
+ await s.handleFrame('terminal_closed', {
+ 'streamId': streamId,
+ 'code': 'TERMINAL_TAKEN_OVER',
+ });
+
+ expect(s.status, TerminalSessionStatus.takenOver);
+ expect(s.errorMessage, 'Another client connected to this terminal.');
+ expect(s.takenOverBy, isNull);
+ });
+
+ test('a lost socket does not overwrite a stream someone took', () async {
+ final (s, streamId) = await live();
+ await s.handleFrame('terminal_closed', {
+ 'streamId': streamId,
+ 'code': 'TERMINAL_TAKEN_OVER',
+ });
+
+ s.transportLost('gone');
+ await s.handleFrame('terminal_transport_error', {'code': 'X'});
+
+ expect(s.status, TerminalSessionStatus.takenOver);
+ });
+
+ test('an error about another stream or open is not this one\'s', () async {
+ final (s, _) = await live();
+
+ await s.handleFrame('terminal_error', {
+ 'streamId': _streamId(),
+ 'code': 'BOOM',
+ });
+ await s.handleFrame('terminal_error', {
+ 'requestId': 'other',
+ 'code': 'BOOM',
+ });
+
+ expect(s.status, TerminalSessionStatus.controlling);
+ });
+
+ test(
+ 'an error for this stream fails it with the daemon\'s words',
+ () async {
+ final (s, streamId) = await live();
+
+ await s.handleFrame('terminal_error', {
+ 'streamId': streamId,
+ 'code': 'TERMINAL_PASTE_FAILED',
+ 'message': 'pty write failed',
+ });
+
+ expect(s.status, TerminalSessionStatus.error);
+ expect(s.errorCode, 'TERMINAL_PASTE_FAILED');
+ expect(s.errorMessage, 'pty write failed');
+ },
+ );
+
+ test('an error with no code is still an error', () async {
+ final (s, _) = await live();
+
+ await s.handleFrame('terminal_error', {});
+
+ expect(s.errorCode, 'TERMINAL_ERROR');
+ });
+
+ test('a refused paste leaves the stream alone', () async {
+ final (s, streamId) = await live();
+
+ await s.handleFrame('terminal_error', {
+ 'streamId': streamId,
+ 'code': 'TERMINAL_PASTE_INVALID',
+ });
+
+ expect(s.status, TerminalSessionStatus.controlling);
+ });
+
+ test(
+ 'a refused keystroke realigns the count once, not per refusal',
+ () async {
+ final (s, streamId) = await live();
+ for (final key in ['a', 'b', 'c']) {
+ s.terminal.textInput(key);
+ await Future<void>.delayed(const Duration(milliseconds: 10));
+ }
+ expect(_inputSeqs(wire), [0, 1, 2]);
+
+ for (var i = 0; i < 2; i++) {
+ await s.handleFrame('terminal_error', {
+ 'streamId': streamId,
+ 'code': 'TERMINAL_INPUT_INVALID',
+ 'expectedSeq': 1,
+ });
+ }
+ s.terminal.textInput('d');
+ await Future<void>.delayed(const Duration(milliseconds: 10));
+
+ expect(_inputSeqs(wire).last, 1);
+ expect(s.status, TerminalSessionStatus.controlling);
+ },
+ );
+
+ test(
+ 'a refused keystroke from a daemon that does not say reopens',
+ () async {
+ final (s, streamId) = await live();
+
+ await s.handleFrame('terminal_error', {
+ 'streamId': streamId,
+ 'code': 'TERMINAL_INPUT_INVALID',
+ });
+ await Future<void>.delayed(Duration.zero);
+
+ expect(wire.last('terminal_close'), {'streamId': streamId});
+ expect(wire.of('terminal_open'), hasLength(2));
+ },
+ );
+
+ test('a polite open refused waits for a person', () async {
+ final s = session(takeover: false);
+ await s.open();
+
+ await s.handleFrame('terminal_error', {
+ 'requestId': wire.last('terminal_open')['requestId'],
+ 'code': 'CONTROL_LEASE_HELD',
+ });
+
+ expect(s.status, TerminalSessionStatus.takenOver);
+ expect(s.errorMessage, 'Another client controls this terminal.');
+ expect(wire.of('terminal_open'), hasLength(1));
+ });
+
+ test(
+ 'a polite open refused after a person arrived asks again, properly',
+ () async {
+ final s = session(takeover: false);
+ await s.open();
+ s.takeover = true;
+
+ await s.handleFrame('terminal_error', {
+ 'requestId': wire.last('terminal_open')['requestId'],
+ 'code': 'CONTROL_LEASE_HELD',
+ });
+ await Future<void>.delayed(Duration.zero);
+
+ expect(wire.of('terminal_open'), hasLength(2));
+ expect(wire.last('terminal_open').containsKey('takeover'), isFalse);
+ },
+ );
+
+ test('an ordinary open that lost the race keeps its retry', () async {
+ final s = session();
+ await s.open();
+
+ await s.handleFrame('terminal_error', {
+ 'requestId': wire.last('terminal_open')['requestId'],
+ 'code': 'CONTROL_LEASE_HELD',
+ });
+
+ expect(s.status, TerminalSessionStatus.error);
+ });
+
+ test(
+ 'the link\'s mode is shown only when it is one the header can draw',
+ () async {
+ final (s, streamId) = await live();
+
+ await s.handleFrame('terminal_link_mode', {
+ 'streamId': streamId,
+ 'mode': 'p2p',
+ });
+ expect(s.linkMode, 'p2p');
+ await s.handleFrame('terminal_link_mode', {
+ 'streamId': streamId,
+ 'mode': 'carrier-pigeon',
+ });
+ expect(s.linkMode, 'p2p');
+ await s.handleFrame('terminal_link_mode', {
+ 'streamId': _streamId(),
+ 'mode': 'relay',
+ });
+ expect(s.linkMode, 'p2p');
+ },
+ );
+
+ test(
+ 'an unknown frame is not the session\'s; a disposed one hears nothing',
+ () async {
+ final s = session(disposeAtEnd: false);
+
+ expect(await s.handleFrame('terminal_whatever', {}), isFalse);
+ s.dispose();
+ expect(await s.handleFrame('terminal_ready', {}), isFalse);
+ await s.open();
+ await s.reopen();
+ expect(wire.of('terminal_open'), isEmpty);
+ },
+ );
+ });
+
+ group('reopening and closing', () {
+ test(
+ 'a stream on its way or alive is not reopened, unless forced',
+ () async {
+ final (s, _) = await live();
+
+ await s.reopen();
+ expect(wire.of('terminal_open'), hasLength(1));
+
+ await s.reopen(force: true);
+ expect(wire.of('terminal_open'), hasLength(2));
+ expect(s.status, TerminalSessionStatus.opening);
+ expect(_screen(s), contains('prompt>'), reason: 'the screen is kept');
+ },
+ );
+
+ test('a dead stream reopens at the measured size', () async {
+ final (s, _) = await live();
+ s.reportViewport(100, 30);
+ s.transportLost('gone');
+
+ await s.reopen();
+
+ expect(wire.last('terminal_open')['cols'], 100);
+ expect(wire.last('terminal_open')['rows'], 30);
+ });
+
+ test('closing says so to the daemon, once there is a stream', () async {
+ final (s, streamId) = await live();
+
+ await s.close();
+ await s.close();
+
+ expect(wire.of('terminal_close'), [
+ {'streamId': streamId},
+ ]);
+ expect(s.status, TerminalSessionStatus.closed);
+ s.transportLost('late');
+ expect(s.status, TerminalSessionStatus.closed);
+ });
+
+ test('a rename is trimmed, and said only when it changes', () async {
+ final s = session();
+ var told = 0;
+ s.addListener(() => told++);
+
+ s.renameAgent(' api ');
+ s.renameAgent('api');
+ s.renameAgent(' ');
+
+ expect(s.agentName, 'api');
+ expect(told, 1);
+ });
+ });
+
+ group('what is typed', () {
+ test('goes out numbered, and nothing before the stream is live', () async {
+ final s = session();
+ await s.open();
+ s.terminal.textInput('early');
+ await Future<void>.delayed(const Duration(milliseconds: 10));
+ expect(wire.binaries, isEmpty);
+
+ final streamId = await ready(s);
+ await s.handleBinary(_keyframe(streamId));
+ s.terminal.textInput('l');
+ await Future<void>.delayed(const Duration(milliseconds: 10));
+ s.terminal.textInput('s\r');
+ await Future<void>.delayed(const Duration(milliseconds: 10));
+
+ expect(_typed(wire), 'ls\r');
+ expect(_inputSeqs(wire), [0, 1]);
+ });
+
+ test('an armed ctrl turns the next key into its chord, once', () async {
+ final (s, _) = await live();
+
+ s.armControl(true);
+ expect(s.controlArmed, isTrue);
+ s.terminal.textInput('c');
+ await Future<void>.delayed(const Duration(milliseconds: 10));
+ s.terminal.textInput('c');
+ await Future<void>.delayed(const Duration(milliseconds: 10));
+
+ expect(_typed(wire), '\x03c');
+ expect(s.controlArmed, isFalse);
+ });
+
+ test(
+ 'clearing the prompt is ctrl-E then ctrl-U, and the keyboard\'s buffer',
+ () async {
+ final (s, _) = await live();
+ final viewport = _Viewport();
+ s.attachViewport(viewport);
+
+ s.clearPrompt();
+ await Future<void>.delayed(const Duration(milliseconds: 10));
+
+ expect(_typed(wire), '\x05\x15');
+ expect(viewport.cleared, 1);
+ s.detachViewport(_Viewport());
+ s.resetInputBuffer();
+ expect(
+ viewport.cleared,
+ 2,
+ reason: 'another view detaching changes nothing',
+ );
+ s.detachViewport(viewport);
+ s.resetInputBuffer();
+ expect(viewport.cleared, 2);
+ },
+ );
+
+ test('a key that cannot be sent is a lost stream', () async {
+ final (s, _) = await live();
+ wire.binarySends = false;
+
+ s.terminal.textInput('x');
+ await Future<void>.delayed(const Duration(milliseconds: 10));
+
+ expect(s.status, TerminalSessionStatus.error);
+ expect(s.errorMessage, 'Terminal input was not sent');
+ });
+
+ test('a paste too big for one frame is split, still in order', () async {
+ final (s, _) = await live();
+ final big = 'x' * (TerminalSession.kInputFrameMaxBytes + 10);
+
+ s.terminal.textInput('$big\r');
+ await Future<void>.delayed(const Duration(milliseconds: 20));
+
+ final frames = wire.binaries
+ .where((f) => f.kind == TerminalBinaryKind.input)
+ .toList();
+ expect(frames.length, greaterThan(1));
+ expect(
+ frames.every(
+ (f) => f.bytes.length <= TerminalSession.kInputFrameMaxBytes,
+ ),
+ isTrue,
+ );
+ expect(_typed(wire), '$big\r');
+ });
+
+ test('a composed message is one turn, not keystrokes', () async {
+ final (s, _) = await live();
+
+ expect(await s.sendComposerText(' '), isFalse);
+ expect(await s.sendComposerText('fix it \n'), isTrue);
+
+ expect(wire.last('message'), {
+ 'content': 'fix it',
+ 'agentId': 'a',
+ 'mode': 'auto',
+ });
+ expect(wire.binaries, isEmpty);
+ });
+
+ test('a watcher sends no message', () async {
+ final s = session();
+ await s.open();
+ await ready(s, readOnly: true);
+
+ expect(await s.sendComposerText('hi'), isFalse);
+ expect(await s.pasteText('hi'), isFalse);
+ });
+
+ test(
+ 'a paste is one frame; one that cannot be sent is a lost stream',
+ () async {
+ final (s, streamId) = await live();
+
+ expect(await s.pasteText(''), isFalse);
+ expect(await s.pasteText('line one\nline two'), isTrue);
+ final paste = wire.binaries.single;
+ expect(paste.kind, TerminalBinaryKind.paste);
+ expect(paste.streamId, streamId);
+ expect(utf8.decode(paste.bytes), 'line one\nline two');
+
+ wire.binarySends = false;
+ expect(await s.pasteText('again'), isFalse);
+ expect(s.errorMessage, 'Terminal paste was not sent');
+ },
+ );
+ });
+
+ group('images and files', () {
+ Future<void> answer(
+ TerminalSession s,
+ String type, [
+ Map<String, dynamic> extra = const {},
+ ]) => s.handleFrame(type, {'streamId': s.streamId, ...extra});
+
+ test(
+ 'an image is announced, sent in chunks, and done when the daemon says',
+ () async {
+ final (s, streamId) = await live();
+ final image = Uint8List(terminalUploadChunkBytes + 5);
+
+ final pasting = s.pasteImage(image);
+ await Future<void>.delayed(Duration.zero);
+ expect(wire.last('terminal_chunked_upload_begin'), {
+ 'streamId': streamId,
+ 'uploadKind': 'image',
+ 'totalBytes': image.length,
+ });
+ expect(s.uploadProgress?.label, 'image');
+
+ await answer(s, 'terminal_chunked_upload_begin_result', {
+ 'accepted': true,
+ });
+ await Future<void>.delayed(Duration.zero);
+ final chunks = wire.binaries
+ .where((f) => f.kind == TerminalBinaryKind.imagePaste)
+ .toList();
+ expect([for (final c in chunks) c.seq], [0, 1]);
+ expect(chunks.first.bytes.length, terminalUploadChunkBytes);
+
+ await answer(s, 'terminal_chunked_upload_progress', {
+ 'bytesWritten': 100,
+ 'totalBytes': image.length,
+ });
+ expect(s.uploadProgress!.bytesWritten, 100);
+ expect(s.uploadProgress!.percent, closeTo(100 / image.length, 1e-9));
+
+ await answer(s, 'terminal_paste_image_result');
+ expect(await pasting, isTrue);
+ expect(s.uploadProgress, isNull);
+ },
+ );
+
+ test('a file carries its name', () async {
+ final (s, _) = await live();
+
+ final pasting = s.pasteFile('notes.md', Uint8List.fromList([1, 2]));
+ await Future<void>.delayed(Duration.zero);
+ expect(
+ wire.last('terminal_chunked_upload_begin')['filename'],
+ 'notes.md',
+ );
+ expect(s.uploadProgress?.label, 'notes.md');
+ await answer(s, 'terminal_chunked_upload_begin_result', {
+ 'accepted': true,
+ });
+ await Future<void>.delayed(Duration.zero);
+ await answer(s, 'terminal_paste_file_result');
+
+ expect(await pasting, isTrue);
+ expect(await s.pasteFile('', Uint8List(1)), isFalse);
+ expect(await s.pasteFile('x', Uint8List(0)), isFalse);
+ expect(await s.pasteImage(Uint8List(0)), isFalse);
+ });
+
+ test('a refused announcement ends it', () async {
+ final (s, _) = await live();
+
+ final pasting = s.pasteImage(Uint8List(3));
+ await Future<void>.delayed(Duration.zero);
+ await answer(s, 'terminal_chunked_upload_begin_result', {
+ 'accepted': false,
+ });
+
+ expect(await pasting, isFalse);
+ expect(s.uploadProgress, isNull);
+ });
+
+ test('one at a time, and cancelling says so', () async {
+ final (s, streamId) = await live();
+
+ final first = s.pasteImage(Uint8List(3));
+ await Future<void>.delayed(Duration.zero);
+ expect(await s.pasteImage(Uint8List(3)), isFalse);
+
+ await s.cancelUpload();
+
+ expect(await first, isFalse);
+ expect(wire.last('terminal_chunked_upload_cancel'), {
+ 'streamId': streamId,
+ });
+ await s.cancelUpload();
+ expect(wire.of('terminal_chunked_upload_cancel'), hasLength(1));
+ });
+
+ test('a stream lost mid-upload settles it at once', () async {
+ final (s, _) = await live();
+
+ final pasting = s.pasteImage(Uint8List(3));
+ await Future<void>.delayed(Duration.zero);
+ s.transportLost('gone');
+
+ expect(await pasting, isFalse);
+ });
+
+ test(
+ 'a chunk the daemon calls malformed ends it and keeps the stream',
+ () async {
+ final (s, streamId) = await live();
+
+ final pasting = s.pasteImage(Uint8List(3));
+ await Future<void>.delayed(Duration.zero);
+ await s.handleFrame('terminal_error', {
+ 'streamId': streamId,
+ 'code': 'TERMINAL_CHUNKED_UPLOAD_INVALID',
+ });
+
+ expect(await pasting, isFalse);
+ expect(s.status, TerminalSessionStatus.controlling);
+ },
+ );
+
+ test(
+ 'an announcement or chunk that cannot be sent is a lost stream',
+ () async {
+ final (s, _) = await live();
+ wire.sends = false;
+ expect(await s.pasteImage(Uint8List(3)), isFalse);
+ expect(s.errorMessage, 'Terminal upload request was not sent');
+
+ wire.sends = true;
+ final (t, _) = await live();
+ wire.binarySends = false;
+ final pasting = t.pasteImage(Uint8List(3));
+ await Future<void>.delayed(Duration.zero);
+ await t.handleFrame('terminal_chunked_upload_begin_result', {
+ 'streamId': t.streamId,
+ 'accepted': true,
+ });
+ expect(await pasting, isFalse);
+ expect(t.errorMessage, 'Terminal upload chunk was not sent');
+ },
+ );
+
+ test('a daemon that never answers the announcement times it out', () {
+ 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.elapse(const Duration(seconds: 11));
+
+ expect(result, isFalse);
+ s.dispose();
+ });
+ });
+
+ test('frames about an upload on another stream are ignored', () async {
+ final (s, _) = await live();
+ final other = _streamId();
+
+ for (final type in [
+ 'terminal_chunked_upload_begin_result',
+ 'terminal_chunked_upload_progress',
+ 'terminal_paste_image_result',
+ ]) {
+ expect(await s.handleFrame(type, {'streamId': other}), isTrue);
+ }
+ expect(s.uploadProgress, isNull);
+ });
+ });
+
+ group('size and scrolling', () {
+ test('the first resize goes at once; a drag is asked for once, where it settles', () async {
+ final (s, streamId) = await live();
+
+ s.resize(100, 30);
+ await Future<void>.delayed(Duration.zero);
+ s.resize(110, 31);
+ s.resize(120, 32);
+ await Future<void>.delayed(const Duration(milliseconds: 80));
+
+ final sizes = [
+ for (final r in wire.of('terminal_resize')) (r['cols'], r['rows']),
+ ];
+ expect(sizes, [(100, 30), (120, 32)]);
+ expect(wire.last('terminal_resize')['streamId'], streamId);
+ expect(wire.last('terminal_resize')['resizeSeq'], 1);
+ });
+
+ test('a resize to the size it already is sends nothing', () async {
+ final (s, _) = await live();
+
+ s.resize(80, 24);
+ await Future<void>.delayed(Duration.zero);
+
+ expect(wire.of('terminal_resize'), isEmpty);
+ });
+
+ test('a resize that cannot be sent is a lost stream', () async {
+ final (s, _) = await live();
+ wire.sends = false;
+
+ s.resize(100, 30);
+ await Future<void>.delayed(Duration.zero);
+
+ expect(s.errorMessage, 'Terminal resize was not sent');
+ });
+
+ test(
+ 'the measured size is asked for as soon as the screen lands',
+ () async {
+ final s = session();
+ await s.open();
+ s.reportViewport(90, 30);
+ final streamId = await ready(s);
+
+ await s.handleBinary(_keyframe(streamId));
+ await Future<void>.delayed(Duration.zero);
+
+ expect(wire.last('terminal_resize')['cols'], 90);
+ },
+ );
+
+ test('Grok\'s scroll goes to tmux, coalesced, flushed on a turn', () async {
+ final (s, streamId) = await live(engine: 'grok');
+
+ s.sendScrollCommand(true, 2);
+ s.sendScrollCommand(true, 3);
+ s.sendScrollCommand(false, 1);
+ await Future<void>.delayed(const Duration(milliseconds: 40));
+ s.sendScrollCommand(true, 0);
+
+ expect(wire.of('terminal_scroll'), [
+ {'streamId': streamId, 'direction': 'up', 'lines': 5},
+ {'streamId': streamId, 'direction': 'down', 'lines': 1},
+ ]);
+ });
+
+ test('any other engine scrolls its own copy', () async {
+ final (s, _) = await live();
+ final viewport = _Viewport();
+ s.attachViewport(viewport);
+
+ s.sendScrollCommand(true, 3);
+ s.scroll(1, 10, 0);
- s.find(TerminalFindAction.next);
+ expect(s.focusInput(), isTrue);
+ await Future<void>.delayed(const Duration(milliseconds: 40));
+
+ expect(wire.of('terminal_scroll'), isEmpty);
+ expect(viewport.scrolls, [(1, 10, 0)]);
- expect(viewport.finds, [TerminalFindAction.next]);
+ });
+
+ test('the cursor blinks locally, never into the stream', () async {
+ final (s, _) = await live();
+
+ s.setCursorBlinkPhase(false);
+ expect(s.terminal.cursorVisibleMode, isFalse);
+ s.setCursorBlinkPhase(false);
+ s.setCursorBlinkPhase(true);
+ expect(s.terminal.cursorVisibleMode, isTrue);
+ expect(wire.binaries, isEmpty);
+ });
+
+ test('an acknowledgement that cannot be sent is a lost stream', () async {
+ final (s, streamId) = await live();
+ wire.sends = false;
+
+ await s.handleBinary(_output(streamId, 1, 'x'));
+ await Future<void>.delayed(const Duration(milliseconds: 40));
+
+ expect(s.errorMessage, 'Terminal ACK was not sent');
+ });
+
+ test('a large burst is acknowledged at once, not on the timer', () async {
+ final (s, streamId) = await live();
+ final before = wire.of('terminal_ack').length;
+
+ await s.handleBinary(_output(streamId, 1, 'y' * (64 * 1024)));
+
+ expect(wire.of('terminal_ack').length, before + 1);
+ });
+ });
+
+ group('who a client is', () {
+ test('only a well-formed introduction is believed', () {
+ expect(TerminalClientDescriptor.fromJson(null), isNull);
+ expect(
+ TerminalClientDescriptor.fromJson({'kind': 'Desk top', 'name': 'x'}),
+ isNull,
+ );
+ expect(
+ TerminalClientDescriptor.fromJson({'kind': 'desktop', 'name': 3}),
+ isNull,
+ );
+ expect(
+ TerminalClientDescriptor.fromJson({'kind': 'desktop', 'name': ' '}),
+ isNull,
+ );
+ expect(
+ TerminalClientDescriptor.fromJson({
+ 'kind': 'desktop',
+ 'name': 'x' * (TerminalClientDescriptor.nameMax + 1),
+ }),
+ isNull,
+ );
+ expect(
+ TerminalClientDescriptor.fromJson({
+ 'kind': 'desktop',
+ 'name': 'Mac',
+ 'machineId': 'not-hex',
+ }),
+ isNull,
+ );
+
+ final mac = TerminalClientDescriptor.fromJson({
+ 'kind': 'desktop',
+ 'name': 'Mac\u0007 mini',
+ 'machineId': 'a' * 16,
+ })!;
+ expect(mac.name, 'Mac mini');
+ expect(mac.toJson()['machineId'], 'a' * 16);
+ });
+
+ test('a desktop is named as the fleet names its machine now', () {
+ final mac = TerminalClientDescriptor(
+ kind: 'desktop',
+ name: 'old name',
+ machineId: 'a' * 16,
+ );
+
+ expect(mac.label((_) => ' Studio '), 'Studio');
+ expect(mac.label((_) => null), 'old name');
+ expect(mac.label((_) => ' '), 'old name');
+ expect(
+ const TerminalClientDescriptor(
+ kind: 'phone',
+ name: 'Pat',
+ ).label((_) => 'never asked'),
+ 'Pat',
+ );
+ });
+
+ test('an upload\'s progress never reads past the ends', () {
+ const empty = UploadProgress(label: 'x', bytesWritten: 5, totalBytes: 0);
+ expect(empty.percent, 0);
+ final over = empty.copyWith(totalBytes: 2);
+ expect(over.percent, 1);
+ expect(over.copyWith().bytesWritten, 5);
+ });
+ });
+}
+
+/// The session's two send channels, recorded.
+class _Wire {
+ final frames = <(String, Map<String, dynamic>)>[];
+ final binaries = <TerminalBinaryFrame>[];
+ bool sends = true;
+ bool binarySends = true;
+
+ Future<bool> send(String type, Map<String, dynamic> payload) async {
+ frames.add((type, payload));
+ return sends;
+ }
+
+ Future<bool> sendBinary(TerminalBinaryFrame frame) async {
+ binaries.add(frame);
+ return binarySends;
+ }
+
+ List<Map<String, dynamic>> of(String type) => [
+ for (final (sent, payload) in frames)
+ if (sent == type) payload,
+ ];
+
+ Map<String, dynamic> last(String type) => of(type).last;
+}
+
+class _Viewport implements TerminalViewport {
+ final scrolls = <(int, int, int)>[];
- final finds = <TerminalFindAction>[];
+ var cleared = 0;
+
+ @override
+ void scroll(int phase, int dy, int velocity) =>
+ scrolls.add((phase, dy, velocity));
+
- @override
- void find(TerminalFindAction action) => finds.add(action);
-
+ @override
+ bool focusInput() => true;
+
+ @override
+ void clearInputBuffer() => cleared++;
+}
+
+var _streams = 0;
+
+String _streamId() =>
+ '00000000-0000-4000-8000-${(++_streams).toString().padLeft(12, '0')}';
+
+TerminalBinaryFrame _keyframe(
+ String streamId, {
+ int seq = 0,
+ String text = 'prompt> ',
+ List<int>? bytes,
+ bool compressed = false,
+}) => TerminalBinaryFrame(
+ kind: TerminalBinaryKind.keyframe,
+ streamId: streamId,
+ seq: seq,
+ bytes: Uint8List.fromList(bytes ?? utf8.encode(text)),
+ compressed: compressed,
+ cols: 80,
+ rows: 24,
+);
+
+TerminalBinaryFrame _output(
+ String streamId,
+ int seq,
+ String? text, {
+ List<int>? bytes,
+ bool compressed = false,
+}) => TerminalBinaryFrame(
+ kind: TerminalBinaryKind.output,
+ streamId: streamId,
+ seq: seq,
+ bytes: Uint8List.fromList(bytes ?? utf8.encode(text!)),
+ compressed: compressed,
+);
+
+TerminalBinaryFrame _sync(String streamId, int seq) => TerminalBinaryFrame(
+ kind: TerminalBinaryKind.sync,
+ streamId: streamId,
+ seq: seq,
+ bytes: Uint8List(0),
+ compressed: false,
+);
+
+/// Everything on the session's screen, as text.
+String _screen(TerminalSession s) {
+ final buffer = s.terminal.buffer;
+ return [
+ for (var i = 0; i < buffer.lines.length; i++)
+ buffer.lines[i].toString().trimRight(),
+ ].join('\n');
+}
+
+String _typed(_Wire wire) => utf8.decode([
+ for (final frame in wire.binaries)
+ if (frame.kind == TerminalBinaryKind.input) ...frame.bytes,
+]);
+
+List<int> _inputSeqs(_Wire wire) => [
+ for (final frame in wire.binaries)
+ if (frame.kind == TerminalBinaryKind.input) frame.seq,
+];