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.

Refactor voice input handling and improve touch target areas

Dev jacob0db4cc80ea69
diff --git a/mobile/lib/core/build_identity.dart b/mobile/lib/core/build_identity.dart
deleted file mode 100644
index f73f90e23..000000000
--- a/mobile/lib/core/build_identity.dart
+++ /dev/null
@@ -1 +0,0 @@
-const desktopAppName = 'Harness';
diff --git a/mobile/lib/phone/agent_index.dart b/mobile/lib/phone/agent_index.dart
index 6fb8a5129..d5b9691ac 100644
--- a/mobile/lib/phone/agent_index.dart
+++ b/mobile/lib/phone/agent_index.dart
@@ -33,16 +33,16 @@ class AgentEntry {
/// Every agent the account can reach, ordered the way the tab draws them.
///
-/// Only machines that are LINKED and answering contribute: an offline machine's agent list is
-/// whatever was last seen there, and drawing it beside live ones would offer rows that cannot be
-/// opened. Those machines are reachable on the Machines tab instead, which is where the thing to
-/// do about them lives.
+/// Only machines that are LINKED and answering contribute — or only re-dialling after answering, see
+/// [phoneMachineListsAgents]: an offline machine's agent list is whatever was last seen there, and
+/// drawing it beside live ones would offer rows that cannot be opened. Those machines are reachable
+/// on the Machines tab instead, which is where the thing to do about them lives.
List<AgentEntry> agentIndex(AppNotifier notifier) {
final entries = <AgentEntry>[];
for (final machine in notifier.machines) {
final state = notifier.stateOf(machine.machineId);
if (state == null) continue;
- if (phoneMachineStatusOf(state) != PhoneMachineStatus.ready) continue;
+ if (!phoneMachineListsAgents(state)) continue;
for (final agent in state.agents) {
entries.add(AgentEntry(machine: state, agent: agent));
}
diff --git a/mobile/lib/phone/agent_row.dart b/mobile/lib/phone/agent_row.dart
deleted file mode 100644
index 7500524f4..000000000
--- a/mobile/lib/phone/agent_row.dart
+++ /dev/null
@@ -1,92 +0,0 @@
-import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
-
-import 'package:harness_mobile/shared/theme/app_theme.dart';
-import 'package:harness_mobile/widgets/engine_identity.dart';
-
-import 'agent_context_line.dart';
-import 'agent_index.dart';
-import 'phone_card.dart';
-import 'status_pill.dart';
-
-/// One agent in the Agents tab: who it is, what it is doing, and where it is.
-///
-/// The same three lines [AgentTile] draws on a machine's own page — the two rows differ now only in
-/// where they get their agent from, and both end in [AgentContextLine] so one agent reached two
-/// ways is not described two ways.
-class AgentRow extends StatelessWidget {
- const AgentRow({
- super.key,
- required this.entry,
- required this.onTap,
- this.onLongPress,
- });
-
- final AgentEntry entry;
- final VoidCallback onTap;
-
- /// The row's `⋯`, held rather than tapped — the same door [AgentTile] opens on a machine's own
- /// page. Optional for the same reason it is there: a row that cannot be OPENED can still be
- /// acted on, and an agent whose terminal has gone is exactly the one somebody wants to delete.
- final VoidCallback? onLongPress;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final agent = entry.agent;
- return PhoneCard(
- height: kPhoneAgentCardHeight,
- onTap: agent.terminalAvailable ? onTap : null,
- onLongPress: onLongPress,
- // A rim in the attention colour, so a waiting agent is findable in a long list without
- // reading a word of it — the list's whole job on a phone.
- border: entry.isWaiting
- ? Border.all(color: AppPalette.warn.withValues(alpha: 0.42))
- : null,
- child: Row(
- children: [
- PhoneCardGlyph(
- child: EngineMark(
- engine: agent.engine,
- displayName: agent.engineDisplayName,
- size: 22,
- ),
- ),
- const SizedBox(width: 14),
- Expanded(
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- agent.name,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: AppPalette.textPrimary,
- fontSize: 16,
- fontWeight: FontWeight.w600,
- ),
- ),
- const SizedBox(height: 3),
- StatusPill(summary: entry.summary),
- const SizedBox(height: 3),
- AgentContextLine(
- project: entry.project,
- machineName: entry.machineName,
- ),
- ],
- ),
- ),
- const SizedBox(width: 8),
- if (agent.terminalAvailable)
- Icon(
- LucideIcons.chevronRight300,
- size: 22,
- color: AppPalette.textFaint,
- ),
- ],
- ),
- );
- }
-}
diff --git a/mobile/lib/phone/agents_page.dart b/mobile/lib/phone/agents_page.dart
index d37f217b7..b8c87d788 100644
--- a/mobile/lib/phone/agents_page.dart
+++ b/mobile/lib/phone/agents_page.dart
@@ -291,12 +291,11 @@ Future<void> showAgentActions(
],
);
-/// The one way into [NewAgentPage] — this page's header button, its empty state, and the Agents
-/// tab's `+` all come through here rather than drifting into three ways of opening it.
+/// The one way into [NewAgentPage] — every door to the form comes through here rather than
+/// drifting into several ways of opening it.
///
/// ⚠️ [machineId] is not a detail the caller may guess at. A new agent needs the machine to list
-/// its folders and name the engines it has, so every door has to establish which machine FIRST:
-/// this page already knows, and the tab asks (`agents_tab.dart`).
+/// its folders and name the engines it has, so every door has to establish which machine FIRST.
/// Returns when the form closes — by creating an agent or by being backed out
/// of — so a caller whose own chrome depends on being the top route can rebuild
/// (see `terminal_page.dart`). Callers that do not care can ignore it.
diff --git a/mobile/lib/phone/agents_tab.dart b/mobile/lib/phone/agents_tab.dart
deleted file mode 100644
index 360140ec0..000000000
--- a/mobile/lib/phone/agents_tab.dart
+++ /dev/null
@@ -1,307 +0,0 @@
-import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
-
-import 'package:harness_mobile/shared/theme/app_theme.dart';
-import 'package:harness_mobile/shared/widgets/empty_state.dart';
-import 'package:harness_mobile/state/app_state.dart';
-
-import 'agent_index.dart';
-import 'agent_row.dart';
-import 'agents_page.dart';
-import 'attention_entry.dart';
-import 'machine_filter_bar.dart';
-import 'phone_card.dart';
-import 'phone_fab.dart';
-import 'phone_header.dart';
-import 'phone_search_button.dart';
-import 'phone_navigation.dart';
-import 'phone_status.dart';
-
-/// Every agent on the account, whichever machine it runs on.
-///
-/// The phone's home, and the direction's whole bet: people remember what an agent is CALLED, not
-/// which computer it happens to be on. The machine is still there — as a filter above the list and
-/// as a line under each name — it just stops being the thing you have to navigate through first.
-class AgentsTab extends StatefulWidget {
- const AgentsTab({super.key, required this.notifier});
-
- final AppNotifier notifier;
-
- @override
- State<AgentsTab> createState() => _AgentsTabState();
-}
-
-class _AgentsTabState extends State<AgentsTab> {
- /// The machine the list is narrowed to, or null for all of them.
- ///
- /// Held as an id rather than a [MachineState]: the state objects are rebuilt as machines answer,
- /// and a filter holding a stale instance would quietly stop matching anything.
- String? _machineId;
-
- @override
- Widget build(BuildContext context) => ListenableBuilder(
- listenable: widget.notifier,
- builder: (context, _) {
- AppTheme.watch(context);
- final machines = filterableMachines(widget.notifier);
- // A machine that goes away — unlinked, or dropped from the account — must not leave the list
- // filtered to nothing with no way to see it is.
- final selected = machines.any((m) => m.machine.machineId == _machineId)
- ? _machineId
- : null;
- final all = agentIndex(widget.notifier);
- final shown = selected == null
- ? all
- : all.where((entry) => entry.machineId == selected).toList();
- final error = widget.notifier.lastError;
- // Only machines that are answering. Creating needs one to list its folders and name the
- // engines it has, so a machine that is offline or still wants its password cannot host a new
- // agent — the same gate the machine's own page puts on its `+`.
- final ready = [
- for (final machine in machines)
- if (phoneMachineStatusOf(machine) == PhoneMachineStatus.ready)
- machine,
- ];
- return Scaffold(
- backgroundColor: AppPalette.windowBg,
- // ⚠️ Absent rather than disabled when nothing can host an agent. The empty state already
- // says where that is fixed (the Machines tab), and a button whose only outcome is an
- // explanation of why it does nothing is worse than no button.
- //
- // It floats above the tab bar without being told to: this Scaffold is the BODY of the
- // shell's (`phone_shell.dart`), whose own `bottomNavigationBar` sits below it.
- floatingActionButton: ready.isEmpty
- ? null
- : PhoneFab(
- icon: LucideIcons.plus300,
- tooltip: 'New agent',
- // Straight to the form, on the first machine that can host an agent. Which machine
- // is the form's first question, and it is changed there.
- onPressed: () => openNewAgent(
- context,
- widget.notifier,
- ready.first.machine.machineId,
- ),
- ),
- body: SafeArea(
- bottom: false,
- child: Column(
- children: [
- // No account avatar here. Settings ▸ Account carries the address
- // and the sign-out, and a second copy in the corner of the home
- // screen bought nothing but a place for them to disagree.
- //
- // The one control the title line does carry is search, because
- // what it searches is not this list: it spans agents AND machines,
- // which is the half of the question this tab cannot answer. It
- // appears only once there is something to find — a glyph that
- // opens an empty screen is worse than no glyph.
- PhoneHeader(
- large: true,
- title: 'Agents',
- trailing: [
- // Only while something is actually waiting — the button draws
- // itself away otherwise, which is why there is no condition
- // here. It sits before search because it is the one control
- // that appears in response to something happening.
- buildAttentionButton(context, widget.notifier),
- if (machines.isNotEmpty)
- PhoneSearchButton(notifier: widget.notifier),
- ],
- ),
- if (error != null)
- _ErrorStrip(message: error, notifier: widget.notifier),
- if (machines.isNotEmpty)
- MachineFilterBar(
- machines: machines,
- selectedId: selected,
- countFor: (id) =>
- all.where((entry) => entry.machineId == id).length,
- totalCount: all.length,
- onSelect: (id) => setState(() => _machineId = id),
- ),
- Expanded(
- child: _Body(
- notifier: widget.notifier,
- entries: shown,
- machines: machines,
- filtered: selected != null,
- ),
- ),
- ],
- ),
- ),
- );
- },
- );
-}
-
-class _Body extends StatelessWidget {
- const _Body({
- required this.notifier,
- required this.entries,
- required this.machines,
- required this.filtered,
- });
-
- final AppNotifier notifier;
- final List<AgentEntry> entries;
- final List<MachineState> machines;
- final bool filtered;
-
- /// Whether anything is still on its way in — a machine connecting, or its agent list not yet
- /// answered. "Loading" and "answered with nothing" must not render the same.
- bool get _stillArriving => machines.any(
- (machine) => switch (phoneMachineStatusOf(machine)) {
- PhoneMachineStatus.connecting => true,
- _ => false,
- },
- );
-
- @override
- Widget build(BuildContext context) {
- if (entries.isEmpty) {
- if (notifier.machines.isEmpty && notifier.machinesLoading) {
- return const PhoneListSkeleton(height: kPhoneAgentCardHeight);
- }
- if (notifier.machines.isEmpty) {
- return const EmptyState(
- icon: LucideIcons.laptopMinimal300,
- title: 'No machines yet',
- message:
- 'Run Harness on a computer signed in to this account and it '
- 'will appear here.',
- );
- }
- if (_stillArriving) {
- return const PhoneListSkeleton(height: kPhoneAgentCardHeight);
- }
- if (filtered) {
- return const EmptyState(
- icon: LucideIcons.squareTerminal300,
- title: 'No agents on this machine',
- message: 'Start one from Harness there and it will appear here.',
- );
- }
- // Machines exist and have answered, but none of them can be reached — every one needs its
- // password or is offline. The Machines tab is where that is fixed, so say so.
- final reachable = machines.any(
- (machine) => phoneMachineStatusOf(machine) == PhoneMachineStatus.ready,
- );
- if (!reachable) {
- return const EmptyState(
- icon: LucideIcons.lockKeyhole300,
- title: 'No machines are open yet',
- message:
- 'Open the Machines tab to enter a machine password, or start '
- 'Harness on a computer that is offline.',
- );
- }
- return const EmptyState(
- icon: LucideIcons.squareTerminal300,
- title: 'No agents yet',
- message: 'Start one from Harness on a machine and it will appear here.',
- );
- }
-
- // The order a swipe on the terminal page walks, split back into the two sections this list
- // draws. Taken from [visibleAgents] rather than assembled here so the page and the list cannot
- // drift apart — the split below is presentation, the order is not.
- final ordered = visibleAgents(entries);
- final waiting = ordered.where((entry) => entry.isWaiting).toList();
- final rest = ordered.where((entry) => !entry.isWaiting).toList();
- return RefreshIndicator(
- onRefresh: notifier.retryMachines,
- child: ListView(
- physics: const AlwaysScrollableScrollPhysics(),
- padding: phoneListPadding(context),
- children: [
- if (waiting.isNotEmpty) ...[
- const _SectionLabel('Waiting for you'),
- for (final entry in waiting) _row(context, ordered, entry),
- const SizedBox(height: 6),
- ],
- if (rest.isNotEmpty) ...[
- if (waiting.isNotEmpty) const _SectionLabel('All agents'),
- for (final entry in rest) _row(context, ordered, entry),
- ],
- ],
- ),
- );
- }
-
- Widget _row(
- BuildContext context,
- List<AgentEntry> ordered,
- AgentEntry entry,
- ) => Padding(
- padding: const EdgeInsets.only(bottom: kPhoneCardGap),
- child: AgentRow(
- entry: entry,
- // The whole visible list goes with the tap, so the page opens as a pager over exactly the
- // agents on screen — the filter chip included. Swiping there walks this order.
- onTap: () => openAgentPager(context, notifier, ordered, entry),
- // The same sheet a machine's own page opens, from [AgentsPage] rather than written again
- // here: one agent reached two ways must not offer two different sets of actions, and the
- // delete wording in particular is the one that has to match.
- onLongPress: () =>
- showAgentActions(context, notifier, entry.machineId, entry.agent),
- ),
- );
-}
-
-class _SectionLabel extends StatelessWidget {
- const _SectionLabel(this.text);
-
- final String text;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- return Padding(
- padding: const EdgeInsets.fromLTRB(4, 8, 4, 8),
- child: Text(
- text.toUpperCase(),
- style: TextStyle(
- color: AppPalette.textFaint,
- fontSize: 11.5,
- fontWeight: FontWeight.w600,
- letterSpacing: 0.5,
- ),
- ),
- );
- }
-}
-
-class _ErrorStrip extends StatelessWidget {
- const _ErrorStrip({required this.message, required this.notifier});
-
- final String message;
- final AppNotifier notifier;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- return Padding(
- padding: const EdgeInsets.fromLTRB(20, 0, 12, 8),
- child: Row(
- children: [
- Icon(LucideIcons.circleAlert300, size: 18, color: AppPalette.warn),
- const SizedBox(width: 8),
- Expanded(
- child: Text(
- message,
- maxLines: 2,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(color: AppPalette.textSecondary, fontSize: 13),
- ),
- ),
- TextButton(
- onPressed: notifier.retryMachines,
- child: const Text('Retry'),
- ),
- ],
- ),
- );
- }
-}
diff --git a/mobile/lib/phone/attention_entry.dart b/mobile/lib/phone/attention_entry.dart
deleted file mode 100644
index 62b8854a1..000000000
--- a/mobile/lib/phone/attention_entry.dart
+++ /dev/null
@@ -1,111 +0,0 @@
-import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
-
-import 'package:harness_mobile/shared/theme/app_theme.dart';
-import 'package:harness_mobile/shared/widgets/app_icon_button.dart';
-import 'package:harness_mobile/state/app_state.dart';
-
-import 'agent_index.dart';
-import 'attention_page.dart';
-import 'phone_navigation.dart';
-
-/// Pushes [AttentionPage].
-///
-/// Separate from the button so anything else that should land there — a notification tap, a
-/// future shortcut — opens the same route rather than pushing its own.
-void openAttentionPage(BuildContext context, AppNotifier notifier) =>
- Navigator.of(context).push(
- phoneRoute((_) => AttentionPage(notifier: notifier)),
- );
-
-/// The way into [AttentionPage], drawn in the Agents tab header's `trailing`.
-///
-/// ⚠️ **Absent when nothing is waiting**, rather than drawn disabled or drawn with a zero badge.
-/// The page's own answer for that case is an empty state, and a glyph whose only outcome is being
-/// told "nothing here" is worse than no glyph — the same rule the search button in that header
-/// keeps. It is also why the count lives on the button rather than beside it: the button only
-/// exists while the count is worth reading.
-Widget buildAttentionButton(BuildContext context, AppNotifier notifier) {
- final waiting = waitingAgents(agentIndex(notifier)).length;
- if (waiting == 0) return const SizedBox.shrink();
- return _AttentionButton(notifier: notifier, count: waiting);
-}
-
-class _AttentionButton extends StatelessWidget {
- const _AttentionButton({required this.notifier, required this.count});
-
- final AppNotifier notifier;
- final int count;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- return Padding(
- padding: const EdgeInsets.only(right: 2),
- child: Stack(
- // The badge overhangs the glyph's box on both axes, the way the tab bar's does.
- clipBehavior: Clip.none,
- children: [
- AppIconButton(
- icon: LucideIcons.bell300,
- size: 22,
- tooltip: count == 1 ? '1 agent waiting' : '$count agents waiting',
- // The glyph itself carries the attention colour: it is only on screen because
- // something IS waiting, so drawing it in the quiet ink every other header control
- // uses would hide the one control worth noticing.
- color: AppPalette.warn,
- onPressed: () => openAttentionPage(context, notifier),
- ),
- Positioned(
- top: -3,
- right: -5,
- // Ignores pointers so the badge cannot eat a tap meant for the button under it —
- // it overhangs the glyph's box, so it sits over the row's padding as well.
- child: IgnorePointer(child: _Badge(count: count)),
- ),
- ],
- ),
- );
- }
-}
-
-/// The count, drawn the same way the Agents tab's own badge is.
-///
-/// Deliberately a second, private copy of `phone_tab_bar.dart`'s `_Badge` rather than a shared
-/// one: that badge rims itself in the tab bar's `panelBg` so it reads as separate from the icon it
-/// overlaps, and this one sits on the page background instead. One widget carrying both would
-/// need a colour argument at every call site to say which surface it is on, which is more moving
-/// parts than the eleven lines it would save.
-class _Badge extends StatelessWidget {
- const _Badge({required this.count});
-
- final int count;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- return Container(
- constraints: const BoxConstraints(minWidth: 16),
- padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
- decoration: BoxDecoration(
- color: AppPalette.warn,
- borderRadius: BorderRadius.circular(999),
- border: Border.all(color: AppPalette.windowBg, width: 1.5),
- ),
- alignment: Alignment.center,
- child: Text(
- // Past 99 the exact figure stops meaning anything and the pill would widen off the glyph.
- count > 99 ? '99+' : '$count',
- style: TextStyle(
- // Follows the theme because the fill does — see the tab bar's badge for the contrast
- // measurements behind this pair.
- color: AppTheme.pick(Colors.white, const Color(0xFF181818)),
- fontSize: 10,
- height: 1.2,
- fontWeight: FontWeight.w700,
- fontFeatures: AppFont.tabularFigures,
- ),
- ),
- );
- }
-}
diff --git a/mobile/lib/phone/attention_page.dart b/mobile/lib/phone/attention_page.dart
deleted file mode 100644
index b523ac124..000000000
--- a/mobile/lib/phone/attention_page.dart
+++ /dev/null
@@ -1,276 +0,0 @@
-import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
-
-import 'package:harness_mobile/shared/theme/app_theme.dart';
-import 'package:harness_mobile/shared/widgets/empty_state.dart';
-import 'package:harness_mobile/state/app_state.dart';
-import 'package:harness_mobile/state/attention.dart';
-import 'package:harness_mobile/widgets/engine_identity.dart';
-
-import 'phone_card.dart';
-import 'phone_header.dart';
-import 'phone_navigation.dart';
-import 'phone_status.dart';
-
-/// Every agent, on every machine, that has stopped to ask the person something.
-///
-/// The desktop reaches the same list with ⇧⌘I and draws it as a searchable picker
-/// (`widgets/swarm_attention.dart`); a phone gets a page instead, because there is no keyboard to
-/// open it with and nothing else to look at while it is open. The badge on the Agents tab already
-/// says HOW MANY are waiting — this is the screen that says which.
-///
-/// ⚠️ It is the one list that does not fall back to the whole roster. A page that showed idle
-/// agents once everything had been answered would be a second, worse Agents tab; when there is
-/// nothing waiting, the right answer is to say so and send the person back.
-class AttentionPage extends StatelessWidget {
- const AttentionPage({super.key, required this.notifier});
-
- final AppNotifier notifier;
-
- @override
- Widget build(BuildContext context) => ListenableBuilder(
- listenable: notifier,
- builder: (context, _) {
- AppTheme.watch(context);
- final entries = attentionEntries(notifier);
- final groups = attentionGroups(entries);
- return Scaffold(
- backgroundColor: AppPalette.windowBg,
- body: SafeArea(
- bottom: false,
- child: Column(
- children: [
- PhoneHeader(
- title: 'Needs input',
- subtitle: entries.isEmpty
- ? null
- : Text(
- entries.length == 1
- ? '1 agent waiting'
- : '${entries.length} agents waiting',
- style: TextStyle(
- color: AppPalette.textSecondary,
- fontSize: 13,
- ),
- ),
- ),
- Expanded(
- child: _Body(notifier: notifier, groups: groups),
- ),
- ],
- ),
- ),
- );
- },
- );
-}
-
-class _Body extends StatelessWidget {
- const _Body({required this.notifier, required this.groups});
-
- final AppNotifier notifier;
- final List<AttentionGroup> groups;
-
- /// Whether anything is still on its way in — a machine connecting, or its agents not yet
- /// answered. "Loading" and "nobody is waiting" must not render the same, which is the one thing
- /// this page's empty state has to get right: the second is good news and the first is not news
- /// at all.
- bool get _stillArriving {
- if (notifier.machines.isEmpty && notifier.machinesLoading) return true;
- for (final machine in notifier.machines) {
- final state = notifier.stateOf(machine.machineId);
- if (state == null) return true;
- if (phoneMachineStatusOf(state) == PhoneMachineStatus.connecting) {
- return true;
- }
- }
- return false;
- }
-
- @override
- Widget build(BuildContext context) {
- if (groups.isEmpty) {
- if (_stillArriving) return const PhoneListSkeleton();
- return const EmptyState(
- icon: LucideIcons.circleCheck300,
- title: 'No agents waiting',
- message: 'Nothing has stopped to ask you anything right now.',
- );
- }
- // Every waiting agent across the whole page, in the order the rows are drawn — so a swipe on
- // the terminal this opens walks THIS list rather than the Agents tab's. Built from the groups
- // rather than recomputed, so the two cannot disagree about the order.
- final ordered = [
- for (final group in groups)
- for (final entry in group.entries) entry.agent,
- ];
- return RefreshIndicator(
- onRefresh: notifier.retryMachines,
- child: ListView(
- physics: const AlwaysScrollableScrollPhysics(),
- padding: phoneListPadding(context),
- children: [
- for (final group in groups) ...[
- _MachineLabel(group.machineName),
- for (final entry in group.entries)
- Padding(
- padding: const EdgeInsets.only(bottom: kPhoneCardGap),
- child: _AttentionRow(
- entry: entry,
- onTap: () => openAgentPager(
- context,
- notifier,
- ordered,
- entry.agent,
- ),
- ),
- ),
- const SizedBox(height: 6),
- ],
- ],
- ),
- );
- }
-}
-
-/// One waiting agent: its engine, its name, and what it is asking.
-///
-/// Taller than the app's other rows on purpose — [PhoneCard]'s fixed 70pt fits a name and a status
-/// line, and the QUESTION is the whole reason to come here. A row that cropped it to a status pill
-/// would send the person into the terminal to find out what the tap was for.
-class _AttentionRow extends StatelessWidget {
- const _AttentionRow({required this.entry, required this.onTap});
-
- final AttentionEntry entry;
- final VoidCallback onTap;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final agent = entry.agent.agent;
- final prompt = entry.promptLine;
- // Held to the same rule as every other row: an agent with no terminal to attach cannot be
- // opened. It still draws — it IS waiting, and hiding it would make the tab's badge count
- // rows this page does not have.
- final open = agent.terminalAvailable;
- return Material(
- color: Colors.transparent,
- child: InkWell(
- onTap: open ? onTap : null,
- borderRadius: BorderRadius.circular(AppCard.radius),
- child: Opacity(
- opacity: open ? 1 : 0.55,
- child: Container(
- padding: const EdgeInsets.fromLTRB(13, 12, 13, 12),
- decoration: BoxDecoration(
- color: AppGlass.rowFill,
- borderRadius: BorderRadius.circular(AppCard.radius),
- // The attention rim every waiting row wears, matching [AgentRow] — the same agent
- // seen on two screens must not be marked two different ways.
- border: Border.all(color: AppPalette.warn.withValues(alpha: 0.42)),
- ),
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- PhoneCardGlyph(
- child: EngineMark(
- engine: agent.engine,
- displayName: agent.engineDisplayName,
- size: 22,
- ),
- ),
- const SizedBox(width: 14),
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- agent.name,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: AppPalette.textPrimary,
- fontSize: 16,
- fontWeight: FontWeight.w600,
- ),
- ),
- const SizedBox(height: 3),
- Text(
- entry.machineName,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: AppPalette.textFaint,
- fontSize: 12.5,
- ),
- ),
- const SizedBox(height: 7),
- // ⚠️ Two lines, never more. The prompt is already collapsed to one line by
- // [AttentionEntry.promptLine]; letting it run further would turn a list into
- // a transcript and push the next waiting agent off the screen.
- Text(
- prompt ?? 'Waiting for you',
- maxLines: 2,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: prompt == null
- ? AppPalette.textFaint
- : AppPalette.textSecondary,
- fontSize: 13.5,
- height: 1.35,
- fontStyle: prompt == null
- ? FontStyle.italic
- : FontStyle.normal,
- ),
- ),
- ],
- ),
- ),
- const SizedBox(width: 8),
- if (open)
- Padding(
- padding: const EdgeInsets.only(top: 11),
- child: Icon(
- LucideIcons.chevronRight300,
- size: 22,
- color: AppPalette.textFaint,
- ),
- ),
- ],
- ),
- ),
- ),
- ),
- );
- }
-}
-
-/// The machine a group of rows belongs to.
-///
-/// The rows name their machine as well, because one is read on its own the moment the page
-/// scrolls past this heading — the heading is what makes the grouping visible, not what carries
-/// the fact.
-class _MachineLabel extends StatelessWidget {
- const _MachineLabel(this.text);
-
- final String text;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- return Padding(
- padding: const EdgeInsets.fromLTRB(4, 8, 4, 8),
- child: Text(
- text.toUpperCase(),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: AppPalette.textFaint,
- fontSize: 11.5,
- fontWeight: FontWeight.w600,
- letterSpacing: 0.5,
- ),
- ),
- );
- }
-}
diff --git a/mobile/lib/phone/machine_filter_bar.dart b/mobile/lib/phone/machine_filter_bar.dart
deleted file mode 100644
index 0016fd2ea..000000000
--- a/mobile/lib/phone/machine_filter_bar.dart
+++ /dev/null
@@ -1,188 +0,0 @@
-import 'package:flutter/material.dart';
-
-import 'package:harness_mobile/shared/theme/app_theme.dart';
-import 'package:harness_mobile/state/app_state.dart';
-import 'phone_status.dart';
-import 'status_pill.dart';
-
-/// The machine chips over the Agents tab.
-///
-/// The machine does not disappear in this direction — it stops being a page you walk through and
-/// becomes a way to narrow the list you are already looking at. A chip for a machine that cannot
-/// be opened is drawn disabled rather than hidden: seeing that a machine needs its password is
-/// half of why somebody would look here at all.
-class MachineFilterBar extends StatelessWidget {
- const MachineFilterBar({
- super.key,
- required this.machines,
- required this.selectedId,
- required this.countFor,
- required this.totalCount,
- required this.onSelect,
- });
-
- final List<MachineState> machines;
-
- /// The machine the list is narrowed to, or null for all of them.
- final String? selectedId;
-
- /// How many agents a machine contributes, for the figure on its chip.
- final int Function(String machineId) countFor;
-
- final int totalCount;
-
- /// Null selects every machine.
- final ValueChanged<String?> onSelect;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- return SizedBox(
- height: 42,
- child: ListView(
- scrollDirection: Axis.horizontal,
- padding: const EdgeInsets.symmetric(horizontal: 16),
- children: [
- _Chip(
- label: 'All',
- count: totalCount,
- selected: selectedId == null,
- onTap: () => onSelect(null),
- ),
- for (final machine in machines) _chipFor(machine),
- ],
- ),
- );
- }
-
- Widget _chipFor(MachineState machine) {
- final id = machine.machine.machineId;
- final status = phoneMachineStatusOf(machine);
- final ready = status == PhoneMachineStatus.ready;
- return _Chip(
- label: machine.machine.displayName,
- // A count only where there is one to give. A machine that has not answered would otherwise
- // read as "0 agents", which is a claim rather than a silence.
- count: ready ? countFor(id) : null,
- tone: phoneMachineSummary(machine).tone,
- selected: selectedId == id,
- // Narrowing to a machine with nothing to show is a dead end, so those chips do not select.
- // They still say what is wrong through their dot, and the Machines tab is where it is fixed.
- onTap: ready ? () => onSelect(id) : null,
- );
- }
-}
-
-class _Chip extends StatelessWidget {
- const _Chip({
- required this.label,
- required this.selected,
- required this.onTap,
- this.count,
- this.tone,
- });
-
- final String label;
- final bool selected;
- final VoidCallback? onTap;
- final int? count;
-
- /// Drawn as the leading dot. Null on the "All" chip, which is not a machine and has no state.
- final PhoneTone? tone;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final enabled = onTap != null;
- return Padding(
- padding: const EdgeInsets.only(right: 7, top: 4, bottom: 4),
- child: Opacity(
- opacity: enabled ? 1 : 0.5,
- child: Material(
- color: selected ? AppSurface.accentWash : AppGlass.rowFill,
- borderRadius: BorderRadius.circular(999),
- child: InkWell(
- onTap: onTap,
- borderRadius: BorderRadius.circular(999),
- child: Container(
- padding: const EdgeInsets.symmetric(horizontal: 12),
- alignment: Alignment.center,
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(999),
- border: Border.all(
- color: selected
- ? AppPalette.accentOnSurface.withValues(alpha: 0.5)
- : AppGlass.hair,
- ),
- ),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- if (tone != null) ...[
- _Dot(tone: tone!),
- const SizedBox(width: 6),
- ],
- ConstrainedBox(
- // A long machine name must not push the chips off the rail; it ellipsises and
- // the ones after it stay reachable.
- //
- // 108 rather than a rounder 140: hostnames run long by default — a stock
- // `caokhanh-Inspiron-3520` or `MacBooks-MacBook-Pro` is over twenty characters
- // — and at 140 just two of them fill a 390pt screen, hiding every chip after
- // them. Ellipsised earlier, four fit, and the leading characters are the part
- // that tells two machines apart anyway.
- constraints: const BoxConstraints(maxWidth: 108),
- child: Text(
- label,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: selected
- ? AppPalette.textPrimary
- : AppPalette.textSecondary,
- fontSize: 13,
- fontWeight: FontWeight.w500,
- ),
- ),
- ),
- if (count != null) ...[
- const SizedBox(width: 6),
- Text(
- '$count',
- style: TextStyle(
- color: AppPalette.textFaint,
- fontSize: 13,
- fontWeight: FontWeight.w500,
- fontFeatures: AppFont.tabularFigures,
- ),
- ),
- ],
- ],
- ),
- ),
- ),
- ),
- ),
- );
- }
-}
-
-class _Dot extends StatelessWidget {
- const _Dot({required this.tone});
-
- final PhoneTone tone;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- return SizedBox.square(
- dimension: 7,
- child: DecoratedBox(
- decoration: BoxDecoration(
- color: phoneToneColor(tone),
- shape: BoxShape.circle,
- ),
- ),
- );
- }
-}
diff --git a/mobile/lib/phone/machines_tab.dart b/mobile/lib/phone/machines_tab.dart
index c5e9fdfd8..ba3051cad 100644
--- a/mobile/lib/phone/machines_tab.dart
+++ b/mobile/lib/phone/machines_tab.dart
@@ -74,9 +74,25 @@ class _Body extends StatelessWidget {
// Taken from [visibleMachines] rather than partitioned here so the page and the list cannot
// drift apart — the split below is presentation, the order is not.
final ordered = visibleMachines(notifier);
- if (ordered.isEmpty && notifier.machinesLoading) {
+ if (ordered.isEmpty &&
+ (notifier.machinesLoading || notifier.machinesRefreshing)) {
return const PhoneListSkeleton();
}
+ // ⚠️ A list that could not be fetched is not an empty one. Drawn as "No machines yet", it told
+ // somebody with three machines to go and set one up — and with nothing in the list there was no
+ // pull-to-refresh either, so no way to try again short of restarting the app.
+ final failure = notifier.lastError;
+ if (ordered.isEmpty && failure != null) {
+ return EmptyState(
+ icon: LucideIcons.circleAlert300,
+ title: "Couldn't load your machines",
+ message: failure,
+ action: FilledButton(
+ onPressed: () => unawaited(notifier.retryMachines()),
+ child: const Text('Try again'),
+ ),
+ );
+ }
if (ordered.isEmpty) {
return const EmptyState(
icon: LucideIcons.laptopMinimal300,
diff --git a/mobile/lib/phone/phone_layout.dart b/mobile/lib/phone/phone_layout.dart
deleted file mode 100644
index 2061482bb..000000000
--- a/mobile/lib/phone/phone_layout.dart
+++ /dev/null
@@ -1,16 +0,0 @@
-import 'package:flutter/widgets.dart';
-
-import 'package:harness_mobile/core/viewer_mode.dart';
-import 'package:harness_mobile/shared/layouts/window_size.dart';
-
-/// The shortest side under which a viewer draws its phone layout — the shell's own compact
-/// breakpoint, so an iPad keeps the rail beside its terminals.
-const double kPhoneShortestSide = WindowSizeClass.compactMax;
-
-/// Whether this screen gets the phone layout: one agent at a time, reached machine → agents →
-/// terminal, instead of the desktop's rail beside a grid of tiles.
-///
-/// A viewer build only. A desktop build always has a window wide enough for the rail, and
-/// resizing one small must not turn it into a phone.
-bool usePhoneLayout(BuildContext context) =>
- kViewerMode && MediaQuery.sizeOf(context).shortestSide < kPhoneShortestSide;
diff --git a/mobile/lib/phone/phone_shell.dart b/mobile/lib/phone/phone_shell.dart
index 69f390675..edc4fe670 100644
--- a/mobile/lib/phone/phone_shell.dart
+++ b/mobile/lib/phone/phone_shell.dart
@@ -1,7 +1,3 @@
-// `Timer` — used only by the kept-but-dead landing rules below, which is also why
-// `phone_navigation.dart` and `phone_status.dart` are still imported here.
-import 'dart:async';
-
import 'package:flutter/material.dart';
import 'package:harness_mobile/state/app_state.dart';
@@ -10,9 +6,7 @@ import '../p2p/phone_terminal_p2p.dart';
import 'agent_home.dart';
import 'agent_index.dart';
import 'machines_tab.dart';
-import 'phone_navigation.dart';
import 'phone_shell_scope.dart';
-import 'phone_status.dart';
import 'phone_tab_bar.dart';
import 'settings_page.dart';
@@ -144,209 +138,6 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {
});
}
- // ── The landing rules this replaced, kept and not called ──────────────────────────────────────
- //
- // ⚠️ **Dead on purpose: nothing below this line runs.** It is the shell's old way of deciding
- // where the app opens, from when the Agents tab's root was a LIST and a terminal had to be pushed
- // over it — so the shell waited for a machine to answer, pushed the pager itself, gave up after
- // [_pendingTimeout], and fell back to Machines when no machine answered at all. [AgentHome] now
- // does all of that as part of drawing itself, without a push and without a timeout, so none of
- // this is wired up any more.
- //
- // Kept because the list screens are kept: `_showTabBar` above and `AgentsTab` are both still here
- // for the same reason, and bringing them back would need these rules back with them.
- // [_followLinkedMachine] above is the live one; the copy here is renamed so the two can sit side
- // by side.
- //
- // `ignore_for_file` is deliberately NOT used: the ignores are per-member, so an unused member
- // added to this class later still gets flagged.
-
- /// An agent waiting for its machine to answer before it can be opened.
- // ignore: unused_field
- ({String machineId, String? agentId, bool afterLink})? _pending;
- // ignore: unused_field
- Timer? _pendingDeadline;
-
- /// How long a machine gets to answer. Past this the phone stays where it is — on a list the person
- /// can act on — rather than jumping into a terminal a minute after they stopped expecting it.
- // ignore: unused_field
- static const _pendingTimeout = Duration(seconds: 45);
-
- /// The last-agent record has not been read yet, so the landing tab cannot be chosen: a reopen
- /// would override it.
- // ignore: unused_field
- bool _readingLastAgent = true;
-
- /// The landing has been decided — by the shell or by the person — and nothing moves on its own
- /// again except [_followLinkedMachineLegacy], which the person asked for by entering a password.
- // ignore: unused_field
- bool _landed = false;
-
- // ignore: unused_element
- Future<void> _reopenLastAgent() async {
- final last = await widget.notifier.lastOpenedAgent.read();
- if (!mounted) return;
- _readingLastAgent = false;
- if (last != null && !_landed) {
- _wait(machineId: last.machineId, agentId: last.agentId, afterLink: false);
- } else {
- _onAppChanged();
- }
- }
-
- // ignore: unused_element
- void _followLinkedMachineLegacy(String machineId) {
- _landed = true;
- // Straight to Agents, before the machine has finished connecting: the row it lands on says
- // "Connecting…", which is what is actually happening, and the agent opens over it once it can.
- setState(() {
- _tab = PhoneTab.agents;
- _tabCanPop =
- _navigators[PhoneTab.agents]?.currentState?.canPop() ?? false;
- });
- _wait(machineId: machineId, agentId: null, afterLink: true);
- }
-
- // ignore: unused_element
- void _wait({
- required String machineId,
- required String? agentId,
- required bool afterLink,
- }) {
- _pending = (machineId: machineId, agentId: agentId, afterLink: afterLink);
- _pendingDeadline?.cancel();
- _pendingDeadline = Timer(_pendingTimeout, _dropPending);
- _onAppChanged();
- }
-
- // ignore: unused_element
- void _dropPending() {
- _pending = null;
- _pendingDeadline?.cancel();
- _pendingDeadline = null;
- if (mounted) _onAppChanged();
- }
-
- // ignore: unused_element
- void _onAppChanged() {
- if (!mounted) return;
- final pending = _pending;
- if (pending == null) {
- _decideLanding();
- return;
- }
- final notifier = widget.notifier;
- final machine = notifier.stateOf(pending.machineId);
- if (machine == null) {
- // Not on the account — or the account's machines have not arrived yet.
- if (notifier.machines.isNotEmpty && !notifier.machinesLoading) {
- _dropPending();
- }
- return;
- }
- switch (phoneMachineStatusOf(machine)) {
- case PhoneMachineStatus.needsPassword:
- return _dropPending();
- case PhoneMachineStatus.offline:
- // ⚠️ Not given up on straight after a link. Accepting a password closes the machine's old
- // socket before dialling a new one, and that close marks the node offline for the moment
- // before the new socket answers. On a relaunch offline is the REST answer, and it holds.
- if (!pending.afterLink) _dropPending();
- return;
- case PhoneMachineStatus.connecting:
- return;
- case PhoneMachineStatus.ready:
- break;
- }
- switch (machine.agentLoadStatus) {
- case AgentLoadStatus.loaded:
- break;
- case AgentLoadStatus.error:
- return _dropPending();
- case AgentLoadStatus.idle ||
- AgentLoadStatus.loading ||
- AgentLoadStatus.needsLink:
- return;
- }
- // Something already open on the Agents tab was opened by the person; it is not covered over.
- if (_navigators[PhoneTab.agents]?.currentState?.canPop() ?? false) {
- _landed = true;
- return _dropPending();
- }
- // The same order the list draws, so the pager swipes to the neighbours the person would see —
- // and "first agent" means the first row of that machine, not the first one it reported.
- final entries = visibleAgents(agentIndex(notifier));
- final target = entries
- .where(
- (entry) =>
- entry.machineId == pending.machineId &&
- entry.agent.terminalAvailable &&
- (pending.agentId == null || entry.agent.id == pending.agentId),
- )
- .firstOrNull;
- if (target == null) {
- // A machine with no agents yet, or a remembered agent since deleted: the list is the answer.
- return _dropPending();
- }
- _landed = true;
- _pending = null;
- _pendingDeadline?.cancel();
- _pendingDeadline = null;
- // After the frame: this runs inside the notifier's notify, which can land mid-build, and a push
- // there trips the navigator's lock.
- _afterFrame(() {
- final navigator = _navigators[PhoneTab.agents]?.currentState;
- if (navigator == null) return;
- setState(() => _tab = PhoneTab.agents);
- openAgentPager(navigator.context, notifier, entries, target);
- _syncCanPop();
- });
- }
-
- /// Machines, once no machine on the account has answered and none is still trying.
- ///
- /// Waits on a machine that is connecting: whether it needs a password is only learned by dialling
- /// it, so a phone that IS linked reads exactly like one that is not for the first second or two.
- /// An empty account decides nothing either — until the list arrives, empty is indistinguishable
- /// from not loaded.
- // ignore: unused_element
- void _decideLanding() {
- if (_landed || _readingLastAgent) return;
- final notifier = widget.notifier;
- if (notifier.machines.isEmpty) return;
- for (final machine in notifier.machines) {
- final state = notifier.stateOf(machine.machineId);
- if (state == null) return;
- switch (phoneMachineStatusOf(state)) {
- case PhoneMachineStatus.ready:
- _landed = true;
- return;
- case PhoneMachineStatus.connecting:
- return;
- case PhoneMachineStatus.needsPassword || PhoneMachineStatus.offline:
- continue;
- }
- }
- _landed = true;
- _afterFrame(() {
- setState(() {
- _tab = PhoneTab.machines;
- _tabCanPop =
- _navigators[PhoneTab.machines]?.currentState?.canPop() ?? false;
- });
- });
- }
-
- // ignore: unused_element
- void _afterFrame(VoidCallback action) {
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (mounted) action();
- });
- WidgetsBinding.instance.ensureVisualUpdate();
- }
-
- // ── End of the kept-but-dead landing rules ────────────────────────────────────────────────────
-
/// Back in the foreground: a p2p retry waiting out its delay fires now, and so does every machine
/// socket the phone lost while it was away. Going to the background needs nothing — the OS
/// suspends the socket, and the redial tears the old wire down and negotiates a fresh one.
@@ -478,9 +269,8 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {
// ⚠️ Hidden, not removed. The terminal is the screen the phone
// opens on, and the three-tab bar under it is on its way out — but
// the tabs themselves still carry the whole app: every page here is
- // rooted in one of them, [_select] is what pops a tab back and
- // keeps its stack, and the landing rules above still choose between
- // them. Deleting the bar would take all of that with it.
+ // rooted in one of them, and [_select] is what pops a tab back and
+ // keeps its stack. Deleting the bar would take all of that with it.
//
// So the shell is unchanged and only the bar is not drawn. Flip
// [_showTabBar] to bring it straight back, and everything below is
diff --git a/mobile/lib/phone/phone_status.dart b/mobile/lib/phone/phone_status.dart
index 66cc6f344..a41f2b669 100644
--- a/mobile/lib/phone/phone_status.dart
+++ b/mobile/lib/phone/phone_status.dart
@@ -39,6 +39,22 @@ PhoneMachineStatus phoneMachineStatusOf(MachineState machine) {
return answering ? PhoneMachineStatus.ready : PhoneMachineStatus.connecting;
}
+/// Whether [machine]'s agents belong on the agent screens: it is answering, or it answered and its
+/// socket is only dialling again.
+///
+/// ⚠️ **The second half is what keeps a terminal on screen through a dropped socket.** Backgrounding
+/// the app drops it every time, and a machine counted only while [PhoneMachineStatus.ready] took its
+/// agents out of the list for the length of the redial — the pager, whose pages ARE that list, was
+/// thrown away and the screen fell back to "Connecting to your machine…" on every return to the app.
+/// A first connect has no list yet, so it still waits like one.
+bool phoneMachineListsAgents(MachineState machine) =>
+ switch (phoneMachineStatusOf(machine)) {
+ PhoneMachineStatus.ready => true,
+ PhoneMachineStatus.connecting =>
+ machine.agentLoadStatus == AgentLoadStatus.loaded,
+ PhoneMachineStatus.needsPassword || PhoneMachineStatus.offline => false,
+ };
+
PhoneSummary phoneMachineSummary(MachineState machine) =>
switch (phoneMachineStatusOf(machine)) {
PhoneMachineStatus.needsPassword => (
diff --git a/mobile/lib/phone/terminal_search.dart b/mobile/lib/phone/terminal_search.dart
index 50ed59b9b..4360d2098 100644
--- a/mobile/lib/phone/terminal_search.dart
+++ b/mobile/lib/phone/terminal_search.dart
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/widgets/touch_target.dart';
import 'package:harness_mobile/state/app_state.dart';
import 'phone_search_index.dart';
@@ -362,17 +363,19 @@ class _ClearButton extends StatelessWidget {
: Semantics(
button: true,
label: 'Clear',
- child: GestureDetector(
- behavior: HitTestBehavior.opaque,
- onTap: onTap,
- child: Padding(
- // Padding, not size: the glyph stays small while the target
- // reaches a thumb.
- padding: const EdgeInsets.only(left: 8),
- child: Icon(
- LucideIcons.circleX300,
- size: 16,
- color: AppPalette.textFaint,
+ // The padding alone left a 24x16 target; [TouchTarget] takes it
+ // to a thumb's without moving the field beside it.
+ child: TouchTarget(
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onTap,
+ child: Padding(
+ padding: const EdgeInsets.only(left: 8),
+ child: Icon(
+ LucideIcons.circleX300,
+ size: 16,
+ color: AppPalette.textFaint,
+ ),
),
),
),
diff --git a/mobile/lib/phone/voice_input_controller.dart b/mobile/lib/phone/voice_input_controller.dart
index da5d4f23c..383e7b778 100644
--- a/mobile/lib/phone/voice_input_controller.dart
+++ b/mobile/lib/phone/voice_input_controller.dart
@@ -225,11 +225,18 @@ class VoiceInputController extends ChangeNotifier {
/// when delivery fails, so nothing said has to be said twice.
///
/// Send while still talking ends the take first: one tap finishes the
- /// sentence and sends it. A take that comes back as nothing sends nothing,
- /// rather than the half of the message that was heard before it.
+ /// sentence and sends it. A take that FAILED sends nothing, rather than the
+ /// half of the message that was heard before it.
+ ///
+ /// ⚠️ A take too short to be speech is not a failure: nothing was said in it,
+ /// so nothing is missing. That is the retry face held to talk — a quick tap
+ /// on it has to send the words kept from the send that did not land, and it
+ /// used to be dropped with the tap, leaving no way to send them but saying
+ /// something new.
Future<void> submit(Future<bool> Function(String text) deliver) async {
if (_isSending || _status == VoiceInputStatus.transcribing) return;
- if (_status == VoiceInputStatus.listening && !await _transcribeTake()) {
+ if (_status == VoiceInputStatus.listening &&
+ await _transcribeTake() == _Take.failed) {
return;
}
final text = transcript.trim();
@@ -276,14 +283,14 @@ class VoiceInputController extends ChangeNotifier {
super.dispose();
}
- /// True when the take's words, if any, joined the transcript.
- Future<bool> _transcribeTake() async {
+ /// Ends the take, and adds what it heard to the transcript.
+ Future<_Take> _transcribeTake() async {
final take = _take;
_takeLimit?.cancel();
_setStatus(VoiceInputStatus.transcribing);
try {
final recording = await _recorder.stop();
- if (take != _take) return false;
+ if (take != _take) return _Take.failed;
appLog.info(
'voice',
recording == null
@@ -296,23 +303,23 @@ class VoiceInputController extends ChangeNotifier {
// something the person did not mean to do.
if (recording != null && recording.length < minTake) {
_setStatus(VoiceInputStatus.idle);
- return false;
+ return _Take.tap;
}
if (recording == null || recording.peak < silencePeak) {
_setStatus(VoiceInputStatus.idle, notice: VoiceNotice.noSound);
- return false;
+ return _Take.failed;
}
final language = _language.value;
final words = await transcriber(recording.wav, language);
// The count, never the words: a transcript is what someone said.
appLog.info('voice', 'stt[$language]: ${words.length} chars');
- if (take != _take) return false;
+ if (take != _take) return _Take.failed;
_heard = _joinWords(_heard, words);
_setStatus(
VoiceInputStatus.idle,
notice: words.isEmpty ? VoiceNotice.nothingHeard : null,
);
- return words.isNotEmpty;
+ return words.isEmpty ? _Take.failed : _Take.heard;
} catch (error) {
// ⚠️ Every throwable, not only [Exception]: a reply of an unexpected shape
// fails as a TypeError, and one that escaped would leave the status on
@@ -321,7 +328,7 @@ class VoiceInputController extends ChangeNotifier {
if (take == _take) {
_setStatus(VoiceInputStatus.idle, notice: VoiceNotice.notTranscribed);
}
- return false;
+ return _Take.failed;
}
}
@@ -385,3 +392,16 @@ class VoiceInputController extends ChangeNotifier {
String _joinWords(String first, String second) =>
[first.trim(), second.trim()].where((part) => part.isNotEmpty).join(' ');
+
+/// How a take ended, as [VoiceInputController.submit] needs to know it.
+enum _Take {
+ /// Its words joined the transcript.
+ heard,
+
+ /// Too short to be speech — a tap, with nothing said and so nothing lost.
+ tap,
+
+ /// Something was meant and did not arrive: silence, nothing transcribed, an
+ /// upload that failed, or a take abandoned mid-flight.
+ failed,
+}
diff --git a/mobile/lib/phone/voice_mic_action.dart b/mobile/lib/phone/voice_mic_action.dart
index f3827d1e9..edc2746ce 100644
--- a/mobile/lib/phone/voice_mic_action.dart
+++ b/mobile/lib/phone/voice_mic_action.dart
@@ -71,10 +71,10 @@ VoiceMicAction _tapAction(VoiceInputController voice, TerminalSession session) {
/// [VoiceInputController.startHold] and [VoiceInputController.finishHold] —
/// a start and a release that know about each other, rather than two calls
/// racing over a status neither of them owns.
-/// - **Words held from a failed send are sent by holding again.** The tap mode
-/// shows an arrow for that; here the retry rides along with the next take,
-/// because `submit` sends the whole transcript and a take that transcribes to
-/// nothing still carries what was held.
+/// - **Words held from a failed send go with the next press.** A quick tap on
+/// the retry face sends them as they are — a take too short to be speech is
+/// no failure, see [VoiceInputController.submit] — and a hold that says more
+/// sends them with what it adds.
VoiceMicAction _holdAction(
VoiceInputController voice,
TerminalSession session,
diff --git a/mobile/lib/shared/layouts/window_size.dart b/mobile/lib/shared/layouts/window_size.dart
deleted file mode 100644
index 33bb29101..000000000
--- a/mobile/lib/shared/layouts/window_size.dart
+++ /dev/null
@@ -1,49 +0,0 @@
-import 'package:flutter/widgets.dart';
-
-/// The width bands the shell branches on.
-///
-/// One definition, in one place, so "narrow" means the same number to every
-/// piece of chrome rather than each one inventing its own threshold.
-///
-/// These are WINDOW widths, not device classes. A desktop window dragged down
-/// to 500pt is [compact] for the same reason a phone is, and is laid out the
-/// same way — there is no separate mobile build to branch on, and a rule that
-/// asked "is this a phone?" would leave the narrow desktop window broken.
-///
-/// The lower edge is Material's 600. The upper one is this app's own: the pane
-/// grid's floor for a usable terminal tile is about 336pt (`_MinTile` in
-/// `widgets/pane_grid.dart`, 40 columns at the default font), and [expanded]
-/// is meant to mean "two of those side by side, with the chrome around them" —
-/// which 840 does not buy and 1024 does.
-enum WindowSizeClass {
- /// One thing at a time. Chrome that cannot earn its width collapses.
- compact,
-
- /// Everything is present, with less room around it.
- medium,
-
- /// The size the app is drawn for.
- expanded;
-
- /// First width that is no longer [compact].
- static const double compactMax = 600;
-
- /// First width that is [expanded].
- static const double mediumMax = 1024;
-
- static WindowSizeClass fromWidth(double width) => switch (width) {
- < compactMax => WindowSizeClass.compact,
- < mediumMax => WindowSizeClass.medium,
- _ => WindowSizeClass.expanded,
- };
-
- /// The class of the WINDOW.
- ///
- /// Prefer [fromWidth] with a `LayoutBuilder`'s own constraint for anything
- /// laid out narrower than the window: a strip inside a split should answer
- /// for the box it was given, not for the screen it happens to sit on.
- static WindowSizeClass of(BuildContext context) =>
- fromWidth(MediaQuery.sizeOf(context).width);
-
- bool get isCompact => this == WindowSizeClass.compact;
-}
diff --git a/mobile/lib/shared/widgets/app_icon_button.dart b/mobile/lib/shared/widgets/app_icon_button.dart
index d774bd42e..76e7a8731 100644
--- a/mobile/lib/shared/widgets/app_icon_button.dart
+++ b/mobile/lib/shared/widgets/app_icon_button.dart
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import '../theme/app_theme.dart';
+import 'touch_target.dart';
/// A small icon affordance that lifts under the pointer.
///
@@ -212,6 +213,12 @@ class _AppIconButtonState extends State<AppIconButton>
);
final tooltip = widget.tooltip;
- return tooltip == null ? button : Tooltip(message: tooltip, child: button);
+ // The 24pt box is what reads right as a glyph with a lift; a thumb needs
+ // 44 — see [TouchTarget].
+ return TouchTarget(
+ child: tooltip == null
+ ? button
+ : Tooltip(message: tooltip, child: button),
+ );
}
}
diff --git a/mobile/lib/shared/widgets/touch_target.dart b/mobile/lib/shared/widgets/touch_target.dart
new file mode 100644
index 000000000..65d40db06
--- /dev/null
+++ b/mobile/lib/shared/widgets/touch_target.dart
@@ -0,0 +1,50 @@
+import 'dart:math' as math;
+
+import 'package:flutter/rendering.dart';
+import 'package:flutter/widgets.dart';
+
+/// The smallest thing a thumb can reliably hit — Apple's 44pt.
+const double minTouchTarget = 44;
+
+/// Lets a small control be pressed across a [minTouchTarget] square around it
+/// while it takes, and draws in, only its own size.
+///
+/// ⚠️ **Hit area only, never layout.** Headers here are laid out from their
+/// controls' drawn sizes — the terminal page flies its buttons from positions
+/// computed off the 24pt box — so padding the control out to 44pt would move
+/// every row it sits in. This is what Material's padded tap target does,
+/// without the padding.
+///
+/// The reach stops at the parents' own bounds: a point outside the row a
+/// control sits in never reaches it to be tested.
+class TouchTarget extends SingleChildRenderObjectWidget {
+ const TouchTarget({super.key, required Widget super.child});
+
+ @override
+ RenderObject createRenderObject(BuildContext context) => _RenderTouchTarget();
+}
+
+class _RenderTouchTarget extends RenderProxyBox {
+ @override
+ bool hitTest(BoxHitTestResult result, {required Offset position}) {
+ if (super.hitTest(result, position: position)) return true;
+ final child = this.child;
+ if (child == null) return false;
+ final reachX = math.max(0.0, (minTouchTarget - size.width) / 2);
+ final reachY = math.max(0.0, (minTouchTarget - size.height) / 2);
+ final target = Rect.fromLTRB(
+ -reachX,
+ -reachY,
+ size.width + reachX,
+ size.height + reachY,
+ );
+ if (!target.contains(position)) return false;
+ // Handed to the child at its centre, so it answers as though pressed there.
+ final center = child.size.center(Offset.zero);
+ return result.addWithRawTransform(
+ transform: MatrixUtils.forceToPoint(center),
+ position: center,
+ hitTest: (result, position) => child.hitTest(result, position: center),
+ );
+ }
+}
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index fda425fb7..e931db02f 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -2575,68 +2575,85 @@ class AppNotifier extends ChangeNotifier {
onAuthFailure: _signedOutAtRuntime,
onLocalFailure: _onLocalFailure,
onEvent: _handleEvent,
- onStatus: (machineId, nextStatus) {
- final machine = machineStates[machineId];
- if (machine == null) return;
- machine.connectionStatus = nextStatus;
- if (nextStatus == ConnectionStatus.connected) {
- machine.needsLink = false;
- _stopLinkRetry(machineId);
- // A daemon that just came up — first connect, or a reconnect after it
- // restarted — has never been told what is on the grid. Without this
- // the dial goes back to beeping about tiles in plain sight until the
- // next time a pane happens to change.
- _announceOpenPanesToDial();
- // ...nor which tile this window is looking at. The daemon repeats that to the dial after every
- // list push, which is what keeps the two screens from drifting apart — but it can only repeat
- // something it has been told, and until now the first telling waited for the focus to CHANGE.
- // A daemon restarted mid-session therefore had nothing to say, and a dial that re-anchored onto
- // the wrong tile stayed there.
- _announceAppFocus();
- // The local CLI never hands back `connected` until it has terminated E2EE (or confirmed
- // none is needed, for its own machine) — every machine's data is ready to load right away,
- // with no separate app-side readiness gate to wait on anymore.
- if (machine.isLocalMachine) {
- machine.transportMode = MachineTransportMode.localPlaintext;
- } else {
- machine.transportMode = MachineTransportMode.cloudE2ee;
- }
- // Route through _applyNodeStatus (not just `machine.nodeOnline = true`) for every machine,
- // not only the local one — a successful select IS the machine being reachable again, and
- // this is what lets a pending agent (captured below on disconnect) reattach automatically
- // instead of leaving the user stuck on the empty "select a machine" placeholder.
- unawaited(_applyNodeStatus(machine, true));
- unawaited(_loadMachineData(machine, force: true));
- _startAgentSyncTimer(machineId);
- } else if (nextStatus == ConnectionStatus.reconnecting ||
- nextStatus == ConnectionStatus.disconnected) {
- _stopAgentSyncTimer(machineId);
- _clearMachineActivity(machine);
- if (machine.isLocalMachine) {
- machine.transportMode = MachineTransportMode.localOffline;
- }
- // Same reasoning as above, mirrored: capture pendingOfflineAgentId from the currently-open
- // terminal (if any) so the connected branch above can reattach it, for every machine — this
- // used to be local-only, which is why a remote machine's terminal never came back on its own
- // after `harness start` on that machine, even though the guide screen promised it would.
- //
- // NOT while the machine is unlinked. NO_PEER_LINK is the local CLI failing a lookup in its
- // own peer table (remoteRelay.ts `dial`) before anything is dialled, so neither that close
- // nor the one `_startLinkRetry`'s `closeMachine` fires every few seconds says anything about
- // whether the OTHER computer is up — our socket never reaches it. Forcing nodeOnline false
- // here overwrote the REST `/api/machines` status, the one signal that does, and painted
- // every unlinked machine as off. Keyed on the sticky flag rather than the 4404 close on
- // purpose: the retry loop's own close() lands as a plain `disconnected` too. needsLink is
- // set by onLocalFailure, which runs before this branch for 4404 (see WsConn._onDone).
- if (!machine.needsLink) {
- unawaited(_applyNodeStatus(machine, false));
- }
- }
- notifyListeners();
- },
+ onStatus: _onConnectionStatus,
);
}
+ /// What a machine's socket coming up, dropping or re-dialling does to the model.
+ void _onConnectionStatus(String machineId, ConnectionStatus nextStatus) {
+ final machine = machineStates[machineId];
+ if (machine == null) return;
+ machine.connectionStatus = nextStatus;
+ if (nextStatus == ConnectionStatus.connected) {
+ machine.needsLink = false;
+ _stopLinkRetry(machineId);
+ // A daemon that just came up — first connect, or a reconnect after it
+ // restarted — has never been told what is on the grid. Without this
+ // the dial goes back to beeping about tiles in plain sight until the
+ // next time a pane happens to change.
+ _announceOpenPanesToDial();
+ // ...nor which tile this window is looking at. The daemon repeats that to the dial after every
+ // list push, which is what keeps the two screens from drifting apart — but it can only repeat
+ // something it has been told, and until now the first telling waited for the focus to CHANGE.
+ // A daemon restarted mid-session therefore had nothing to say, and a dial that re-anchored onto
+ // the wrong tile stayed there.
+ _announceAppFocus();
+ // The local CLI never hands back `connected` until it has terminated E2EE (or confirmed
+ // none is needed, for its own machine) — every machine's data is ready to load right away,
+ // with no separate app-side readiness gate to wait on anymore.
+ if (machine.isLocalMachine) {
+ machine.transportMode = MachineTransportMode.localPlaintext;
+ } else {
+ machine.transportMode = MachineTransportMode.cloudE2ee;
+ }
+ // Route through _applyNodeStatus (not just `machine.nodeOnline = true`) for every machine,
+ // not only the local one — a successful select IS the machine being reachable again, and
+ // this is what lets a pending agent (captured below on disconnect) reattach automatically
+ // instead of leaving the user stuck on the empty "select a machine" placeholder.
+ unawaited(_applyNodeStatus(machine, true));
+ unawaited(_loadMachineData(machine, force: true));
+ _startAgentSyncTimer(machineId);
+ } else if (nextStatus == ConnectionStatus.reconnecting ||
+ nextStatus == ConnectionStatus.disconnected) {
+ _stopAgentSyncTimer(machineId);
+ _clearMachineActivity(machine);
+ if (machine.isLocalMachine) {
+ machine.transportMode = MachineTransportMode.localOffline;
+ }
+ // Same reasoning as above, mirrored: capture pendingOfflineAgentId from the currently-open
+ // terminal (if any) so the connected branch above can reattach it, for every machine — this
+ // used to be local-only, which is why a remote machine's terminal never came back on its own
+ // after `harness start` on that machine, even though the guide screen promised it would.
+ //
+ // NOT while the machine is unlinked. NO_PEER_LINK is the local CLI failing a lookup in its
+ // own peer table (remoteRelay.ts `dial`) before anything is dialled, so neither that close
+ // nor the one `_startLinkRetry`'s `closeMachine` fires every few seconds says anything about
+ // whether the OTHER computer is up — our socket never reaches it. Forcing nodeOnline false
+ // here overwrote the REST `/api/machines` status, the one signal that does, and painted
+ // every unlinked machine as off. Keyed on the sticky flag rather than the 4404 close on
+ // purpose: the retry loop's own close() lands as a plain `disconnected` too. needsLink is
+ // set by onLocalFailure, which runs before this branch for 4404 (see WsConn._onDone).
+ //
+ // ⚠️ Nor from a viewer. Its socket is the phone's own line to the relay — backgrounding the
+ // app drops it, and so does a tunnel — and losing it says nothing about the machine at the
+ // other end, which `node_status`, `/api/machines` and a timed-out request still report. Read
+ // as offline, every return to the app flashed "Offline" and threw the pager away. The
+ // streams on it are dead all the same: told so, and put back once the socket is.
+ if (!machine.needsLink) {
+ if (viewer == null) {
+ unawaited(_applyNodeStatus(machine, false));
+ } else {
+ _markSessionsUnreachable(machine, 'Connection lost. Reconnecting…');
+ }
+ }
+ }
+ notifyListeners();
+ }
+
+ @visibleForTesting
+ void connectionStatusForTest(String machineId, ConnectionStatus status) =>
+ _onConnectionStatus(machineId, status);
+
/// The machine list is being fetched and there is nothing to show meanwhile.
///
/// Only the FIRST fetch sets it: a refresh over a list already on screen
diff --git a/mobile/lib/state/attention.dart b/mobile/lib/state/attention.dart
deleted file mode 100644
index 2627b5c74..000000000
--- a/mobile/lib/state/attention.dart
+++ /dev/null
@@ -1,106 +0,0 @@
-import 'package:harness_mobile/phone/agent_index.dart';
-import 'package:harness_mobile/state/app_state.dart';
-import 'package:harness_mobile/state/pending_question.dart';
-
-/// One agent that has stopped to ask the person something, together with everything needed to
-/// draw it and to open it.
-///
-/// The desktop's equivalent (`state/swarm_attention.dart`) is built out of `SwarmDestination`s,
-/// because there a selection has to decide WHICH pane of WHICH swarm the agent lands in. A phone
-/// has neither: one tap, one full-screen terminal. So this carries the agent itself instead, and
-/// the whole destination/ranking half of the desktop file is dropped rather than ported into a
-/// shape nothing here would read.
-class AttentionEntry {
- const AttentionEntry({required this.agent, required this.question});
-
- /// The agent and its machine, from the same [agentIndex] the Agents tab and the tab badge are
- /// built from — so a row here cannot exist for an agent the list refuses to draw.
- final AgentEntry agent;
-
- /// What it is asking, when the question is still on screen at the other end.
- ///
- /// ⚠️ Nullable on purpose, and not the same thing as "no question". `blockedAgents` is what marks
- /// an agent as waiting in the first place, so in practice this is set — but the entry is built
- /// from the agent index rather than from the question map, and a row that vanished because its
- /// prompt text was momentarily unavailable would be worse than one drawn without its prompt.
- final PendingQuestion? question;
-
- String get machineId => agent.machineId;
- String get machineName => agent.machineName;
- String get agentId => agent.agent.id;
-
- /// Stable across rebuilds — a machine and an agent, the pair the app keys everything else on.
- String get id => '$machineId/$agentId';
-
- /// The question as a row prints it: one line, whitespace collapsed.
- ///
- /// A prompt arrives as whatever the pane held, newlines and runs of spaces included, and a
- /// `maxLines: 2` `Text` of that draws a mostly-empty box. Collapsing here rather than in the
- /// widget keeps the trimming with the data, the way the desktop keeps its search fields.
- String? get promptLine {
- final prompt = question?.prompt.replaceAll(RegExp(r'\s+'), ' ').trim();
- return prompt == null || prompt.isEmpty ? null : prompt;
- }
-}
-
-/// Every agent waiting on an answer, oldest question first.
-///
-/// Ordered by [PendingQuestion.since] like the desktop's picker, for the same reason: the one that
-/// has been waiting longest is the one holding work up. Ties — and an agent whose question is not
-/// in the map — fall back to [AttentionEntry.id] so the list cannot reshuffle itself under a
-/// finger already reaching for a row.
-List<AttentionEntry> attentionEntries(AppNotifier notifier) {
- final entries = [
- for (final agent in waitingAgents(agentIndex(notifier)))
- AttentionEntry(
- agent: agent,
- question: notifier.questionFor(agent.machineId, agent.agent.id),
- ),
- ];
- entries.sort((a, b) {
- final aSince = a.question?.since;
- final bSince = b.question?.since;
- if (aSince != null && bSince != null) {
- final age = aSince.compareTo(bSince);
- if (age != 0) return age;
- } else if (aSince != bSince) {
- // An entry with no question sorts last: it is the one we know least about.
- return aSince == null ? 1 : -1;
- }
- return a.id.compareTo(b.id);
- });
- return entries;
-}
-
-/// The same entries, grouped by machine and keeping the order above within each group.
-///
-/// The machines themselves are ordered by their most urgent entry — the first one [attentionEntries]
-/// produced for them — so a machine whose agent has waited longest heads the page. Anything else
-/// (account order, alphabetical) would bury the row the page exists to surface.
-List<AttentionGroup> attentionGroups(List<AttentionEntry> entries) {
- final byMachine = <String, List<AttentionEntry>>{};
- for (final entry in entries) {
- (byMachine[entry.machineId] ??= []).add(entry);
- }
- return [
- for (final rows in byMachine.values)
- AttentionGroup(
- machineId: rows.first.machineId,
- machineName: rows.first.machineName,
- entries: List.unmodifiable(rows),
- ),
- ];
-}
-
-/// One machine's worth of waiting agents.
-class AttentionGroup {
- const AttentionGroup({
- required this.machineId,
- required this.machineName,
- required this.entries,
- });
-
- final String machineId;
- final String machineName;
- final List<AttentionEntry> entries;
-}
diff --git a/mobile/lib/terminal/terminal_session.dart b/mobile/lib/terminal/terminal_session.dart
index a29e38623..55193c8f6 100644
--- a/mobile/lib/terminal/terminal_session.dart
+++ b/mobile/lib/terminal/terminal_session.dart
@@ -11,6 +11,7 @@ import 'control_chord.dart';
import 'terminal_binary.dart';
import 'terminal_input.dart';
import 'terminal_viewport.dart';
+import 'utf8_chunks.dart';
typedef TerminalFrameSender = Future<bool> Function(
String type,
@@ -567,7 +568,7 @@ class TerminalSession extends ChangeNotifier {
}
// Publish a complete screen atomically. A damaged snapshot must
// leave the retained screen available while resync recovers.
- final decoded = _decodeUtf8(_prepareKeyframeBytes(bytes));
+ final decoded = decodeUtf8Chunk(_prepareKeyframeBytes(bytes));
final replacement = _newTerminal(bindCallbacks: false)
..resize(_clampCols(nextCols), _clampRows(nextRows))
..write(decoded.text);
@@ -714,43 +715,12 @@ class TerminalSession extends ChangeNotifier {
// Most packets end on a scalar boundary. Decode their existing byte view
// directly; only a split UTF-8 scalar needs a joined buffer.
final combined = _utf8Tail.isEmpty ? bytes : <int>[..._utf8Tail, ...bytes];
- final decoded = _decodeUtf8(combined);
+ final decoded = decodeUtf8Chunk(combined);
if (decoded.text.isNotEmpty) _writeTerminalText(decoded.text);
_utf8Tail = decoded.tail;
return true;
}
- ({String text, List<int> tail}) _decodeUtf8(List<int> combined) {
- for (
- var tailLength = 0;
- tailLength <= min(3, combined.length);
- tailLength++
- ) {
- try {
- final text = utf8.decoder.convert(
- combined,
- 0,
- combined.length - tailLength,
- );
- return (
- text: text,
- tail: tailLength == 0
- ? const []
- : combined.sublist(combined.length - tailLength),
- );
- } on FormatException {
- // A UTF-8 scalar can span at most four bytes; retain only a trailing
- // partial scalar before falling back to replacement rendering below.
- }
- }
- // PTY output is byte-oriented. A snapshot cut can rarely land between the
- // leading and continuation bytes of a scalar, leaving a continuation byte
- // at the start of the post-cut frame. Real terminals render malformed UTF-8
- // as U+FFFD; resyncing the entire screen creates a second keyframe race and
- // cannot recover the missing pre-cut byte anyway.
- return (text: utf8.decode(combined, allowMalformed: true), tail: const []);
- }
-
List<int> _prepareKeyframeBytes(Uint8List bytes) {
if (engineId != 'grok') return bytes;
diff --git a/mobile/lib/terminal/utf8_chunks.dart b/mobile/lib/terminal/utf8_chunks.dart
new file mode 100644
index 000000000..6a6e2906e
--- /dev/null
+++ b/mobile/lib/terminal/utf8_chunks.dart
@@ -0,0 +1,44 @@
+import 'dart:convert';
+
+const _lenient = Utf8Decoder(allowMalformed: true);
+
+/// One chunk of pty output as text, and the bytes at its end that begin a
+/// character the next chunk finishes.
+///
+/// ⚠️ **The split is found by reading the last three bytes, not by decoding
+/// and retrying.** A chunk cut mid-character is ordinary — every ⏺, box rule
+/// and accented Vietnamese letter a TUI draws is two to four bytes — and the
+/// old way decoded the whole chunk up to four times over, throwing and
+/// catching a `FormatException` on each miss, on the UI thread.
+///
+/// Malformed bytes anywhere else render as U+FFFD, as a real terminal renders
+/// them: a snapshot cut can land inside a character, and resyncing the whole
+/// screen cannot recover the byte that was cut off anyway.
+({String text, List<int> tail}) decodeUtf8Chunk(List<int> bytes) {
+ final end = bytes.length - _unfinishedTail(bytes);
+ return (
+ text: _lenient.convert(bytes, 0, end),
+ tail: end == bytes.length ? const [] : bytes.sublist(end),
+ );
+}
+
+/// How many bytes at the end of [bytes] begin a character not yet complete.
+int _unfinishedTail(List<int> bytes) {
+ // A character is at most four bytes, so its lead byte is at most three back
+ // from the last one.
+ for (var back = 1; back <= 4 && back <= bytes.length; back++) {
+ final byte = bytes[bytes.length - back];
+ if (byte & 0xC0 == 0x80) continue; // A continuation byte: keep looking.
+ final length = byte >= 0xF0
+ ? 4
+ : byte >= 0xE0
+ ? 3
+ : byte >= 0xC0
+ ? 2
+ : 1;
+ return length > back ? back : 0;
+ }
+ // Only continuation bytes: nothing leads them, so there is nothing to wait
+ // for — they are malformed, and render as such.
+ return 0;
+}
diff --git a/mobile/lib/ws/ws_conn.dart b/mobile/lib/ws/ws_conn.dart
index 34b9e5623..d712b01a6 100644
--- a/mobile/lib/ws/ws_conn.dart
+++ b/mobile/lib/ws/ws_conn.dart
@@ -300,7 +300,9 @@ class WsConn {
void _onRaw(dynamic raw) {
final codec = _codec;
if (raw is List<int>) {
- final bytes = Uint8List.fromList(raw);
+ // The socket already hands over a Uint8List; copying it cost one allocation per chunk of
+ // terminal output, for nothing.
+ final bytes = raw is Uint8List ? raw : Uint8List.fromList(raw);
_inboundTail = _inboundTail
.then((_) async {
final local = codec == null ? bytes : codec.decodeBinary(bytes);
diff --git a/mobile/test/machines_load_failure_test.dart b/mobile/test/machines_load_failure_test.dart
new file mode 100644
index 000000000..8aa0d1d29
--- /dev/null
+++ b/mobile/test/machines_load_failure_test.dart
@@ -0,0 +1,45 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/phone/machines_tab.dart';
+import 'package:harness_mobile/state/app_state.dart';
+
+/// An account whose machines cannot be fetched — the relay down, the phone offline.
+class _Unreachable extends AppNotifier {
+ _Unreachable()
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ );
+
+ int attempts = 0;
+
+ @override
+ Future<void> ensureCliDaemonReady() async {
+ attempts++;
+ throw StateError('The network connection was lost.');
+ }
+}
+
+void main() {
+ testWidgets('machines that could not load say so, and offer another go', (
+ tester,
+ ) async {
+ final app = _Unreachable();
+ addTearDown(app.dispose);
+ await app.retryMachines();
+ await tester.pumpWidget(MaterialApp(home: MachinesTab(notifier: app)));
+
+ // Not "No machines yet": that tells somebody with three machines to go and
+ // set one up.
+ expect(find.text('No machines yet'), findsNothing);
+ expect(find.text("Couldn't load your machines"), findsOneWidget);
+
+ await tester.tap(find.text('Try again'));
+ await tester.pump();
+
+ expect(app.attempts, 2);
+ });
+}
diff --git a/mobile/test/phone_new_agent_test.dart b/mobile/test/phone_new_agent_test.dart
index 53681869e..1c9f36485 100644
--- a/mobile/test/phone_new_agent_test.dart
+++ b/mobile/test/phone_new_agent_test.dart
@@ -3,7 +3,6 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/auth/auth_session.dart';
import 'package:harness_mobile/core/config.dart';
import 'package:harness_mobile/core/models.dart';
-import 'package:harness_mobile/phone/agents_tab.dart';
import 'package:harness_mobile/phone/new_agent_page.dart';
import 'package:harness_mobile/state/app_state.dart';
import 'package:harness_mobile/ws/ws_conn.dart';
@@ -33,7 +32,7 @@ class _Conn extends WsConn {
///
/// The second is the whole point of the picker's filter: an agent cannot be created on a machine
/// that has not listed its folders or named its engines, so it must not be offered as a host.
-AppNotifier _app({required bool anyReady}) {
+AppNotifier _app() {
final app = AppNotifier(
config: AppConfig.dev,
authSession: AuthSession(),
@@ -53,7 +52,7 @@ AppNotifier _app({required bool anyReady}) {
);
app.machines = [ready, sleeping];
app.machineStates['ready'] = MachineState(ready)
- ..nodeOnline = anyReady
+ ..nodeOnline = true
..connectionStatus = ConnectionStatus.connected
..agentLoadStatus = AgentLoadStatus.loaded;
// Harness is not running there: offline, whatever the socket says.
@@ -64,48 +63,27 @@ AppNotifier _app({required bool anyReady}) {
return app;
}
-Future<void> _pump(WidgetTester tester, AppNotifier app) async {
- await tester.pumpWidget(MaterialApp(home: AgentsTab(notifier: app)));
- await tester.pumpAndSettle();
-}
-
void main() {
- testWidgets(
- 'the + opens the form on the first machine answering, and offers no other',
- (tester) async {
- final app = _app(anyReady: true);
- addTearDown(app.dispose);
- await _pump(tester, app);
-
- await tester.tap(find.byType(FloatingActionButton));
- await tester.pump();
- await tester.pump(const Duration(milliseconds: 600));
-
- // ⚠️ Scoped to the form. Both machines also name themselves in the
- // filter bar behind it, so an unscoped finder sees every machine twice
- // and reads the offline one as offered when it is not.
- Finder inForm(String text) => find.descendant(
- of: find.byType(NewAgentPage),
- matching: find.text(text),
- );
-
- expect(inForm('Studio'), findsOneWidget);
- expect(
- inForm('Laptop'),
- findsNothing,
- reason: 'an offline machine cannot host a new agent',
- );
- },
- );
-
- testWidgets('no + at all while nothing can host an agent', (tester) async {
- final app = _app(anyReady: false);
+ testWidgets('the form offers only machines that can host an agent', (
+ tester,
+ ) async {
+ final app = _app();
addTearDown(app.dispose);
- await _pump(tester, app);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: NewAgentPage(notifier: app, machineId: 'ready'),
+ ),
+ );
+ await tester.pumpAndSettle();
+ // The machine row unfolds into the others there are to choose from.
+ await tester.tap(find.text('Studio'));
+ await tester.pumpAndSettle();
- // Absent, not disabled: the empty state already says to open the Machines
- // tab, and a button whose only outcome is that same explanation is worse
- // than no button.
- expect(find.byType(FloatingActionButton), findsNothing);
+ expect(find.text('Studio'), findsOneWidget);
+ expect(
+ find.text('Laptop'),
+ findsNothing,
+ reason: 'an offline machine cannot host a new agent',
+ );
});
}
diff --git a/mobile/test/phone_socket_drop_test.dart b/mobile/test/phone_socket_drop_test.dart
new file mode 100644
index 000000000..d9630a7f7
--- /dev/null
+++ b/mobile/test/phone_socket_drop_test.dart
@@ -0,0 +1,52 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/phone/agent_index.dart';
+import 'package:harness_mobile/phone/phone_status.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/terminal/terminal_session.dart';
+
+import 'agent_pager_fixture.dart';
+
+/// The phone's socket to the relay drops every time the app is backgrounded. That is the phone's
+/// line going, not the machine — and the screen must read it that way.
+void main() {
+ test('a viewer keeps the machine online and its agents on screen', () {
+ final app = pagerApp(PagerConn(), viewer: true);
+ addTearDown(app.dispose);
+ final session = liveAgent(app, 'b');
+
+ app.connectionStatusForTest('m', ConnectionStatus.reconnecting);
+
+ final machine = app.stateOf('m')!;
+ expect(machine.nodeOnline, isTrue, reason: 'not "Offline"');
+ expect(phoneMachineStatusOf(machine), PhoneMachineStatus.connecting);
+ expect(
+ agentIndex(app),
+ hasLength(pagerAgentIds.length),
+ reason: 'the pager is built from this list',
+ );
+ // Its stream went with the socket, and is put back once the socket is.
+ expect(session.status, TerminalSessionStatus.error);
+ expect(machine.pendingOfflineAgentId, 'b');
+ });
+
+ test('a desktop still reads its CLI socket dropping as offline', () {
+ final app = pagerApp(PagerConn());
+ addTearDown(app.dispose);
+ liveAgent(app, 'b');
+
+ app.connectionStatusForTest('m', ConnectionStatus.reconnecting);
+
+ expect(app.stateOf('m')!.nodeOnline, isFalse);
+ });
+
+ test('a machine that has never answered lists nothing yet', () {
+ final app = pagerApp(PagerConn(), viewer: true);
+ addTearDown(app.dispose);
+ app.stateOf('m')!
+ ..connectionStatus = ConnectionStatus.connecting
+ ..agentLoadStatus = AgentLoadStatus.idle;
+
+ expect(agentIndex(app), isEmpty);
+ });
+}
diff --git a/mobile/test/touch_target_test.dart b/mobile/test/touch_target_test.dart
new file mode 100644
index 000000000..b72777d28
--- /dev/null
+++ b/mobile/test/touch_target_test.dart
@@ -0,0 +1,57 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/shared/widgets/app_icon_button.dart';
+import 'package:harness_mobile/shared/widgets/touch_target.dart';
+
+/// A glyph drawn small is still pressed with a thumb.
+void main() {
+ Future<int Function()> pumpButton(WidgetTester tester) async {
+ var presses = 0;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Center(
+ child: SizedBox(
+ height: 60,
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ AppIconButton(icon: Icons.search, onPressed: () => presses++),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ return () => presses;
+ }
+
+ testWidgets('a tap just outside the drawn button still presses it', (
+ tester,
+ ) async {
+ final presses = await pumpButton(tester);
+ final center = tester.getCenter(find.byType(AppIconButton));
+
+ // 18pt off centre: outside the 24pt box, inside a 44pt target.
+ await tester.tapAt(center + const Offset(0, 18));
+ await tester.tapAt(center - const Offset(0, 18));
+
+ expect(presses(), 2);
+ });
+
+ testWidgets('the button takes no more room than it draws', (tester) async {
+ await pumpButton(tester);
+
+ expect(tester.getSize(find.byType(AppIconButton)), const Size(24, 24));
+ });
+
+ testWidgets('a tap past the target is not the button\'s', (tester) async {
+ final presses = await pumpButton(tester);
+ final center = tester.getCenter(find.byType(AppIconButton));
+
+ await tester.tapAt(center + const Offset(0, minTouchTarget / 2 + 4));
+
+ expect(presses(), 0);
+ });
+}
diff --git a/mobile/test/utf8_chunks_test.dart b/mobile/test/utf8_chunks_test.dart
new file mode 100644
index 000000000..f5d5ddd4e
--- /dev/null
+++ b/mobile/test/utf8_chunks_test.dart
@@ -0,0 +1,48 @@
+import 'dart:convert';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/terminal/utf8_chunks.dart';
+
+/// pty output arrives in chunks cut wherever the socket cut them — mid-character
+/// as often as not, for the glyphs a TUI draws.
+void main() {
+ /// [text] delivered in two chunks cut at every byte, reassembled the way the
+ /// session does it.
+ List<String> everyCut(String text) {
+ final bytes = utf8.encode(text);
+ return [
+ for (var cut = 0; cut <= bytes.length; cut++)
+ () {
+ final first = decodeUtf8Chunk(bytes.sublist(0, cut));
+ final second = decodeUtf8Chunk([
+ ...first.tail,
+ ...bytes.sublist(cut),
+ ]);
+ expect(second.tail, isEmpty);
+ return first.text + second.text;
+ }(),
+ ];
+ }
+
+ test('a character cut anywhere comes out whole', () {
+ for (final text in ['⏺ Done', 'Hôm nay là thứ mấy?', '─┬─', 'ship 🚀 it']) {
+ expect(everyCut(text), everyElement(text), reason: text);
+ }
+ });
+
+ test('a chunk that ends on a whole character keeps nothing back', () {
+ final decoded = decodeUtf8Chunk(utf8.encode('plain ascii ⏺'));
+
+ expect(decoded.text, 'plain ascii ⏺');
+ expect(decoded.tail, isEmpty);
+ });
+
+ test('bytes that lead nowhere render as U+FFFD, and the rest survives', () {
+ // A continuation byte with nothing before it — a snapshot cut — then text,
+ // then the first byte of a character still to come.
+ final decoded = decodeUtf8Chunk([0x8F, ...utf8.encode('ok'), 0xE2]);
+
+ expect(decoded.text, '�ok');
+ expect(decoded.tail, [0xE2]);
+ });
+}
diff --git a/mobile/test/voice_input_controller_test.dart b/mobile/test/voice_input_controller_test.dart
index 39cb0b426..46a952e1e 100644
--- a/mobile/test/voice_input_controller_test.dart
+++ b/mobile/test/voice_input_controller_test.dart
@@ -213,6 +213,65 @@ void main() {
expect(voice.isSending, isFalse);
});
+ group('the retry face, held to talk', () {
+ Future<void> failOneSend() async {
+ backend.replies.add('deploy');
+ await voice.startListening();
+ await voice.stopListening();
+ await voice.submit((_) async => false);
+ }
+
+ test('a quick tap sends the words held from the failed send', () async {
+ await failOneSend();
+ final delivered = <String>[];
+ recorder.captured = (
+ wav: Uint8List.fromList([1, 2, 3, 4]),
+ length: const Duration(milliseconds: 120),
+ peak: 0,
+ );
+
+ await voice.startHold((text) async {
+ delivered.add(text);
+ return true;
+ });
+ await voice.finishHold((text) async {
+ delivered.add(text);
+ return true;
+ });
+
+ expect(delivered, ['deploy']);
+ expect(voice.isIdle, isTrue);
+ expect(backend.calls, hasLength(1), reason: 'a tap is not uploaded');
+ });
+
+ test('a take that failed still sends none of the message', () async {
+ await failOneSend();
+ backend.fails = true;
+ var delivered = false;
+
+ await voice.startHold((_) async => delivered = true);
+ await voice.finishHold((_) async => delivered = true);
+
+ expect(delivered, isFalse, reason: 'what was just said is missing');
+ expect(voice.transcript, 'deploy');
+ });
+
+ test('a quick tap with nothing held sends nothing', () async {
+ recorder.captured = (
+ wav: Uint8List.fromList([1, 2, 3, 4]),
+ length: const Duration(milliseconds: 120),
+ peak: 0,
+ );
+ var delivered = false;
+
+ await voice.startHold((_) async => delivered = true);
+ await voice.finishHold((_) async => delivered = true);
+
+ expect(delivered, isFalse);
+ expect(voice.notice, isNull, reason: 'a brushed button is not reported');
+ });
+ });
+
test('clearing mid-transcription drops the words when they arrive', () async {
backend.pending = Completer<String>();
await voice.startListening();