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.

35.1 KB
Raw Blame
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:url_launcher/url_launcher.dart';

import 'package:harness_mobile/phone/phone_navigation.dart';
import 'package:harness_mobile/phone/tty.dart';
import 'package:harness_mobile/phone/tty_controls.dart';
import 'package:harness_mobile/shared/theme/app_ink.dart';
import 'package:harness_mobile/shared/theme/app_space.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/shared/theme/app_type.dart';

export 'swarm_file_links.dart' show swarmAttachmentHost, swarmAttachmentLink;
export 'swarm_message_style.dart'
    show swarmChatCard, swarmChatHair, swarmChatText;

import 'model.dart';
import 'swarm_attachment.dart';
import 'swarm_attachment_store.dart';
import 'swarm_code_block.dart';
import 'swarm_file_kind.dart';
import 'swarm_file_links.dart';
import 'swarm_file_viewer.dart';
import 'swarm_message_text.dart';
import 'swarm_voice_bubble.dart';
import 'swarm_message_style.dart';
import 'swarm_face.dart';
import 'swarm_ship_row.dart';
import 'swarm_special_rows.dart';

/// `@name` or `@name@domain`, as people tag in chat. Never right after a
/// letter, digit, `@` or `/` (an address, a path, a link), and a name never
/// ends in a dot: `@dee.` closes a sentence. The backend and the desktop read
/// tags by this same rule; test/fixtures/tag_fixture.json is the table all
/// three pass.
final _tag = RegExp(
  r'(?<![\w@/])@([\w+-]+(?:\.[\w+-]+)*)(@[\w-]+(?:\.[\w-]+)+)?',
);
final _oneWord = RegExp(r'^[\w+-]+(?:\.[\w+-]+)*$');
final _fence = RegExp(r'^ {0,3}(`{3,}|~{3,})');
final _codeSpan = RegExp(r'(?<!`)(`+)(?!`)[\s\S]*?(?<!`)\1(?!`)');
final _linkTarget = RegExp(r'\]\([^)\]]*\)');
final _bareLink = RegExp(r'\b(?:https?://|www\.)\S+', caseSensitive: false);
String _blank(String text) => text.replaceAll(RegExp(r'[^\n]'), ' ');

/// [text] with what is never a tag blanked out, each character kept in its
/// place: fenced and indented code, code spans, bare links and link
/// destinations.
String _prose(String text) {
  final lines = text.split('\n');
  String? fence;
  var indented = false;
  for (var i = 0; i < lines.length; i++) {
    final line = lines[i];
    if (fence != null) {
      final close = _fence.firstMatch(line);
      if (close != null &&
          close[1]![0] == fence[0] &&
          close[1]!.length >= fence.length &&
          line.substring(close[0]!.length).trim().isEmpty) {
        fence = null;
      }
      lines[i] = _blank(line);
      continue;
    }
    final open = _fence.firstMatch(line);
    if (open != null &&
        !(open[1]![0] == '`' &&
            line.substring(open[0]!.length).contains('`'))) {
      fence = open[1];
      lines[i] = _blank(line);
      indented = false;
      continue;
    }
    // Indented code starts after a blank line (or the first line) and runs
    // while its lines stay indented.
    final startsCode =
        RegExp(r'^( {4}|\t)').hasMatch(line) &&
        line.trim().isNotEmpty &&
        (indented || i == 0 || lines[i - 1].trim().isEmpty);
    indented = startsCode || (indented && line.trim().isEmpty);
    if (startsCode) lines[i] = _blank(line);
  }
  String blanked(Match m) => _blank(m[0]!);
  return lines
      .join('\n')
      .replaceAllMapped(_codeSpan, blanked)
      .replaceAllMapped(_linkTarget, blanked)
      .replaceAllMapped(_bareLink, blanked);
}

/// The names an @mention in a message is marked for, as the desktop marks
/// them: the chat's agents here, and per message the people it tags. A name
/// of one word is marked where the shared tag rule finds it; an agent's name
/// of several words by the pattern made once for every message drawn with it.
class SwarmMentions {
  SwarmMentions(List<String> names)
    : names = List.unmodifiable(names),
      _words = {
        for (final name in names)
          if (_oneWord.hasMatch(name)) name.toLowerCase(),
      },
      _pattern = names.every(_oneWord.hasMatch)
          ? null
          : RegExp(
              // Longest first, so "@Nova 2" is not read as "@Nova".
              '(?<![\\w@/])@(?:${([for (final name in names)
                if (!_oneWord.hasMatch(name)) name]..sort((a, b) => b.length.compareTo(a.length))).map(RegExp.escape).join('|')})(?![\\w])',
              caseSensitive: false,
            );

  final List<String> names;
  final Set<String> _words;
  final RegExp? _pattern;

  /// [text] with each @mention of one of [names] or [tagged] marked. A tag by
  /// full address is a tagged person's only when it is their address in
  /// [addresses] (by username), as the backend matches it to their email.
  TextSpan span(
    String text,
    TextStyle style, {
    Iterable<String> tagged = const [],
    Map<String, String> addresses = const {},
  }) {
    if (!text.contains('@') || (names.isEmpty && tagged.isEmpty)) {
      return TextSpan(text: text, style: style);
    }
    final words = {..._words, for (final name in tagged) name.toLowerCase()};
    final known = {
      for (final MapEntry(:key, :value) in addresses.entries)
        key.toLowerCase(): value.toLowerCase(),
    };
    bool marks(Match match) {
      final name = match[1]!.toLowerCase();
      if (match[2] == null) return words.contains(name);
      if (known.containsValue('$name${match[2]!.toLowerCase()}')) return true;
      return words.contains(name) && !known.containsKey(name);
    }

    final prose = _prose(text);
    final ranges = [
      for (final match in _tag.allMatches(prose))
        if (marks(match)) (match.start, match.end),
      if (_pattern case final pattern?)
        for (final match in pattern.allMatches(prose)) (match.start, match.end),
    ]..sort((a, b) => a.$1.compareTo(b.$1));
    if (ranges.isEmpty) return TextSpan(text: text, style: style);
    return TextSpan(style: style, children: _marked(text, ranges));
  }
}

List<InlineSpan> _marked(String text, List<(int, int)> marks) {
  final spans = <InlineSpan>[];
  var at = 0;
  for (final (start, end) in marks) {
    if (start < at) continue;
    if (start > at) spans.add(TextSpan(text: text.substring(at, start)));
    spans.add(
      TextSpan(
        text: text.substring(start, end),
        // The desktop's tag pill (message_text.dart).
        style: TextStyle(
          color: AppPalette.accentOnSurface,
          backgroundColor: AppSurface.accentWash,
          fontWeight: FontWeight.w600,
        ),
      ),
    );
    at = end;
  }
  if (at < text.length) spans.add(TextSpan(text: text.substring(at)));
  return spans;
}

/// A message's frame: avatar, then who wrote it, their role and [trailing]
/// (its time) — none of it for a follow-up — then [body]. With [onAvatar],
/// the avatar and the room beside it are one thumb-sized target.
class SwarmMessageFrame extends StatelessWidget {
  const SwarmMessageFrame({
    super.key,
    required this.avatar,
    required this.grouped,
    required this.header,
    required this.body,
    this.onAvatar,
    this.avatarKey,
    this.avatarLabel,
  });

  final Widget avatar;
  final bool grouped;
  final Widget header;
  final List<Widget> body;
  final VoidCallback? onAvatar;
  final Key? avatarKey;

  /// What the avatar's target is read as.
  final String? avatarLabel;

  /// The avatar's column: the avatar and the room after it, a thumb wide.
  static const double column = 44;

  /// Around a message in the chat's column, a post's and a skeleton's too;
  /// one [grouped] under the message before it leaves no room above.
  static EdgeInsets padding({bool grouped = false}) => EdgeInsets.fromLTRB(
    AppSpace.s,
    grouped ? 0 : AppSpace.s,
    AppSpace.s,
    AppSpace.s,
  );

  /// Between a message's header and its words.
  static const double bodyGap = AppSpace.xs;

  @override
  Widget build(BuildContext context) => Row(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      SizedBox(
        width: column,
        child: grouped
            ? null
            : onAvatar == null
            ? Align(alignment: Alignment.topLeft, child: avatar)
            : Semantics(
                button: true,
                label: avatarLabel,
                child: GestureDetector(
                  key: avatarKey,
                  behavior: HitTestBehavior.opaque,
                  onTap: onAvatar,
                  child: SizedBox(
                    height: column,
                    child: Align(alignment: Alignment.topLeft, child: avatar),
                  ),
                ),
              ),
      ),
      Expanded(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [if (!grouped) header, ...body],
        ),
      ),
    ],
  );
}

/// What a deleted message reads, in place of its text (backend
/// messageEdits.ts `DELETED_TEXT`).
const swarmDeletedText = 'This message was deleted.';

/// One message: avatar, who wrote it, their role and when — none of it for a
/// follow-up — then what it answers, its text ("(edited)" under it once its
/// author changed it), its files, its [reactions] and its [thread]'s line. A
/// deleted one keeps only "This message was deleted." and its thread's line.
/// A tap opens its actions, a long-press [onLongPress]; lit for a moment when
/// a quote leads to it, and while it is find's current match; a quieter fill
/// while it is one of find's other matches.
class SwarmMessageRow extends StatelessWidget {
  const SwarmMessageRow({
    super.key,
    required this.message,
    required this.name,
    required this.look,
    required this.role,
    this.askTag,
    this.pm = false,
    required this.mentions,
    this.tagged = const [],
    this.taggedAddresses = const {},
    this.taggedLabels = const {},
    this.readerId = '',
    required this.grouped,
    required this.lit,
    this.followed = false,
    this.match = false,
    required this.quote,
    required this.actions,
    required this.onTap,
    required this.onReply,
    this.inThread = false,
    this.onAuthor,
    this.reactions,
    this.thread,
    this.below,
    this.receipt,
    this.card,
    this.links,
    this.onLongPress,
    this.references = const {},
    this.onOpenConversation,
  });

  final SuperTabMessage message;
  final String name;

  /// What its author wears.
  final SwarmLook look;
  final String? role;

  /// Where the ask it is stands, after the time; null for any other message.
  final String? askTag;

  /// Its author is its project's coordinator ([SuperTabSnapshot.isLead]),
  /// whatever its role is called: it wears manager blue.
  final bool pm;

  final SwarmMentions mentions;

  /// The usernames of the people [message] tags: each reads as a pill where
  /// the text says it.
  final List<String> tagged;

  /// Their addresses, by username: a tag by full address is theirs only when
  /// it is this one.
  final Map<String, String> taggedAddresses;

  /// What a tagged person's pill reads, by username: the name they set. The
  /// text keeps `@username`; one with no name here reads as it is written.
  final Map<String, String> taggedLabels;

  /// Who reads it: a message that tags them stands out.
  final String readerId;
  final bool grouped, lit, actions;

  /// The row a quote led to: lit, then fading. Only it animates — a fade on
  /// every row would give each its own ticker.
  final bool followed;

  /// One of find's matches (swarm_chat_find.dart): a quiet fill, under
  /// [lit]'s.
  final bool match;
  final Widget? quote;
  final VoidCallback onTap;

  /// The numbered conversations `#N` links in a message can open.
  final Map<int, String> references;

  /// Opens a conversation resolved from [references].
  final ValueChanged<String>? onOpenConversation;

  /// Null where the person cannot post, or in the thread itself.
  final VoidCallback? onReply;

  /// [onReply] opens the message's thread: "Reply in thread", where a
  /// message from before threads keeps "Reply" and its inline quote.
  final bool inThread;

  /// Who wrote it, in a sheet; null where nothing opens.
  final VoidCallback? onAuthor;

  /// Under its text and files: the live card this message is
  /// (swarm_live_card.dart); null for a plain message.
  final Widget? card;

  /// Under its text, files and card: the messages its links point at
  /// (swarm_link_previews.dart); null when it links to none.
  final Widget? links;

  /// Drawn under its text and files: its reaction counts.
  final Widget? reactions;

  /// Under its reactions: the line of the thread it is the root of.
  final Widget? thread;

  /// Under its reactions: what the person may do with it besides Reply — the
  /// PM's private line answered in the project chat.
  final Widget? below;

  /// Under all that: where the delivery of the person's newest message stands
  /// (swarm_message_receipt.dart); null for every other message.
  final Widget? receipt;

  /// Opens its long-press sheet: reactions, Copy link to message, and Edit
  /// and Delete on the reader's own. None for a deleted message.
  final VoidCallback? onLongPress;

  /// One of the message's files, with what asks for a fresh link to it
  /// (swarm_file_links.dart): the chat's Swarm, this message and the file.
  Widget _attachment(BuildContext context, SuperTabAttachment file) {
    final ref = SwarmFileRef(
      file,
      conversationId: message.conversationId,
      messageId: message.id,
      reader: SwarmFiles.of(context),
    );
    // A voice message's clip is its bubble, which plays only.
    if (file.voice case final voice?) {
      return SwarmVoiceBubble(file: file, voice: voice, fileRef: ref);
    }
    final link = ref.current;
    return SwarmAttachment(
      file: file,
      link: link,
      thumb: ref.currentThumb,
      fileRef: ref,
      chip: SwarmFileChip(file: file, link: link, fileRef: ref),
    );
  }

  @override
  Widget build(BuildContext context) {
    // A ship line is a card, not a message from its author.
    if (swarmShips(message)) {
      return SwarmShipRow(
        key: ValueKey('swarm-message-${message.id}'),
        message: message,
      );
    }
    // Notes that are not chat from their author, as Desktop draws them.
    final special = ValueKey('swarm-message-${message.id}');
    if (message.terminalEvent) {
      return SwarmTerminalRow(key: special, message: message);
    }
    if (message.route case final route?) {
      return SwarmRouteRow(key: special, message: message, route: route);
    }
    // A row kept as it was is not built again: it follows a theme or font
    // change itself.
    AppTheme.watch(context);
    final tty = Tty.of(context);
    final at = message.createdAt?.toLocal();
    String two(int n) => n.toString().padLeft(2, '0');
    final key = ValueKey('swarm-message-${message.id}');
    final padding = SwarmMessageFrame.padding(grouped: grouped);
    // A deleted message keeps only its words and its thread's line.
    final deletedBody = !message.deleted
        ? null
        : <Widget>[
            if (lit) SizedBox(key: ValueKey('swarm-lit-${message.id}')),
            ?quote,
            Padding(
              padding: const EdgeInsets.only(top: SwarmMessageFrame.bodyGap),
              child: Text(
                swarmDeletedText,
                key: ValueKey('swarm-deleted-${message.id}'),
                style: swarmChatText(
                  16,
                  color: AppPalette.textFaint,
                  height: 1.42,
                ).copyWith(fontStyle: FontStyle.italic),
              ),
            ),
            ?thread,
          ];
    final frame = SwarmMessageFrame(
      grouped: grouped,
      onAvatar: onAuthor,
      avatarKey: ValueKey('swarm-author-${message.id}'),
      avatarLabel: name,
      avatar: SwarmChatAvatar(
        name: name,
        id: message.authorId,
        agent: message.fromAgent,
        pm: pm,
        picture: look.picture,
        status: look.status,
      ),
      header: SwarmMessageHeader(
        name: name,
        agent: message.fromAgent,
        role: role,
        trailing: at == null
            ? null
            : Text(
                '${two(at.hour)}:${two(at.minute)}',
                style: tty.style(color: AppPalette.textFaint, size: 12.5),
              ),
        tag: askTag == null
            ? null
            : Text(
                askTag!,
                style: tty.style(color: AppPalette.textFaint, size: 12.5),
              ),
      ),
      body:
          deletedBody ??
          [
            if (lit) SizedBox(key: ValueKey('swarm-lit-${message.id}')),
            if (match && !lit)
              SizedBox(key: ValueKey('swarm-match-${message.id}')),
            ?quote,
            ?swarmTerminalNote(message),
            // A voice message's text is its words, never shown: it plays only
            // (anh Dee, 2026-11-04).
            if (!message.attachments.any((file) => file.voice != null))
              for (final part in swarmTextParts(message.text))
                if (part.code)
                  SwarmCodeBlock(code: part.text, name: part.name, onTap: onTap)
                else
                  Padding(
                    padding: const EdgeInsets.only(
                      top: SwarmMessageFrame.bodyGap,
                    ),
                    child: SwarmMessageText(
                      text: part.text,
                      mentionNames: mentions.names,
                      references: references,
                      tagged: tagged,
                      addresses: taggedAddresses,
                      labels: taggedLabels,
                      onTap: onTap,
                      onOpenConversation: onOpenConversation,
                    ),
                  ),
            if (message.editedAt != null)
              Padding(
                padding: const EdgeInsets.only(top: AppSpace.xs),
                child: Text(
                  '(edited)',
                  key: ValueKey('swarm-edited-${message.id}'),
                  style: AppType.caption(color: AppPalette.textFaint),
                ),
              ),
            ?swarmCutShort(message),
            for (final file in message.attachments) _attachment(context, file),
            ?card,
            ?links,
            ?reactions,
            ?thread,
            ?below,
            ?receipt,
            if (actions)
              Padding(
                padding: const EdgeInsets.only(top: AppSpace.s),
                child: Wrap(
                  spacing: 6,
                  runSpacing: 6,
                  children: [
                    if (onReply case final reply?)
                      SwarmSmallButton(
                        key: ValueKey('swarm-reply-${message.id}'),
                        icon: inThread
                            ? LucideIcons.messageSquareReply
                            : LucideIcons.reply,
                        label: inThread ? 'Reply in thread' : 'Reply',
                        onTap: reply,
                      ),
                    // A voice message's text is its words, never handed
                    // over: it plays only (anh Dee, 2026-11-04).
                    if (!message.attachments.any((file) => file.voice != null))
                      SwarmCopyButton(text: message.text),
                  ],
                ),
              ),
          ],
    );
    // A deleted message has nothing left to react to, copy or change.
    final held = onLongPress == null || message.deleted
        ? frame
        : GestureDetector(
            behavior: HitTestBehavior.translucent,
            onLongPress: onLongPress,
            child: frame,
          );
    // A message that tags the reader stands out, as Slack marks one that
    // names you: an accent bar on its edge over a wash of the accent. The
    // bar is drawn over the row, so nothing in it moves.
    final taggedYou =
        readerId.isNotEmpty && message.mentions.contains(readerId);
    final bar = taggedYou
        ? BoxDecoration(
            border: Border(
              left: BorderSide(color: AppPalette.accentOnSurface, width: 3),
            ),
          )
        : null;
    if (!followed) {
      // Find's matches; its current one keeps its light once a post moved
      // the list's target away.
      if (match) {
        return Container(
          key: key,
          padding: padding,
          decoration: BoxDecoration(
            color: lit
                ? AppPalette.accentOnSurface.withValues(alpha: 0.16)
                : _matchFill,
            borderRadius: BorderRadius.circular(AppControl.rowRadius),
          ),
          foregroundDecoration: bar,
          child: held,
        );
      }
      if (!taggedYou) return Padding(key: key, padding: padding, child: held);
      return KeyedSubtree(
        key: key,
        child: Container(
          key: ValueKey('swarm-tagged-you-${message.id}'),
          padding: padding,
          decoration: BoxDecoration(color: AppSurface.accentWash),
          foregroundDecoration: bar,
          child: held,
        ),
      );
    }
    return AnimatedContainer(
      key: key,
      duration: const Duration(milliseconds: 600),
      curve: Curves.easeOut,
      padding: padding,
      decoration: BoxDecoration(
        color: lit
            ? AppPalette.accentOnSurface.withValues(alpha: 0.16)
            : match
            ? _matchFill
            : taggedYou
            ? AppSurface.accentWash
            : Colors.transparent,
        borderRadius: BorderRadius.circular(AppControl.rowRadius),
      ),
      foregroundDecoration: bar,
      child: held,
    );
  }
}

/// A find match's fill: half a lit row's.
Color get _matchFill => AppPalette.accentOnSurface.withValues(alpha: 0.08);

/// A message's first line: who, in what role, then [trailing] — its time,
/// or how its post is going — and [tag], where the ask it is stands.
class SwarmMessageHeader extends StatelessWidget {
  const SwarmMessageHeader({
    super.key,
    required this.name,
    required this.agent,
    this.role,
    this.trailing,
    this.tag,
  });

  final String name;
  final bool agent;
  final String? role;
  final Widget? trailing, tag;

  @override
  Widget build(BuildContext context) {
    final tty = Tty.of(context);
    return Wrap(
      spacing: 6,
      crossAxisAlignment: WrapCrossAlignment.center,
      children: [
        Text(
          name,
          style: swarmChatText(
            13.5,
            color: agent ? tty.cyan : tty.green,
            weight: FontWeight.w600,
          ),
        ),
        if (role case final role?) SwarmRoleBadge(role),
        ?trailing,
        ?tag,
      ],
    );
  }
}

/// A role's compact badge: PM, Dev, Rev.
class SwarmRoleBadge extends StatelessWidget {
  const SwarmRoleBadge(this.label, {super.key});

  final String label;

  @override
  Widget build(BuildContext context) {
    final tty = Tty.of(context);
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: AppSpace.xs),
      decoration: BoxDecoration(
        border: Border.all(color: swarmChatHair(tty)),
        borderRadius: BorderRadius.circular(AppCard.insetRadius),
      ),
      child: Text(
        label,
        style: tty
            .style(
              color: AppPalette.textSecondary,
              weight: FontWeight.w600,
              size: 11,
            )
            .copyWith(height: 16 / 11, letterSpacing: 0.44),
      ),
    );
  }
}

/// Who wrote a message, in a circle: an agent's initial on its own deep
/// colour — blue for a Product Manager, as the prototype has River — the
/// person's on theirs, white on each — or the picture they chose, and a
/// person's status emoji while it lasts.
class SwarmChatAvatar extends StatelessWidget {
  const SwarmChatAvatar({
    super.key,
    required this.name,
    required this.id,
    required this.agent,
    this.pm = false,
    this.picture,
    this.status,
    this.diameter = size,
  });

  static const double size = 32;

  /// How wide it is drawn: [size] beside a message, smaller in a thread's
  /// line.
  final double diameter;

  /// The member palette's hues in the order the chat has always given them,
  /// so no one's colour moves: the [pm]'s blue first, then the six an agent
  /// takes by its id (blue, teal, violet, amber, rose, green, slate).
  static final _agents = [
    for (final hue in const [0, 1, 5, 3, 4, 2, 7])
      AppPalette.avatarPalette[hue],
  ];

  final String name, id;
  final bool agent;

  /// A project's coordinator, whatever its role is called: the prototype's
  /// blue, kept for them alone.
  final bool pm;

  /// What they chose to wear; null wears the initial.
  final SuperTabAvatarPicture? picture;

  /// A person's status; null for an agent.
  final SuperTabPersonStatus? status;

  @override
  Widget build(BuildContext context) {
    final fill = !agent
        ? AppPalette.avatarFillDark
        : pm
        ? _agents.first
        : _agents[1 +
              id.codeUnits.fold(0, (a, b) => a + b) % (_agents.length - 1)];
    final initial = name.trim().isEmpty
        ? '?'
        : name.trim().characters.first.toUpperCase();
    return SwarmStatusFace(
      name: name,
      size: diameter,
      status: status,
      face: SwarmFace(
        picture: picture,
        size: diameter,
        tint: fill,
        fallback: Container(
          width: diameter,
          height: diameter,
          alignment: Alignment.center,
          decoration: BoxDecoration(color: fill, shape: BoxShape.circle),
          child: Text(
            initial,
            style: swarmChatText(
              13.5 * diameter / size,
              color: AppInk.onFill,
              weight: FontWeight.w600,
            ),
          ),
        ),
      ),
    );
  }
}

/// What a reply answers: its author and the start of its text, or that it
/// is not loaded. A tap leads to it. A message link's preview wears it too,
/// naming the [chat] its message is in.
class SwarmQuote extends StatelessWidget {
  const SwarmQuote({
    super.key,
    this.author,
    this.chat,
    this.text,
    this.onTap,
    this.label = 'Go to the quoted message',
  });

  /// Null while the original is not loaded.
  final String? author, text;

  /// After [author]: the chat the message is in, when it is another one.
  final String? chat;
  final VoidCallback? onTap;

  /// What a tap does, read aloud.
  final String label;

  @override
  Widget build(BuildContext context) {
    final tty = Tty.of(context);
    final quote = Container(
      width: double.infinity,
      margin: const EdgeInsets.symmetric(vertical: AppSpace.xs),
      padding: const EdgeInsets.symmetric(
        horizontal: AppSpace.m,
        vertical: AppSpace.s,
      ),
      decoration: BoxDecoration(
        color: tty.text.withValues(alpha: 0.05),
        border: Border(left: BorderSide(color: AppPalette.textFaint, width: 3)),
        borderRadius: const BorderRadius.horizontal(
          left: Radius.circular(4),
          right: Radius.circular(10),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (author case final author?)
            Text.rich(
              TextSpan(
                text: author,
                children: [
                  if (chat case final chat?)
                    TextSpan(
                      text: ' · $chat',
                      style: swarmChatText(
                        13.5,
                        color: AppPalette.textSecondary,
                      ),
                    ),
                ],
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: swarmChatText(13.5, weight: FontWeight.w600),
            ),
          Text(
            text ?? "The original message isn't loaded.",
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            style: swarmChatText(14, color: AppPalette.textSecondary),
          ),
        ],
      ),
    );
    if (onTap == null) return quote;
    return Semantics(
      button: true,
      label: label,
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: onTap,
        child: quote,
      ),
    );
  }
}

/// A message's action — Reply, Copy, Send again: small, rounded, raised.
class SwarmSmallButton extends StatelessWidget {
  const SwarmSmallButton({
    super.key,
    required this.icon,
    required this.label,
    required this.onTap,
  });

  final IconData icon;
  final String label;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    final tty = Tty.of(context);
    return Semantics(
      button: true,
      label: label,
      excludeSemantics: true,
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: onTap,
        child: Container(
          constraints: const BoxConstraints(minHeight: 36),
          padding: const EdgeInsets.symmetric(horizontal: AppSpace.m),
          decoration: BoxDecoration(
            color: ttyRaised(tty),
            border: Border.all(color: swarmChatHair(tty)),
            borderRadius: BorderRadius.circular(AppControl.radius),
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(icon, size: 16, color: AppPalette.textPrimary),
              const SizedBox(width: 8),
              Text(label, style: swarmChatText(14, weight: FontWeight.w500)),
            ],
          ),
        ),
      ),
    );
  }
}

/// How long Copy reads Copied after a copy.
const kSwarmCopiedFor = Duration(seconds: 3);

/// A message's Copy (Tony, 11-02): once the clipboard has [text] it reads
/// Copied with a check for [kSwarmCopiedFor]. Taps meanwhile neither copy again
/// nor restart that time. A copy that failed stays Copy, to try again.
class SwarmCopyButton extends StatefulWidget {
  const SwarmCopyButton({super.key, required this.text});

  final String text;

  @override
  State<SwarmCopyButton> createState() => _SwarmCopyButtonState();
}

class _SwarmCopyButtonState extends State<SwarmCopyButton> {
  bool _copying = false;
  Timer? _reset;

  bool get _copied => _reset != null;

  Future<void> _copy() async {
    if (_copying || _copied) return;
    _copying = true;
    try {
      await Clipboard.setData(ClipboardData(text: widget.text));
    } on PlatformException {
      return;
    } finally {
      _copying = false;
    }
    if (!mounted) return;
    setState(() {
      _reset = Timer(kSwarmCopiedFor, () {
        if (mounted) setState(() => _reset = null);
      });
    });
  }

  @override
  void dispose() {
    _reset?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => SwarmSmallButton(
    icon: _copied ? LucideIcons.check : LucideIcons.copy,
    label: _copied ? 'Copied' : 'Copy',
    onTap: () => unawaited(_copy()),
  );
}

/// A file's size as a chat shows it: whole kilobytes, rounded up, or megabytes to one place.
String swarmFileSize(int bytes) {
  final kb = (bytes / 1024).ceil();
  return kb < 1024 ? '$kb KB' : '${(kb / 1024).toStringAsFixed(1)} MB';
}

/// Opens a chat file's link; tests replace it.
@visibleForTesting
Future<bool> Function(Uri url) swarmOpenFile = (url) =>
    launchUrl(url, mode: LaunchMode.inAppBrowserView);

/// A message's file, marked by its kind ([swarmFileIcon]), opened when its
/// link is the backend's: a text or Markdown file in the app
/// ([SwarmFileViewer]), any other in the browser. With [fileRef], a link
/// about to end is asked for again first (swarm_file_links.dart); a reader
/// who lost access is told so, and a failed ask can be tapped again.
class SwarmFileChip extends StatefulWidget {
  const SwarmFileChip({
    super.key,
    required this.file,
    required this.link,
    this.fileRef,
    this.store,
  });

  final SuperTabAttachment file;
  final Uri? link;
  final SwarmFileRef? fileRef;

  /// Where a text file read in the app is kept; the app's own
  /// ([swarmAttachments]) by default.
  final SwarmAttachmentStore? store;

  @override
  State<SwarmFileChip> createState() => _SwarmFileChipState();
}

class _SwarmFileChipState extends State<SwarmFileChip> {
  /// A fresh link is being asked for: another tap waits for it.
  bool _opening = false;

  bool get _opens =>
      widget.fileRef != null ? !widget.fileRef!.refused : widget.link != null;

  Future<void> _open() async {
    final ref = widget.fileRef;
    if (ref == null) {
      if (widget.link case final url?) _show(url);
      return;
    }
    if (_opening) return;
    setState(() => _opening = true);
    final messenger = ScaffoldMessenger.maybeOf(context);
    final Uri? found;
    try {
      found = await swarmOpenableLink(
        context,
        ref,
        onProblem: (text) =>
            messenger?.showSnackBar(SnackBar(content: Text(text))),
      );
    } finally {
      if (mounted) setState(() => _opening = false);
    }
    final url = found;
    if (url != null && mounted) _show(url);
  }

  /// Opens the file at [url]: a text file in the app, any other in the
  /// browser, as the desktop does.
  void _show(Uri url) {
    final file = widget.file;
    if (!swarmOpensAsText(file)) {
      unawaited(swarmOpenFile(url));
      return;
    }
    final store = widget.store ?? swarmAttachments;
    final turn = store.turns.value, ref = widget.fileRef;
    unawaited(
      Navigator.of(context).push(
        phoneRoute(
          (_) => SwarmFileViewer(
            file: file,
            url: url,
            fileRef: ref,
            store: store,
            turn: turn,
            openInBrowser: (url) => swarmOpenFile(url),
          ),
          listensForItself: true,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final file = widget.file;
    final tty = Tty.of(context);
    final size = swarmFileSize(file.size);
    final opens = _opens;
    final color = !opens ? AppPalette.textFaint : tty.blue;
    return Padding(
      padding: const EdgeInsets.only(top: AppSpace.s),
      child: Semantics(
        button: opens,
        label: 'File: ${file.name}, $size',
        excludeSemantics: true,
        child: GestureDetector(
          key: ValueKey('swarm-file-chip-${file.id}'),
          behavior: HitTestBehavior.opaque,
          onTap: !opens || _opening ? null : () => unawaited(_open()),
          child: Container(
            constraints: const BoxConstraints(minHeight: 40),
            padding: const EdgeInsets.symmetric(horizontal: AppSpace.m),
            decoration: BoxDecoration(
              color: swarmChatCard(tty),
              border: Border.all(color: swarmChatHair(tty)),
              borderRadius: BorderRadius.circular(AppControl.radius),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(swarmFileIcon(file.name), size: 16, color: color),
                const SizedBox(width: 8),
                Flexible(
                  child: Text(
                    file.name,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: swarmChatText(14, color: color),
                  ),
                ),
                const SizedBox(width: AppSpace.xs),
                Text(
                  '·',
                  style: swarmChatText(13, color: AppPalette.textFaint),
                ),
                const SizedBox(width: AppSpace.xs),
                Text(
                  size,
                  style: swarmChatText(13, color: AppPalette.textFaint),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}