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.

feat(mobile): tabs are made and filled from the phone's own tabs panel

bubu-dudu47cfeff69615
diff --git a/mobile/lib/phone/desk_add_agent_sheet.dart b/mobile/lib/phone/desk_add_agent_sheet.dart
new file mode 100644
index 000000000..a4bde2a15
--- /dev/null
+++ b/mobile/lib/phone/desk_add_agent_sheet.dart
@@ -0,0 +1,194 @@
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+
+import 'agent_index.dart';
+import 'agent_tile.dart';
+import 'phone_card.dart';
+
+/// What joins a tab: an agent the account already has, or one made now.
+///
+/// ```
+/// ──────────────────────────────────
+/// Add to “harness mobile”
+/// ┌────────────────────────────┐
+/// │ + New agent │
+/// └────────────────────────────┘
+/// ┌────────────────────────────┐
+/// │ ◆ api-3 Live › │
+/// └────────────────────────────┘
+/// ```
+///
+/// ⚠️ **The agents come first and "New agent" sits above them, rather than the
+/// two being a choice made before either is seen.** Both `+`s on the tabs panel
+/// land here, and in both cases the common move is to put something that is
+/// already running somewhere else — a person who wants a NEW agent is one tap
+/// from the form they would have opened anyway, and one who wants an existing
+/// one is looking at it.
+///
+/// [choices] is what this sheet may offer: for a tab, the agents it does not
+/// already hold. An empty list is drawn as a sentence rather than as a hole —
+/// an account whose every agent is already in the tab has nothing to pick, and
+/// the "New agent" row above still works.
+///
+/// [onCreate] is null where no machine can host one (all asleep, or wanting a
+/// password), which leaves that row out rather than drawn dead.
+Future<void> showDeskAddAgentSheet(
+ BuildContext context, {
+ required String title,
+ required List<AgentEntry> choices,
+ required void Function(AgentEntry entry) onPick,
+ required VoidCallback? onCreate,
+}) => showModalBottomSheet<void>(
+ context: context,
+ useRootNavigator: true,
+ showDragHandle: true,
+ backgroundColor: AppPalette.panelBg,
+ isScrollControlled: true,
+ builder: (sheetContext) => _AddAgentSheet(
+ title: title,
+ choices: choices,
+ // Closed first, then acted on — the same order every row in the tabs panel
+ // takes, so a terminal this opens never arrives under a sheet still on its
+ // way out.
+ onPick: (entry) {
+ Navigator.of(sheetContext).pop();
+ onPick(entry);
+ },
+ onCreate: onCreate == null
+ ? null
+ : () {
+ Navigator.of(sheetContext).pop();
+ onCreate();
+ },
+ ),
+);
+
+/// The rows' side inset: [phoneListPadding]'s 16, the measure the tabs panel
+/// gives its own rows.
+const double _sideInset = 16;
+
+class _AddAgentSheet extends StatelessWidget {
+ const _AddAgentSheet({
+ required this.title,
+ required this.choices,
+ required this.onPick,
+ required this.onCreate,
+ });
+
+ final String title;
+ final List<AgentEntry> choices;
+ final void Function(AgentEntry entry) onPick;
+ final VoidCallback? onCreate;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final onCreate = this.onCreate;
+ return SafeArea(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(_sideInset, 2, _sideInset, 12),
+ child: Text(
+ title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ color: AppPalette.textPrimary,
+ fontSize: 17,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ ),
+ // The same half-screen the tabs panel keeps, for the same reason: the
+ // sheet must not stand up and sit down as one account's three agents
+ // give way to another's dozen.
+ SizedBox(
+ height: MediaQuery.sizeOf(context).height * 0.5,
+ child: ListView.separated(
+ padding: EdgeInsets.fromLTRB(
+ _sideInset,
+ 0,
+ _sideInset,
+ MediaQuery.paddingOf(context).bottom + 8,
+ ),
+ itemCount: choices.length + (onCreate == null ? 0 : 1),
+ separatorBuilder: (context, index) =>
+ const SizedBox(height: kPhoneCardGap),
+ itemBuilder: (context, index) {
+ if (onCreate != null && index == 0) {
+ return _NewAgentRow(onTap: onCreate);
+ }
+ final entry = choices[index - (onCreate == null ? 0 : 1)];
+ return AgentTile(
+ machine: entry.machine,
+ agent: entry.agent,
+ onTap: () => onPick(entry),
+ );
+ },
+ ),
+ ),
+ if (choices.isEmpty)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(_sideInset, 0, _sideInset, 8),
+ child: Text(
+ 'Every agent this phone can open is already here.',
+ style: TextStyle(
+ color: AppPalette.textSecondary,
+ fontSize: 13.5,
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+/// "New agent", drawn as a card the same height as the agents under it so the
+/// list reads as one column of things that can be put in a tab.
+class _NewAgentRow extends StatelessWidget {
+ const _NewAgentRow({required this.onTap});
+
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ return PhoneCard(
+ height: kPhoneAgentCardHeight,
+ onTap: onTap,
+ child: Row(
+ children: [
+ PhoneCardGlyph(
+ child: Icon(
+ LucideIcons.plus300,
+ size: 22,
+ color: AppPalette.accentOnSurface,
+ ),
+ ),
+ const SizedBox(width: 14),
+ Expanded(
+ child: Text(
+ 'New agent',
+ style: TextStyle(
+ color: AppPalette.textPrimary,
+ fontSize: 15.5,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ ),
+ Icon(
+ LucideIcons.chevronRight300,
+ size: 18,
+ color: AppPalette.textFaint,
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/desk_tab_strip.dart b/mobile/lib/phone/desk_tab_strip.dart
index 84f492a13..a1c311ce8 100644
--- a/mobile/lib/phone/desk_tab_strip.dart
+++ b/mobile/lib/phone/desk_tab_strip.dart
@@ -1,5 +1,8 @@
+import 'dart:async';
+
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
@@ -21,12 +24,19 @@ import 'desk_groups.dart';
/// from the row would read as a tab somebody deleted, and refusing the tap would
/// leave the person tapping a name that never answers — picked, it says what is
/// wrong in the space below, where there is room for the sentence.
-class DeskTabStrip extends StatelessWidget {
+///
+/// ⚠️ **It scrolls, and the tab being shown is scrolled TO.** A desk of a dozen
+/// tabs is wider than a phone, and the one you are in is as likely to be the
+/// tenth as the first — opened at the left-hand end, the panel would say
+/// nothing about where you are until a thumb went looking. See
+/// [_DeskTabStripState._reveal].
+class DeskTabStrip extends StatefulWidget {
const DeskTabStrip({
super.key,
required this.groups,
required this.selectedId,
required this.onPick,
+ this.onAddTab,
});
/// Every tab, in the desk's own order, with the leftover group last — see
@@ -39,6 +49,11 @@ class DeskTabStrip extends StatelessWidget {
final void Function(DeskGroup group) onPick;
+ /// A tab of its own for an agent picked or made now. Null leaves the `+`
+ /// undrawn — a desk that cannot be written to has nothing for it to do; see
+ /// [AppNotifier.deskWritable].
+ final VoidCallback? onAddTab;
+
/// The row's height, which the popup counts into its own.
///
/// One 15pt line, the bar under it, and the air that keeps the names off the
@@ -53,28 +68,146 @@ class DeskTabStrip extends StatelessWidget {
/// — read as two, narrow enough that four fit on a phone without scrolling.
static const double _gap = 22;
+ @override
+ State<DeskTabStrip> createState() => _DeskTabStripState();
+}
+
+class _DeskTabStripState extends State<DeskTabStrip> {
+ /// Rides whichever name is the selected one, so the row can be scrolled to
+ /// it without knowing how wide any of the others are — names keep their own
+ /// widths here, so there is no index-times-extent to jump to.
+ final _selected = GlobalKey();
+
+ @override
+ void initState() {
+ super.initState();
+ // The panel is on its way up as this runs: no animation, because there is
+ // nothing yet for a scroll to be seen moving against.
+ WidgetsBinding.instance.addPostFrameCallback((_) => _reveal(Duration.zero));
+ }
+
+ @override
+ void didUpdateWidget(DeskTabStrip old) {
+ super.didUpdateWidget(old);
+ // A tab picked by hand is already under the thumb; this is for the ones
+ // picked by something else — a tab made by the `+`, which lands at the far
+ // right of a row that was not scrolled there.
+ if (old.selectedId != widget.selectedId) {
+ WidgetsBinding.instance.addPostFrameCallback(
+ (_) => _reveal(const Duration(milliseconds: 220)),
+ );
+ }
+ }
+
+ void _reveal(Duration duration) {
+ final context = _selected.currentContext;
+ if (context == null || !mounted) return;
+ unawaited(
+ Scrollable.ensureVisible(
+ context,
+ // Centred rather than merely brought inside the edge: a name flush
+ // against the right-hand end reads as the last tab there is.
+ alignment: 0.5,
+ duration: duration,
+ curve: Curves.easeOutCubic,
+ ),
+ );
+ }
+
@override
Widget build(BuildContext context) {
AppTheme.watch(context);
+ final groups = widget.groups;
+ final selectedId = widget.selectedId;
+ final onPick = widget.onPick;
+ final onAddTab = widget.onAddTab;
+ const sideInset = DeskTabStrip.sideInset;
+ const height = DeskTabStrip.height;
+ const gap = DeskTabStrip._gap;
return SizedBox(
height: height,
- // Scrolls, because a desk can carry more tabs than a phone is wide. The
- // names keep their own widths — nothing is squeezed to make a row fit,
- // which is what turns tab names into `Deskt…`, `Dock…`.
- child: ListView.separated(
- scrollDirection: Axis.horizontal,
- padding: const EdgeInsets.symmetric(horizontal: sideInset),
- itemCount: groups.length,
- separatorBuilder: (context, index) => const SizedBox(width: _gap),
- itemBuilder: (context, index) {
- final group = groups[index];
- return _DeskTabName(
- name: group.name,
- selected: group.id == selectedId,
- reachable: !group.isEmpty,
- onTap: () => onPick(group),
- );
+ child: Row(
+ children: [
+ Expanded(
+ // Scrolls, because a desk can carry more tabs than a phone is wide.
+ // The names keep their own widths — nothing is squeezed to make a
+ // row fit, which is what turns tab names into `Deskt…`, `Dock…`.
+ child: ListView.separated(
+ scrollDirection: Axis.horizontal,
+ padding: EdgeInsets.only(
+ left: sideInset,
+ // A full inset only where the row ends in nothing. Beside the
+ // `+`, the button's own margin is the gap, and a name stopping
+ // an inset short of it as well reads as a row that ran out
+ // rather than one that scrolls.
+ right: onAddTab == null ? sideInset : 4,
+ ),
+ itemCount: groups.length,
+ separatorBuilder: (context, index) => const SizedBox(width: gap),
+ itemBuilder: (context, index) {
+ final group = groups[index];
+ final selected = group.id == selectedId;
+ return _DeskTabName(
+ key: selected ? _selected : null,
+ name: group.name,
+ selected: selected,
+ reachable: !group.isEmpty,
+ onTap: () => onPick(group),
+ );
+ },
+ ),
+ ),
+ // ⚠️ **Pinned beside the names, not carried at the end of them.** The
+ // row scrolls, and a `+` that scrolls with it is a control that goes
+ // away exactly when the desk is big enough to want another tab. Out
+ // here it is always the rightmost thing on the row — which is also
+ // what says it belongs to the row rather than to the list below.
+ if (onAddTab != null) _AddTabButton(onTap: onAddTab),
+ ],
+ ),
+ );
+ }
+}
+
+/// The `+` that opens a tab, at the right-hand end of the names.
+///
+/// ⚠️ **An icon alone, and it can be, because of where it stands.** The other
+/// `+` on this panel — the one that adds an agent to the tab being read — is a
+/// full-width row down in the list, carrying the words. Two bare `+`s would be
+/// a guess; a mark on the tab row and a labelled row in the agent list are two
+/// different things before either is read. See [showDeskTabsPopup].
+class _AddTabButton extends StatelessWidget {
+ const _AddTabButton({required this.onTap});
+
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ return Semantics(
+ button: true,
+ label: 'New tab',
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () {
+ HapticFeedback.selectionClick();
+ onTap();
},
+ child: Padding(
+ // A thumb's worth of row either side of a 20pt glyph, and the strip's
+ // own inset on the outside so it lines up with `⋯` in the header.
+ padding: const EdgeInsets.only(
+ left: 10,
+ right: DeskTabStrip.sideInset,
+ ),
+ child: Center(
+ child: Icon(
+ LucideIcons.plus300,
+ size: 20,
+ color: AppPalette.textSecondary,
+ ),
+ ),
+ ),
),
);
}
@@ -89,6 +222,7 @@ class DeskTabStrip extends StatelessWidget {
/// the non-positioned child that sizes the whole thing, and the bar spans it.
class _DeskTabName extends StatelessWidget {
const _DeskTabName({
+ super.key,
required this.name,
required this.selected,
required this.reachable,
diff --git a/mobile/lib/phone/desk_tabs_popup.dart b/mobile/lib/phone/desk_tabs_popup.dart
index 30287fa5b..69e266794 100644
--- a/mobile/lib/phone/desk_tabs_popup.dart
+++ b/mobile/lib/phone/desk_tabs_popup.dart
@@ -1,4 +1,8 @@
+import 'dart:async';
+
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness_mobile/core/last_opened_agent.dart' show AgentRef;
import 'package:harness_mobile/shared/theme/app_theme.dart';
@@ -6,10 +10,13 @@ import 'package:harness_mobile/state/app_state.dart';
import 'agent_index.dart';
import 'agent_tile.dart';
+import 'agents_page.dart' show openNewAgent;
+import 'desk_add_agent_sheet.dart';
import 'desk_groups.dart';
import 'desk_tab_strip.dart';
import 'phone_card.dart';
import 'phone_navigation.dart';
+import 'phone_status.dart';
/// The account's tabs, and the agents inside the one being read, as a panel up
/// from the bottom of the terminal.
@@ -62,7 +69,7 @@ Future<void> showDeskTabsPopup(
// this panel keeps.
isScrollControlled: true,
builder: (sheetContext) => _DeskTabsPanel(
- groups: groups,
+ notifier: notifier,
initialId: active.id,
showing: showing,
// Close first, then open: the terminal this pushes must not arrive
@@ -84,13 +91,17 @@ const double _sideInset = 16;
/// The panel itself: the tab names, and the rows of whichever tab is picked.
class _DeskTabsPanel extends StatefulWidget {
const _DeskTabsPanel({
- required this.groups,
+ required this.notifier,
required this.initialId,
required this.showing,
required this.onOpen,
});
- final List<DeskGroup> groups;
+ /// ⚠️ **The groups are rebuilt from here on every change, not passed in
+ /// once.** An agent added to a tab from this panel has to appear in it while
+ /// the panel is still open — a list computed before the sheet was shown
+ /// answered a tap by doing nothing visible at all.
+ final AppNotifier notifier;
/// The tab the panel opens on — the one the agent on screen belongs to.
final String? initialId;
@@ -106,25 +117,158 @@ class _DeskTabsPanel extends StatefulWidget {
class _DeskTabsPanelState extends State<_DeskTabsPanel> {
late String? _selectedId = widget.initialId;
+ List<DeskGroup> get _groups =>
+ deskGroups(widget.notifier, visibleAgents(agentIndex(widget.notifier)));
+
/// The tab being read. Falls back to the first, which is only reachable if
/// the desk dropped a tab while the panel was open.
- DeskGroup get _group =>
- widget.groups.where((group) => group.id == _selectedId).firstOrNull ??
- widget.groups.first;
+ DeskGroup _groupIn(List<DeskGroup> groups) =>
+ groups.where((group) => group.id == _selectedId).firstOrNull ??
+ groups.first;
+
+ /// Whether [group] can take another agent: a real tab on a desk this phone
+ /// may write to. The leftover group is not a tab — there is nothing to add
+ /// an agent TO — and neither is the single group a phone with no desk shows.
+ bool _canAddTo(DeskGroup group) =>
+ group.id != null && widget.notifier.deskWritable;
+
+ /// Every agent this phone could put in a tab: the ones it can actually open,
+ /// which is the same test [deskGroups] makes of the ones already in them.
+ List<AgentEntry> get _openable => [
+ for (final entry in visibleAgents(agentIndex(widget.notifier)))
+ if (entry.agent.terminalAvailable) entry,
+ ];
+
+ /// The machine a new agent would be made on: the first that can host one,
+ /// which is also the form's own first question and changed there. Null where
+ /// none can — every machine asleep, or wanting its password — and that is
+ /// what leaves "New agent" out of the sheet rather than drawn dead.
+ String? get _hostMachineId => [
+ for (final machine in filterableMachines(widget.notifier))
+ if (phoneMachineStatusOf(machine) == PhoneMachineStatus.ready) machine,
+ ].firstOrNull?.machine.machineId;
+
+ AgentRef _refOf(AgentEntry entry) =>
+ (machineId: entry.machineId, agentId: entry.agent.id);
+
+ /// Whether an empty [group] is empty because its agents are out of REACH, or
+ /// because it holds none at all.
+ ///
+ /// The two look identical on screen and are nothing alike: the first is a
+ /// machine asleep and the agents are still there, the second is a tab that
+ /// has been emptied or has only just been made. Read from the desk itself —
+ /// [DeskGroup] carries the agents this phone can open, which is by definition
+ /// none in both cases.
+ bool _everHeldAgents(DeskGroup group) =>
+ widget.notifier.deskTabs
+ .where((tab) => tab.id == group.id)
+ .firstOrNull
+ ?.panes
+ .isNotEmpty ??
+ false;
+
+ /// The `+` on the tab row: a tab of its own for an agent picked or made now.
+ ///
+ /// ⚠️ **The tab is written only once there is something to put in it.** A
+ /// tab created up front and then abandoned — the form cancelled, the machine
+ /// refusing — would be an empty tab on every computer the person owns, put
+ /// there by a tap they took back. For a new agent that means arming
+ /// [AppNotifier.openNextAgentInNewDeskTab] and letting the agent's own
+ /// arrival make the tab.
+ void _addTab() {
+ final notifier = widget.notifier;
+ final host = _hostMachineId;
+ unawaited(
+ showDeskAddAgentSheet(
+ context,
+ title: 'New tab',
+ choices: _openable,
+ onPick: (entry) {
+ final group = DeskGroup(
+ id: notifier.createDeskTabFor(
+ _refOf(entry),
+ name: entry.agent.name,
+ ),
+ name: entry.agent.name,
+ entries: [entry],
+ );
+ if (group.id == null) return;
+ // Opened, not merely listed: the tab exists now and the phone is in
+ // it, and a panel that stayed put would say neither.
+ widget.onOpen(group, entry);
+ },
+ onCreate: host == null
+ ? null
+ : () {
+ notifier.openNextAgentInNewDeskTab();
+ Navigator.of(context).pop();
+ unawaited(
+ openNewAgent(
+ context,
+ notifier,
+ host,
+ ).whenComplete(notifier.forgetNewDeskTabIntent),
+ );
+ },
+ ),
+ );
+ }
+
+ /// The `+` at the foot of a tab's list: another agent in the tab being read.
+ ///
+ /// The panel stays open on the way back — this is a list being filled, and
+ /// the agent appears in it under the thumb that added it.
+ void _addAgentTo(DeskGroup group) {
+ final id = group.id;
+ if (id == null) return;
+ final notifier = widget.notifier;
+ final host = _hostMachineId;
+ unawaited(
+ showDeskAddAgentSheet(
+ context,
+ title: 'Add to “${group.name}”',
+ choices: [
+ for (final entry in _openable)
+ if (!group.holds(_refOf(entry))) entry,
+ ],
+ onPick: (entry) => notifier.addAgentToDeskTab(id, _refOf(entry)),
+ onCreate: host == null
+ ? null
+ : () {
+ // The tab the phone is in is the tab an agent made here joins
+ // — see [PhoneDesk.adopt] — so this is what aims that.
+ notifier.selectDeskTab(id);
+ Navigator.of(context).pop();
+ unawaited(openNewAgent(context, notifier, host));
+ },
+ ),
+ );
+ }
@override
Widget build(BuildContext context) {
AppTheme.watch(context);
- final group = _group;
+ return ListenableBuilder(
+ listenable: widget.notifier,
+ builder: (context, _) => _panel(context),
+ );
+ }
+
+ Widget _panel(BuildContext context) {
+ final groups = _groups;
+ final group = _groupIn(groups);
return SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
DeskTabStrip(
- groups: widget.groups,
+ groups: groups,
selectedId: group.id,
onPick: (picked) => setState(() => _selectedId = picked.id),
+ // Undrawn on a desk that cannot be written to — see
+ // [AppNotifier.deskWritable].
+ onAddTab: widget.notifier.deskWritable ? _addTab : null,
),
const SizedBox(height: 6),
// ⚠️ **One height, whatever the tab holds.** Sized to its contents,
@@ -135,8 +279,28 @@ class _DeskTabsPanelState extends State<_DeskTabsPanel> {
// keeps the other half.
SizedBox(
height: MediaQuery.sizeOf(context).height * 0.5,
+ // ⚠️ **An empty tab keeps its sentence AND gets the `+`.** The two
+ // answer different halves of the same screen: the sentence says
+ // why there is nothing here, and the `+` is what to do about it.
+ // Dropped in favour of the row, a tab whose machine is asleep
+ // silently became a tab that merely had nothing in it.
child: group.isEmpty
- ? const _TabIsEmpty()
+ ? Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ _TabIsEmpty(everHeldAgents: _everHeldAgents(group)),
+ if (_canAddTo(group))
+ Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: _sideInset,
+ ),
+ child: _AddAgentRow(
+ tabName: group.name,
+ onTap: () => _addAgentTo(group),
+ ),
+ ),
+ ],
+ )
: ListView.separated(
padding: EdgeInsets.fromLTRB(
_sideInset,
@@ -144,10 +308,23 @@ class _DeskTabsPanelState extends State<_DeskTabsPanel> {
_sideInset,
MediaQuery.paddingOf(context).bottom + 8,
),
- itemCount: group.entries.length,
+ itemCount:
+ group.entries.length + (_canAddTo(group) ? 1 : 0),
separatorBuilder: (context, index) =>
const SizedBox(height: kPhoneCardGap),
itemBuilder: (context, index) {
+ // ⚠️ **Last in the list, and shaped like the rows above
+ // it rather than like the `+` on the tab row.** This one
+ // adds an agent to the tab being read; that one opens a
+ // tab. Two identical marks would be a guess, so the one
+ // that could be mistaken carries the words — and standing
+ // IN the list is itself the sentence "into this list".
+ if (index == group.entries.length) {
+ return _AddAgentRow(
+ tabName: group.name,
+ onTap: () => _addAgentTo(group),
+ );
+ }
final entry = group.entries[index];
final showing =
entry.machineId == widget.showing.machineId &&
@@ -175,11 +352,119 @@ class _DeskTabsPanelState extends State<_DeskTabsPanel> {
}
}
+/// The `+` at the foot of a tab's agents: one more agent in THIS tab.
+///
+/// ⚠️ **A row, not a mark, and that is the whole of how it is told apart from
+/// the `+` on the tab row above.** They are the same glyph doing two different
+/// things, so nothing rests on the glyph: this one is as wide as the agent
+/// rows, sits at the end of them, is drawn in the dashes that mean "not filled
+/// in yet", and says which tab it fills. See [DeskTabStrip].
+class _AddAgentRow extends StatelessWidget {
+ const _AddAgentRow({required this.tabName, required this.onTap});
+
+ final String tabName;
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ return Semantics(
+ button: true,
+ label: 'Add agent to $tabName',
+ // ⚠️ The words on the row are "this tab", which is clear under a thumb
+ // that has just read the tab's name and useless read aloud on its own.
+ // Excluded, the row announces the tab it fills.
+ excludeSemantics: true,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () {
+ HapticFeedback.selectionClick();
+ onTap();
+ },
+ child: CustomPaint(
+ painter: _DashedRim(color: AppGlass.hair),
+ child: SizedBox(
+ height: 56,
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Icon(
+ LucideIcons.plus300,
+ size: 18,
+ color: AppPalette.textSecondary,
+ ),
+ const SizedBox(width: 8),
+ Flexible(
+ child: Text(
+ 'Add agent to this tab',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ color: AppPalette.textSecondary,
+ fontSize: 14.5,
+ fontWeight: FontWeight.w500,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// The dashes around [_AddAgentRow]. A card's own rim is a hairline all the way
+/// round, which is what every FILLED row here wears; broken, it reads as a
+/// place for a row rather than as one.
+class _DashedRim extends CustomPainter {
+ const _DashedRim({required this.color});
+
+ final Color color;
+
+ static const double _radius = 14;
+ static const double _dash = 5;
+ static const double _gap = 4;
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ final rim = Path()
+ ..addRRect(
+ RRect.fromRectAndRadius(
+ Offset.zero & size,
+ const Radius.circular(_radius),
+ ),
+ );
+ final brush = Paint()
+ ..style = PaintingStyle.stroke
+ ..strokeWidth = 1
+ ..color = color;
+ for (final metric in rim.computeMetrics()) {
+ var at = 0.0;
+ while (at < metric.length) {
+ canvas.drawPath(
+ metric.extractPath(at, (at + _dash).clamp(0, metric.length)),
+ brush,
+ );
+ at += _dash + _gap;
+ }
+ }
+ }
+
+ @override
+ bool shouldRepaint(_DashedRim old) => old.color != color;
+}
+
/// A tab whose agents are all out of reach — the machine they run on is asleep
/// or wants its password. The tab is still listed and still opens to this,
/// because a tab missing from the row reads as one somebody deleted.
class _TabIsEmpty extends StatelessWidget {
- const _TabIsEmpty();
+ const _TabIsEmpty({required this.everHeldAgents});
+
+ /// Whether the tab holds agents this phone cannot reach, as opposed to no
+ /// agents at all — see [_DeskTabsPanelState._everHeldAgents].
+ final bool everHeldAgents;
@override
Widget build(BuildContext context) {
@@ -187,8 +472,10 @@ class _TabIsEmpty extends StatelessWidget {
return Padding(
padding: const EdgeInsets.fromLTRB(_sideInset, 10, _sideInset, 18),
child: Text(
- 'Nothing here this phone can open — the machine these agents run on '
- 'is asleep or wants its password.',
+ everHeldAgents
+ ? 'Nothing here this phone can open — the machine these agents run '
+ 'on is asleep or wants its password.'
+ : 'This tab has no agents yet.',
style: TextStyle(color: AppPalette.textSecondary, fontSize: 13.5),
),
);
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index c151fc7d7..a60a8e5c1 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -547,6 +547,29 @@ class AppNotifier extends ChangeNotifier {
/// The tab the screen has worked out it is showing — see [PhoneDesk.note].
void noteDeskTab(String? tabId) => _desk.note(tabId);
+ /// Whether the desk can be WRITTEN to — what the two `+`s on the tabs panel
+ /// are drawn on. False before the first read answers, and on a backend with
+ /// no desk at all: a `+` there would queue ops nothing will ever take.
+ bool get deskWritable => _desk.enabled;
+
+ /// An agent that already exists joins the tab the person picked — the `+` at
+ /// the foot of a tab's list. See [PhoneDesk.addToTab].
+ void addAgentToDeskTab(String tabId, AgentRef agent) =>
+ _desk.addToTab(tabId, agent);
+
+ /// An agent that already exists opens a tab of its own — the `+` on the tab
+ /// row. See [PhoneDesk.createTabFor].
+ String? createDeskTabFor(AgentRef agent, {String? name}) =>
+ _desk.createTabFor(agent, name: name);
+
+ /// The next agent made on this phone gets a tab of its own — armed by the `+`
+ /// on the tab row before the new-agent form opens, and spent (or forgotten)
+ /// by the time that form closes. See [PhoneDesk.openNextAgentInNewTab].
+ void openNextAgentInNewDeskTab() => _desk.openNextAgentInNewTab();
+
+ /// That form closed without making anything.
+ void forgetNewDeskTabIntent() => _desk.forgetNewTabIntent();
+
/// Read the desk now, and wait for it — what a sign-in and the app coming
/// back to the foreground both start without waiting.
@visibleForTesting
@@ -4843,7 +4866,7 @@ class AppNotifier extends ChangeNotifier {
// Created HERE, so it joins the tab this phone is in — the way an agent
// created in a window joins that window's tab. See [PhoneDesk.adopt] for
// what happens when the phone is in no tab.
- _desk.adopt((machineId: machineId, agentId: agent.id));
+ _desk.adopt((machineId: machineId, agentId: agent.id), name: agent.name);
await assignAgentToPane(
null,
machineId,
diff --git a/mobile/lib/state/phone_desk.dart b/mobile/lib/state/phone_desk.dart
index 9644065c9..7f0bdc009 100644
--- a/mobile/lib/state/phone_desk.dart
+++ b/mobile/lib/state/phone_desk.dart
@@ -1,4 +1,5 @@
import 'dart:async';
+import 'dart:math';
import 'package:flutter/foundation.dart';
@@ -20,9 +21,10 @@ import 'desk_sync.dart';
/// attaches the agents either side of the one on screen ahead of a swipe. A
/// projection of THAT would add every agent a thumb passes to whatever tab the
/// phone happened to be in, on every computer the person owns. So nothing here
-/// is derived from `swarms`: the tabs are read, and the only writes are the two
-/// a person makes by hand on the phone — [adopt] for an agent created here, and
-/// [drop] for one deleted here.
+/// is derived from `swarms`: the tabs are read, and every write is one a person
+/// made by hand on the phone — [adopt] for an agent created here, [drop] for one
+/// deleted here, and [createTabFor]/[addToTab] for the two `+`s on the tabs
+/// panel.
///
/// What is NOT on the desk stays per device, as it does on a window: which tab
/// is open ([activeTabId]) is this phone's own, and so is the agent within it.
@@ -196,7 +198,7 @@ class PhoneDesk {
onChanged();
}
- // ── the two writes a phone makes ─────────────────────────────────────────
+ // ── the writes a phone makes ─────────────────────────────────────────────
/// An agent created ON THIS PHONE joins the tab the phone is in, the way one
/// created in a window joins that window's tab.
@@ -206,9 +208,73 @@ class PhoneDesk {
/// reachable here through search. Nothing to do when the phone is not in a tab
/// (the desk is empty, or the person is in the group for agents no tab holds):
/// the agent is then exactly where it would have been anyway.
- void adopt(AgentRef agent) {
+ ///
+ /// [name] is the agent's own, and it is used only by [openNextAgentInNewTab]
+ /// — a tab made for one agent is named after it, which is what a window does
+ /// with a tab it opens.
+ void adopt(AgentRef agent, {String? name}) {
+ if (!_state.enabled) return;
+ final wanted = _newTabForNextAgent;
+ _newTabForNextAgent = false;
+ final pane = DeskPaneRef(
+ machineId: agent.machineId,
+ agentId: agent.agentId,
+ );
+ if (wanted) {
+ createTabFor(agent, name: name);
+ return;
+ }
final tabId = _activeTabId;
- if (!_state.enabled || tabId == null) return;
+ if (tabId == null) return;
+ final tab = _state.synced.where((t) => t.id == tabId).firstOrNull;
+ if (tab == null) return;
+ if (tab.panes.contains(pane)) return;
+ _queue([
+ {'op': 'pane.add', 'tabId': tabId, ...pane.toJson()},
+ ]);
+ }
+
+ /// A new tab holding [agent] alone, and the phone is in it from here.
+ ///
+ /// ⚠️ **Two ops, one write.** `tab.create` and the `pane.add` into it go in a
+ /// single queue: they are applied optimistically in that order, sent in that
+ /// order, and a desk that took the first but refused the second would leave a
+ /// tab nobody asked for on every computer the person owns.
+ ///
+ /// ⚠️ **`nameIsCustom: false`.** The name is the agent's, not one a person
+ /// typed, so a window is free to re-derive it when the tab holds something
+ /// else later — the same as a tab opened on a desktop.
+ ///
+ /// Returns the tab's id, or null where there is no desk to write to.
+ String? createTabFor(AgentRef agent, {String? name}) {
+ if (!_state.enabled) return null;
+ final id = _newTabId();
+ final pane = DeskPaneRef(
+ machineId: agent.machineId,
+ agentId: agent.agentId,
+ );
+ _queue([
+ {
+ 'op': 'tab.create',
+ 'id': id,
+ 'name': (name == null || name.trim().isEmpty) ? 'New tab' : name.trim(),
+ 'nameIsCustom': false,
+ 'index': _state.synced.length,
+ },
+ {'op': 'pane.add', 'tabId': id, ...pane.toJson()},
+ ]);
+ // In it, because the person made it to be in it. Written directly rather
+ // than through [select] so this does not notify twice — [_queue] already
+ // has.
+ _activeTabId = id;
+ return id;
+ }
+
+ /// An agent that already exists joins a tab the person picked — which need
+ /// not be the tab the phone is in. Silent where the tab has it already: the
+ /// panel offers agents a tab lacks, but the desk can have moved underneath.
+ void addToTab(String tabId, AgentRef agent) {
+ if (!_state.enabled) return;
final tab = _state.synced.where((t) => t.id == tabId).firstOrNull;
if (tab == null) return;
final pane = DeskPaneRef(
@@ -221,6 +287,33 @@ class PhoneDesk {
]);
}
+ /// The next agent made on this phone opens a TAB of its own instead of
+ /// joining the one the phone is in — the `+` on the tab row, which asks for
+ /// a new agent and then has nowhere to put it until the machine answers with
+ /// one.
+ ///
+ /// ⚠️ **Disarmed by the very next [adopt], whether or not it was this one.**
+ /// An intent that outlived a cancelled form would put somebody's next agent —
+ /// made minutes later from the terminal's own `+` — in a tab of its own.
+ /// [forgetNewTabIntent] is the cancel path; between the two, the flag cannot
+ /// survive the screen that set it.
+ void openNextAgentInNewTab() => _newTabForNextAgent = true;
+
+ /// The form closed without making anything — see [openNextAgentInNewTab].
+ void forgetNewTabIntent() => _newTabForNextAgent = false;
+
+ bool _newTabForNextAgent = false;
+
+ /// The desk's ids are 32 hex characters (backend `lib/desk.ts`), and a tab
+ /// made here has to look like one made anywhere else.
+ String _newTabId() {
+ const hex = '0123456789abcdef';
+ final random = Random();
+ return String.fromCharCodes([
+ for (var i = 0; i < 32; i++) hex.codeUnitAt(random.nextInt(16)),
+ ]);
+ }
+
/// An agent deleted on this phone leaves every tab that held it.
///
/// A window that had it open removes it too, as soon as it hears the agent is
@@ -313,6 +406,7 @@ class PhoneDesk {
pause();
_joining = null;
_activeTabId = null;
+ _newTabForNextAgent = false;
_state.reset();
}
diff --git a/mobile/test/desk_tab_add_test.dart b/mobile/test/desk_tab_add_test.dart
new file mode 100644
index 000000000..d9024299e
--- /dev/null
+++ b/mobile/test/desk_tab_add_test.dart
@@ -0,0 +1,219 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/phone/agent_home.dart';
+import 'package:harness_mobile/phone/agent_tile.dart';
+import 'package:harness_mobile/phone/phone_shell_scope.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/state/desk_sync.dart';
+
+import 'agent_pager_fixture.dart';
+import 'desk_fixture.dart';
+
+/// The two `+`s on the tabs panel: one opens a tab, one fills the tab being
+/// read.
+///
+/// ⚠️ **They are the same glyph, so every test here asserts on what was WRITTEN
+/// to the desk rather than on what was tapped.** A `+` that made a tab where it
+/// should have added an agent would look identical on screen and be wrong on
+/// every computer the person owns.
+void main() {
+ Future<AppNotifier> pumpHome(
+ WidgetTester tester, {
+ required List<DeskTab> tabs,
+ }) async {
+ final app = await deskApp(
+ PagerConn(),
+ // Nothing here is about the terminals themselves — see [deskApp].
+ opensTerminals: false,
+ tabs: tabs,
+ );
+ addTearDown(app.dispose);
+ // ⚠️ A phone's shape, not the 800x600 a widget test defaults to. Both
+ // sheets here keep half the screen for their list, and on a landscape
+ // window the rows to tap sit below the bottom edge.
+ tester.view.physicalSize = const Size(400, 1400);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ final request = ValueNotifier<({String machineId, String agentId})?>(null);
+ addTearDown(request.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: PhoneShellScope(
+ onMachineLinked: (_) {},
+ onOpenAgent: (machineId, agentId) =>
+ request.value = (machineId: machineId, agentId: agentId),
+ child: AgentHome(notifier: app, openAgent: request),
+ ),
+ ),
+ );
+ await tester.pump();
+ return app;
+ }
+
+ /// ⚠️ Timed pumps, never `pumpAndSettle`: these pages draw the "Attaching…"
+ /// skeleton, which breathes for ever. The waits are the sheets' own
+ /// animations.
+ Future<void> openPanel(WidgetTester tester) async {
+ await tester.tap(find.byTooltip('Tabs'));
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 400));
+ }
+
+ Future<void> showTab(WidgetTester tester, String tab) async {
+ await tester.tap(find.text(tab));
+ await tester.pump();
+ }
+
+ Future<void> settleSheet(WidgetTester tester) async {
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 400));
+ }
+
+ /// An agent's row, wherever it is drawn.
+ Finder row(String agent) => find.byWidgetPredicate(
+ (widget) => widget is AgentTile && widget.agent.id == agent,
+ );
+
+ testWidgets('the + on the tab row opens a tab holding the agent picked', (
+ tester,
+ ) async {
+ final app = await pumpHome(
+ tester,
+ tabs: [
+ deskTab('t1', 'Desktop', ['a']),
+ ],
+ );
+
+ await openPanel(tester);
+ await tester.tap(find.bySemanticsLabel('New tab'));
+ await settleSheet(tester);
+ // `c` is in no tab, so its row exists only in the sheet.
+ await tester.tap(row('c'));
+ await settleSheet(tester);
+
+ final written = deskApiOf(app).written;
+ expect(written, hasLength(2));
+ expect(written.first['op'], 'tab.create');
+ expect(
+ written.first['name'],
+ 'c',
+ reason: 'a tab made for one agent is named after it',
+ );
+ expect(
+ written.first['nameIsCustom'],
+ false,
+ reason: 'the name is the agent\'s, not one a person typed',
+ );
+ expect(written[1], {
+ 'op': 'pane.add',
+ 'tabId': written.first['id'],
+ 'machineId': 'm',
+ 'agentId': 'c',
+ });
+ expect(app.deskTabs.map((tab) => tab.name), [
+ 'Desktop',
+ 'c',
+ ], reason: 'the new tab is last on the row');
+ expect(
+ app.activeDeskTabId,
+ written.first['id'],
+ reason: 'the person made it to be in it',
+ );
+ });
+
+ testWidgets('the + under a tab adds the agent to THAT tab', (tester) async {
+ final app = await pumpHome(
+ tester,
+ tabs: [
+ deskTab('t1', 'Desktop', ['a']),
+ deskTab('t2', 'Docker', ['b']),
+ ],
+ );
+
+ await openPanel(tester);
+ await showTab(tester, 'Docker');
+ await tester.tap(find.bySemanticsLabel('Add agent to Docker'));
+ await settleSheet(tester);
+ await tester.tap(row('d'));
+ await settleSheet(tester);
+
+ expect(deskApiOf(app).written, [
+ {'op': 'pane.add', 'tabId': 't2', 'machineId': 'm', 'agentId': 'd'},
+ ]);
+ expect(
+ app.deskTabs
+ .firstWhere((tab) => tab.id == 't2')
+ .panes
+ .map((pane) => pane.agentId),
+ ['b', 'd'],
+ );
+ expect(
+ row('d'),
+ findsOneWidget,
+ reason: 'the panel stays open, and the agent is in the list it filled',
+ );
+ });
+
+ testWidgets('a tab is not offered the agents it already holds', (
+ tester,
+ ) async {
+ await pumpHome(
+ tester,
+ tabs: [
+ deskTab('t1', 'Desktop', ['a', 'b']),
+ ],
+ );
+
+ await openPanel(tester);
+ await tester.tap(find.bySemanticsLabel('Add agent to Desktop'));
+ await settleSheet(tester);
+
+ // `a` and `b` are in the tab, and the panel under the sheet still draws
+ // their rows — one each, from the list behind, and none from the sheet.
+ expect(row('a'), findsOneWidget);
+ expect(row('b'), findsOneWidget);
+ expect(row('c'), findsOneWidget);
+ expect(row('d'), findsOneWidget);
+ });
+
+ testWidgets('a tab emptied of agents says so, and can still be filled', (
+ tester,
+ ) async {
+ await pumpHome(tester, tabs: [deskTab('t1', 'Empty', [])]);
+
+ await openPanel(tester);
+ // The panel opens on the group holding the agent on screen, which is the
+ // leftover one — every agent is outside this tab.
+ await showTab(tester, 'Empty');
+
+ expect(find.text('This tab has no agents yet.'), findsOneWidget);
+ expect(
+ find.textContaining('asleep'),
+ findsNothing,
+ reason: 'a tab holding nothing is not a tab whose machine is away',
+ );
+ expect(find.bySemanticsLabel('Add agent to Empty'), findsOneWidget);
+ });
+
+ testWidgets('the agents no tab holds are offered no + of their own', (
+ tester,
+ ) async {
+ await pumpHome(
+ tester,
+ tabs: [
+ deskTab('t1', 'Desktop', ['a']),
+ ],
+ );
+
+ await openPanel(tester);
+ await showTab(tester, 'Other');
+
+ // "Other" is not a tab — there is nothing on the desk to add an agent to.
+ expect(find.textContaining('Add agent to'), findsNothing);
+ expect(
+ find.bySemanticsLabel('New tab'),
+ findsOneWidget,
+ reason: 'the tab row keeps its own +, whichever group is being read',
+ );
+ });
+}