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.

19.9 KB
Raw Blame
// Folders dropped on a Swarm chat's composer: their paths go into the message
// at the cursor, dropped files still attach, and when the chat's agents run on
// another computer the box says so and offers the folder as a zip instead.
import 'dart:async';
import 'dart:io';
import 'dart:math';

import 'package:archive/archive.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/super_tabs/attachment_upload.dart';
import 'package:harness/super_tabs/controller.dart';
import 'package:harness/super_tabs/folder_zip.dart';
import 'package:harness/super_tabs/view.dart';
import 'package:harness/state/harness_attachments.dart';
import 'package:path/path.dart' as p;

import 'support/super_tab_fixture.dart';

void main() {
  final composer = find.byKey(const ValueKey('super-message-composer'));
  final hint = find.byKey(const ValueKey('super-folder-path-hint'));
  final surface = find.byKey(const ValueKey('super-message-composer-surface'));

  late Directory root;
  late ConversationServer server;
  setUp(() => root = Directory.systemTemp.createTempSync('swarm-folder-drop'));
  tearDown(() => root.deleteSync(recursive: true));

  /// A real folder under [root], so the drop can tell it from a file. Its
  /// path is this computer's own, as a drop gives it: on Windows a `/` in it
  /// would end up in the name a dropped file is attached by.
  Directory folder(String name) =>
      Directory(p.join(root.path, name))..createSync();

  /// The chat's one agent runs on [machineId]; this computer is `here`.
  Future<SuperTabController> open(
    WidgetTester tester, {
    String machineId = 'here',
  }) async {
    // One logical pixel per device pixel, so the platform's drop position
    // needs no scaling on any host.
    tester.view.devicePixelRatio = 1;
    addTearDown(tester.view.resetDevicePixelRatio);
    server = ConversationServer();
    (server.state['agents'] as List).add({
      'id': 'lead-agent',
      'name': 'Lead',
      'displayName': 'Atlas',
      'machineId': machineId,
      'harnessId': 'native-lead',
      'contributorId': 'owner',
      'configuration': {'engine': 'claude'},
    });
    (server.state['conversations'] as List)[0]
      ..['leadId'] = 'lead-agent'
      ..['agentIds'] = ['lead-agent'];
    final controller = server.controller();
    await controller.refresh();
    await tester.binding.setSurfaceSize(const Size(1100, 800));
    addTearDown(() => tester.binding.setSurfaceSize(null));
    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          body: SuperTabView(
            controller: controller,
            onInvite: () {},
            onAddAgent: (_) {},
            onOpenTerminal: (_) {},
            machineName: (_) => 'Test Mac',
            isThisComputer: (machine) => machine == 'here',
          ),
        ),
      ),
    );
    await tester.pumpAndSettle();
    return controller;
  }

  Future<void> close(WidgetTester tester, SuperTabController c) async {
    await tester.pumpWidget(const SizedBox());
    await c.flush();
    c.dispose();
  }

  Future<void> platform(String method, Object arguments) =>
      TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
          .handlePlatformMessage(
            'desktop_drop',
            const StandardMethodCodec().encodeMethodCall(
              MethodCall(method, arguments),
            ),
            (_) {},
          );

  /// Lets files be read and the zip's isolate answer, a frame at a time,
  /// until [done]. While a message is [sending] its spinner never settles.
  Future<void> settle(
    WidgetTester tester,
    bool Function() done, {
    bool sending = false,
  }) async {
    for (var i = 0; i < 200 && !done(); i++) {
      await tester.runAsync(
        () => Future<void>.delayed(const Duration(milliseconds: 20)),
      );
      await tester.pump();
    }
    if (!sending) await tester.pumpAndSettle();
  }

  /// Drops on the composer: [method] and [arguments] as the platform sends
  /// them, then waits [until] the drop has landed. The drop is delivered on
  /// the test's clock, as the composer's other work is, never inside
  /// `runAsync`: a drop handled there leaves frames on the real clock, and a
  /// later isolate then never lets the test finish.
  Future<void> dropAs(
    WidgetTester tester,
    String method,
    Object arguments, {
    required bool Function() until,
  }) async {
    final inside = tester.getCenter(surface);
    await platform('entered', [inside.dx, inside.dy]);
    await tester.pump();
    await platform(method, arguments);
    await settle(tester, until);
  }

  /// Drops [paths] the way Linux and Windows report them: paths alone, a
  /// folder not told apart from a file.
  Future<void> drop(
    WidgetTester tester,
    List<String> paths, {
    required bool Function() until,
  }) => dropAs(tester, 'performOperation', paths, until: until);

  TextEditingController field(WidgetTester tester) =>
      tester.widget<TextField>(composer).controller!;

  List<String> names(SuperTabController c) => [
    for (final file in c.attachments('lead').files) file.name,
  ];

  test('a Windows path goes in as it is, its backslashes its own, and in '
      'quotes only for a space or a shell character', () {
    expect(
      folderPathText(r'C:\Users\RUNNER~1\AppData\docs', isWindows: true),
      r'C:\Users\RUNNER~1\AppData\docs',
    );
    expect(
      folderPathText(r'C:\Users\me\my notes', isWindows: true),
      r'"C:\Users\me\my notes"',
    );
    expect(
      folderPathText(r'C:\work\cost$HOME', isWindows: true),
      r'"C:\work\cost$HOME"',
    );
    expect(
      folderPathText(r'/work/back\slash', isWindows: false),
      r'"/work/back\\slash"',
    );
  });

  testWidgets('a dropped folder puts its path at the cursor', (tester) async {
    final controller = await open(tester);
    final docs = folder('docs');
    await tester.enterText(composer, 'see please');
    field(tester).selection = const TextSelection.collapsed(offset: 4);

    await drop(tester, [
      docs.path,
    ], until: () => field(tester).text.contains(docs.path));

    expect(field(tester).text, 'see ${docs.path} please');
    expect(
      field(tester).selection,
      TextSelection.collapsed(offset: 'see ${docs.path} '.length),
    );
    expect(controller.draft('lead'), 'see ${docs.path} please');
    expect(names(controller), isEmpty);
    await close(tester, controller);
  });

  testWidgets('several folders go in space-separated, quoted when a path has '
      'a space', (tester) async {
    final controller = await open(tester);
    final plain = folder('plain'), spaced = folder('my notes');
    await tester.enterText(composer, 'Read');

    await drop(tester, [
      plain.path,
      spaced.path,
    ], until: () => field(tester).text.contains(spaced.path));

    expect(field(tester).text, 'Read ${plain.path} "${spaced.path}" ');
    await close(tester, controller);
  });

  testWidgets('a folder macOS marks as one pastes its path too', (
    tester,
  ) async {
    final controller = await open(tester);
    // A folder that is gone by now: macOS's own word that it is a folder is
    // enough, nothing is read from it.
    await dropAs(tester, 'performOperation_macos', [
      {'path': '/Volumes/Work/project', 'isDirectory': true},
    ], until: () => field(tester).text.isNotEmpty);

    expect(field(tester).text, '/Volumes/Work/project ');
    expect(names(controller), isEmpty);
    await close(tester, controller);
  });

  testWidgets('a dropped file still attaches and leaves the text alone', (
    tester,
  ) async {
    final controller = await open(tester);
    final log = File(p.join(root.path, 'trace.log'))..writeAsStringSync('boom');
    await tester.enterText(composer, 'Here');

    await drop(tester, [log.path], until: () => names(controller).isNotEmpty);

    expect(names(controller), ['trace.log']);
    expect(field(tester).text, 'Here');
    await close(tester, controller);
  });

  testWidgets('a mixed drop attaches the files and pastes the folder paths', (
    tester,
  ) async {
    final controller = await open(tester);
    final log = File(p.join(root.path, 'trace.log'))..writeAsStringSync('boom');
    final src = folder('src');

    await drop(
      tester,
      [log.path, src.path],
      until: () =>
          names(controller).isNotEmpty && field(tester).text.isNotEmpty,
    );

    expect(names(controller), ['trace.log']);
    expect(field(tester).text, '${src.path} ');
    await close(tester, controller);
  });

  testWidgets('no hint when the chat\'s agents are on this computer', (
    tester,
  ) async {
    final controller = await open(tester);

    await drop(tester, [
      folder('src').path,
    ], until: () => field(tester).text.isNotEmpty);

    expect(hint, findsNothing);
    await close(tester, controller);
  });

  testWidgets('the hint says the path is here when the chat\'s agents are '
      'elsewhere, and goes with the path', (tester) async {
    final controller = await open(tester, machineId: 'studio');

    await drop(tester, [
      folder('src').path,
    ], until: () => field(tester).text.isNotEmpty);

    expect(hint, findsOneWidget);
    expect(
      find.descendant(
        of: hint,
        matching: find.text(
          "This path is on this computer. Agents on other computers can't "
          'open it.',
        ),
      ),
      findsOneWidget,
    );
    expect(
      find.descendant(of: hint, matching: find.text('Attach as zip')),
      findsOneWidget,
    );

    await tester.enterText(composer, 'never mind');
    await tester.pump();
    expect(hint, findsNothing);
    await close(tester, controller);
  });

  testWidgets('a folder dropped twice is still one path to zip', (
    tester,
  ) async {
    final controller = await open(tester, machineId: 'studio');
    final src = folder('src');
    File('${src.path}/main.dart').writeAsStringSync('void main() {}');
    await drop(tester, [
      src.path,
    ], until: () => field(tester).text.contains(src.path));
    await drop(
      tester,
      [src.path],
      until: () =>
          field(tester).text.indexOf(src.path) !=
          field(tester).text.lastIndexOf(src.path),
    );

    expect(
      find.descendant(
        of: hint,
        matching: find.text(
          "This path is on this computer. Agents on other computers can't "
          'open it.',
        ),
      ),
      findsOneWidget,
    );
    await close(tester, controller);
  });

  testWidgets('Attach as zip takes the path out and attaches the folder', (
    tester,
  ) async {
    final controller = await open(tester, machineId: 'studio');
    final src = folder('src');
    File('${src.path}/main.dart').writeAsStringSync('void main() {}');
    Directory('${src.path}/lib').createSync();
    File('${src.path}/lib/a.dart').writeAsStringSync('// a');
    await tester.enterText(composer, 'Look at');
    await drop(tester, [
      src.path,
    ], until: () => field(tester).text.contains(src.path));
    expect(field(tester).text, 'Look at ${src.path} ');

    await tester.tap(find.text('Attach as zip'));
    await settle(tester, () => names(controller).isNotEmpty);

    expect(names(controller), ['src.zip']);
    expect(field(tester).text, 'Look at ');
    expect(controller.draft('lead'), 'Look at ');
    expect(hint, findsNothing);
    final zip = ZipDecoder().decodeBytes(
      controller.attachments('lead').files.single.bytes!,
    );
    final entries = {
      for (final entry in zip.files)
        if (entry.isFile) entry.name: String.fromCharCodes(entry.content),
    };
    expect(entries, {
      'src/main.dart': 'void main() {}',
      'src/lib/a.dart': '// a',
    });
    await close(tester, controller);
  });

  testWidgets('a zip that lands while an input method composes takes its '
      'path out once composing ends', (tester) async {
    final controller = await open(tester, machineId: 'studio');
    final src = folder('src');
    File('${src.path}/main.dart').writeAsStringSync('void main() {}');
    await tester.enterText(composer, 'Look at');
    await drop(tester, [
      src.path,
    ], until: () => field(tester).text.contains(src.path));

    await tester.tap(find.text('Attach as zip'));
    await tester.pump();
    // Telex is composing `à` when the zip lands (task #3245).
    await tester.tap(composer);
    await tester.pump();
    final typed = 'Look at ${src.path} à';
    final composing = TextEditingValue(
      text: typed,
      selection: TextSelection.collapsed(offset: typed.length),
      composing: TextRange(start: typed.length - 1, end: typed.length),
    );
    tester.testTextInput.updateEditingValue(composing);
    await tester.pump();
    await settle(tester, () => names(controller).isNotEmpty);

    expect(names(controller), ['src.zip']);
    expect(
      field(tester).value,
      composing,
      reason: 'the zip replaces nothing under the marked text',
    );

    tester.testTextInput.updateEditingValue(
      TextEditingValue(
        text: typed,
        selection: TextSelection.collapsed(offset: typed.length),
      ),
    );
    await tester.pumpAndSettle();
    expect(field(tester).text, 'Look at à');
    expect(controller.draft('lead'), 'Look at à');
    await close(tester, controller);
  });

  testWidgets('a folder over the attachment limit is not zipped, and its '
      'path stays', (tester) async {
    final controller = await open(tester, machineId: 'studio');
    final big = folder('big');
    File('${big.path}/blob.bin')
        .writeAsBytesSync(List.filled(kSuperTabFolderZipMaxBytes + 1, 0));
    await drop(tester, [
      big.path,
    ], until: () => field(tester).text.contains(big.path));

    await tester.tap(find.text('Attach as zip'));
    await settle(tester, () => find.byType(SnackBar).evaluate().isNotEmpty);

    expect(names(controller), isEmpty);
    expect(find.text('big is over 10 MB.'), findsOneWidget);
    expect(field(tester).text, '${big.path} ');
    await close(tester, controller);
  });

  testWidgets('a zip that lands while its message is sending is not kept '
      'for the next one', (tester) async {
    final controller = await open(tester, machineId: 'studio');
    final src = folder('src');
    File('${src.path}/main.dart').writeAsStringSync('void main() {}');
    await tester.enterText(composer, 'Look at');
    await drop(tester, [
      src.path,
    ], until: () => field(tester).text.contains(src.path));

    await tester.tap(find.text('Attach as zip'));
    server.holdReads = Completer<void>();
    await tester.tap(find.byTooltip('Send message'));
    await tester.pump();
    // The zip has its answer while the send still waits on the server.
    await settle(tester, () => names(controller).isNotEmpty, sending: true);
    server.holdReads!.complete();
    server.holdReads = null;
    await tester.pumpAndSettle();

    expect(
      (server.posts.single['command'] as Map)['text'],
      'Look at ${src.path}',
    );
    expect(names(controller), isEmpty);
    await close(tester, controller);
  });

  testWidgets('a refused message keeps its folder path, and Retry sends '
      'it', (tester) async {
    final controller = await open(tester, machineId: 'studio');
    await drop(tester, [
      folder('src').path,
    ], until: () => field(tester).text.isNotEmpty);

    server.refuse = {'code': 'CONFLICT', 'message': 'Try again.'};
    await tester.tap(find.byTooltip('Send message'));
    await tester.pumpAndSettle();
    // The refused message waits in the chat with its path.
    server.refuse = null;
    await tester.tap(find.text('Retry'));
    await tester.pumpAndSettle();

    expect(
      (server.messages.single['text'] as String),
      contains(folder('src').path),
    );
    await close(tester, controller);
  });

  testWidgets('two folders of one name are both attached, the second '
      'numbered', (tester) async {
    final controller = await open(tester, machineId: 'studio');
    final first = Directory(p.join(root.path, 'a', 'src'))
      ..createSync(recursive: true);
    final second = Directory(p.join(root.path, 'b', 'src'))
      ..createSync(recursive: true);
    File('${first.path}/one.txt').writeAsStringSync('1');
    File('${second.path}/two.txt').writeAsStringSync('2');
    await drop(tester, [
      first.path,
      second.path,
    ], until: () => field(tester).text.contains(second.path));

    await tester.tap(find.text('Attach as zip'));
    await settle(tester, () => names(controller).length == 2);

    expect(names(controller), ['src.zip', 'src-2.zip']);
    expect(field(tester).text, isEmpty);
    await close(tester, controller);
  });

  testWidgets('a zip the message has no room for keeps its path', (
    tester,
  ) async {
    final controller = await open(tester, machineId: 'studio');
    controller.attachments('lead').add([
      for (var i = 0; i < kSuperTabAttachmentMaxFiles; i++)
        HarnessAttachment('file-$i.txt', Uint8List.fromList([i + 1])),
    ]);
    final src = folder('src');
    File('${src.path}/main.dart').writeAsStringSync('void main() {}');
    await drop(tester, [
      src.path,
    ], until: () => field(tester).text.contains(src.path));

    await tester.tap(find.text('Attach as zip'));
    await settle(tester, () => find.byType(SnackBar).evaluate().isNotEmpty);

    expect(find.text('Attach at most 10 files.'), findsOneWidget);
    expect(names(controller), isNot(contains('src.zip')));
    expect(field(tester).text, '${src.path} ');
    expect(hint, findsOneWidget);
    await close(tester, controller);
  });

  testWidgets('a folder whose zip comes out over the limit keeps its path', (
    tester,
  ) async {
    final controller = await open(tester, machineId: 'studio');
    final src = folder('src');
    // Under the limit as files, over it once zipped: random bytes do not
    // compress, and the archive adds its headers.
    final random = Random(1);
    File('${src.path}/noise.bin').writeAsBytesSync([
      for (var i = 0; i < kSuperTabFolderZipMaxBytes - 16; i++)
        random.nextInt(256),
    ]);
    await drop(tester, [
      src.path,
    ], until: () => field(tester).text.contains(src.path));

    await tester.tap(find.text('Attach as zip'));
    await settle(tester, () => find.byType(SnackBar).evaluate().isNotEmpty);

    expect(find.text('src.zip is over 10 MB.'), findsOneWidget);
    expect(names(controller), isEmpty);
    expect(field(tester).text, '${src.path} ');
    await close(tester, controller);
  });

  testWidgets(
    'a path a shell would read differently goes in quoted, its '
    'quotes, dollars, backticks and backslashes escaped',
    (tester) async {
      final controller = await open(tester);
      final quoted = folder('my "notes"'),
          dollar = folder(r'cost$HOME'),
          tick = folder('run`date`'),
          slash = folder(r'back\slash'),
          apostrophe = folder("it's");
      final r = root.path;

      await drop(tester, [
        quoted.path,
        dollar.path,
        tick.path,
        slash.path,
        apostrophe.path,
      ], until: () => field(tester).text.contains('it'));

      expect(
        field(tester).text,
        '"$r/my \\"notes\\"" "$r/cost\\\$HOME" "$r/run\\`date\\`" '
        '"$r/back\\\\slash" "$r/it\'s" ',
      );
      await close(tester, controller);
    },
    // macOS and Linux names: a Windows name cannot hold `"`, and `\` is its
    // separator. The Windows rule is the unit test above. (testWidgets takes
    // no skip reason, only a bool.)
    skip: Platform.isWindows,
  );

  testWidgets('Attach as zip takes out a path it quoted', (tester) async {
    final controller = await open(tester, machineId: 'studio');
    // Escaped on macOS and Linux, quoted alone on Windows.
    final quoted = folder(r'cost$HOME');
    File(p.join(quoted.path, 'a.txt')).writeAsStringSync('a');
    await tester.enterText(composer, 'See');
    await drop(tester, [
      quoted.path,
    ], until: () => field(tester).text.contains('cost'));

    await tester.tap(find.text('Attach as zip'));
    await settle(tester, () => names(controller).isNotEmpty);

    expect(names(controller), [r'cost$HOME.zip']);
    expect(field(tester).text, 'See ');
    await close(tester, controller);
  });
}