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.

Combined merge 10-31 A: three reviewed Desktop PRs (#2443 #2439 #2442) (#2444)

0xken15692a6d85e981
diff --git a/backend/src/superTabs/mentions.test.ts b/backend/src/superTabs/mentions.test.ts
index ed2cc2cc0..317a48204 100644
--- a/backend/src/superTabs/mentions.test.ts
+++ b/backend/src/superTabs/mentions.test.ts
@@ -46,6 +46,18 @@ describe('people tagging people', () => {
expect(f.send(f.group, ['owner'], peer).mentions).toEqual(['owner'])
})
+ it('a thread reply carries its tags and agents as a chat message does (Desktop thread @, 10-31)', () => {
+ const f = fixture()
+ f.run({ type: 'conversation.agent', conversationId: f.group, agentId: f.worker, present: true, lead: false })
+ const root = f.say(f.group, 'Should we ship the copy?')
+ const reply = f.run({ type: 'message.send', conversationId: f.group, text: 'Please check @peer', replyTo: root.id,
+ recipientIds: [f.worker], mentions: ['peer'] }, owner,
+ { reply: { id: root.id, conversationId: f.group, author: root.author, createdAt: 1000, thread: root.thread ?? root.id } }).messages.at(-1)!
+ expect(reply.thread).toBe(root.thread ?? root.id)
+ expect(reply.mentions).toEqual(['peer'])
+ expect(reply.recipients).toEqual([f.worker])
+ })
+
it('drops the author’s own tag', () => {
const f = fixture()
expect(f.send(f.group, ['owner', 'peer']).mentions).toEqual(['peer'])
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index f0149719e..871867acb 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -102,6 +102,7 @@ import '../super_tabs/backend_transport.dart';
import '../super_tabs/client.dart';
import '../super_tabs/controller.dart';
import '../super_tabs/join_machine.dart';
+import '../super_tabs/identity.dart' show superTabMachineName;
import '../super_tabs/view_store.dart';
import '../super_tabs/notifications.dart' show superTabMentionNotice;
import '../measurement/setup_preference_store.dart';
@@ -1369,6 +1370,24 @@ class AppNotifier extends ChangeNotifier {
/// setup — [signedIn] is presumed true until the CLI has been asked.
bool get signInStepNext => _signInStep && viewer == null && !signedIn;
+ /// Whether Harness was on this computer before this launch, so the sign-in
+ /// page can say it is set up rather than look like a first run (Scholes's
+ /// end-to-end test of 1.3.44, finding 5). False on the launch that first
+ /// installed it, the tour's.
+ bool get harnessSetUpBefore => !_firstHarnessLaunch;
+ bool _firstHarnessLaunch = false;
+
+ /// This computer as the sign-in page names it: its own row (the daemon's
+ /// while signed out), else its host name, without Bonjour's `.local`.
+ /// Null when neither is known. Only ever this computer's own name: no
+ /// account, and no other machine.
+ String? get thisComputerName {
+ final row = localMachineState?.machine.name?.trim();
+ final name = row != null && row.isNotEmpty ? row : localHostnameOrNull();
+ if (name == null || name.isEmpty) return null;
+ return superTabMachineName(name);
+ }
+
/// Whether RootShell shows the sign-in step in place of the workspace: from
/// the moment setup (and its tour) hands over, until an account arrives.
bool get signInStepShowing {
@@ -6659,6 +6678,7 @@ class AppNotifier extends ChangeNotifier {
// box and installed OpenCode in its first pane, about 90 s to a first result against 55 s on a Mac.
// They wait for what setup brings until it is ready ([_continueAfterEnvironmentReady]).
if (firstHarness) {
+ _firstHarnessLaunch = true;
agentPrefetch?.setupRunning = true;
agentPrefetch?.start();
// The tour's final line announces sign-in: see [signInStepShowing].
@@ -10212,10 +10232,36 @@ class AppNotifier extends ChangeNotifier {
}
if (localEndpoint != null) _updateLocalProjectSnapshot(localEndpoint);
_autoConnectAndLoadMachines();
+ _startBackgroundRereads();
+ notifyListeners();
+ // A grant that has just arrived places what waited for it (R2).
+ _placeSharedPanesSoon();
+ }
+
+ /// The background re-reads a signed-in window keeps: each connected
+ /// machine's agent sync and the machine list's safety net. A guest keeps
+ /// none (an unattended computer on the sign-in page goes idle); the local
+ /// service itself stays supervised. Sign-out cancels them in
+ /// [_clearAccountWorkspace], and sign-in starts them here again.
+ void _startBackgroundRereads() {
+ if (_disposed || isGuest) return;
+ for (final machine in machineStates.values) {
+ if (machine.connectionStatus == ConnectionStatus.connected) {
+ _startAgentSyncTimer(machine.machine.machineId);
+ }
+ }
// The list is pushed (`machines_changed`); this only catches a missed push.
_sharingDiscoveryTimer ??= Timer.periodic(machineListSafetyNetInterval, (
- _,
+ timer,
) {
+ // Belt and braces: sign-out cancels it, and a guest never arms it.
+ if (isGuest) {
+ timer.cancel();
+ if (identical(_sharingDiscoveryTimer, timer)) {
+ _sharingDiscoveryTimer = null;
+ }
+ return;
+ }
// The desk is pushed too, and a missed desk push is caught here as well:
// one small GET, and an unchanged revision applies nothing.
if (!_disposed &&
@@ -10234,9 +10280,6 @@ class AppNotifier extends ChangeNotifier {
}
unawaited(_rereadMachinesInBackground(pushed: false));
});
- notifyListeners();
- // A grant that has just arrived places what waited for it (R2).
- _placeSharedPanesSoon();
}
/// The inventory has answered, and answered for now: loaded, not loading,
@@ -10588,6 +10631,9 @@ class AppNotifier extends ChangeNotifier {
}
void _startAgentSyncTimer(String machineId) {
+ // A guest asks nothing on a timer: an unattended computer on the sign-in
+ // page must go idle. Sign-in starts it ([_startBackgroundRereads]).
+ if (isGuest) return;
if (_agentSyncTimers.containsKey(machineId)) return;
_agentSyncTimers[machineId] = Timer.periodic(agentSyncInterval, (_) {
final machine = machineStates[machineId];
@@ -18774,6 +18820,52 @@ class AppNotifier extends ChangeNotifier {
}
/// Keep a group member visible while its terminal is unavailable.
+ /// Takes pane [paneId] out of Swarm tab [swarmId] only: one of the person's
+ /// own panes a Personal project showed behind its [term]
+ /// (super_tabs/personal_projects.dart). The tab it lives in keeps it and its
+ /// session, and nothing is remembered as closed.
+ Future<void> releaseSuperTabView(String swarmId, int paneId) async {
+ final tab = swarms
+ .where((s) => s.id == swarmId && s.isSuperTab)
+ .firstOrNull;
+ final pane = tab?.panes.where((p) => p.id == paneId).firstOrNull;
+ if (tab == null || pane == null || _disposed) return;
+ final wasFocused = identical(activeSwarm, tab) && focusedPaneId == paneId;
+ tab.remove(pane);
+ _settlePins(tab);
+ _persistLayout();
+ selectedMachineId = focusedPane?.machineId;
+ if (wasFocused) _announceAppFocus();
+ notifyListeners();
+ if (!allPanes.contains(pane)) await _detachSession(pane, sendClose: true);
+ }
+
+ /// Swarm tab [swarmId] lays out its panes as [source] does: a Personal
+ /// project's panes that are exactly one tab's keep that tab's split sizes.
+ void copySuperTabLayout(String swarmId, Swarm source) {
+ final tab = swarms
+ .where((s) => s.id == swarmId && s.isSuperTab)
+ .firstOrNull;
+ if (tab == null || _disposed || tab.panes.length != source.panes.length) {
+ return;
+ }
+ final count = '${tab.panes.length}:';
+ tab.presets.remove(tab.panes.length);
+ if (source.presets[source.panes.length] case final preset?) {
+ tab.presets[tab.panes.length] = preset;
+ }
+ tab.paneSizes.removeWhere((key, _) => key.startsWith(count));
+ for (final MapEntry(:key, :value) in source.paneSizes.entries) {
+ if (key.startsWith(count)) tab.paneSizes[key] = value;
+ }
+ final arranged = source.arrangedKey?.startsWith(count) == true;
+ tab.arranged = arranged ? source.arranged : null;
+ tab.arrangedKey = arranged ? source.arrangedKey : null;
+ tab.gridColumns = source.gridColumns;
+ _persistLayout();
+ notifyListeners();
+ }
+
void reserveSuperTabPane(String swarmId, String machineId, String harnessId) {
final tab = swarms
.where((s) => s.id == swarmId && s.superTabId != null)
diff --git a/desktop/lib/super_tabs/account_keys.dart b/desktop/lib/super_tabs/account_keys.dart
index e9fe1e472..c14406f55 100644
--- a/desktop/lib/super_tabs/account_keys.dart
+++ b/desktop/lib/super_tabs/account_keys.dart
@@ -9,7 +9,9 @@ import '../core/local_key_value_store.dart';
/// - `super_tab.launch.<account>.<tab>.<conversation>`: an unsent New Harness
/// or New Project;
/// - `super_tab.hidden.<account>`: the Swarms hidden on this browser;
-/// - `super_tab.personal.<account>`: the Swarm last chosen in the switcher.
+/// - `super_tab.personal.<account>`: the Swarm last chosen in the switcher;
+/// - `super_tab.repos.<account>`: the projects made for their repos in their
+/// Personal Swarm (personal_projects.dart).
/// The saved views' own keys (`super_tab.view…`, `super_tab.saved_by`) are
/// [SuperTabSavedViews]', which forgets them itself.
String? swarmKeyAccount(String key) {
@@ -17,7 +19,7 @@ String? swarmKeyAccount(String key) {
final parts = key.substring('super_tab.'.length).split('.');
return switch (parts) {
['launch', final account, _, ...] => account,
- ['hidden' || 'personal', final account] => account,
+ ['hidden' || 'personal' || 'repos', final account] => account,
['view' || 'views' || 'saved_by' || 'signed_out', ...] => null,
[final account, _] => account,
_ => null,
diff --git a/desktop/lib/super_tabs/composer_tags.dart b/desktop/lib/super_tabs/composer_tags.dart
new file mode 100644
index 000000000..507c74e08
--- /dev/null
+++ b/desktop/lib/super_tabs/composer_tags.dart
@@ -0,0 +1,283 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../widgets/desktop_chrome.dart';
+import 'controller.dart';
+import 'identity.dart';
+import 'model.dart';
+
+/// `@` tags in a composer, the same in the main chat's box and a thread's
+/// reply box: where a tag is being typed, who it offers, how a pick goes into
+/// the text, the list of choices, its keys, and Backspace taking a whole tag.
+
+/// A completion row: a workgroup, or someone to tag with their face and
+/// whether they are a person or an agent ([kind]).
+typedef SuperTabComposerChoice = ({
+ String label,
+ String? detail,
+ VoidCallback choose,
+ Widget? leading,
+ String? kind,
+});
+
+/// The most choices a list shows.
+const superTabCompletionLimit = 6;
+
+/// The `@` tag typed up to the caret of [value]: where it starts and ends and
+/// what follows the `@`, lowercased. None while text is selected or composed,
+/// when the reader dismissed it here ([dismissed], the text before the caret
+/// then), or once it says one of [tags] in full.
+({int start, int end, String query})? superTabTagAtCaret(
+ TextEditingValue value, {
+ required String? dismissed,
+ required Iterable<String> tags,
+}) {
+ if (!value.selection.isValid ||
+ !value.selection.isCollapsed ||
+ (value.composing.isValid && !value.composing.isCollapsed)) {
+ return null;
+ }
+ final end = value.selection.baseOffset;
+ final prefix = value.text.substring(0, end);
+ final match = RegExp(r'(?:^|\s)@([^@\n]*)$').firstMatch(prefix);
+ if (match == null || prefix == dismissed) return null;
+ final query = match.group(1)!;
+ if (tags.contains('@${query.trimRight()}')) return null;
+ return (start: prefix.lastIndexOf('@'), end: end, query: query.toLowerCase());
+}
+
+/// An agent's name as the chat shows it.
+String superTabAgentName(SuperTabController c, SuperTabAgent agent) =>
+ c.snapshot?.agentName(agent.id, fallback: agent.name) ?? agent.name;
+
+/// Who `@` offers in [group]: the people who read it, then its agents,
+/// filtered by [query]. Never the reader. Without [agents] (a thread its own
+/// Buddy session answers, where only that session hears a reply), people
+/// alone. [choose] puts the picked one in the text.
+List<SuperTabComposerChoice> superTabTagChoices(
+ SuperTabController c,
+ SuperTabConversation group,
+ String query, {
+ required String Function(String machineId) machineName,
+ required void Function(String id, String name) choose,
+ bool agents = true,
+}) {
+ final snapshot = c.snapshot;
+ if (snapshot == null) return const [];
+ final project = snapshot.projectFor(group.id);
+ bool reads(SuperTabPerson person) => switch (group) {
+ SuperTabConversation(:final audience?) => audience.contains(person.id),
+ _ when group.buddyOwnerId != null => person.id == group.buddyOwnerId,
+ _ =>
+ project == null ||
+ !project.isPrivate ||
+ project.ownerId == person.id ||
+ project.memberIds.contains(person.id),
+ };
+ final people = snapshot.people.where(
+ (person) =>
+ person.id != c.accountId &&
+ reads(person) &&
+ person.username.contains(query),
+ );
+ final offered = agents
+ ? snapshot.agents.where(
+ (agent) =>
+ group.agentIds.contains(agent.id) &&
+ // A thread's own session answers only there: nobody tags it.
+ agent.buddySession == null &&
+ '${superTabAgentName(c, agent)} ${agent.engine}'
+ .toLowerCase()
+ .contains(query),
+ )
+ : const <SuperTabAgent>[];
+ return [
+ for (final person in people)
+ (
+ label: person.username,
+ detail: null,
+ choose: () => choose(person.id, person.username),
+ leading: SuperTabAvatar.person(person, size: SuperTabAvatar.rowSize),
+ kind: 'person',
+ ),
+ for (final agent in offered)
+ (
+ label: superTabAgentName(c, agent),
+ detail: '${agent.engine} ${machineName(agent.machineId)}'.trim(),
+ choose: () => choose(agent.id, superTabAgentName(c, agent)),
+ leading: SuperTabAvatar.agent(agent, size: SuperTabAvatar.rowSize),
+ kind: 'agent',
+ ),
+ ].take(superTabCompletionLimit).toList();
+}
+
+/// [value] with the tag typed at [at] replaced by [token] and a space, the
+/// caret after it.
+TextEditingValue superTabInsertTag(
+ TextEditingValue value,
+ ({int start, int end, String query}) at,
+ String token,
+) {
+ final text = value.text.replaceRange(at.start, at.end, '$token ');
+ return TextEditingValue(
+ text: text,
+ selection: TextSelection.collapsed(offset: at.start + token.length + 1),
+ );
+}
+
+/// What a key does while [choices] show under a focused composer: arrows move
+/// the selection ([move]), Tab and Enter pick, Escape [dismiss]es the list.
+/// Null for any other key, a key with a modifier, or none shown: the box
+/// handles it as usual. [choices] is read only for a plain key press.
+KeyEventResult? superTabCompletionKey(
+ KeyEvent event, {
+ required List<SuperTabComposerChoice> Function() choices,
+ required int index,
+ required void Function(int index) move,
+ required VoidCallback dismiss,
+}) {
+ final keys = HardwareKeyboard.instance;
+ if (event is! KeyDownEvent ||
+ keys.isControlPressed ||
+ keys.isMetaPressed ||
+ keys.isAltPressed ||
+ keys.isShiftPressed) {
+ return null;
+ }
+ final shown = choices();
+ if (shown.isEmpty) return null;
+ final key = event.logicalKey;
+ if (key == LogicalKeyboardKey.arrowDown ||
+ key == LogicalKeyboardKey.arrowUp) {
+ move(
+ (index + (key == LogicalKeyboardKey.arrowDown ? 1 : -1)) % shown.length,
+ );
+ return KeyEventResult.handled;
+ }
+ if (key == LogicalKeyboardKey.tab || key == LogicalKeyboardKey.enter) {
+ shown[index.clamp(0, shown.length - 1)].choose();
+ return KeyEventResult.handled;
+ }
+ if (key == LogicalKeyboardKey.escape) {
+ dismiss();
+ return KeyEventResult.handled;
+ }
+ return null;
+}
+
+/// The list of [choices] above a composer, [index] selected; each row keyed
+/// by [rowKeys] so a move can scroll it into view.
+class SuperTabCompletionList extends StatelessWidget {
+ const SuperTabCompletionList({
+ super.key,
+ required this.listKey,
+ required this.choices,
+ required this.index,
+ required this.rowKeys,
+ });
+
+ final Key listKey;
+ final List<SuperTabComposerChoice> choices;
+ final int index;
+ final List<GlobalKey> rowKeys;
+
+ @override
+ Widget build(BuildContext context) => Material(
+ color: DesktopChrome.surface,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),
+ side: BorderSide(color: DesktopChrome.rim),
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight: MediaQuery.sizeOf(context).height * .3,
+ ),
+ child: ListView(
+ key: listKey,
+ shrinkWrap: true,
+ padding: const EdgeInsets.symmetric(
+ vertical: grid.AppDesktop.controlGap / 2,
+ ),
+ children: [
+ for (var i = 0; i < choices.length; i++)
+ ListTile(
+ key: rowKeys[i],
+ dense: true,
+ selected: i == index.clamp(0, choices.length - 1),
+ selectedTileColor: grid.AppSurface.selectedFill,
+ selectedColor: DesktopChrome.foreground,
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: grid.AppDesktop.groupGap,
+ ),
+ leading: choices[i].leading,
+ trailing: choices[i].kind == null
+ ? null
+ : Text(choices[i].kind!, style: DesktopChrome.metadata()),
+ title: Text(
+ choices[i].label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(),
+ ),
+ subtitle: choices[i].detail == null
+ ? null
+ : Text(
+ choices[i].detail!,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(),
+ ),
+ onTap: choices[i].choose,
+ ),
+ ],
+ ),
+ ),
+ );
+}
+
+/// Backspace right after a tag takes the whole tag, as in Slack: deleting the
+/// character before the caret, where one of [tags] ends, removes that tag.
+/// The draft then no longer holds it, so its agent is no longer addressed.
+class SuperTabTagBackspace extends TextInputFormatter {
+ SuperTabTagBackspace(this.tags);
+
+ final Iterable<String> Function() tags;
+
+ @override
+ TextEditingValue formatEditUpdate(
+ TextEditingValue oldValue,
+ TextEditingValue newValue,
+ ) {
+ final caret = oldValue.selection;
+ if (!caret.isValid ||
+ !caret.isCollapsed ||
+ caret.baseOffset == 0 ||
+ (newValue.composing.isValid && !newValue.composing.isCollapsed)) {
+ return newValue;
+ }
+ final end = caret.baseOffset;
+ if (newValue.selection != TextSelection.collapsed(offset: end - 1) ||
+ newValue.text != oldValue.text.replaceRange(end - 1, end, '')) {
+ return newValue;
+ }
+ final before = oldValue.text.substring(0, end);
+ final after = oldValue.text.substring(end);
+ if (after.isNotEmpty && !after.startsWith(RegExp(r'[\s.,!?;:]'))) {
+ return newValue;
+ }
+ for (final tag in tags()) {
+ final start = end - tag.length;
+ if (!before.endsWith(tag) ||
+ (start > 0 && !before[start - 1].contains(RegExp(r'\s')))) {
+ continue;
+ }
+ return TextEditingValue(
+ text: oldValue.text.replaceRange(start, end, ''),
+ selection: TextSelection.collapsed(offset: start),
+ );
+ }
+ return newValue;
+ }
+}
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index e00e8d6db..07ef2ddc7 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -681,6 +681,10 @@ class SuperTabController extends ChangeNotifier {
final _threadBefore = <String, Map<String, dynamic>>{};
final _threadDrafts = <String, String>{};
+ /// The people and agents picked with `@` in each thread's reply box, by its
+ /// conversation and root, as [_mentions] holds the chat's own.
+ final _threadMentions = <(String, String), Map<String, String>>{};
+
/// The thread open beside the chat.
({String conversationId, String root})? openedThread;
final _attachments = <String, HarnessAttachments>{};
@@ -944,6 +948,10 @@ class SuperTabController extends ChangeNotifier {
.toList();
}
+ /// Whether [conversationId]'s terminals are open as a group ([term]).
+ bool groupTerminalsOpen(String conversationId) =>
+ !accessRevoked && !devicesSelected && _terminals[conversationId] == '*';
+
void selectGroupTerminals(String conversationId) {
if (_disposed ||
accessRevoked ||
@@ -1265,6 +1273,7 @@ class SuperTabController extends ChangeNotifier {
_uploadErrors.removeWhere(
(key, _) => key is (String, String) && gone(key.$1),
);
+ _threadMentions.removeWhere((key, _) => gone(key.$1));
if (openedThread case final open? when gone(open.conversationId)) {
openedThread = null;
}
@@ -1309,7 +1318,30 @@ class SuperTabController extends ChangeNotifier {
}
String threadDraft(String root) => _threadDrafts[root] ?? '';
- void setThreadDraft(String root, String text) => _threadDrafts[root] = text;
+ void setThreadDraft(String root, String text) {
+ _threadDrafts[root] = text;
+ // A tag the text no longer says is no longer picked.
+ for (final MapEntry(key: thread, value: tags) in _threadMentions.entries) {
+ if (thread.$2 == root) {
+ tags.removeWhere((_, token) => !containsMention(text, token));
+ }
+ }
+ _threadMentions.removeWhere((_, tags) => tags.isEmpty);
+ }
+
+ /// The tags picked in the reply box of [root]'s thread in [conversationId].
+ Map<String, String> threadMentions(String conversationId, String root) =>
+ Map.unmodifiable(_threadMentions[(conversationId, root)] ?? const {});
+
+ /// [id] picked as [token] in the open thread's reply box, while its draft
+ /// says it.
+ void threadMention(String id, String token) {
+ final open = openedThread;
+ if (open == null || accessRevoked) return;
+ if (!containsMention(threadDraft(open.root), token)) return;
+ (_threadMentions[(open.conversationId, open.root)] ??= {})[id] = token;
+ _changed();
+ }
/// How many pages a thread reads when it opens; past them "Show earlier
/// replies" reads on, a page at a time.
@@ -1418,10 +1450,27 @@ class SuperTabController extends ChangeNotifier {
_pending != null) {
return null;
}
- final ids = await _uploadAll(open.conversationId, owner, (
- open.conversationId,
- open.root,
- ));
+ final thread = (open.conversationId, open.root);
+ // The tags as picked when sent: the box may take new ones meanwhile.
+ final picked = Map<String, String>.of(_threadMentions[thread] ?? const {});
+ final (:tagged, :addressed) = _tagsSaid(picked, text);
+ final failure = addressed.any((id) => !selected!.agentIds.contains(id))
+ ? 'A mentioned agent is no longer in this conversation. Remove its mention or choose another agent.'
+ // Only its own session hears a session's thread (backend
+ // routeBuddySession): another agent's tag there would be refused.
+ : addressed.isNotEmpty &&
+ (newSession || threadSession(open.root) != null)
+ ? 'Only this thread\'s session hears a reply here. Remove the agent\'s mention.'
+ : null;
+ if (failure != null) {
+ _failOperation(
+ failure,
+ command: {'conversationId': open.conversationId, 'replyTo': open.root},
+ );
+ _changed();
+ return null;
+ }
+ final ids = await _uploadAll(open.conversationId, owner, thread);
if (ids == null) return null;
final before = _pending;
final operationId = superTabOperationId();
@@ -1430,16 +1479,19 @@ class SuperTabController extends ChangeNotifier {
'conversationId': open.conversationId,
'text': text,
'replyTo': open.root,
- 'recipientIds': const <String>[],
+ 'recipientIds': addressed,
+ if (tagged.isNotEmpty) 'mentions': tagged,
// A session's thread stays in the thread: never also sent.
if (alsoSend && !newSession) 'alsoSend': true,
if (newSession) 'newSession': true,
if (ids.isNotEmpty) 'attachmentIds': ids,
});
if (_pending case final pending? when !identical(pending, before)) {
+ _sendingMentions[pending['operationId'] as String] = picked;
// Only a draft still holding what went: more may have been typed since.
if (_threadDrafts[open.root]?.trim() == text) {
_threadDrafts.remove(open.root);
+ _threadMentions.remove(thread);
}
onSending?.call();
_changed();
@@ -1484,6 +1536,9 @@ class SuperTabController extends ChangeNotifier {
}
} else {
_threadDrafts[root] = text;
+ if (refused.mentions.isNotEmpty) {
+ _threadMentions[(conversationId, root)] = refused.mentions;
+ }
}
unawaited(
_persist().catchError((Object _) {
@@ -2210,6 +2265,22 @@ class SuperTabController extends ChangeNotifier {
_saveSoon();
}
+ /// The tags of [picked] that [text] still says: a person's is a tag, an
+ /// agent's makes it a recipient.
+ ({List<String> tagged, List<String> addressed}) _tagsSaid(
+ Map<String, String> picked,
+ String text,
+ ) {
+ final said = picked.entries
+ .where((entry) => containsMention(text, entry.value))
+ .map((entry) => entry.key);
+ bool isPerson(String id) => snapshot?.people.any((p) => p.id == id) == true;
+ return (
+ tagged: said.where(isPerson).toList(),
+ addressed: said.where((id) => !isPerson(id)).toList(),
+ );
+ }
+
static bool containsMention(String text, String token) =>
RegExp('(?:^|\\s)${RegExp.escape(token)}(?=\$|\\s|[.,!?;:])')
.hasMatch(text);
@@ -3826,15 +3897,9 @@ class SuperTabController extends ChangeNotifier {
(files.isNotEmpty || newSession || !canQueueText))) {
return null;
}
- // A tag the text still says: an agent's is a recipient, a person's a tag.
- final said = mentions(selectedId).entries
- .where((entry) => containsMention(text, entry.value))
- .map((entry) => entry.key);
- bool isPerson(String id) => snapshot?.people.any((p) => p.id == id) == true;
- final tagged = said.where(isPerson).toList();
- final addressed = recipients.isEmpty
- ? said.where((id) => !isPerson(id)).toList()
- : recipients;
+ final said = _tagsSaid(mentions(selectedId), text);
+ final tagged = said.tagged;
+ final addressed = recipients.isEmpty ? said.addressed : recipients;
if (addressed.any((id) => !selected!.agentIds.contains(id))) {
_failOperation(
'A mentioned agent is no longer in this conversation. Remove its mention or choose another agent.',
diff --git a/desktop/lib/super_tabs/personal_projects.dart b/desktop/lib/super_tabs/personal_projects.dart
new file mode 100644
index 000000000..ce334d242
--- /dev/null
+++ b/desktop/lib/super_tabs/personal_projects.dart
@@ -0,0 +1,425 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:clock/clock.dart';
+import 'package:cryptography/dart.dart' show DartSha256;
+import 'package:flutter/foundation.dart';
+
+import '../state/app_state.dart';
+import '../state/swarm.dart';
+import '../state/terminal_pane.dart';
+import 'controller.dart';
+import 'model.dart';
+import 'swarm_switcher.dart' show PersonalSwarm;
+
+/// A person's panes as projects of their Personal Swarm (Dee, 10-30 design;
+/// "build the rest, but leave the tabs", 10-31): every pane of theirs joins
+/// the project of its repo, whatever tab it is in, the same repo on each of
+/// their computers being one project, and a pane with no repo joins
+/// # scratch. A project's [term] shows those very panes: the tab keeps them,
+/// and nothing about a tab changes.
+///
+/// Which pane belongs where is worked out here, on the person's own Desktop,
+/// from the panes it already shows. Nothing of a pane is sent anywhere: the
+/// server learns only each project's name, as a private project of a Swarm
+/// that has no one else in it.
+///
+/// Not yet: a repo that already has a team project joining that one. It
+/// crosses Swarms and needs its own security review.
+
+/// The key of the project for panes with no repo.
+const kScratchRepo = 'scratch';
+const kScratchProjectName = 'scratch';
+
+/// A pane's repo as one string for every computer: the remote's host and path,
+/// lower case, without scheme, user, password, port or `.git`, so
+/// `[email protected]:Owner/Api.git` and `https://github.com/owner/api` are one.
+/// Null for no remote, or one only this computer can reach (a folder).
+String? normalizedRemote(String? remote) {
+ var text = remote?.trim() ?? '';
+ if (text.isEmpty) return null;
+ String? host, path;
+ final url = RegExp(
+ r'^([a-z][a-z0-9+.-]*)://(.*)$',
+ caseSensitive: false,
+ ).firstMatch(text);
+ if (url != null) {
+ if (url.group(1)!.toLowerCase() == 'file') return null;
+ final rest = url.group(2)!;
+ final slash = rest.indexOf('/');
+ if (slash <= 0) return null;
+ var authority = rest.substring(0, slash);
+ authority = authority.substring(authority.lastIndexOf('@') + 1);
+ host = authority.replaceFirst(RegExp(r':\d*$'), '');
+ path = rest.substring(slash + 1);
+ } else {
+ // scp-like `user@host:owner/repo`; a path (`/x`, `./x`, `C:\x`) is no remote.
+ final scp = RegExp(r'^(?:[^@/\\]+@)?([^:/\\]+):(?!//)(.+)$')
+ .firstMatch(text);
+ if (scp == null || scp.group(1)!.length < 2) return null;
+ host = scp.group(1);
+ path = scp.group(2);
+ }
+ final parts = path!
+ .replaceFirst(RegExp(r'\.git/*$', caseSensitive: false), '')
+ .split('/')
+ .where((p) => p.isNotEmpty && p != '.' && p != '..')
+ .toList();
+ if (host == null || host.isEmpty || parts.isEmpty) return null;
+ return [host, ...parts].join('/').toLowerCase();
+}
+
+/// The repo's own name: `github.com/owner/api` is `api`.
+String repoName(String repo) => repo.split('/').last;
+
+/// The name that tells two repos of one name apart: `api (owner/api)`.
+String repoLongName(String repo) {
+ final parts = repo.split('/');
+ final tail = parts.length > 2 ? parts.sublist(parts.length - 2) : parts;
+ return '${repoName(repo)} (${tail.join('/')})';
+}
+
+String _hash(String text) => const DartSha256()
+ .hashSync(utf8.encode(text))
+ .bytes
+ .map((b) => b.toRadixString(16).padLeft(2, '0'))
+ .join()
+ .substring(0, 24);
+
+/// The request id a repo's project is created with: the same on every
+/// computer of the person's, so the server answers each with the one project
+/// (backend commands.ts `project.create`: the project's id comes from it).
+String personalProjectOperation(String repo) =>
+ repo == kScratchRepo ? 'personal-scratch' : 'personal-repo-${_hash(repo)}';
+
+/// One of the person's panes, the tab it is first in, and its repo
+/// ([kScratchRepo] for none).
+typedef PersonalPane = ({Swarm tab, TerminalPane pane, String repo});
+
+/// The person's own panes in their tabs, in tab order then each tab's reading
+/// order, each once. Swarm tabs, viewers and panes on another person's or a
+/// shared machine, or on a Harness Team account, are left out.
+List<PersonalPane> personalPanes(AppNotifier app) {
+ final seen = <(String, String)>{};
+ final out = <PersonalPane>[];
+ for (final tab in app.swarms) {
+ if (tab.isSuperTab || tab.isUtility) continue;
+ for (final pane in tab.panesInReadingOrder) {
+ final agentId = pane.agentId;
+ if (agentId == null || pane.isViewer) continue;
+ final machine = app.stateOf(pane.machineId);
+ if (machine == null ||
+ machine.belongsToOtherAccount ||
+ machine.machine.isTeamAccount) {
+ continue;
+ }
+ if (!seen.add((pane.machineId, agentId))) continue;
+ final agent = machine.agents.where((a) => a.id == agentId).firstOrNull;
+ out.add((
+ tab: tab,
+ pane: pane,
+ repo: normalizedRemote(agent?.project?.remote) ?? kScratchRepo,
+ ));
+ }
+ }
+ return out;
+}
+
+/// The projects made for the person's repos in their Personal Swarm, per app:
+/// made once, remembered on this computer, and found again by the same
+/// request on another.
+class PersonalProjects extends ChangeNotifier {
+ PersonalProjects._(this.app);
+ static final _of = Expando<PersonalProjects>();
+ static PersonalProjects of(AppNotifier app) =>
+ _of[app] ??= PersonalProjects._(app);
+
+ final AppNotifier app;
+
+ /// The longest wait before a failed repo's project is asked for again.
+ static const maxRetryWait = Duration(minutes: 5);
+
+ /// Each account's remembered projects, one key for all their Personal
+ /// Swarms: `super_tab.repos.<account>` (account_keys.dart sweeps it).
+ static String storageKey(String account) => 'super_tab.repos.$account';
+
+ /// Per account and Personal Swarm: repo to project id, null once the person
+ /// deleted it (it is not made again).
+ final _known = <String, Map<String, Map<String, String?>>>{};
+
+ /// Repos renamed to their long name, per account and Swarm.
+ final _renamed = <String, Map<String, Set<String>>>{};
+ final _loads = <String, Future<void>>{};
+ final _syncing = <String>{};
+ final _again = <String>{};
+ final _failures = <String, int>{};
+ final _retryAt = <String, DateTime>{};
+
+ /// The Personal Swarm [c] reads, while it is the signed-in person's alone
+ /// with no one else in it. Never a team Swarm.
+ bool eligible(SuperTabController c) {
+ final account = app.currentUser?.id;
+ final snapshot = c.snapshot;
+ return account != null &&
+ c.accountId == account &&
+ !c.accessRevoked &&
+ snapshot != null &&
+ identical(app.superTabs.peek(c.tabId), c) &&
+ PersonalSwarm.of(app).id == c.tabId &&
+ snapshot.ownerId == account &&
+ snapshot.people.every((p) => p.id == account);
+ }
+
+ Map<String, String?> _projects(String account, String swarm) =>
+ (_known[account] ??= {})[swarm] ??= {};
+
+ /// Which repos' panes the project [projectId] shows.
+ Set<String> _reposOf(String account, String swarm, String projectId) => {
+ for (final MapEntry(:key, :value)
+ in _known[account]?[swarm]?.entries ?? <MapEntry<String, String?>>[])
+ if (value == projectId) key,
+ };
+
+ /// The panes project [conversationId] of [c] shows behind [term], in their
+ /// tabs' order: its lead conversation in the person's own Personal Swarm,
+ /// else none. The very panes the tabs hold.
+ List<TerminalPane> panesFor(SuperTabController c, String conversationId) {
+ if (!eligible(c)) {
+ if (c.accessRevoked) _forget(c.accountId, c.tabId);
+ return const [];
+ }
+ final snapshot = c.snapshot!;
+ if (!snapshot.isProjectLead(conversationId)) return const [];
+ final project = snapshot.projectFor(conversationId);
+ if (project == null) return const [];
+ final repos = _reposOf(c.accountId, c.tabId, project.id);
+ if (repos.isEmpty) return const [];
+ return [
+ for (final entry in personalPanes(app))
+ if (repos.contains(entry.repo)) entry.pane,
+ ];
+ }
+
+ /// The tab all of [panes] come from, when they are exactly its panes: its
+ /// split sizes are theirs.
+ Swarm? soleTab(List<TerminalPane> panes) {
+ if (panes.isEmpty) return null;
+ final entries = personalPanes(app);
+ final tabs = {
+ for (final pane in panes)
+ entries.where((e) => identical(e.pane, pane)).firstOrNull?.tab,
+ };
+ if (tabs.length != 1) return null;
+ final tab = tabs.single;
+ if (tab == null || tab.panes.length != panes.length) return null;
+ final ordered = tab.panesInReadingOrder;
+ for (var i = 0; i < panes.length; i++) {
+ if (!identical(ordered[i], panes[i])) return null;
+ }
+ return tab;
+ }
+
+ /// Personal lost: what this computer kept of its projects goes.
+ void _forget(String account, String swarm) {
+ final had = _known[account]?.remove(swarm) != null;
+ _renamed[account]?.remove(swarm);
+ // Called while a view builds: saved after, and no one is told now.
+ if (had) unawaited(_save(account));
+ }
+
+ Future<void> _load(String account) => _loads[account] ??= () async {
+ try {
+ final raw = await app.superTabs.storage.read(storageKey(account));
+ if (raw == null || raw.isEmpty) return;
+ final saved = jsonDecode(raw);
+ if (saved is! Map) return;
+ for (final MapEntry(key: swarm, value: entry) in saved.entries) {
+ if (swarm is! String || entry is! Map) continue;
+ final projects = _projects(account, swarm);
+ final repos = entry['projects'];
+ if (repos is Map) {
+ for (final MapEntry(:key, :value) in repos.entries) {
+ if (key is String && (value == null || value is String)) {
+ projects.putIfAbsent(key, () => value as String?);
+ }
+ }
+ }
+ final renamed = entry['renamed'];
+ if (renamed is List) {
+ ((_renamed[account] ??= {})[swarm] ??= {}).addAll(
+ renamed.whereType<String>(),
+ );
+ }
+ }
+ } catch (_) {
+ // Nothing kept: each project is asked for again, and the server answers
+ // with the one it made.
+ }
+ }();
+
+ Future<void> _save(String account) async {
+ final known = _known[account] ?? const {};
+ final value = jsonEncode({
+ for (final MapEntry(key: swarm, value: projects) in known.entries)
+ swarm: {
+ 'projects': projects,
+ 'renamed': [...?_renamed[account]?[swarm]],
+ },
+ });
+ try {
+ await app.superTabs.storage.write(storageKey(account), value);
+ } catch (_) {
+ // Kept for this run; the next asks the server again, which repeats.
+ }
+ }
+
+ /// Makes the projects [c]'s Personal Swarm still lacks for the person's
+ /// panes, one request at a time, and tells apart two repos of one name.
+ /// Anything that answers after the Swarm, its access or the account
+ /// changed is dropped.
+ Future<void> sync(SuperTabController c) async {
+ if (!eligible(c)) {
+ if (c.accessRevoked) _forget(c.accountId, c.tabId);
+ return;
+ }
+ final account = c.accountId, swarm = c.tabId;
+ final scope = '$account/$swarm';
+ if (!_syncing.add(scope)) {
+ _again.add(scope);
+ return;
+ }
+ try {
+ await _load(account);
+ do {
+ _again.remove(scope);
+ if (!eligible(c)) return;
+ final projects = _projects(account, swarm);
+ final wanted = {for (final p in personalPanes(app)) p.repo};
+ var made = false;
+ for (final repo in wanted) {
+ if (projects.containsKey(repo)) continue;
+ final retryAt = _retryAt['$scope/$repo'];
+ if (retryAt != null && clock.now().isBefore(retryAt)) continue;
+ final answer = await _create(c, repo);
+ if (!eligible(c)) return;
+ if (answer case (:final id)) {
+ projects[repo] = id;
+ made = true;
+ await _save(account);
+ notifyListeners();
+ }
+ }
+ // The new projects read before two of one name are told apart.
+ if (made && !await _reread(c)) return;
+ if (!eligible(c)) return;
+ if (await _tellApart(c) && eligible(c)) await _reread(c);
+ } while (_again.contains(scope));
+ } finally {
+ _syncing.remove(scope);
+ }
+ }
+
+ /// Reads [c] again; false when that failed (the next change asks again).
+ Future<bool> _reread(SuperTabController c) async {
+ try {
+ await c.refresh();
+ return true;
+ } catch (_) {
+ return false;
+ }
+ }
+
+ /// Creates (or finds again) [repo]'s project: its id, null once the person
+ /// deleted it, or nothing on a failure, asked again after a wait that
+ /// doubles up to [maxRetryWait] when the Swarm next changes.
+ Future<({String? id})?> _create(SuperTabController c, String repo) async {
+ final key = '${c.accountId}/${c.tabId}/$repo';
+ try {
+ final answer = await c.request(
+ 'POST',
+ '/api/super-tabs/${Uri.encodeComponent(c.tabId)}/commands',
+ body: {
+ 'operationId': personalProjectOperation(repo),
+ 'command': {
+ 'type': 'project.create',
+ // Every computer sends the same request, so the name is the repo's
+ // own; two of one name are told apart after ([_tellApart]).
+ 'name': repo == kScratchRepo ? kScratchProjectName : repoName(repo),
+ 'visibility': 'private',
+ 'brief': '',
+ },
+ },
+ );
+ final id = superTabMap(answer['result'])['projectId'];
+ if (id is! String || id.isEmpty) throw const FormatException();
+ _failures.remove(key);
+ _retryAt.remove(key);
+ return (id: id);
+ } on SuperTabFailure catch (failure) {
+ // Deleted by the person: kept deleted (backend store.ts answers a
+ // repeated create of a deleted project so).
+ if (failure.code == 'NOT_FOUND' &&
+ failure.message.contains('deleted') &&
+ eligible(c)) {
+ return (id: null);
+ }
+ _failed(key);
+ } catch (_) {
+ _failed(key);
+ }
+ return null;
+ }
+
+ void _failed(String key) {
+ final count = _failures[key] = (_failures[key] ?? 0) + 1;
+ final wait = Duration(seconds: 5 << count.clamp(1, 6));
+ _retryAt[key] = clock.now().add(wait < maxRetryWait ? wait : maxRetryWait);
+ }
+
+ /// Two repos of one name, both still under it: each is renamed to its long
+ /// name, once. A name the person chose stays.
+ Future<bool> _tellApart(SuperTabController c) async {
+ final account = c.accountId, swarm = c.tabId;
+ final projects = _projects(account, swarm);
+ final renamed = (_renamed[account] ??= {})[swarm] ??= {};
+ final byName = <String, List<String>>{};
+ for (final MapEntry(key: repo, value: id) in projects.entries) {
+ if (id == null || repo == kScratchRepo) continue;
+ (byName[repoName(repo)] ??= []).add(repo);
+ }
+ var changed = false;
+ for (final repos in byName.values.where((r) => r.length > 1)) {
+ for (final repo in repos) {
+ if (renamed.contains(repo)) continue;
+ final id = projects[repo]!;
+ final project = c.snapshot?.projectById(id);
+ if (project == null || project.name != repoName(repo)) continue;
+ try {
+ await c.request(
+ 'POST',
+ '/api/super-tabs/${Uri.encodeComponent(swarm)}/commands',
+ body: {
+ 'operationId': 'personal-rename-${_hash(repo)}',
+ 'command': {
+ 'type': 'project.rename',
+ 'projectId': id,
+ 'name': repoLongName(repo),
+ },
+ },
+ );
+ } catch (_) {
+ continue;
+ }
+ if (!eligible(c)) return changed;
+ renamed.add(repo);
+ changed = true;
+ await _save(account);
+ }
+ }
+ return changed;
+ }
+
+ @visibleForTesting
+ Map<String, String?> knownForTest(String account, String swarm) =>
+ Map.of(_known[account]?[swarm] ?? const {});
+}
diff --git a/desktop/lib/super_tabs/thread_panel.dart b/desktop/lib/super_tabs/thread_panel.dart
index 049d4c910..9570c65fb 100644
--- a/desktop/lib/super_tabs/thread_panel.dart
+++ b/desktop/lib/super_tabs/thread_panel.dart
@@ -14,6 +14,7 @@ import '../widgets/new_harness_paste.dart';
import 'buddy_sessions.dart';
import 'composer_files.dart';
import 'composer_newline.dart';
+import 'composer_tags.dart';
import 'composer_toggle.dart';
import 'controller.dart';
import 'jump_to_latest.dart';
@@ -30,6 +31,7 @@ class SuperTabThreadPanel extends StatefulWidget {
required this.row,
required this.outgoing,
this.sessionActivity,
+ this.machineName,
});
final SuperTabController controller;
@@ -45,6 +47,9 @@ class SuperTabThreadPanel extends StatefulWidget {
/// without it, what the Swarm alone says.
final SuperTabSessionActivity? sessionActivity;
+ /// A machine's name, said beside an agent `@` offers.
+ final String Function(String machineId)? machineName;
+
@override
State<SuperTabThreadPanel> createState() => _SuperTabThreadPanelState();
}
@@ -68,9 +73,20 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {
// The newest row (reply or one on its way), as built and as last measured:
// earlier replies arriving above do not change it.
String? _newest, _newestMeasured;
+ // `@` in the reply box, as in the chat's (composer_tags.dart): the choice
+ // selected, and the text before the caret where the list was dismissed.
+ final _tagIndex = ValueNotifier(0);
+ final _tagDismissed = ValueNotifier<String?>(null);
+ final _tagRows = List.generate(superTabCompletionLimit, (_) => GlobalKey());
+ late final _tagBackspace = SuperTabTagBackspace(
+ () => c.threadMentions(_conversationId, widget.root).values,
+ );
SuperTabController get c => widget.controller;
+ /// The conversation this thread is in.
+ String get _conversationId => c.openedThread?.conversationId ?? c.selectedId;
+
@override
void initState() {
super.initState();
@@ -93,6 +109,8 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {
_composer.text = c.threadDraft(widget.root);
_alsoSend = false;
_newSession = false;
+ _tagIndex.value = 0;
+ _tagDismissed.value = null;
}
}
@@ -101,6 +119,8 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {
_scroll.dispose();
_composer.dispose();
_focus.dispose();
+ _tagIndex.dispose();
+ _tagDismissed.dispose();
super.dispose();
}
@@ -197,9 +217,56 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {
/// The box was edited: keep it as this thread's draft.
void _edited(String text) {
c.setThreadDraft(widget.root, text);
+ _tagIndex.value = 0;
+ _tagDismissed.value = null;
setState(() {});
}
+ /// The `@` tag typed at the caret.
+ ({int start, int end, String query})? get _tagAt => superTabTagAtCaret(
+ _composer.value,
+ dismissed: _tagDismissed.value,
+ tags: c.threadMentions(_conversationId, widget.root).values,
+ );
+
+ /// Who `@` offers in this reply: whom the chat's box offers, except agents
+ /// where the thread's own Buddy session alone hears the reply.
+ List<SuperTabComposerChoice> get _tagChoices {
+ final group = c.selected;
+ if (!_writable || group == null) return const [];
+ final at = _tagAt;
+ if (at == null) return const [];
+ return superTabTagChoices(
+ c,
+ group,
+ at.query,
+ machineName: widget.machineName ?? (_) => '',
+ choose: _chooseTag,
+ agents: !_startsSession && c.threadSession(widget.root) == null,
+ );
+ }
+
+ void _chooseTag(String id, String name) {
+ final at = _tagAt;
+ if (at == null) return;
+ final token = '@$name';
+ final value = superTabInsertTag(_composer.value, at, token);
+ c.setThreadDraft(widget.root, value.text);
+ c.threadMention(id, token);
+ _composer.value = value;
+ _tagIndex.value = 0;
+ _focus.requestFocus();
+ setState(() {});
+ }
+
+ void _moveTag(int index) {
+ _tagIndex.value = index;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ final row = _tagRows[index].currentContext;
+ if (mounted && row != null) Scrollable.ensureVisible(row, alignment: .5);
+ });
+ }
+
Future<void> _send() async {
if (!_writable ||
_busy ||
@@ -401,6 +468,28 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
+ ListenableBuilder(
+ listenable: Listenable.merge([
+ _composer,
+ _tagIndex,
+ _tagDismissed,
+ ]),
+ builder: (context, _) {
+ final choices = _tagChoices;
+ if (choices.isEmpty) return const SizedBox.shrink();
+ return Padding(
+ padding: const EdgeInsets.only(
+ bottom: grid.AppDesktop.controlGap,
+ ),
+ child: SuperTabCompletionList(
+ listKey: const ValueKey('super-thread-completions'),
+ choices: choices,
+ index: _tagIndex.value,
+ rowKeys: _tagRows,
+ ),
+ );
+ },
+ ),
_composerBox(),
// Its place is kept while New session is offered, so the
// box never moves as the choice is toggled.
@@ -469,6 +558,20 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {
SuperTabComposerChips(controller: c, files: files),
Focus(
onKeyEvent: (_, event) {
+ final composing = _composer.value.composing;
+ final picked =
+ _focus.hasFocus &&
+ !(composing.isValid && !composing.isCollapsed)
+ ? superTabCompletionKey(
+ event,
+ choices: () => _tagChoices,
+ index: _tagIndex.value,
+ move: _moveTag,
+ dismiss: () => _tagDismissed.value = _composer.text
+ .substring(0, _composer.selection.baseOffset),
+ )
+ : null;
+ if (picked != null) return picked;
switch (composerEnter(
event,
focused: _focus.hasFocus,
@@ -496,6 +599,7 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {
minLines: 1,
maxLines: 6,
maxLength: kComposerMaxLength,
+ inputFormatters: [_tagBackspace],
keyboardType: TextInputType.multiline,
style: DesktopChrome.text(),
decoration: InputDecoration(
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index e07bd0633..ab8c22c31 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -27,15 +27,16 @@ import 'roster.dart';
import 'recording_notice.dart';
import 'profile_actions.dart';
import 'live_card.dart';
+import 'personal_projects.dart';
import 'pull_request_facts.dart';
import 'pull_requests.dart';
import 'composer_files.dart';
import 'composer_newline.dart';
+import 'composer_tags.dart';
import 'composer_toggle.dart';
import 'controller.dart';
import 'dialog_scope.dart';
import 'folder_zip.dart';
-import 'identity.dart';
import 'instructions_panel.dart';
import 'model.dart';
import 'prompt_alerts.dart';
@@ -61,15 +62,7 @@ import 'project_options.dart';
import 'pane_layout.dart';
import '../widgets/dial_list_scroll.dart';
-/// A completion row: a workgroup, or someone to tag with their face and
-/// whether they are a person or an agent ([kind]).
-typedef _ComposerChoice = ({
- String label,
- String? detail,
- VoidCallback choose,
- Widget? leading,
- String? kind,
-});
+typedef _ComposerChoice = SuperTabComposerChoice;
/// The contents of one app tab. Its title stays in the app's existing tab bar.
/// [terminal] is the existing native pane, with its own controls and input.
@@ -179,7 +172,7 @@ class _SuperTabViewState extends State<SuperTabView>
// The composer's completions are drawn by builders of their own, so typing
// and choosing among them never rebuild the transcript.
final _mentionIndex = ValueNotifier(0);
- late final _tagBackspace = _TagBackspace(
+ late final _tagBackspace = SuperTabTagBackspace(
() => c.mentions(c.selectedId).values,
);
final _dismissedMention = ValueNotifier<String?>(null);
@@ -191,7 +184,10 @@ class _SuperTabViewState extends State<SuperTabView>
/// The chats whose dropped folders are being zipped.
final _zipping = <String>{};
- final _completionKeys = List.generate(6, (_) => GlobalKey());
+ final _completionKeys = List.generate(
+ superTabCompletionLimit,
+ (_) => GlobalKey(),
+ );
SuperTabController get c => widget.controller;
/// The open project's week board, read once for the right pane's members
@@ -216,8 +212,7 @@ class _SuperTabViewState extends State<SuperTabView>
widget.app?.devicesEnabled == true &&
!c.accessRevoked;
- String _agentName(SuperTabAgent agent) =>
- c.snapshot?.agentName(agent.id, fallback: agent.name) ?? agent.name;
+ String _agentName(SuperTabAgent agent) => superTabAgentName(c, agent);
String _authorName(SuperTabMessage message) =>
c.snapshot?.authorName(message) ?? message.authorName;
@@ -1028,87 +1023,35 @@ class _SuperTabViewState extends State<SuperTabView>
});
}
- ({int start, int end, String query})? get _mentionAtCursor {
- final value = _composer.value;
- if (!value.selection.isValid ||
- !value.selection.isCollapsed ||
- (value.composing.isValid && !value.composing.isCollapsed)) {
- return null;
- }
- final end = value.selection.baseOffset;
- final prefix = value.text.substring(0, end);
- final match = RegExp(r'(?:^|\s)@([^@\n]*)$').firstMatch(prefix);
- if (match == null || prefix == _dismissedMention.value) return null;
- final start = prefix.lastIndexOf('@');
- final query = match.group(1)!;
- if (c.mentions(c.selectedId).values.contains('@${query.trimRight()}')) {
- return null;
- }
- return (start: start, end: end, query: query.toLowerCase());
- }
+ ({int start, int end, String query})? get _mentionAtCursor =>
+ superTabTagAtCaret(
+ _composer.value,
+ dismissed: _dismissedMention.value,
+ tags: c.mentions(c.selectedId).values,
+ );
- /// Who `@` offers: the people who read this conversation, then its agents,
- /// filtered by what follows the `@`. Never the reader.
+ /// Who `@` offers here ([superTabTagChoices]).
List<_ComposerChoice> get _mentionChoices {
final mention = _mentionAtCursor;
- final snapshot = c.snapshot, group = c.selected;
- if (mention == null || snapshot == null || group == null) return const [];
- final project = snapshot.projectFor(group.id);
- bool reads(SuperTabPerson person) => switch (group) {
- SuperTabConversation(:final audience?) => audience.contains(person.id),
- _ when group.buddyOwnerId != null => person.id == group.buddyOwnerId,
- _ =>
- project == null ||
- !project.isPrivate ||
- project.ownerId == person.id ||
- project.memberIds.contains(person.id),
- };
- final people = snapshot.people.where(
- (person) =>
- person.id != c.accountId &&
- reads(person) &&
- person.username.contains(mention.query),
- );
- final agents = snapshot.agents.where(
- (agent) =>
- group.agentIds.contains(agent.id) &&
- // A thread's own session answers only there: nobody tags it.
- agent.buddySession == null &&
- '${_agentName(agent)} ${agent.engine}'.toLowerCase().contains(
- mention.query,
- ),
+ final group = c.selected;
+ if (mention == null || group == null) return const [];
+ return superTabTagChoices(
+ c,
+ group,
+ mention.query,
+ machineName: widget.machineName,
+ choose: _chooseMention,
);
- return [
- for (final person in people)
- (
- label: person.username,
- detail: null,
- choose: () => _chooseMention(person.id, person.username),
- leading: SuperTabAvatar.person(person, size: SuperTabAvatar.rowSize),
- kind: 'person',
- ),
- for (final agent in agents)
- (
- label: _agentName(agent),
- detail: '${agent.engine} ${widget.machineName(agent.machineId)}',
- choose: () => _chooseMention(agent.id, _agentName(agent)),
- leading: SuperTabAvatar.agent(agent, size: SuperTabAvatar.rowSize),
- kind: 'agent',
- ),
- ].take(_completionKeys.length).toList();
}
void _chooseMention(String id, String name) {
final at = _mentionAtCursor;
if (at == null) return;
final token = '@$name';
- final text = _composer.text.replaceRange(at.start, at.end, '$token ');
- c.setDraft(c.selectedId, text);
+ final value = superTabInsertTag(_composer.value, at, token);
+ c.setDraft(c.selectedId, value.text);
c.mention(c.selectedId, id, token);
- _composer.value = TextEditingValue(
- text: text,
- selection: TextSelection.collapsed(offset: at.start + token.length + 1),
- );
+ _composer.value = value;
_mentionIndex.value = 0;
_focus.requestFocus();
}
@@ -2000,10 +1943,19 @@ class _SuperTabViewState extends State<SuperTabView>
bool get _menuNamesViews =>
_phone && !_devicesVisible && !_notificationsVisible;
+ /// How many terminals [group]'s [term] opens: its agents', and in the
+ /// person's own Personal Swarm their panes of its project.
+ int _terminalCount(SuperTabConversation group) =>
+ group.agentIds.length +
+ switch (widget.app) {
+ final app? => PersonalProjects.of(app).panesFor(c, group.id).length,
+ null => 0,
+ };
+
/// Opens the group's terminals beside the chat; null when it has none this
/// reader may open (a read-only viewer's terminal reads are refused).
VoidCallback? _openTerminals(SuperTabConversation group) =>
- group.agentIds.isNotEmpty && c.canWrite
+ _terminalCount(group) > 0 && c.canWrite
? () {
setState(() => _showPullRequests = false);
widget.onOpenGroupTerminals?.call();
@@ -2150,7 +2102,7 @@ class _SuperTabViewState extends State<SuperTabView>
key: const ValueKey('super-terminals'),
icon: AppIcons.terminal,
size: AppIcons.inlineSize,
- tooltip: 'Group terminals (${group.agentIds.length})',
+ tooltip: 'Group terminals (${_terminalCount(group)})',
selected: _terminalsVisible,
color: _terminalsVisible
? DesktopChrome.foreground
@@ -2218,7 +2170,7 @@ class _SuperTabViewState extends State<SuperTabView>
menuChildren: [
if (views) ...[
item(
- 'Group terminals (${group.agentIds.length})',
+ 'Group terminals (${_terminalCount(group)})',
_openTerminals(group),
),
item('Pull requests', _openPullRequests),
@@ -2625,6 +2577,7 @@ class _SuperTabViewState extends State<SuperTabView>
outgoing: (sent) => _outgoingRow(sent, byId, grouped: false),
sessionActivity: (session) =>
superTabSessionActivity(c, widget.app, session),
+ machineName: widget.machineName,
);
}
@@ -3336,62 +3289,11 @@ class _SuperTabViewState extends State<SuperTabView>
if (choices.isEmpty) return const SizedBox.shrink();
return Padding(
padding: const EdgeInsets.fromLTRB(24, 8, 24, 0),
- child: Material(
- color: DesktopChrome.surface,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(
- DesktopChrome.controlRadius,
- ),
- side: BorderSide(color: DesktopChrome.rim),
- ),
- clipBehavior: Clip.antiAlias,
- child: ConstrainedBox(
- constraints: BoxConstraints(
- maxHeight: MediaQuery.sizeOf(context).height * .3,
- ),
- child: ListView(
- key: const ValueKey('super-composer-completions'),
- shrinkWrap: true,
- padding: const EdgeInsets.symmetric(vertical: 4),
- children: [
- for (var i = 0; i < choices.length; i++)
- ListTile(
- key: _completionKeys[i],
- dense: true,
- selected:
- i ==
- _mentionIndex.value.clamp(0, choices.length - 1),
- selectedTileColor: grid.AppSurface.selectedFill,
- selectedColor: DesktopChrome.foreground,
- contentPadding: const EdgeInsets.symmetric(
- horizontal: 16,
- ),
- leading: choices[i].leading,
- trailing: choices[i].kind == null
- ? null
- : Text(
- choices[i].kind!,
- style: DesktopChrome.metadata(),
- ),
- title: Text(
- choices[i].label,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: DesktopChrome.control(),
- ),
- subtitle: choices[i].detail == null
- ? null
- : Text(
- choices[i].detail!,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: DesktopChrome.metadata(),
- ),
- onTap: choices[i].choose,
- ),
- ],
- ),
- ),
+ child: SuperTabCompletionList(
+ listKey: const ValueKey('super-composer-completions'),
+ choices: choices,
+ index: _mentionIndex.value,
+ rowKeys: _completionKeys,
),
);
},
@@ -3438,43 +3340,20 @@ class _SuperTabViewState extends State<SuperTabView>
),
child: Focus(
onKeyEvent: (node, event) {
- final keys = HardwareKeyboard.instance;
final composing = _composer.value.composing;
- final choices =
+ final picked =
_focus.hasFocus &&
- event is KeyDownEvent &&
- !keys.isControlPressed &&
- !keys.isMetaPressed &&
- !keys.isAltPressed &&
- !keys.isShiftPressed &&
!(composing.isValid && !composing.isCollapsed)
- ? _completionChoices
- : const <_ComposerChoice>[];
- if (choices.isNotEmpty) {
- final key = event.logicalKey;
- if (key == LogicalKeyboardKey.arrowDown ||
- key == LogicalKeyboardKey.arrowUp) {
- _moveCompletion(
- (_mentionIndex.value +
- (key == LogicalKeyboardKey.arrowDown ? 1 : -1)) %
- choices.length,
- );
- return KeyEventResult.handled;
- }
- if (key == LogicalKeyboardKey.tab ||
- key == LogicalKeyboardKey.enter) {
- choices[_mentionIndex.value.clamp(0, choices.length - 1)]
- .choose();
- return KeyEventResult.handled;
- }
- if (key == LogicalKeyboardKey.escape) {
- _dismissedMention.value = _composer.text.substring(
- 0,
- _composer.selection.baseOffset,
- );
- return KeyEventResult.handled;
- }
- }
+ ? superTabCompletionKey(
+ event,
+ choices: () => _completionChoices,
+ index: _mentionIndex.value,
+ move: _moveCompletion,
+ dismiss: () => _dismissedMention.value = _composer.text
+ .substring(0, _composer.selection.baseOffset),
+ )
+ : null;
+ if (picked != null) return picked;
if (event is KeyDownEvent &&
event.logicalKey == LogicalKeyboardKey.escape &&
_readAll()) {
@@ -3899,51 +3778,6 @@ class _SuperTabViewState extends State<SuperTabView>
);
}
-/// Backspace right after a tag takes the whole tag, as in Slack: deleting the
-/// character before the caret, where one of [tags] ends, removes that tag.
-/// The draft then no longer holds it, so its agent is no longer addressed.
-class _TagBackspace extends TextInputFormatter {
- _TagBackspace(this.tags);
-
- final Iterable<String> Function() tags;
-
- @override
- TextEditingValue formatEditUpdate(
- TextEditingValue oldValue,
- TextEditingValue newValue,
- ) {
- final caret = oldValue.selection;
- if (!caret.isValid ||
- !caret.isCollapsed ||
- caret.baseOffset == 0 ||
- (newValue.composing.isValid && !newValue.composing.isCollapsed)) {
- return newValue;
- }
- final end = caret.baseOffset;
- if (newValue.selection != TextSelection.collapsed(offset: end - 1) ||
- newValue.text != oldValue.text.replaceRange(end - 1, end, '')) {
- return newValue;
- }
- final before = oldValue.text.substring(0, end);
- final after = oldValue.text.substring(end);
- if (after.isNotEmpty && !after.startsWith(RegExp(r'[\s.,!?;:]'))) {
- return newValue;
- }
- for (final tag in tags()) {
- final start = end - tag.length;
- if (!before.endsWith(tag) ||
- (start > 0 && !before[start - 1].contains(RegExp(r'\s')))) {
- continue;
- }
- return TextEditingValue(
- text: oldValue.text.replaceRange(start, end, ''),
- selection: TextSelection.collapsed(offset: start),
- );
- }
- return newValue;
- }
-}
-
/// Records its row's context while built, so [_SuperTabViewState] can find
/// the row a message is shown in.
class _BuiltRow extends StatefulWidget {
diff --git a/desktop/lib/super_tabs/workspace.dart b/desktop/lib/super_tabs/workspace.dart
index 55f0efb70..50f5dca2c 100644
--- a/desktop/lib/super_tabs/workspace.dart
+++ b/desktop/lib/super_tabs/workspace.dart
@@ -11,7 +11,9 @@ import 'controller.dart';
import 'dialog_scope.dart';
import 'model.dart';
import 'pane.dart';
+import 'personal_projects.dart';
import 'sharing.dart';
+import 'swarm_switcher.dart' show PersonalSwarm;
import 'terminal_unavailable.dart';
import 'view.dart';
@@ -39,8 +41,8 @@ class SuperTabWorkspace extends StatefulWidget {
class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {
final _canvasKey = GlobalKey();
AppNotifier get app => widget.app;
- (String, String, String?, String, bool)? _terminalRequest;
- (String, String, String?, String, bool)? _readyRequest;
+ (String, String, String?, String, bool, String)? _terminalRequest;
+ (String, String, String?, String, bool, String)? _readyRequest;
// Navigation never undoes a person's stop. Only the pane's explicit Resume
// action may restart a saved session, with the Swarm's native context.
(String, String)? _resumeRequest;
@@ -104,7 +106,15 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {
super.dispose();
}
+ /// The person's own panes a Personal project shows behind its [term]: the
+ /// panes their tabs hold, never a copy (personal_projects.dart).
+ List<TerminalPane> _localPanes(SuperTabController controller) =>
+ controller.groupTerminalsOpen(controller.selectedId)
+ ? PersonalProjects.of(app).panesFor(controller, controller.selectedId)
+ : const [];
+
void _syncTerminal(SuperTabController controller, String swarmId) {
+ final local = _localPanes(controller);
final devices =
controller.devicesSelected &&
app.devicesEnabled &&
@@ -126,6 +136,7 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {
.join(','),
controller.accountId,
controller.canWrite,
+ local.map((p) => '${p.machineId}/${p.agentId}').join(','),
);
if (_terminalRequest == request) return;
_clearNativeContext();
@@ -163,11 +174,25 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {
// Keep only the dashboard when revisiting Devices, also removing
// the chat slot or session restored from its former split layout.
if (devices && pane.isDevices) continue;
- if (!agents.any(
- (a) => a.machineId == pane.machineId && a.harnessId == pane.agentId,
- )) {
+ final shown =
+ agents.any(
+ (a) =>
+ a.machineId == pane.machineId &&
+ a.harnessId == pane.agentId,
+ ) ||
+ local.any(
+ (p) =>
+ p.machineId == pane.machineId && p.agentId == pane.agentId,
+ );
+ if (!shown) {
if (!current()) return;
- await app.closePane(pane.id, swarmId: swarmId);
+ // One of the person's own panes leaves this view only: its tab
+ // keeps it, and it is no closed harness.
+ if (_isPersonsOwn(pane, swarmId)) {
+ await app.releaseSuperTabView(swarmId, pane.id);
+ } else {
+ await app.closePane(pane.id, swarmId: swarmId);
+ }
}
}
if (devices) {
@@ -187,10 +212,31 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {
resume == (request.$2, agent.id),
);
}
+ for (final pane in local) {
+ if (!current()) return;
+ // The very pane its tab shows, as it is there: same session, same
+ // input and composer. No Swarm terminal sharing is asked for.
+ await app.assignAgentToPane(
+ null,
+ pane.machineId,
+ pane.agentId!,
+ swarmId: swarmId,
+ inputContext: pane.inputContext,
+ watchOnly: pane.watchOnly,
+ autoTile: true,
+ focus: false,
+ intent: AttachIntent.automatic,
+ );
+ }
+ if (current() && agents.isEmpty && tab != null) {
+ if (PersonalProjects.of(app).soleTab(local) case final source?) {
+ app.copySuperTabLayout(swarmId, source);
+ }
+ }
if (current()) {
if (tab != null) tab.zoomedPaneId = null;
final focused = agents.where((a) => a.id == focus?.$2).firstOrNull;
- if (focused != null || agents.length == 1) {
+ if (focused != null || agents.length + local.length == 1) {
if ((focused == null
? tab?.panes.firstOrNull
: tab?.panes
@@ -211,6 +257,15 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {
});
}
+ /// Whether [pane] in Swarm tab [swarmId] is one of the person's own panes,
+ /// held by one of their other tabs too.
+ bool _isPersonsOwn(TerminalPane pane, String swarmId) => app.swarms.any(
+ (tab) =>
+ tab.id != swarmId &&
+ !tab.isSuperTab &&
+ tab.panes.any((p) => identical(p, pane)),
+ );
+
Future<void> _open(
SuperTabAgent agent,
SuperTabController controller,
@@ -468,15 +523,23 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {
return ListenableBuilder(
listenable: controller,
builder: (context, _) {
+ if (PersonalSwarm.of(app).id == controller.tabId) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) {
+ unawaited(PersonalProjects.of(app).sync(controller));
+ }
+ });
+ }
_syncTerminal(controller, tab.id);
final agents = controller.terminalAgents(controller.selectedId);
+ final local = _localPanes(controller);
final devices =
controller.devicesSelected &&
app.devicesEnabled &&
!controller.accessRevoked;
final showTerminal =
_readyRequest == _terminalRequest &&
- (devices || agents.isNotEmpty) &&
+ (devices || agents.isNotEmpty || local.isNotEmpty) &&
tab.panes.isNotEmpty;
// The terminal canvas is mounted either way; whether a person can see it is this.
WidgetsBinding.instance.addPostFrameCallback((_) {
@@ -495,6 +558,14 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {
'',
),
titles: {
+ for (final p in local)
+ if (app
+ .stateOf(p.machineId)
+ ?.agents
+ .where((a) => a.id == p.agentId)
+ .firstOrNull
+ case final agent?)
+ (p.machineId, p.agentId!): agent.name,
for (final a in agents)
(a.machineId, a.harnessId): controller.snapshot!.agentName(
a.id,
@@ -552,7 +623,7 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {
unawaited(_chooseAgentGroup(controller, tab.id, agent)),
onOpenGroupTerminals: () =>
controller.selectGroupTerminals(controller.selectedId),
- terminalsVisible: agents.isNotEmpty,
+ terminalsVisible: agents.isNotEmpty || local.isNotEmpty,
app: app,
machineName: (machine) =>
app.stateOf(machine)?.machine.displayName ??
@@ -561,7 +632,7 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {
app.stateOf(machine)?.isLocalMachine == true,
terminal: showTerminal
? terminal
- : devices || agents.isNotEmpty
+ : devices || agents.isNotEmpty || local.isNotEmpty
? const Center(child: CircularProgressIndicator())
: null,
onCloseTerminal: () {
diff --git a/desktop/lib/widgets/sign_in_step.dart b/desktop/lib/widgets/sign_in_step.dart
index 96467b736..7d7f2675d 100644
--- a/desktop/lib/widgets/sign_in_step.dart
+++ b/desktop/lib/widgets/sign_in_step.dart
@@ -5,6 +5,7 @@ import 'package:flutter/services.dart';
import '../auth/phone_sign_in.dart';
import '../auth/sign_in_provider.dart';
+import '../core/runtime_platform.dart';
import '../logging/app_log.dart';
import '../shared/theme/app_icons.dart';
import '../shared/theme/app_theme.dart' as grid;
@@ -42,6 +43,27 @@ const signInStepBenefits = [
(icon: AppIcons.panelsTopLeft, line: 'Same tabs on every computer'),
];
+/// The bottom bar's line while nothing is under way: which computer this is,
+/// and whether Harness is already set up on it (Scholes's end-to-end test of
+/// 1.3.44, finding 5: every relaunch showed a bare page that knew nothing of
+/// the computer). [mac] words it "This Mac", else "This computer".
+String signInStepReadyLine({
+ String? computerName,
+ bool setUp = false,
+ bool mac = true,
+}) {
+ final here = mac ? 'This Mac' : 'This computer';
+ final name = computerName?.trim();
+ if (name == null || name.isEmpty) {
+ return setUp
+ ? '$here is set up. Sign in to continue.'
+ : 'Sign in to continue.';
+ }
+ return setUp
+ ? '$here ($name) is set up. Sign in to continue.'
+ : '$here: $name. Sign in to continue.';
+}
+
/// The page itself, apart from the app: what it says and its three controls.
class SignInStep extends StatelessWidget {
const SignInStep({
@@ -58,6 +80,7 @@ class SignInStep extends StatelessWidget {
this.signOutError,
this.onRetrySignOut,
this.recovery,
+ this.readyLine = 'Sign in to continue.',
});
/// Continue with Google, Continue with Apple, or — with no provider — Email,
@@ -89,6 +112,10 @@ class SignInStep extends StatelessWidget {
final VoidCallback? onRetrySignOut;
final Widget? recovery;
+ /// The bottom bar's line while nothing is under way
+ /// ([signInStepReadyLine]).
+ final String readyLine;
+
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
@@ -111,7 +138,7 @@ class SignInStep extends StatelessWidget {
? 'Signing in…'
: sessionExpired
? 'Your session ended. Sign in again to continue.'
- : 'Sign in to continue.',
+ : readyLine,
),
],
);
@@ -540,6 +567,11 @@ class _SignInStepScreenState extends State<SignInStepScreen> {
finishing: app.signingIn && !app.canCancelLogin,
error: app.loginBrowserError ?? _error,
sessionExpired: app.sessionExpired,
+ readyLine: signInStepReadyLine(
+ computerName: app.thisComputerName,
+ setUp: app.harnessSetUpBefore,
+ mac: RuntimePlatform.isMacOS,
+ ),
signingOut: app.signingOut,
signOutError: app.signOutError,
onRetrySignOut: () => unawaited(app.logout()),
diff --git a/desktop/test/sign_in_step_flow_test.dart b/desktop/test/sign_in_step_flow_test.dart
index d7761d147..d604dd0ef 100644
--- a/desktop/test/sign_in_step_flow_test.dart
+++ b/desktop/test/sign_in_step_flow_test.dart
@@ -674,4 +674,28 @@ void main() {
});
});
});
+
+ group('whether the sign-in page calls this computer set up', () {
+ test('not on the launch that first installs Harness', () async {
+ final app = _Desktop(_Login());
+ addTearDown(app.dispose);
+ await app.bootstrap();
+ expect(app.harnessSetUpBefore, isFalse);
+ });
+
+ test('yes on a relaunch, which installs nothing', () async {
+ final app = _Desktop(_Login(), installed: true);
+ addTearDown(app.dispose);
+ await app.bootstrap();
+ expect(app.signInStepShowing, isTrue);
+ expect(app.harnessSetUpBefore, isTrue);
+ });
+
+ test('yes when only a repair ran on a computer that had Harness', () async {
+ final app = _Desktop(_Login())..harnessInstalledBefore = () => true;
+ addTearDown(app.dispose);
+ await app.bootstrap();
+ expect(app.harnessSetUpBefore, isTrue);
+ });
+ });
}
diff --git a/desktop/test/sign_in_step_machine_line_test.dart b/desktop/test/sign_in_step_machine_line_test.dart
new file mode 100644
index 000000000..5dd46d9fe
--- /dev/null
+++ b/desktop/test/sign_in_step_machine_line_test.dart
@@ -0,0 +1,256 @@
+/// The sign-in page names this computer (Scholes's end-to-end test of Desktop
+/// 1.3.44, finding 5): every relaunch showed the bare page, with nothing about
+/// a computer the app already knows. The bottom bar's line now says which
+/// computer this is, and that Harness is set up on it when it was there before
+/// this launch. Only this computer's own name is ever shown: no account, no
+/// other machine. `HARNESS_SIGN_IN_CAPTURE_DIR` writes the three lines in both
+/// themes.
+library;
+
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/core/runtime_platform.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/widgets/sign_in_step.dart';
+
+import 'support/capture.dart';
+
+final _line = find.byKey(const Key('sign-in-step-ready-line'));
+final _boundary = GlobalKey();
+
+String _lineText(WidgetTester tester) => tester.widget<Text>(_line).data!;
+
+Machine _machine(String id, String? name) => Machine(
+ machineId: id,
+ name: name,
+ computerId: 'computer-$id',
+ authMode: MachineAuthMode.remote,
+ status: 'online',
+);
+
+AppNotifier _app() => AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+)..status = AppStatus.authenticated;
+
+void _thisComputer(AppNotifier app, String? name) {
+ final machine = _machine('local', name);
+ app.machines = [...app.machines, machine];
+ app.machineStates['local'] = MachineState(machine)..localOnly = true;
+}
+
+void _otherMachine(AppNotifier app, String name) {
+ final machine = _machine('other', name);
+ app.machines = [...app.machines, machine];
+ app.machineStates['other'] = MachineState(machine);
+}
+
+Future<void> _mountPage(
+ WidgetTester tester, {
+ required String readyLine,
+ Brightness brightness = Brightness.dark,
+ bool finishing = false,
+ bool sessionExpired = false,
+ bool signingOut = false,
+}) async {
+ final previous = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previous);
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1280, 800);
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ home: RepaintBoundary(
+ key: _boundary,
+ child: SignInStep(
+ onSignIn: (_) {},
+ onApprove: (_) {},
+ readyLine: readyLine,
+ finishing: finishing,
+ sessionExpired: sessionExpired,
+ signingOut: signingOut,
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+}
+
+Future<void> _mountScreen(WidgetTester tester, AppNotifier app) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1280, 800);
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SignInStepScreen(app: app),
+ ),
+ );
+ await tester.pump();
+}
+
+void main() {
+ setUpAll(
+ () => loadCaptureFonts(Platform.environment['HARNESS_SIGN_IN_CAPTURE_DIR']),
+ );
+
+ group('the line', () {
+ test('a computer Harness was on before: set up, and its name', () {
+ expect(
+ signInStepReadyLine(computerName: 'Studio', setUp: true),
+ 'This Mac (Studio) is set up. Sign in to continue.',
+ );
+ });
+
+ test('a first run: its name', () {
+ expect(
+ signInStepReadyLine(computerName: 'Studio'),
+ 'This Mac: Studio. Sign in to continue.',
+ );
+ });
+
+ test('no name known yet', () {
+ expect(signInStepReadyLine(), 'Sign in to continue.');
+ expect(signInStepReadyLine(computerName: ' '), 'Sign in to continue.');
+ expect(
+ signInStepReadyLine(setUp: true),
+ 'This Mac is set up. Sign in to continue.',
+ );
+ });
+
+ test('Linux and Windows say computer', () {
+ expect(
+ signInStepReadyLine(computerName: 'box', setUp: true, mac: false),
+ 'This computer (box) is set up. Sign in to continue.',
+ );
+ expect(
+ signInStepReadyLine(computerName: 'box', mac: false),
+ 'This computer: box. Sign in to continue.',
+ );
+ });
+ });
+
+ group('the page', () {
+ testWidgets('shows the line in its bottom bar', (tester) async {
+ const line = 'This Mac (Studio) is set up. Sign in to continue.';
+ await _mountPage(tester, readyLine: line);
+ expect(_lineText(tester), line);
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('what is under way still wins over it', (tester) async {
+ const line = 'This Mac: Studio. Sign in to continue.';
+ await _mountPage(tester, readyLine: line, finishing: true);
+ expect(_lineText(tester), 'Signing in…');
+ await _mountPage(tester, readyLine: line, signingOut: true);
+ expect(_lineText(tester), 'Signing out…');
+ await _mountPage(tester, readyLine: line, sessionExpired: true);
+ expect(
+ _lineText(tester),
+ 'Your session ended. Sign in again to continue.',
+ );
+ });
+
+ for (final brightness in Brightness.values) {
+ for (final (name, line) in [
+ ('set-up', signInStepReadyLine(computerName: 'Studio', setUp: true)),
+ ('first-run', signInStepReadyLine(computerName: 'Studio')),
+ ('no-name', signInStepReadyLine()),
+ ]) {
+ testWidgets('draws the $name line in ${brightness.name}', (
+ tester,
+ ) async {
+ await _mountPage(tester, readyLine: line, brightness: brightness);
+ expect(tester.takeException(), isNull);
+ expect(_lineText(tester), line);
+ await captureBoundary(
+ tester,
+ _boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary,
+ Platform.environment['HARNESS_SIGN_IN_CAPTURE_DIR'],
+ 'sign-in-machine-$name-${brightness.name}',
+ );
+ });
+ }
+ }
+ });
+
+ group('on the app', () {
+ String expected(String? name, {required bool setUp}) => signInStepReadyLine(
+ computerName: name,
+ setUp: setUp,
+ mac: RuntimePlatform.isMacOS,
+ );
+
+ testWidgets('names this computer by its own row, without .local', (
+ tester,
+ ) async {
+ final app = _app();
+ addTearDown(app.dispose);
+ _thisComputer(app, 'Studio.local');
+ expect(app.thisComputerName, 'Studio');
+ await _mountScreen(tester, app);
+ // Nothing installed Harness on this launch in a test: it was set up.
+ expect(_lineText(tester), expected('Studio', setUp: true));
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('a name a person chose stays as it is', (tester) async {
+ final app = _app();
+ addTearDown(app.dispose);
+ _thisComputer(app, 'Ken’s Studio');
+ expect(app.thisComputerName, 'Ken’s Studio');
+ });
+
+ testWidgets('never another machine’s name', (tester) async {
+ final app = _app();
+ addTearDown(app.dispose);
+ _otherMachine(app, 'Someone else’s laptop');
+ _thisComputer(app, 'Studio');
+ await _mountScreen(tester, app);
+ expect(_lineText(tester), isNot(contains('laptop')));
+ expect(_lineText(tester), expected('Studio', setUp: true));
+
+ // With no row of its own yet, the host name stands in — still never
+ // the other machine.
+ app.machineStates.remove('local');
+ app.machines = [app.machines.first];
+ expect(app.thisComputerName, isNot(contains('laptop')));
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('follows this computer’s row as it arrives and changes', (
+ tester,
+ ) async {
+ final app = _app();
+ addTearDown(app.dispose);
+ await _mountScreen(tester, app);
+ final before = _lineText(tester);
+ expect(before, isNot(contains('Studio-2')));
+
+ _thisComputer(app, 'Studio-2');
+ app.notifyListeners();
+ await tester.pump();
+ expect(_lineText(tester), expected('Studio-2', setUp: true));
+
+ // A sign-out clears the rows: the old row's name goes with them.
+ app.machineStates.clear();
+ app.machines = [];
+ app.notifyListeners();
+ await tester.pump();
+ expect(_lineText(tester), isNot(contains('Studio-2')));
+ await tester.pumpWidget(const SizedBox());
+ });
+ });
+}
diff --git a/desktop/test/signed_out_polling_test.dart b/desktop/test/signed_out_polling_test.dart
new file mode 100644
index 000000000..d27d2b66b
--- /dev/null
+++ b/desktop/test/signed_out_polling_test.dart
@@ -0,0 +1,292 @@
+/// A signed-out computer stays quiet.
+///
+/// Without an account the app still prepares this computer's workspace behind
+/// the sign-in page (a guest window), and that used to arm the same background
+/// re-reads a signed-in window keeps: the agent list every minute and the
+/// machine list every five, for as long as nobody signed in. An unattended
+/// computer left on the sign-in page never went idle (Scholes's end-to-end
+/// test of Desktop 1.3.44, finding 4).
+///
+/// These pin that a guest asks nothing on a timer, that signing in starts the
+/// re-reads, and that signing out stops them again. The local service itself
+/// keeps running: supervision and the first read are not polls.
+library;
+
+import 'dart:async';
+
+import 'package:fake_async/fake_async.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/auth/cli_login.dart';
+import 'package:harness/auth/sign_in_provider.dart';
+import 'package:harness/bootstrap/environment_provisioner.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/ws/local_cli_discovery.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'swarm_state_test.dart' show MemoryStore;
+
+const _computerId = 'aabbccddeeff0011';
+
+const _thisComputer = Machine(
+ machineId: 'local-machine',
+ name: 'Studio',
+ computerId: _computerId,
+ authMode: MachineAuthMode.remote,
+ status: 'online',
+);
+
+/// What the app asks, counted: the machine list (through the CLI to the
+/// backend) and every request on this computer's socket.
+class _Asked {
+ int machineReads = 0;
+ int agentReads = 0;
+}
+
+class _Api extends ApiClient {
+ _Api(this.asked)
+ : super(
+ config: AppConfig.dev,
+ session: AuthSession(storage: MemoryStore()),
+ );
+ final _Asked asked;
+
+ @override
+ Future<Map<String, dynamic>?> me() async => null;
+
+ @override
+ Future<Map<String, dynamic>?> desk() async => null;
+
+ @override
+ Future<Map<String, dynamic>?> daemonDevices() async => null;
+
+ @override
+ Future<List<Machine>> machines() async {
+ asked.machineReads++;
+ return const [_thisComputer];
+ }
+}
+
+class _Login extends CliLogin {
+ _Login({this.loggedIn = false});
+ bool loggedIn;
+ Completer<void>? pending;
+
+ @override
+ Future<CliAuthStatus> checkStatus() async =>
+ CliAuthStatus(loggedIn: loggedIn);
+
+ // Never the real CLI: this Mac stays signed in whatever a test does.
+ @override
+ Future<void> logout() async => loggedIn = false;
+
+ @override
+ Future<void> login({
+ required void Function(String) onAuthorizeUrl,
+ SignInProvider? provider,
+ }) async {
+ final wait = pending = Completer<void>();
+ await wait.future;
+ loggedIn = true;
+ }
+}
+
+class _Setup extends EnvironmentProvisioner {
+ _Setup() : super(isMacOS: true);
+
+ @override
+ Future<EnvironmentReadiness> ensureReady({
+ required void Function(EnvironmentReadiness value) onProgress,
+ EnvironmentReadiness? resumeFrom,
+ bool install = true,
+ EnvironmentSetupMode? mode,
+ }) async {
+ final ready = EnvironmentReadiness(
+ steps: {
+ for (final step in EnvironmentStep.values)
+ step: EnvironmentStepStatus.ready,
+ },
+ phase: EnvironmentSetupPhase.ready,
+ mode: EnvironmentSetupMode.automatic,
+ );
+ onProgress(ready);
+ return ready;
+ }
+}
+
+class _Discovery extends LocalCliDiscovery {
+ _Discovery() : super(config: AppConfig.dev);
+ @override
+ Future<String?> computerId() async => _computerId;
+ @override
+ Future<LocalCliEndpoint?> discover({String? expectedComputerId}) async =>
+ LocalCliEndpoint(
+ computerId: _computerId,
+ wsUri: Uri.parse('ws://127.0.0.1:18473/ws'),
+ protocolVersion: localWsProtocolVersion,
+ terminalProtocolVersion: 1,
+ machineId: 'local-machine',
+ backendOnline: true,
+ );
+}
+
+class _Connection extends WsConn {
+ _Connection(this.asked)
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'local-machine',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ final _Asked asked;
+
+ @override
+ Future<void> waitUntilReady({required Duration timeout}) async {}
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ if (type == 'agents_list') asked.agentReads++;
+ return const {'agents': []};
+ }
+}
+
+class _Desktop extends AppNotifier {
+ _Desktop(this.cli, this.asked)
+ : super(
+ config: AppConfig.dev,
+ configStore: null,
+ authSession: AuthSession(storage: MemoryStore()),
+ cliLogin: cli,
+ environmentProvisioner: _Setup(),
+ localCliDiscovery: _Discovery(),
+ connectionForTest: (_) => _Connection(asked),
+ ) {
+ api = _Api(asked);
+ }
+
+ final _Login cli;
+ final _Asked asked;
+
+ @override
+ Future<void> ensureCliDaemonReady() async {}
+}
+
+/// Boots [app] and connects this computer, as a launch does.
+void _launch(FakeAsync async, _Desktop app) {
+ unawaited(app.bootstrap());
+ async.flushMicrotasks();
+ async.elapse(const Duration(seconds: 1));
+ // The socket's own connect: what starts a signed-in window's agent sync.
+ app.onMachineConnectedForTest('local-machine');
+ async.elapse(const Duration(seconds: 1));
+}
+
+void main() {
+ test('a signed-out computer asks nothing on a timer', () {
+ fakeAsync((async) {
+ final asked = _Asked();
+ final app = _Desktop(_Login(), asked);
+ _launch(async, app);
+ expect(app.isGuest, isTrue);
+ expect(app.signInStepShowing, isTrue);
+
+ final machines = asked.machineReads;
+ final agents = asked.agentReads;
+ // Far past both intervals: the minute's agent sync and the five-minute
+ // machine safety net would each have fired many times.
+ async.elapse(const Duration(minutes: 30));
+ expect(
+ asked.agentReads,
+ agents,
+ reason: 'no agent sync while signed out',
+ );
+ expect(
+ asked.machineReads,
+ machines,
+ reason: 'no machine re-read while signed out',
+ );
+ app.dispose();
+ async.flushMicrotasks();
+ });
+ });
+
+ test('signing in starts the background re-reads', () {
+ fakeAsync((async) {
+ final asked = _Asked();
+ final cli = _Login();
+ final app = _Desktop(cli, asked);
+ _launch(async, app);
+ expect(app.isGuest, isTrue);
+
+ unawaited(app.signInFromStep(SignInProvider.google));
+ async.flushMicrotasks();
+ cli.pending!.complete();
+ async.elapse(const Duration(seconds: 1));
+ expect(app.signedIn, isTrue);
+ expect(app.signInStepShowing, isFalse);
+
+ final machines = asked.machineReads;
+ final agents = asked.agentReads;
+ async.elapse(AppNotifier.agentSyncInterval);
+ async.flushMicrotasks();
+ expect(
+ asked.agentReads,
+ greaterThan(agents),
+ reason: 'the minute agent sync runs once signed in',
+ );
+ async.elapse(AppNotifier.machineListSafetyNetInterval);
+ async.flushMicrotasks();
+ expect(
+ asked.machineReads,
+ greaterThan(machines),
+ reason: 'the machine safety net runs once signed in',
+ );
+ app.dispose();
+ async.flushMicrotasks();
+ });
+ });
+
+ test('signing out stops them again', () {
+ fakeAsync((async) {
+ final asked = _Asked();
+ final app = _Desktop(_Login(loggedIn: true), asked);
+ _launch(async, app);
+ expect(app.isGuest, isFalse);
+
+ // Signed in: both run.
+ final before = asked.agentReads;
+ async.elapse(AppNotifier.agentSyncInterval);
+ async.flushMicrotasks();
+ expect(asked.agentReads, greaterThan(before));
+
+ unawaited(app.logout());
+ async.elapse(const Duration(seconds: 5));
+ expect(app.isGuest, isTrue);
+ // The guest's own socket connects again on the computer id.
+ app.onMachineConnectedForTest('local-machine');
+ async.elapse(const Duration(seconds: 1));
+
+ final machines = asked.machineReads;
+ final agents = asked.agentReads;
+ async.elapse(const Duration(minutes: 30));
+ expect(asked.agentReads, agents, reason: 'no agent sync after sign-out');
+ expect(
+ asked.machineReads,
+ machines,
+ reason: 'no machine re-read after sign-out',
+ );
+ app.dispose();
+ async.flushMicrotasks();
+ });
+ });
+}
diff --git a/desktop/test/super_tab_personal_projects_test.dart b/desktop/test/super_tab_personal_projects_test.dart
new file mode 100644
index 000000000..0c80a232f
--- /dev/null
+++ b/desktop/test/super_tab_personal_projects_test.dart
@@ -0,0 +1,746 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:clock/clock.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/swarm.dart';
+import 'package:harness/state/terminal_pane.dart';
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/personal_projects.dart';
+import 'package:harness/super_tabs/swarm_switcher.dart';
+import 'package:harness/super_tabs/workspace.dart';
+import 'package:harness/widgets/pane_grid.dart';
+
+import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;
+import 'support/capture.dart';
+
+/// Set to a folder to write the PR's pictures there.
+final _shots = Platform.environment['PERSONAL_PROJECTS_SHOTS'];
+
+/// A pane's agent, in a checkout of [remote] (none for a folder).
+Agent _agent(String id, {String? remote, String cwd = '/work/x'}) => Agent(
+ id: id,
+ name: 'Agent $id',
+ engine: 'codex',
+ terminalAvailable: true,
+ project: AgentProject(
+ name: cwd.split('/').last,
+ cwd: cwd,
+ root: remote == null ? null : cwd,
+ remote: remote,
+ ),
+);
+
+MachineState _machine(
+ AppNotifier app,
+ String id, {
+ bool shared = false,
+ String? sessionKind,
+}) {
+ final machine = Machine(
+ machineId: id,
+ authMode: MachineAuthMode.remote,
+ name: 'Mac $id',
+ isShared: shared,
+ ownerName: shared ? 'Kim' : null,
+ sessionKind: sessionKind,
+ );
+ app.machines = [...app.machines, machine];
+ return app.machineStates[id] = MachineState(machine)
+ ..nodeOnline = true
+ ..agentLoadStatus = AgentLoadStatus.loaded;
+}
+
+var _paneIds = 9000;
+TerminalPane _pane(String machineId, String agentId) =>
+ TerminalPane(id: _paneIds++, machineId: machineId, agentId: agentId);
+
+/// A desk tab of the person's, holding [panes] in this order.
+Swarm _tab(AppNotifier app, String id, List<TerminalPane> panes) {
+ final tab = Swarm(id: id, name: id)..panes.addAll(panes);
+ app.swarms.add(tab);
+ return tab;
+}
+
+List<Map<String, dynamic>> _commands(
+ SuperTabLaunchFixture f, [
+ String type = 'project.create',
+]) => [
+ for (final post in f.connection.server.posts)
+ if ((post['command'] as Map?)?['type'] == type)
+ Map<String, dynamic>.from(post),
+];
+
+/// The fixture's Swarm, made the person's Personal one: theirs alone, and
+/// picked here before.
+Future<SuperTabController> _personal(
+ SuperTabLaunchFixture f, {
+ List<String> people = const ['owner'],
+}) async {
+ f.connection.server.state
+ ..['name'] = 'Personal'
+ ..['ownerId'] = 'owner'
+ ..['people'] = [
+ for (final person in people)
+ {
+ 'id': person,
+ 'email': '[email protected]',
+ 'role': person == 'owner' ? 'owner' : 'collaborator',
+ },
+ ];
+ await f.app.superTabs.storage.write('super_tab.personal.owner', tabId);
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Personal');
+ PersonalSwarm.of(f.app).id;
+ for (var i = 0; i < 20; i++) {
+ await Future<void>.microtask(() {});
+ }
+ expect(PersonalSwarm.of(f.app).id, tabId);
+ final c = await f.app.superTabs.open(tabId);
+ await c.refresh();
+ return c;
+}
+
+/// Two repos and a folder across two of the person's Macs, in two tabs:
+/// `one` holds the api on this Mac, then a folder; `two` holds the web app,
+/// then the api again on the laptop under another URL form.
+({TerminalPane api, TerminalPane folder, TerminalPane web, TerminalPane api2})
+_desk(SuperTabLaunchFixture f) {
+ f.app.machineStates['m']!.agents = [
+ _agent('n1', remote: '[email protected]:Acme/api.git', cwd: '/w/api'),
+ _agent('n2', cwd: '/Users/me/notes'),
+ _agent('n3', remote: 'https://github.com/acme/web', cwd: '/w/web'),
+ ];
+ _machine(f.app, 'laptop').agents = [
+ _agent('n1', remote: 'https://github.com/acme/api', cwd: '/x/api-copy'),
+ ];
+ final panes = (
+ api: _pane('m', 'n1'),
+ folder: _pane('m', 'n2'),
+ web: _pane('m', 'n3'),
+ api2: _pane('laptop', 'n1'),
+ );
+ _tab(f.app, 'one', [panes.api, panes.folder]);
+ _tab(f.app, 'two', [panes.web, panes.api2]);
+ return panes;
+}
+
+void main() {
+ setUpAll(() => loadCaptureFonts(_shots));
+
+ for (final brightness in Brightness.values) {
+ testWidgets('pictures of Personal\'s projects, chat and [term], in '
+ '${brightness.name}', (tester) async {
+ if (_shots == null) return;
+ final previous = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previous);
+ tester.view.devicePixelRatio = 2;
+ tester.view.physicalSize = const Size(2560, 1440);
+ addTearDown(tester.view.reset);
+ final f = SuperTabLaunchFixture();
+ _desk(f);
+ final c = await _personal(f);
+ await PersonalProjects.of(f.app).sync(c);
+ final api = c.snapshot!.projects
+ .firstWhere((p) => p.name == 'api')
+ .leadConversationId;
+ c.select(api);
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ home: Scaffold(
+ body: ListenableBuilder(
+ listenable: f.app,
+ builder: (_, _) => SuperTabWorkspace(
+ app: f.app,
+ canvas: PaneGrid(notifier: f.app, swarmMode: true),
+ onAddAgent: (_) {},
+ onNewProject: () {},
+ onNewSwarm: () {},
+ ),
+ ),
+ ),
+ ),
+ );
+ for (var i = 0; i < 10; i++) {
+ await tester.pump(const Duration(milliseconds: 20));
+ }
+ await captureWindow(tester, _shots, 'personal-chat-${brightness.name}');
+ await tester.tap(find.byTooltip('Group terminals (2)'));
+ for (var i = 0; i < 20; i++) {
+ await tester.pump(const Duration(milliseconds: 20));
+ }
+ await captureWindow(tester, _shots, 'personal-term-${brightness.name}');
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ f.app.superTabs.dispose();
+ await tester.pump();
+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
+ }
+
+ group('a repo is one string on every computer', () {
+ test('ssh, https, case, user, port and .git are the same repo', () {
+ const forms = [
+ '[email protected]:Acme/Api.git',
+ 'https://github.com/acme/api',
+ 'https://github.com/acme/api.git/',
+ 'ssh://[email protected]:22/acme/api.git',
+ 'https://user:[email protected]/acme/api',
+ ];
+ for (final form in forms) {
+ expect(normalizedRemote(form), 'github.com/acme/api', reason: form);
+ }
+ });
+
+ test('a folder or nothing is no repo', () {
+ for (final form in [
+ null,
+ '',
+ '/srv/git/api.git',
+ './api',
+ 'file:///srv/git/api.git',
+ r'C:\repos\api',
+ ]) {
+ expect(normalizedRemote(form), isNull, reason: form);
+ }
+ });
+
+ test('the request id never carries the URL', () {
+ final id = personalProjectOperation('github.com/acme/api');
+ expect(id, startsWith('personal-repo-'));
+ expect(id, isNot(contains('acme')));
+ expect(id, personalProjectOperation('github.com/acme/api'));
+ expect(id, isNot(personalProjectOperation('github.com/other/api')));
+ expect(personalProjectOperation(kScratchRepo), 'personal-scratch');
+ });
+
+ test('two repos of one name have long names that tell them apart', () {
+ expect(repoName('github.com/acme/api'), 'api');
+ expect(repoLongName('github.com/acme/api'), 'api (acme/api)');
+ expect(repoLongName('gitlab.com/team/sub/api'), 'api (sub/api)');
+ });
+ });
+
+ group('the person\'s panes, by repo', () {
+ test('every pane joins its repo whatever tab it is in, in tab order', () {
+ final f = SuperTabLaunchFixture();
+ final p = _desk(f);
+ final panes = personalPanes(f.app);
+ expect([for (final e in panes) e.pane], [p.api, p.folder, p.web, p.api2]);
+ expect(
+ [for (final e in panes) e.repo],
+ [
+ 'github.com/acme/api',
+ kScratchRepo,
+ 'github.com/acme/web',
+ 'github.com/acme/api',
+ ],
+ );
+ });
+
+ test('a pane twice in the tabs counts once, where it is first', () {
+ final f = SuperTabLaunchFixture();
+ final p = _desk(f);
+ f.app.swarms.firstWhere((s) => s.id == 'two').panes.add(p.api);
+ expect(
+ personalPanes(f.app)
+ .where((e) => identical(e.pane, p.api))
+ .single
+ .tab
+ .id,
+ 'one',
+ );
+ });
+
+ test(
+ 'panes on another person\'s, a shared or a Team machine are left out',
+ () {
+ final f = SuperTabLaunchFixture();
+ _machine(f.app, 'kims', shared: true).agents = [
+ _agent('k1', remote: '[email protected]:kim/secret.git'),
+ ];
+ _machine(f.app, 'team', sessionKind: 'team').agents = [
+ _agent('t1', remote: '[email protected]:acme/team.git'),
+ ];
+ f.app.machineStates['m']!.agents = [_agent('n1')];
+ _tab(f.app, 'mixed', [
+ _pane('kims', 'k1'),
+ _pane('team', 't1'),
+ _pane('m', 'n1'),
+ ]);
+ expect([for (final e in personalPanes(f.app)) e.pane.agentId], ['n1']);
+ },
+ );
+
+ test('a Swarm tab\'s panes are not the person\'s tabs', () {
+ final f = SuperTabLaunchFixture();
+ f.app.machineStates['m']!.agents = [_agent('n1')];
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
+ f.app.activeSwarm.panes.add(_pane('m', 'n1'));
+ expect(personalPanes(f.app), isEmpty);
+ });
+ });
+
+ group('Personal\'s projects', () {
+ test(
+ 'each repo, and # scratch, is made once as a private project',
+ () async {
+ final f = SuperTabLaunchFixture();
+ _desk(f);
+ final c = await _personal(f);
+ await PersonalProjects.of(f.app).sync(c);
+ final creates = _commands(f);
+ expect(
+ [for (final p in creates) p['operationId']],
+ [
+ personalProjectOperation('github.com/acme/api'),
+ 'personal-scratch',
+ personalProjectOperation('github.com/acme/web'),
+ ],
+ );
+ expect(
+ [for (final p in creates) p['command']['name']],
+ ['api', 'scratch', 'web'],
+ );
+ expect(
+ creates.every((p) => p['command']['visibility'] == 'private'),
+ isTrue,
+ );
+ final names = [for (final p in c.snapshot!.projects) p.name];
+ expect(names, containsAll(['api', 'scratch', 'web']));
+
+ // Again: nothing.
+ await PersonalProjects.of(f.app).sync(c);
+ expect(_commands(f), hasLength(3));
+
+ // The app restarted on the same computer: what it kept, no request.
+ final restarted = SuperTabLaunchFixture();
+ restarted.store.values.addAll(f.store.values);
+ restarted.connection.server.state
+ ..clear()
+ ..addAll(f.connection.server.state);
+ _desk(restarted);
+ final rc = await _personal(restarted);
+ await PersonalProjects.of(restarted.app).sync(rc);
+ expect(_commands(restarted), isEmpty);
+ expect(
+ PersonalProjects.of(restarted.app).knownForTest('owner', tabId),
+ PersonalProjects.of(f.app).knownForTest('owner', tabId),
+ );
+ },
+ );
+
+ test('nothing is sent of a pane but its project\'s name', () async {
+ final f = SuperTabLaunchFixture();
+ _desk(f);
+ final c = await _personal(f);
+ await PersonalProjects.of(f.app).sync(c);
+ final sent = f.connection.server.posts.toString();
+ for (final leak in [
+ 'acme',
+ '/w/',
+ '/Users/me',
+ 'notes',
+ 'n1',
+ 'laptop',
+ ]) {
+ expect(sent, isNot(contains(leak)), reason: leak);
+ }
+ });
+
+ test('another computer of the person\'s finds the same projects', () async {
+ final f = SuperTabLaunchFixture();
+ _desk(f);
+ final c = await _personal(f);
+ await PersonalProjects.of(f.app).sync(c);
+ final first = PersonalProjects.of(f.app).knownForTest('owner', tabId);
+
+ // The laptop: its own app and store, the same Swarm and account.
+ final laptop = SuperTabLaunchFixture();
+ laptop.connection.server.state
+ ..clear()
+ ..addAll(f.connection.server.state);
+ laptop.connection.server.receipts.addAll(f.connection.server.receipts);
+ _desk(laptop);
+ final lc = await _personal(laptop);
+ final before = _projectCount(laptop);
+ await PersonalProjects.of(laptop.app).sync(lc);
+ expect(_projectCount(laptop), before);
+ expect(
+ PersonalProjects.of(laptop.app).knownForTest('owner', tabId),
+ first,
+ );
+ });
+
+ test('a project the person deleted is not made again', () async {
+ final f = SuperTabLaunchFixture();
+ f.app.machineStates['m']!.agents = [
+ _agent('n1', remote: '[email protected]:acme/api.git'),
+ ];
+ _tab(f.app, 'one', [_pane('m', 'n1')]);
+ final c = await _personal(f);
+ f.connection.server
+ ..refuse = {
+ 'code': 'NOT_FOUND',
+ 'message': 'This project was deleted. Create a new project.',
+ }
+ ..refuseStatus = 404;
+ await PersonalProjects.of(f.app).sync(c);
+ expect(PersonalProjects.of(f.app).knownForTest('owner', tabId), {
+ 'github.com/acme/api': null,
+ });
+ f.connection.server.refuse = null;
+ await PersonalProjects.of(f.app).sync(c);
+ // The refused create, then none.
+ expect(_commands(f), hasLength(1));
+ });
+
+ test('a failed create is asked again later, then works', () async {
+ final f = SuperTabLaunchFixture();
+ f.app.machineStates['m']!.agents = [
+ _agent('n1', remote: '[email protected]:acme/api.git'),
+ ];
+ _tab(f.app, 'one', [_pane('m', 'n1')]);
+ final c = await _personal(f);
+ var now = DateTime(2026, 10, 31, 9);
+ Future<void> sync() =>
+ withClock(Clock(() => now), () => PersonalProjects.of(f.app).sync(c));
+ f.connection.server
+ ..refuse = {'code': 'SERVICE_UNAVAILABLE', 'message': 'Busy.'}
+ ..refuseStatus = 503;
+ await sync();
+ await sync();
+ expect(_commands(f), hasLength(1), reason: 'waits before asking again');
+ f.connection.server.refuse = null;
+ now = now.add(const Duration(seconds: 11));
+ await sync();
+ expect(_commands(f), hasLength(2));
+ expect(
+ PersonalProjects.of(f.app).knownForTest('owner', tabId).values.single,
+ isNotNull,
+ );
+ });
+
+ test(
+ 'never in a team Swarm, nor a Personal one someone else is in',
+ () async {
+ final team = SuperTabLaunchFixture();
+ _desk(team);
+ team.app.bindSuperTab(team.app.activeSwarmId, tabId, 'Pilot');
+ final tc = await team.app.superTabs.open(tabId);
+ await tc.refresh();
+ await PersonalProjects.of(team.app).sync(tc);
+ expect(_commands(team), isEmpty);
+
+ final shared = SuperTabLaunchFixture();
+ _desk(shared);
+ final sc = await _personal(shared, people: ['owner', 'kim']);
+ await PersonalProjects.of(shared.app).sync(sc);
+ expect(_commands(shared), isEmpty);
+ expect(PersonalProjects.of(shared.app).panesFor(sc, 'lead'), isEmpty);
+ },
+ );
+
+ test('an answer after the account changed is dropped', () async {
+ final f = SuperTabLaunchFixture();
+ _desk(f);
+ final c = await _personal(f);
+ final hold = f.connection.server.holdCommands = Completer<void>();
+ final syncing = PersonalProjects.of(f.app).sync(c);
+ await Future<void>.delayed(Duration.zero);
+ f.app.currentUser = const CurrentUserProfile(
+ id: 'other',
+ email: '[email protected]',
+ );
+ hold.complete();
+ await syncing;
+ expect(_commands(f), hasLength(1));
+ expect(PersonalProjects.of(f.app).knownForTest('owner', tabId), isEmpty);
+ expect(
+ await f.app.superTabs.storage.read(
+ PersonalProjects.storageKey('owner'),
+ ),
+ isNull,
+ );
+ });
+
+ test('an answer after someone joined Personal is dropped', () async {
+ final f = SuperTabLaunchFixture();
+ _desk(f);
+ final c = await _personal(f);
+ final hold = f.connection.server.holdCommands = Completer<void>();
+ final syncing = PersonalProjects.of(f.app).sync(c);
+ await Future<void>.delayed(Duration.zero);
+ (f.connection.server.state['people'] as List).add({
+ 'id': 'kim',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ });
+ await c.refresh();
+ hold.complete();
+ await syncing;
+ expect(_commands(f), hasLength(1));
+ expect(PersonalProjects.of(f.app).knownForTest('owner', tabId), isEmpty);
+ expect(
+ await f.app.superTabs.storage.read(
+ PersonalProjects.storageKey('owner'),
+ ),
+ isNull,
+ );
+ });
+
+ test('losing access drops answers in flight and what was kept', () async {
+ final f = SuperTabLaunchFixture();
+ _desk(f);
+ final c = await _personal(f);
+ await PersonalProjects.of(f.app).sync(c);
+ final lead = c.snapshot!.projects
+ .firstWhere((p) => p.name == 'api')
+ .leadConversationId;
+ expect(PersonalProjects.of(f.app).panesFor(c, lead), hasLength(2));
+
+ f.app.machineStates['m']!.agents = [
+ ...f.app.machineStates['m']!.agents,
+ _agent('n4', remote: '[email protected]:acme/docs.git'),
+ ];
+ _tab(f.app, 'three', [_pane('m', 'n4')]);
+ final hold = f.connection.server.holdCommands = Completer<void>();
+ final syncing = PersonalProjects.of(f.app).sync(c);
+ await Future<void>.delayed(Duration.zero);
+ c.accessRevoked = true;
+ hold.complete();
+ await syncing;
+ expect(PersonalProjects.of(f.app).panesFor(c, lead), isEmpty);
+ expect(PersonalProjects.of(f.app).knownForTest('owner', tabId), isEmpty);
+ });
+
+ test('two repos of one name become two projects told apart', () async {
+ final f = SuperTabLaunchFixture();
+ f.app.machineStates['m']!.agents = [
+ _agent('n1', remote: '[email protected]:acme/api.git'),
+ _agent('n2', remote: '[email protected]:kim/api.git'),
+ _agent('n3', remote: '[email protected]:acme/web.git'),
+ ];
+ _tab(f.app, 'one', [
+ _pane('m', 'n1'),
+ _pane('m', 'n2'),
+ _pane('m', 'n3'),
+ ]);
+ final c = await _personal(f);
+ await PersonalProjects.of(f.app).sync(c);
+ final names = [for (final p in c.snapshot!.projects) p.name];
+ expect(names, containsAll(['api (acme/api)', 'api (kim/api)', 'web']));
+ expect(names, isNot(contains('api')));
+ // Each was created under the repo's own name, the same on every computer.
+ expect(
+ [for (final p in _commands(f)) p['command']['name']],
+ ['api', 'api', 'web'],
+ );
+ // Once.
+ await PersonalProjects.of(f.app).sync(c);
+ expect(_commands(f, 'project.rename'), hasLength(2));
+ });
+
+ test('a name the person chose stays', () async {
+ final f = SuperTabLaunchFixture();
+ f.app.machineStates['m']!.agents = [
+ _agent('n1', remote: '[email protected]:acme/api.git'),
+ ];
+ _tab(f.app, 'one', [_pane('m', 'n1')]);
+ final c = await _personal(f);
+ await PersonalProjects.of(f.app).sync(c);
+ final id = PersonalProjects.of(f.app)
+ .knownForTest('owner', tabId)['github.com/acme/api']!;
+ final project = (f.connection.server.state['projects'] as List)
+ .cast<Map<String, dynamic>>()
+ .firstWhere((p) => p['id'] == id);
+ project['name'] = 'Backend';
+ await c.refresh();
+ f.app.machineStates['m']!.agents = [
+ ...f.app.machineStates['m']!.agents,
+ _agent('n2', remote: '[email protected]:kim/api.git'),
+ ];
+ f.app.swarms.firstWhere((s) => s.id == 'one').panes.add(_pane('m', 'n2'));
+ await PersonalProjects.of(f.app).sync(c);
+ final renames = _commands(f, 'project.rename');
+ expect(renames, hasLength(1));
+ expect(renames.single['command']['name'], 'api (kim/api)');
+ expect(project['name'], 'Backend');
+ });
+
+ test('a pane whose repo changes moves to that repo\'s project', () async {
+ final f = SuperTabLaunchFixture();
+ final p = _desk(f);
+ final c = await _personal(f);
+ await PersonalProjects.of(f.app).sync(c);
+ String lead(String name) => c.snapshot!.projects
+ .firstWhere((p) => p.name == name)
+ .leadConversationId;
+ final projects = PersonalProjects.of(f.app);
+ expect(projects.panesFor(c, lead('scratch')), [p.folder]);
+
+ // The folder becomes a checkout of the web app.
+ f.app.machineStates['m']!.agents = [
+ for (final a in f.app.machineStates['m']!.agents)
+ a.id == 'n2'
+ ? _agent('n2', remote: '[email protected]:acme/web.git')
+ : a,
+ ];
+ expect(projects.panesFor(c, lead('scratch')), isEmpty);
+ expect(projects.panesFor(c, lead('web')), [p.folder, p.web]);
+ });
+
+ test('renaming or closing a tab keeps the projects', () async {
+ final f = SuperTabLaunchFixture();
+ final p = _desk(f);
+ final c = await _personal(f);
+ await PersonalProjects.of(f.app).sync(c);
+ final api = c.snapshot!.projects
+ .firstWhere((p) => p.name == 'api')
+ .leadConversationId;
+ f.app.swarms.firstWhere((s) => s.id == 'one')
+ ..name = 'Renamed'
+ ..nameIsCustom = true;
+ expect(PersonalProjects.of(f.app).panesFor(c, api), [p.api, p.api2]);
+ f.app.swarms.removeWhere((s) => s.id == 'one');
+ expect(PersonalProjects.of(f.app).panesFor(c, api), [p.api2]);
+ await PersonalProjects.of(f.app).sync(c);
+ expect(_commands(f), hasLength(3));
+ });
+ });
+
+ group('[term]', () {
+ testWidgets(
+ 'shows the very panes the tabs hold, and the tabs stay as they are',
+ (tester) async {
+ await tester.binding.setSurfaceSize(const Size(1280, 800));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final f = SuperTabLaunchFixture();
+ final p = _desk(f);
+ p.api
+ ..composerVisible = true
+ ..watchOnly = false;
+ late SuperTabController c;
+ c = await _personal(f);
+ await PersonalProjects.of(f.app).sync(c);
+ final one = f.app.swarms.firstWhere((s) => s.id == 'one');
+ final two = f.app.swarms.firstWhere((s) => s.id == 'two');
+ final before = (
+ one: [...one.panes],
+ two: [...two.panes],
+ closed: f.app.closedHistory.length,
+ );
+ final api = c.snapshot!.projects
+ .firstWhere((p) => p.name == 'api')
+ .leadConversationId;
+ c.select(api);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: ListenableBuilder(
+ listenable: f.app,
+ builder: (_, _) => SuperTabWorkspace(
+ app: f.app,
+ canvas: const Text('Native terminals'),
+ onAddAgent: (_) {},
+ ),
+ ),
+ ),
+ ),
+ );
+ for (var i = 0; i < 10; i++) {
+ await tester.pump(const Duration(milliseconds: 20));
+ }
+ expect(find.byTooltip('Group terminals (2)'), findsOneWidget);
+ await tester.tap(find.byTooltip('Group terminals (2)'));
+ for (var i = 0; i < 20; i++) {
+ await tester.pump(const Duration(milliseconds: 20));
+ }
+ final swarm = f.app.swarms.firstWhere((s) => s.superTabId == tabId);
+ expect(swarm.panes, hasLength(2));
+ expect(identical(swarm.panes[0], p.api), isTrue);
+ expect(identical(swarm.panes[1], p.api2), isTrue);
+ expect(one.panes, before.one);
+ expect(two.panes, before.two);
+ expect(p.api.composerVisible, isTrue);
+ expect(p.api.watchOnly, isFalse);
+ expect(p.api.inputContext, isNull);
+ // No Swarm terminal sharing was asked for.
+ expect(
+ f.connection.server.posts.where(
+ (post) => post['conversationId'] != null && post['agentId'] != null,
+ ),
+ isEmpty,
+ );
+
+ // Back to the chat: the Swarm view lets them go, the tabs keep them.
+ c.selectTerminal(api, null);
+ for (var i = 0; i < 20; i++) {
+ await tester.pump(const Duration(milliseconds: 20));
+ }
+ expect(swarm.panes, isEmpty);
+ expect(one.panes, before.one);
+ expect(two.panes, before.two);
+ expect(f.app.allPanes, containsAll([p.api, p.api2]));
+ expect(f.app.closedHistory, hasLength(before.closed));
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ f.app.superTabs.dispose();
+ await tester.pump();
+ },
+ );
+
+ testWidgets('a project of one tab\'s panes keeps that tab\'s sizes', (
+ tester,
+ ) async {
+ final f = SuperTabLaunchFixture();
+ f.app.machineStates['m']!.agents = [
+ _agent('n1', remote: '[email protected]:acme/api.git'),
+ _agent('n2', remote: '[email protected]:acme/api.git', cwd: '/w/wt'),
+ ];
+ final tab = _tab(f.app, 'one', [_pane('m', 'n1'), _pane('m', 'n2')]);
+ tab.gridColumns = 2;
+ late SuperTabController c;
+ c = await _personal(f);
+ await PersonalProjects.of(f.app).sync(c);
+ final api = c.snapshot!.projects
+ .firstWhere((p) => p.name == 'api')
+ .leadConversationId;
+ c
+ ..select(api)
+ ..selectGroupTerminals(api);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: ListenableBuilder(
+ listenable: f.app,
+ builder: (_, _) => SuperTabWorkspace(
+ app: f.app,
+ canvas: const Text('Native terminals'),
+ onAddAgent: (_) {},
+ ),
+ ),
+ ),
+ ),
+ );
+ for (var i = 0; i < 20; i++) {
+ await tester.pump(const Duration(milliseconds: 20));
+ }
+ final swarm = f.app.swarms.firstWhere((s) => s.superTabId == tabId);
+ expect(swarm.panes, tab.panes);
+ expect(swarm.gridColumns, 2);
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ f.app.superTabs.dispose();
+ await tester.pump();
+ });
+ });
+}
+
+int _projectCount(SuperTabLaunchFixture f) =>
+ (f.connection.server.state['projects'] as List? ?? const []).length;
diff --git a/desktop/test/super_tab_thread_tags_test.dart b/desktop/test/super_tab_thread_tags_test.dart
new file mode 100644
index 000000000..96fcdfa03
--- /dev/null
+++ b/desktop/test/super_tab_thread_tags_test.dart
@@ -0,0 +1,496 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/view.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'super_tab_mentions_test.dart' show tagRuns;
+import 'support/super_tab_fixture.dart';
+
+/// @ in a thread reply works as in the main chat (Dee, 10-31): the same
+/// picker of people and agents, the same Backspace rule, and the reply
+/// carries its tags, so the tagged person or agent is told.
+/// Set to a folder to write the PR's screenshots there.
+final shots = Platform.environment['SUPER_TAB_THREAD_TAG_SHOTS'];
+final _picture = GlobalKey();
+
+Future<void> shot(WidgetTester tester, String name) async {
+ await tester.runAsync(() async {
+ final boundary =
+ _picture.currentContext!.findRenderObject()! as RenderRepaintBoundary;
+ final image = await boundary.toImage();
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(shots!).create(recursive: true);
+ await File('$shots/$name.png').writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+}
+
+void main() {
+ setUpAll(() async {
+ if (shots != null) await loadPreviewFonts();
+ });
+ final composer = find.byKey(const ValueKey('super-thread-composer'));
+ final picker = find.byKey(const ValueKey('super-thread-completions'));
+ final mainPicker = find.byKey(const ValueKey('super-composer-completions'));
+ final panel = find.byKey(const ValueKey('super-thread-panel'));
+
+ late SuperTabController shown;
+
+ void testTags(
+ String description,
+ Future<void> Function(WidgetTester tester) body, {
+ TestVariant<Object?> variant = const DefaultTestVariant(),
+ bool skip = false,
+ }) => testWidgets(
+ description,
+ (tester) async {
+ await body(tester);
+ await tester.pumpWidget(const SizedBox());
+ await shown.flush();
+ },
+ variant: variant,
+ skip: skip,
+ );
+
+ /// The owner, ken and dee in a Swarm whose chats hold the agent Kestrel;
+ /// the lead chat has a thread at message-1, and a second at message-3.
+ ConversationServer swarm() {
+ final server = ConversationServer()..threads = true;
+ server.state['people'] = [
+ {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},
+ {'id': 'ken', 'email': '[email protected]', 'role': 'collaborator'},
+ {'id': 'dee', 'email': '[email protected]', 'role': 'collaborator'},
+ ];
+ server.state['agents'] = [
+ {
+ 'id': 'kestrel',
+ 'name': 'Builder',
+ 'displayName': 'Kestrel',
+ 'machineId': 'host',
+ 'harnessId': 'session',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'codex'},
+ },
+ // In the Swarm, but in no chat here.
+ {
+ 'id': 'outsider',
+ 'name': 'Builder',
+ 'displayName': 'Kelpie',
+ 'machineId': 'host',
+ 'harnessId': 'other',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'claude'},
+ },
+ ];
+ for (final group in server.state['conversations'] as List) {
+ (group as Map)['agentIds'] = ['kestrel'];
+ }
+ server.append('Should we do thread replies?');
+ server.append('Yes, like Slack.');
+ server.messages.last
+ ..['thread'] = 'message-1'
+ ..['replyTo'] = 'message-1';
+ server.append('Second topic.');
+ return server;
+ }
+
+ Future<SuperTabController> show(
+ WidgetTester tester,
+ ConversationServer server, {
+ String root = 'message-1',
+ Brightness brightness = Brightness.dark,
+ }) async {
+ await tester.binding.setSurfaceSize(const Size(1400, 900));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final before = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = before);
+ final c = shown = server.controller();
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) =>
+ RepaintBoundary(key: _picture, child: child),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ c.openThread(root);
+ await tester.pumpAndSettle();
+ expect(panel, findsOneWidget);
+ addTearDown(c.dispose);
+ return c;
+ }
+
+ List<String> choices(WidgetTester tester) => [
+ for (final tile in tester.widgetList<ListTile>(
+ find.descendant(of: picker, matching: find.byType(ListTile)),
+ ))
+ (tile.title as Text).data!,
+ ];
+
+ String text(WidgetTester tester) =>
+ tester.widget<TextField>(composer).controller!.text;
+
+ Future<void> type(WidgetTester tester, String value) async {
+ await tester.tap(composer);
+ await tester.enterText(composer, value);
+ await tester.pumpAndSettle();
+ }
+
+ Map<String, dynamic> lastCommand(ConversationServer server) =>
+ Map<String, dynamic>.from(server.posts.last['command'] as Map);
+
+ testTags('@ in a thread reply offers people, then agents, as typed', (
+ tester,
+ ) async {
+ await show(tester, swarm());
+ await type(tester, 'Please check @ke');
+ expect(choices(tester), ['ken15', 'Kestrel']);
+ expect(
+ find.descendant(of: picker, matching: find.text('person')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: picker, matching: find.text('agent')),
+ findsOneWidget,
+ );
+ // Never the reader; never an agent outside this chat.
+ await type(tester, 'Please check @');
+ expect(choices(tester), ['ken15', 'dee', 'Kestrel']);
+ // The main chat's own picker does not open for the thread's box.
+ expect(mainPicker, findsNothing);
+ });
+
+ testTags(
+ 'a picked tag is sent with the reply: a person tagged, an agent addressed',
+ (tester) async {
+ final server = swarm();
+ final c = await show(tester, server);
+ await type(tester, 'Please check @ke');
+ // Enter picks, it does not send.
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(text(tester), 'Please check @ken15 ');
+ expect(c.threadMentions('lead', 'message-1'), {'ken': '@ken15'});
+ expect(server.posts, isEmpty);
+ expect(picker, findsNothing);
+ // Tab picks too.
+ await type(tester, 'Please check @ken15 and @Kes');
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pumpAndSettle();
+ expect(text(tester), 'Please check @ken15 and @Kestrel ');
+ expect(server.posts, isEmpty);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ final command = lastCommand(server);
+ expect(command['type'], 'message.send');
+ expect(command['replyTo'], 'message-1');
+ expect(command['text'], 'Please check @ken15 and @Kestrel');
+ expect(command['mentions'], ['ken']);
+ expect(command['recipientIds'], ['kestrel']);
+ // Sent, the box and its tags are free for the next reply.
+ expect(text(tester), isEmpty);
+ expect(c.threadMentions('lead', 'message-1'), isEmpty);
+ // The reply in the thread shows its tag as the chat does.
+ await c.loadThread();
+ await tester.pumpAndSettle();
+ expect(tagRuns(tester).where((run) => run == '@ken15'), isNotEmpty);
+ },
+ );
+
+ testTags('a reply that tags no one goes to no one but the usual reader', (
+ tester,
+ ) async {
+ final server = swarm();
+ await show(tester, server);
+ // Typed, not picked: no tag of the reader's choosing goes with it.
+ await type(tester, 'Thanks @nobody');
+ expect(picker, findsNothing);
+ await tester.tap(find.byKey(const ValueKey('super-thread-send')));
+ await tester.pumpAndSettle();
+ final command = lastCommand(server);
+ expect(command['recipientIds'], isEmpty);
+ expect(command.containsKey('mentions'), isFalse);
+ });
+
+ testTags(
+ 'Backspace right after a tag takes the whole tag, and it is not sent',
+ (tester) async {
+ final server = swarm();
+ final c = await show(tester, server);
+ await type(tester, 'Please check @Kes');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(text(tester), 'Please check @Kestrel ');
+ expect(c.threadMentions('lead', 'message-1'), {'kestrel': '@Kestrel'});
+ // The space the tag brought goes first, as any character does.
+ await tester.sendKeyEvent(LogicalKeyboardKey.backspace);
+ await tester.pumpAndSettle();
+ expect(text(tester), 'Please check @Kestrel');
+ expect(c.threadMentions('lead', 'message-1'), {'kestrel': '@Kestrel'});
+ await tester.sendKeyEvent(LogicalKeyboardKey.backspace);
+ await tester.pumpAndSettle();
+ expect(text(tester), 'Please check ');
+ expect(
+ tester.widget<TextField>(composer).controller!.selection,
+ const TextSelection.collapsed(offset: 13),
+ );
+ expect(c.threadMentions('lead', 'message-1'), isEmpty);
+ // No picker springs up in its place.
+ expect(picker, findsNothing);
+ await type(tester, 'Please check');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(lastCommand(server)['recipientIds'], isEmpty);
+ },
+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),
+ );
+
+ testTags('Escape closes the picker first, then the thread', (tester) async {
+ final c = await show(tester, swarm());
+ await type(tester, 'Please check @');
+ expect(picker, findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(picker, findsNothing);
+ expect(panel, findsOneWidget);
+ expect(text(tester), 'Please check @');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(c.openedThread, isNull);
+ });
+
+ testTags('arrow keys move through the choices; a click picks one', (
+ tester,
+ ) async {
+ final c = await show(tester, swarm());
+ await type(tester, '@');
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(text(tester), '@dee ');
+ await type(tester, '@dee @Kes');
+ await tester.tap(
+ find.descendant(of: picker, matching: find.text('Kestrel')),
+ );
+ await tester.pumpAndSettle();
+ expect(text(tester), '@dee @Kestrel ');
+ expect(c.threadMentions('lead', 'message-1'), {
+ 'dee': '@dee',
+ 'kestrel': '@Kestrel',
+ });
+ });
+
+ testTags('a private chat offers only the people who read it', (tester) async {
+ final server = swarm();
+ ((server.state['conversations'] as List)[0] as Map)['audience'] = {
+ 'people': [
+ {'id': 'owner', 'generation': 'fixture'},
+ {'id': 'dee', 'generation': 'fixture'},
+ ],
+ };
+ await show(tester, server);
+ await type(tester, '@');
+ expect(choices(tester), ['dee', 'Kestrel']);
+ });
+
+ testTags(
+ 'each thread keeps its own tags, apart from the main chat and each other',
+ (tester) async {
+ final server = swarm();
+ final c = await show(tester, server);
+ await type(tester, '@ke');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(c.threadMentions('lead', 'message-1'), {'ken': '@ken15'});
+ // The main chat holds none of the thread's tags.
+ expect(c.mentions('lead'), isEmpty);
+ // Another thread starts with its own, empty.
+ c.openThread('message-3');
+ await tester.pumpAndSettle();
+ expect(text(tester), isEmpty);
+ expect(c.threadMentions('lead', 'message-3'), isEmpty);
+ // The same name typed there, not picked, tags no one.
+ await type(tester, '@ken15 look');
+ expect(picker, findsNothing);
+ await tester.tap(find.byKey(const ValueKey('super-thread-send')));
+ await tester.pumpAndSettle();
+ final command = lastCommand(server);
+ expect(command['replyTo'], 'message-3');
+ expect(command.containsKey('mentions'), isFalse);
+ // Back in the first thread, its draft and tag are as left.
+ c.openThread('message-1');
+ await tester.pumpAndSettle();
+ expect(text(tester), '@ken15 ');
+ expect(c.threadMentions('lead', 'message-1'), {'ken': '@ken15'});
+ },
+ );
+
+ testTags('an agent that left the chat since it was tagged is not sent', (
+ tester,
+ ) async {
+ final server = swarm();
+ final c = await show(tester, server);
+ await type(tester, 'Please check @Kes');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ for (final group in server.state['conversations'] as List) {
+ (group as Map)['agentIds'] = <String>[];
+ }
+ server.revision++;
+ await c.refresh();
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(server.posts, isEmpty);
+ expect(
+ c.threadComposerError('lead', 'message-1') ?? c.error,
+ contains('no longer in this conversation'),
+ );
+ });
+
+ testTags('lost access clears the thread tags and the picker', (tester) async {
+ final server = swarm();
+ final c = await show(tester, server);
+ await type(tester, '@ke');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await type(tester, '@ken15 @');
+ expect(picker, findsOneWidget);
+ c.revokeAccess('You no longer have access.');
+ await tester.pumpAndSettle();
+ expect(c.threadMentions('lead', 'message-1'), isEmpty);
+ expect(picker, findsNothing);
+ expect(find.text('ken15'), findsNothing);
+ });
+
+ group('Buddy threads', () {
+ /// The reader's own Buddy chat ('offline') with its main Buddy, and a
+ /// thread at its first message.
+ ConversationServer buddyChat() {
+ final server = swarm();
+ server.state['threadSessions'] = true;
+ final chat = (server.state['conversations'] as List)[1] as Map
+ ..['kind'] = 'buddy'
+ ..['buddyOwnerId'] = 'owner'
+ ..['title'] = 'Wren';
+ (server.state['agents'] as List).add({
+ 'id': 'buddy-main',
+ 'name': 'Wren',
+ 'displayName': 'Wren',
+ 'machineId': 'mac',
+ 'harnessId': 'h-main',
+ 'contributorId': 'owner',
+ 'buddyOf': {'personId': 'owner', 'generation': 'g1'},
+ 'configuration': {'engine': 'claude'},
+ });
+ chat['agentIds'] = ['buddy-main'];
+ server.append('Measure prod CPU', conversationId: 'offline');
+ server.append('Another question', conversationId: 'offline');
+ return server;
+ }
+
+ Future<SuperTabController> showBuddy(
+ WidgetTester tester,
+ ConversationServer server,
+ String root,
+ ) async {
+ final c = await show(tester, server);
+ c.select('offline');
+ await tester.pumpAndSettle();
+ c.openThread(root);
+ await tester.pumpAndSettle();
+ return c;
+ }
+
+ testTags('a Buddy thread offers its Buddy, as the chat does', (
+ tester,
+ ) async {
+ final server = buddyChat();
+ await showBuddy(tester, server, 'message-4');
+ await type(tester, '@');
+ expect(choices(tester), ['Wren']);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ final command = lastCommand(server);
+ expect(command['conversationId'], 'offline');
+ expect(command['replyTo'], 'message-4');
+ expect(command['recipientIds'], ['buddy-main']);
+ });
+
+ testTags(
+ 'a thread its own session answers offers no agent: only the session '
+ 'hears it',
+ (tester) async {
+ final server = buddyChat();
+ final chat = (server.state['conversations'] as List)[1] as Map;
+ chat['buddySessions'] = [
+ {
+ 'thread': 'message-4',
+ 'startId': 'start',
+ 'agentId': 'session-1',
+ 'at': 1,
+ },
+ ];
+ (server.state['agents'] as List).add({
+ 'id': 'session-1',
+ 'name': 'Wren',
+ 'displayName': 'Wren',
+ 'machineId': 'mac',
+ 'harnessId': 'h-session',
+ 'contributorId': 'owner',
+ 'buddyOf': {'personId': 'owner', 'generation': 'g1'},
+ 'buddySession': {'thread': 'message-4', 'from': 1},
+ 'configuration': {'engine': 'claude'},
+ });
+ chat['agentIds'] = ['buddy-main', 'session-1'];
+ final c = await showBuddy(tester, server, 'message-4');
+ expect(c.threadSession('message-4'), isNotNull);
+ await type(tester, '@');
+ expect(picker, findsNothing);
+ // In another thread of the chat, the Buddy is offered again.
+ c.openThread('message-5');
+ await tester.pumpAndSettle();
+ await type(tester, '@');
+ expect(choices(tester), ['Wren']);
+ },
+ );
+ });
+
+ for (final brightness in Brightness.values) {
+ testTags('screenshots for review, ${brightness.name}', (tester) async {
+ final server = swarm();
+ final c = await show(tester, server, brightness: brightness);
+ await type(tester, 'Please check @');
+ await shot(tester, 'thread-picker-${brightness.name}');
+ await type(tester, 'Please check @ke');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await c.loadThread();
+ await tester.pumpAndSettle();
+ await shot(tester, 'thread-sent-${brightness.name}');
+ }, skip: shots == null);
+ }
+}
diff --git a/desktop/test/super_tab_web_sign_out_test.dart b/desktop/test/super_tab_web_sign_out_test.dart
index 100fdfd48..1d213ce16 100644
--- a/desktop/test/super_tab_web_sign_out_test.dart
+++ b/desktop/test/super_tab_web_sign_out_test.dart
@@ -80,6 +80,7 @@ void main() {
expect(swarmKeyAccount('super_tab.launch.owner.desk.lead'), 'owner');
expect(swarmKeyAccount('super_tab.hidden.owner'), 'owner');
expect(swarmKeyAccount('super_tab.personal.owner'), 'owner');
+ expect(swarmKeyAccount('super_tab.repos.owner'), 'owner');
for (final key in [
'super_tab.view.owner.tab',
'super_tab.views.owner',
diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dart
index 72c04b3c5..bb6773565 100644
--- a/desktop/test/support/super_tab_fixture.dart
+++ b/desktop/test/support/super_tab_fixture.dart
@@ -969,6 +969,10 @@ class ConversationServer {
],
);
messages.last['replyTo'] = command['replyTo'];
+ // The people it tags, as the backend keeps them (commands.ts).
+ if (command['mentions'] case final List tagged) {
+ messages.last['mentions'] = [...tagged];
+ }
// A reply joins its message's thread at the root; one to a message
// written before threads stays inline (backend commands.ts).
final target = messages
diff --git a/scripts/ui-style-allowlist/desktop.json b/scripts/ui-style-allowlist/desktop.json
index 97f48bf5f..b50a4f8f3 100644
--- a/scripts/ui-style-allowlist/desktop.json
+++ b/scripts/ui-style-allowlist/desktop.json
@@ -83,7 +83,7 @@
"edge-insets": 2
},
"desktop/lib/super_tabs/view.dart": {
- "edge-insets": 22,
+ "edge-insets": 20,
"border-radius": 1
}
}