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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
⌘B: "What's up?", recent prompts, and the pane the words land in lights (#1152)
Dee9725b86352c0
diff --git a/desktop/lib/core/task_history.dart b/desktop/lib/core/task_history.dartnew file mode 100644index 000000000..d16ef1f2e--- /dev/null+++ b/desktop/lib/core/task_history.dart@@ -0,0 +1,91 @@+import 'dart:convert';++import 'local_key_value_store.dart';++/// What the person has said to ⌘B, newest first: the box's recent prompts, as a search box keeps its+/// recent searches. Picking one says it again, decided on what the desk looks like now. Saved when it is+/// submitted, so one that could not be sent is there to try again. Kept on this computer, in the app's+/// state file, like the recent projects (`ProjectHistory`) — and only for the account that said them:+/// another account signing in on this Mac sees none of them, as it takes none of another's tabs+/// (`PaneLayoutStore.restorableFor`).+class TaskHistory {+ TaskHistory(this._storage);++ final LocalKeyValueStore? _storage;+ static const _key = 'task_box_recent_v1';++ /// How many are kept; the box shows fewer.+ static const keep = 20;++ /// Longer than this is a pasted document, not a prompt worth offering again.+ static const maxChars = 2000;++ String? _owner;+ final _recent = <String>[];+ Future<void>? _loading;+ Future<void> _saving = Future.value();+ int _revision = 0;++ /// The prompts [account] said; none for an account that is not known, or not theirs.+ List<String> recentFor(String? account) =>+ account != null && account == _owner+ ? List.unmodifiable(_recent)+ : const [];++ Future<void> load() => _loading ??= _load();++ Future<void> _load() async {+ final revision = _revision;+ try {+ final raw = await _storage?.read(_key);+ if (raw == null || _revision != revision) return;+ final decoded = jsonDecode(raw);+ if (decoded is! Map ||+ decoded['owner'] is! String ||+ decoded['prompts'] is! List) {+ return;+ }+ _owner = decoded['owner'] as String;+ _recent+ ..clear()+ ..addAll(+ (decoded['prompts'] as List)+ .whereType<String>()+ .map((prompt) => prompt.trim())+ .where(_valid)+ .toSet()+ .take(keep),+ );+ } catch (_) {+ // A missing or unreadable history is no history: the box still works.+ }+ }++ static bool _valid(String prompt) =>+ prompt.isNotEmpty && prompt.length <= maxChars;++ /// [prompt] said again moves to the top rather than appearing twice. Said by an account that is not+ /// the one on record, it starts that account's history over; by none known, it is not kept.+ Future<void> add(String prompt, {required String? account}) async {+ final text = prompt.trim();+ if (account == null || !_valid(text)) return;+ await load();+ _revision++;+ if (_owner != account) {+ _owner = account;+ _recent.clear();+ }+ final rest = _recent.where((said) => said != text).take(keep - 1).toList();+ _recent+ ..clear()+ ..add(text)+ ..addAll(rest);+ final snapshot = jsonEncode({'owner': account, 'prompts': _recent});+ _saving = _saving.then((_) async {+ try {+ await _storage?.write(_key, snapshot);+ } catch (_) {}+ });+ await _saving;+ }+}diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 8b5346f5d..32f7ddc44 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -6290,6 +6290,8 @@ class _SwarmScreenState extends State<SwarmScreen> {id: taskRouteSessionId(machineId, agentId),at: DateTime.now(),);+ // The receipt is the new pane lighting, as a send's is the pane it landed in.+ app.markLanding(machineId, agentId);spoken?.sent(agentId);} else {spoken?.cancelled();diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 54ff9dd87..439165193 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -62,6 +62,7 @@ import '../core/machine_resources.dart';import '../core/project_folder.dart';import '../core/git_worktree.dart';import '../core/project_history.dart';+import '../core/task_history.dart';import '../core/project_preview.dart';import '../core/repository_clone.dart';import '../core/retry.dart';@@ -3126,6 +3127,7 @@ class AppNotifier extends ChangeNotifier {agentPreference = AgentPreference(paneLayoutStore?.storage),firstArrival = FirstArrival(paneLayoutStore?.storage),projectHistory = ProjectHistory(paneLayoutStore?.storage),+ taskHistory = TaskHistory(paneLayoutStore?.storage),session = authSession,_store = configStore,config = configStore?.config ?? config,@@ -3264,6 +3266,9 @@ class AppNotifier extends ChangeNotifier {final AgentPreference agentPreference;final ProjectHistory projectHistory;+ /// ⌘B's recent prompts (`core/task_history.dart`).+ final TaskHistory taskHistory;+/// The first workspace on a computer new to Harness opens with agents already in it.final FirstArrival firstArrival;@@ -4177,6 +4182,27 @@ class AppNotifier extends ChangeNotifier {/// The session ⌘B last sent a task to, which the router tells Jev so a follow-up finds it.({String id, DateTime at})? lastRoutedTask;+ /// The pane a task just landed in — ⌘B's receipt: its rim lights once (`pane_grid.dart`), so the eye+ /// sees where the words went, in whichever tab. [seq] tells one landing from the next on the same pane.+ final paneLanding =+ ValueNotifier<+ ({String machineId, String agentId, int seq, DateTime at})?+ >(null);+ int _landings = 0;++ void markLanding(String machineId, String agentId) => paneLanding.value = (+ machineId: machineId,+ agentId: agentId,+ seq: ++_landings,+ at: DateTime.now(),+ );++ /// The landing is over: a pane of that session opened later (reopened from ⌘P, restored at sign-in)+ /// must not light for words that landed long ago.+ void endLanding(int seq) {+ if (paneLanding.value?.seq == seq) paneLanding.value = null;+ }+/// ⌘B's send: the session's pane comes forward and the task goes into its prompt, through this app's/// own door on any machine (`deliverTask`). [stillWanted] is asked just before the words are typed:/// the pane comes forward first, and a person who sees the wrong one and presses Esc stops the send.@@ -17394,6 +17420,7 @@ class AppNotifier extends ChangeNotifier {if (cliLogin case final CliLogin cli) {cli.waitingNote.removeListener(_loginWaitingChanged);}+ paneLanding.dispose();_closeOwnerMemories();_agentDownloadsTick?.cancel();agentPrefetch?.close();diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dartindex e4a3d082d..5499c1dfc 100644--- a/desktop/lib/widgets/pane_grid.dart+++ b/desktop/lib/widgets/pane_grid.dart@@ -1330,109 +1330,137 @@ class _PaneCell extends StatelessWidget {onSplit: (axis) => onSplitPane?.call(pane.id, axis),child: child!,),- child: Container(- key: ValueKey('pane-frame:${pane.id}'),- decoration: BoxDecoration(- // UNCHANGED, and deliberately: the terminal renders its own background- // inside this box, so a tile that stops matching the window colour- // shows a seam between the header strip and the terminal under it.- // What changes to make the gaps visible is the field BEHIND the grid- // (see _GridField), which is the part the gaps actually show.- //- // Over a Background: a terminal paints its own translucent fills, so- // the frame adds none (two would stack); a status pane has only this.- color: PaneOpacity.of(context) < 1 && pane.session != null- ? null- : PaneOpacity.fill(context, grid.AppPalette.windowBg),- borderRadius: BorderRadius.circular(_paneRadius),- // The rim is always drawn — it is what gives an unfocused card its- // edge, now that no shared line does. It only CHANGES COLOUR on- // focus, so nothing resizes as focus moves.- border: Border.fromBorderSide(- // Keep the location cue when a pane is alone or zoomed, too.- terminalPaneBorder(focused: focused, remote: remote),+ // Passthrough: the frame keeps the exact constraints the grid gives it. The landing is ALWAYS+ // here, painting nothing between landings, so a landing never reparents the terminal.+ child: Stack(+ fit: StackFit.passthrough,+ children: [+ _frame(+ prefs,+ focused: focused,+ remote: remote,+ dimmed: dimmed,+ blocked: blocked,),+ Positioned.fill(+ child: IgnorePointer(+ child: _PaneLanding(notifier: notifier, pane: pane),+ ),+ ),+ ],+ ),+ ),+ );+ }++ Widget _frame(+ AppearancePrefs prefs, {+ required bool focused,+ required bool remote,+ required bool dimmed,+ required bool blocked,+ }) {+ return Builder(+ builder: (context) => Container(+ key: ValueKey('pane-frame:${pane.id}'),+ decoration: BoxDecoration(+ // UNCHANGED, and deliberately: the terminal renders its own background+ // inside this box, so a tile that stops matching the window colour+ // shows a seam between the header strip and the terminal under it.+ // What changes to make the gaps visible is the field BEHIND the grid+ // (see _GridField), which is the part the gaps actually show.+ //+ // Over a Background: a terminal paints its own translucent fills, so+ // the frame adds none (two would stack); a status pane has only this.+ color: PaneOpacity.of(context) < 1 && pane.session != null+ ? null+ : PaneOpacity.fill(context, grid.AppPalette.windowBg),+ borderRadius: BorderRadius.circular(_paneRadius),+ // The rim is always drawn — it is what gives an unfocused card its+ // edge, now that no shared line does. It only CHANGES COLOUR on+ // focus, so nothing resizes as focus moves.+ border: Border.fromBorderSide(+ // Keep the location cue when a pane is alone or zoomed, too.+ terminalPaneBorder(focused: focused, remote: remote),),- // A neutral gray veil lifts inactive backgrounds and softens their text- // without changing terminal colors. Paint attention above the veil so- // a waiting question keeps its full-strength amber rim. Keep this- // decoration present even when clear: inserting/removing it would- // reparent the terminal and lose its input, scroll and selection state.- foregroundDecoration: BoxDecoration(- color: dimmed- ? const Color(0xFF9D9D9D).withValues(alpha: .30)- : null,- border: blocked- ? Border.all(color: grid.AppPalette.warn, width: 2)- : null,- borderRadius: BorderRadius.circular(_paneRadius),- ),- // Keeps a terminal's constant repainting inside its own layer instead- // of dirtying the whole grid. No key: nothing reads this boundary, it- // only has to exist.- child: ClipRRect(- // Clipped HERE rather than through Container's own clipBehavior.- //- // Both clip, but they clip to different shapes: Container's is the- // decoration's OUTER edge, so the child fills the full radius and- // paints under the rim, leaving a square-shouldered corner peeking- // through the 1px the rim occupies. This one takes the rim's pixel- // off the radius, so the fill stops exactly where the rim starts.- //- // TerminalPanel opens with a ColoredBox across its whole box, and- // that is what was reaching the corners.- borderRadius: BorderRadius.circular(_paneRadius - 1),- child: RepaintBoundary(- child: _FileDropZone(+ ),+ // A neutral gray veil lifts inactive backgrounds and softens their text+ // without changing terminal colors. Paint attention above the veil so+ // a waiting question keeps its full-strength amber rim. Keep this+ // decoration present even when clear: inserting/removing it would+ // reparent the terminal and lose its input, scroll and selection state.+ foregroundDecoration: BoxDecoration(+ color: dimmed ? const Color(0xFF9D9D9D).withValues(alpha: .30) : null,+ border: blocked+ ? Border.all(color: grid.AppPalette.warn, width: 2)+ : null,+ borderRadius: BorderRadius.circular(_paneRadius),+ ),+ // Keeps a terminal's constant repainting inside its own layer instead+ // of dirtying the whole grid. No key: nothing reads this boundary, it+ // only has to exist.+ child: ClipRRect(+ // Clipped HERE rather than through Container's own clipBehavior.+ //+ // Both clip, but they clip to different shapes: Container's is the+ // decoration's OUTER edge, so the child fills the full radius and+ // paints under the rim, leaving a square-shouldered corner peeking+ // through the 1px the rim occupies. This one takes the rim's pixel+ // off the radius, so the fill stops exactly where the rim starts.+ //+ // TerminalPanel opens with a ColoredBox across its whole box, and+ // that is what was reaching the corners.+ borderRadius: BorderRadius.circular(_paneRadius - 1),+ child: RepaintBoundary(+ child: _FileDropZone(+ notifier: notifier,+ pane: pane,+ visible: visible,+ child: _SwapZone(notifier: notifier,- pane: pane,- visible: visible,- child: _SwapZone(+ paneId: pane.id,+ child: _DropZone(notifier: notifier,paneId: pane.id,- child: _DropZone(- notifier: notifier,- paneId: pane.id,- dragging: dragging,- child: ValueListenableBuilder<PaneDragRef?>(- valueListenable: paneDragging,- // The tile being carried fades where it sits, so the grid shows- // where it came FROM while the ghost shows where it is going.- builder: (context, inFlight, child) => Opacity(- opacity: inFlight?.paneId == pane.id ? 0.35 : 1,- child: child,- ),- child: pane.isDevices- ? devicesViewer?.call(context) ??- const SizedBox.shrink()- : pane.isCompanion- ? companionViewer?.call(context) ??- const SizedBox.shrink()- : pane.agentId == null &&- devicesConversation != null &&- notifier.swarms.any(- (tab) =>- tab.isDevices && tab.panes.contains(pane),- )- ? devicesConversation!(context)- : pane.agentId == null &&- companionConversation != null &&- notifier.swarms.any(- (tab) =>- tab.isCompanions &&- tab.panes.contains(pane),- )- ? companionConversation!(context)- : _PaneContent(- notifier: notifier,- pane: pane,- single: _single,- visible: visible,- swarmMode: swarmMode,- onOpenModels: onOpenModels,- onSplitPane: onSplitPane,- ),+ dragging: dragging,+ child: ValueListenableBuilder<PaneDragRef?>(+ valueListenable: paneDragging,+ // The tile being carried fades where it sits, so the grid shows+ // where it came FROM while the ghost shows where it is going.+ builder: (context, inFlight, child) => Opacity(+ opacity: inFlight?.paneId == pane.id ? 0.35 : 1,+ child: child,),+ child: pane.isDevices+ ? devicesViewer?.call(context) ??+ const SizedBox.shrink()+ : pane.isCompanion+ ? companionViewer?.call(context) ??+ const SizedBox.shrink()+ : pane.agentId == null &&+ devicesConversation != null &&+ notifier.swarms.any(+ (tab) =>+ tab.isDevices && tab.panes.contains(pane),+ )+ ? devicesConversation!(context)+ : pane.agentId == null &&+ companionConversation != null &&+ notifier.swarms.any(+ (tab) =>+ tab.isCompanions &&+ tab.panes.contains(pane),+ )+ ? companionConversation!(context)+ : _PaneContent(+ notifier: notifier,+ pane: pane,+ single: _single,+ visible: visible,+ swarmMode: swarmMode,+ onOpenModels: onOpenModels,+ onSplitPane: onSplitPane,+ ),),),),@@ -1444,6 +1472,54 @@ class _PaneCell extends StatelessWidget {}}+/// ⌘B's receipt (`AppNotifier.markLanding`): the selection blue washes over the pane a task just landed+/// in, once, and fades, so the eye finds where the words went. A wash, not a rim: pane rims carry focus+/// and location and never glow (`desktop/design/desktop-design-system.md`). Optional motion, so Reduce+/// Motion skips it and the pane taking focus is the receipt.+const _landingFor = Duration(milliseconds: 900);++class _PaneLanding extends StatelessWidget {+ const _PaneLanding({required this.notifier, required this.pane});++ final AppNotifier notifier;+ final TerminalPane pane;++ @override+ Widget build(BuildContext context) {+ return ValueListenableBuilder(+ valueListenable: notifier.paneLanding,+ builder: (context, landing, _) {+ if (landing == null ||+ landing.machineId != pane.machineId ||+ landing.agentId != pane.agentId ||+ MediaQuery.disableAnimationsOf(context) ||+ // Mounted after the moment has passed: nothing is landing now.+ DateTime.now().difference(landing.at) > _landingFor) {+ return const SizedBox.shrink();+ }+ return TweenAnimationBuilder<double>(+ key: ValueKey('pane-landing:${pane.id}:${landing.seq}'),+ tween: Tween(begin: 1, end: 0),+ duration: _landingFor,+ curve: Curves.easeOut,+ onEnd: () => notifier.endLanding(landing.seq),+ builder: (context, wash, _) => wash == 0+ ? const SizedBox.shrink()+ : DecoratedBox(+ key: ValueKey('pane-landing:${pane.id}'),+ decoration: BoxDecoration(+ color: DesktopChrome.selection.withValues(+ alpha: DesktopChrome.selection.a * wash,+ ),+ borderRadius: BorderRadius.circular(_paneRadius),+ ),+ ),+ );+ },+ );+ }+}+class _PaneContent extends StatelessWidget {const _PaneContent({required this.notifier,diff --git a/desktop/lib/widgets/task_palette.dart b/desktop/lib/widgets/task_palette.dartindex b33343e45..bd589f9b3 100644--- a/desktop/lib/widgets/task_palette.dart+++ b/desktop/lib/widgets/task_palette.dart@@ -1,8 +1,8 @@import 'dart:async';-import 'package:harness/shared/theme/app_icons.dart';import 'package:flutter/material.dart';import 'package:flutter/services.dart';+import 'package:harness/shared/theme/app_icons.dart';import '../core/models.dart';import '../shared/theme/app_theme.dart' as grid;@@ -151,17 +151,7 @@ class _TaskPalette extends StatefulWidget {State<_TaskPalette> createState() => _TaskPaletteState();}-/// [sent] is a BEAT, not a screen. See [_confirmBeat].-enum _Stage { typing, routing, choosing, empty, sent }--/// How long the receipt stays up before the palette closes itself.-///-/// A confident route used to close the instant the daemon answered, on the rule that the text landing in-/// the terminal is the receipt. It is — but only if you are looking at that pane, and ⌘B is most useful-/// exactly when you are not: the agent it picks is often on another machine and behind another tile. So-/// the window says who took the work, briefly, and then gets out of the way. Long enough to read four-/// words, short enough that nobody waits on it.-const Duration _confirmBeat = Duration(milliseconds: 750);+enum _Stage { typing, routing, choosing, empty }class _TaskPaletteState extends State<_TaskPalette> {final TextEditingController _text = TextEditingController();@@ -182,10 +172,6 @@ class _TaskPaletteState extends State<_TaskPalette> {/// across how many computers, and whether a classifier or the name matcher produced this.RouteAnswer? _answer;- /// Which agent took the work — held for the receipt beat, where the design lights that row rather- /// than printing a sentence about it.- String _committed = '';-/// Seconds on the clock while the router thinks.////// The wait can run to twenty seconds, and a spinner that says nothing for that long reads as a hang.@@ -222,13 +208,24 @@ class _TaskPaletteState extends State<_TaskPalette> {void initState() {super.initState();_context = warmTaskRoute(widget.notifier);+ // The recent prompts are read from the state file the first time; the box draws them once they are.+ unawaited(+ widget.notifier.taskHistory.load().then((_) {+ if (mounted) setState(() {});+ }),+ );final spoken = widget.spoken;- if (spoken == null) return;// The transcript goes in the field rather than into a variable the person cannot see: this is the// same palette, and what it is about to route has to be readable — and editable, if the STT heard// "web hook" and meant "webhook".- _text.text = spoken.text;- _text.selection = TextSelection.collapsed(offset: _text.text.length);+ if (spoken != null) {+ _text.text = spoken.text;+ _text.selection = TextSelection.collapsed(offset: _text.text.length);+ }+ // Typing narrows the recent prompts, and lets go of one picked with the arrows. Listened to only+ // now: a transcript set above, before the first frame, has nothing to redraw.+ _text.addListener(_typed);+ if (spoken == null) return;// Acked BEFORE the first frame, not after the route: the daemon is deciding, on a two-second clock,// whether any window is listening at all, and it must not fall back to routing on its own while this// one is up. See cable/windowRoute.ts.@@ -243,6 +240,7 @@ class _TaskPaletteState extends State<_TaskPalette> {@overridevoid dispose() {+ _text.removeListener(_typed);_generation++; // anything still in flight now answers to nobody_ticker?.cancel();_text.dispose();@@ -260,11 +258,15 @@ class _TaskPaletteState extends State<_TaskPalette> {/// router, and a question when it is unsure.Future<void> _decide() async {final task = _text.text.trim();- // Not while one is in flight, and not during the receipt: Return held down, or pressed again as the- // card says who took it, would send the same task twice.- if (task.isEmpty || _stage == _Stage.routing || _stage == _Stage.sent) {- return;- }+ // Not while one is in flight: Return held down would send the same task twice.+ if (task.isEmpty || _stage == _Stage.routing) return;+ // Remembered as it is said, sent or not: one that could not be sent is there to say again.+ unawaited(+ widget.notifier.taskHistory.add(+ task,+ account: widget.notifier.currentUser?.id,+ ),+ );final mine = ++_generation;setState(() {_stage = _Stage.routing;@@ -312,23 +314,6 @@ class _TaskPaletteState extends State<_TaskPalette> {);return;}- // The receipt lights the row of the session that took it.- final taker = RouteCandidate(- agentId: session.agentId,- machineId: session.machineId,- name: session.name,- machine: session.machine,- recent: session.asks.firstOrNull ?? '',- engine: session.engine,- );- _answer = RouteAnswer(- agentId: session.agentId,- machineId: session.machineId,- name: session.name,- confidence: 1,- reason: '',- candidates: [taker],- );final failure = await widget.notifier.sendTaskToSession(session.machineId,session.agentId,@@ -348,13 +333,14 @@ class _TaskPaletteState extends State<_TaskPalette> {id: decision.sessionId!,at: DateTime.now(),);- widget.spoken?.sent(session.agentId);- setState(() {- _stage = _Stage.sent;- _committed = session.agentId;- });- await Future<void>.delayed(_confirmBeat);- if (!mounted || mine != _generation) return;+ _landed(session.machineId, session.agentId);+ }++ /// The words are in. The box goes at once and the pane they landed in lights (`markLanding`): the+ /// receipt is where the work went, not a line about it in a box that is in the way of seeing it.+ void _landed(String machineId, String agentId) {+ widget.spoken?.sent(agentId);+ widget.notifier.markLanding(machineId, agentId);Navigator.of(context).pop();}@@ -399,7 +385,7 @@ class _TaskPaletteState extends State<_TaskPalette> {}if (answer.confidence >= _confidentEnough) {- _answer = answer; // so the receipt can name who took it+ _answer = answer;await _commit(answer.agentId, answer.machineId, task);return;}@@ -490,27 +476,111 @@ class _TaskPaletteState extends State<_TaskPalette> {id: taskRouteSessionId(machineId, agentId),at: DateTime.now(),);- // Landed. Tell the daemon before the beat, not after: it is holding the dial's overlay open on this- // answer, and three quarters of a second is long enough to be seen as a stall on a device whose only- // feedback is that overlay.- widget.spoken?.sent(agentId);- // Light the row that took it, then close — see [_confirmBeat].- setState(() {- _stage = _Stage.sent;- _committed = agentId;- });- await Future<void>.delayed(_confirmBeat);- if (!mounted || mine != _generation) return;- Navigator.of(context).pop();+ // The old router may name no machine: the pane then opens where the send went (`sendRoutedTask`).+ final target = machineId.isNotEmpty+ ? machineId+ : (widget.notifier.viewer == null+ ? widget.notifier.localMachineState+ : widget.notifier.ownedActionMachine)+ ?.machine+ .machineId;+ _landed(target ?? machineId, agentId);}- /// The candidate row for an id, when the answer carried one. The winner is always among them, so a- /// confident route can name its taker without a second lookup.- RouteCandidate? _named(String agentId) {- for (final candidate in _answer?.candidates ?? const <RouteCandidate>[]) {- if (candidate.agentId == agentId) return candidate;- }- return null;+ /// How many recent prompts the box offers: as many as a search box shows, and the same six the+ /// welcome page's recent harnesses stop at.+ static const _recentShown = 6;++ /// The recent prompt picked with the arrows, if one is: Return says it instead of what is typed.+ int? _recentCursor;++ /// The recent prompts that fit what is typed, newest first: all of them in an empty box, then those+ /// that contain the words so far. None while it decides, and none for a prompt of several lines.+ List<String> get _suggestions {+ if (_stage != _Stage.typing) return const [];+ // A prompt of several lines keeps its arrows for its own lines: checked before trimming, which would+ // drop the newline just typed.+ if (_text.text.contains('\n')) return const [];+ final typed = _text.text.trim().toLowerCase();+ return widget.notifier.taskHistory+ .recentFor(widget.notifier.currentUser?.id)+ .where((said) {+ final lower = said.toLowerCase();+ return typed.isEmpty || (lower.contains(typed) && lower != typed);+ })+ .take(_recentShown)+ .toList();+ }++ String? get _picked {+ final at = _recentCursor;+ final suggestions = _suggestions;+ return at == null || at >= suggestions.length ? null : suggestions[at];+ }++ void _typed() {+ if (!mounted) return;+ setState(() => _recentCursor = null);+ }++ /// A recent prompt picked: said again, as a search box runs a recent search — decided on the desk as it+ /// is now, so it may go somewhere other than it went before.+ KeyEventResult _sayAgain(String prompt) {+ _text.removeListener(_typed);+ _text.value = TextEditingValue(+ text: prompt,+ selection: TextSelection.collapsed(offset: prompt.length),+ );+ _text.addListener(_typed);+ _recentCursor = null;+ unawaited(_decide());+ return KeyEventResult.handled;+ }++ /// A recent prompt's row: the clock of a past search, and the words.+ Widget _recentRow(String prompt, {required bool active}) {+ final ink = active ? grid.AppDesktop.onSelection : DesktopChrome.foreground;+ return Semantics(+ selected: active,+ button: true,+ label: 'Say again: $prompt',+ child: InkWell(+ mouseCursor: SystemMouseCursors.click,+ onTap: () => _sayAgain(prompt),+ borderRadius: BorderRadius.circular(grid.AppDesktop.rowRadius),+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),+ decoration: BoxDecoration(+ color: active ? grid.AppDesktop.selection : null,+ borderRadius: BorderRadius.circular(grid.AppDesktop.rowRadius),+ ),+ child: Row(+ children: [+ ExcludeSemantics(+ child: Icon(+ AppIcons.history,+ size: 16,+ color: active+ ? grid.AppDesktop.selectionDetail+ : DesktopChrome.muted,+ ),+ ),+ const SizedBox(width: 12),+ Expanded(+ child: ExcludeSemantics(+ child: Text(+ prompt.replaceAll(RegExp(r'\s+'), ' '),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(color: ink),+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ );}KeyEventResult _onFieldKey(FocusNode node, KeyEvent event) {@@ -534,9 +604,25 @@ class _TaskPaletteState extends State<_TaskPalette> {// ⇧Enter is the newline — ignored here so the field does what it always does with it.final shift = HardwareKeyboard.instance.isShiftPressed;if (isEnter && !shift && _stage != _Stage.choosing) {+ final picked = _picked;+ if (picked != null) return _sayAgain(picked);unawaited(_decide());return KeyEventResult.handled; // …and NOT a newline}+ final suggestions = _suggestions;+ final down = event.logicalKey == LogicalKeyboardKey.arrowDown;+ if (_stage != _Stage.choosing &&+ suggestions.isNotEmpty &&+ (down || event.logicalKey == LogicalKeyboardKey.arrowUp)) {+ // Down from the field onto the first, up past the first back to the field.+ final at = _recentCursor;+ setState(+ () => _recentCursor = down+ ? (at == null ? 0 : (at + 1).clamp(0, suggestions.length - 1))+ : (at == null || at == 0 ? null : at - 1),+ );+ return KeyEventResult.handled;+ }if (_stage != _Stage.choosing) return KeyEventResult.ignored;if (event.logicalKey == LogicalKeyboardKey.arrowDown) {@@ -616,7 +702,7 @@ class _TaskPaletteState extends State<_TaskPalette> {// and the common case must not cost a reach for the mouse.// Read-only rather than disabled while the router thinks: a disabled field drops the focus,// and the focus is what Esc is listening on.- readOnly: working || _stage == _Stage.sent,+ readOnly: working,style: DesktopChrome.text(size: 17, height: 1.35),cursorColor: DesktopChrome.accent,cursorWidth: 2,@@ -631,7 +717,7 @@ class _TaskPaletteState extends State<_TaskPalette> {enabledBorder: InputBorder.none,focusedBorder: InputBorder.none,disabledBorder: InputBorder.none,- hintText: 'Describe the work…',+ hintText: "What's up?",hintStyle: DesktopChrome.text(size: 17,color: DesktopChrome.muted,@@ -681,6 +767,13 @@ class _TaskPaletteState extends State<_TaskPalette> {Widget _results() {switch (_stage) {case _Stage.typing:+ final suggestions = _suggestions;+ if (suggestions.isEmpty) return const SizedBox.shrink();+ return _panel([+ for (var i = 0; i < suggestions.length; i++)+ _recentRow(suggestions[i], active: i == _recentCursor),+ ]);+case _Stage.routing:return const SizedBox.shrink();@@ -699,27 +792,6 @@ class _TaskPaletteState extends State<_TaskPalette> {),]);- case _Stage.sent:- // The receipt is the ROW, lit. The design drew this state and it is better than the line of text- // it replaces: the eye is already on the row, and a lit row answers "who" as well as "done".- final taker = _named(_committed);- return _panel([- Padding(- padding: EdgeInsets.fromLTRB(16, 8, 16, 6),- child: Row(- children: [- Icon(AppIcons.check, size: 14, color: DesktopChrome.accent),- SizedBox(width: 8),- Text(- 'Task sent',- style: grid.AppType.body(color: DesktopChrome.accent),- ),- ],- ),- ),- if (taker != null) _row(taker, active: false, taken: true),- ]);-case _Stage.choosing:return _panel([_question(),@@ -738,11 +810,7 @@ class _TaskPaletteState extends State<_TaskPalette> {for (var i = 0; i < _choices.length; i++)KeyedSubtree(key: i < _rowKeys.length ? _rowKeys[i] : null,- child: _row(- _choices[i],- active: i == _cursor,- taken: false,- ),+ child: _row(_choices[i], active: i == _cursor),),],),@@ -833,13 +901,9 @@ class _TaskPaletteState extends State<_TaskPalette> {}/// Shared picker anatomy keeps machine context legible in narrow windows.- Widget _row(- RouteCandidate candidate, {- required bool active,- required bool taken,- }) {+ Widget _row(RouteCandidate candidate, {required bool active}) {final fit = candidate.confidence;- final selected = active || taken;+ final selected = active;final ink = selected? grid.AppDesktop.onSelection: DesktopChrome.foreground;@@ -853,18 +917,10 @@ class _TaskPaletteState extends State<_TaskPalette> {return Semantics(selected: active,child: InkWell(- mouseCursor: taken- ? SystemMouseCursors.basic- : SystemMouseCursors.click,- onTap: taken- ? null- : () => unawaited(- _commit(- candidate.agentId,- candidate.machineId,- _text.text.trim(),- ),- ),+ mouseCursor: SystemMouseCursors.click,+ onTap: () => unawaited(+ _commit(candidate.agentId, candidate.machineId, _text.text.trim()),+ ),borderRadius: BorderRadius.circular(grid.AppDesktop.rowRadius),child: Container(padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),@@ -901,15 +957,12 @@ class _TaskPaletteState extends State<_TaskPalette> {],),),- if (fit > 0 || taken) ...[+ if (fit > 0) ...[const SizedBox(width: 12),- if (taken)- Icon(AppIcons.check, size: 16, color: ink)- else- Text(- fit.toStringAsFixed(2),- style: DesktopChrome.metadata(color: detail),- ),+ Text(+ fit.toStringAsFixed(2),+ style: DesktopChrome.metadata(color: detail),+ ),],],),diff --git a/desktop/test/route_card_test.dart b/desktop/test/route_card_test.dartindex fa2952887..e3f75d5f6 100644--- a/desktop/test/route_card_test.dart+++ b/desktop/test/route_card_test.dart@@ -26,6 +26,7 @@ class _App extends AppNotifier {authMode: MachineAuthMode.remote,name: 'Office',);+ currentUser = const CurrentUserProfile(id: 'u1', email: '[email protected]');machines = [machine];machineStates['m'] = MachineState(machine)..nodeOnline = true@@ -57,12 +58,16 @@ class _App extends AppNotifier {TaskRouteDecision? Function(String text)? decision;+ /// Holds the decision until it completes, when set.+ Future<void>? later;+@overrideFuture<TaskRouteDecision?> routeDecide(String text,TaskRouteChoices choices,) async {payloads.add(choices.toPayload());+ await later;if (decision case final decide?) return decide(text);final answer = reply(text);return answer == null ? null : TaskRouteDecision.fromJson(answer, choices);@@ -428,10 +433,11 @@ void main() {expect(app.sent, [('m', 'a0', "what's the D3 retention rate")]);expect(app.routed, isEmpty);expect(app.lastRoutedTask?.id, _session);- // The receipt names who took it, then the card goes.- expect(find.text('Analyze Harness usage data'), findsOneWidget);- await tester.pumpAndSettle(const Duration(seconds: 1));+ // No receipt in the box: it goes at once, and the pane the words landed in lights.+ await tester.pump();expect(find.byType(TextField), findsNothing);+ expect(app.paneLanding.value?.agentId, 'a0');+ expect(app.paneLanding.value?.machineId, 'm');expect(await result(), isNull);});@@ -541,18 +547,28 @@ void main() {expect(app.routed, isEmpty);});- testWidgets('Return during the receipt does not send the task again', (- tester,- ) async {- final (app, _) = await _open(tester);- app.reply = (_) => {'decided': 'session', 'id': _session, 'via': 'jev'};- await _say(tester, "what's the D3 retention rate");- expect(app.sent, hasLength(1));- await tester.sendKeyEvent(LogicalKeyboardKey.enter);- await tester.pump();- await tester.pumpAndSettle(const Duration(seconds: 1));- expect(app.sent, hasLength(1));- });+ testWidgets(+ 'Return pressed again while it decides does not send the task twice',+ (tester) async {+ final (app, _) = await _open(tester);+ final answer = Completer<Map<String, dynamic>?>();+ app.decision = null;+ app.later = answer.future;+ app.reply = (_) => {'decided': 'session', 'id': _session, 'via': 'jev'};+ await tester.enterText(+ find.byType(TextField),+ "what's the D3 retention rate",+ );+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ answer.complete(null);+ await tester.pumpAndSettle();+ expect(app.sent, hasLength(1));+ expect(app.payloads, hasLength(1));+ },+ );testWidgets('Esc while the pane comes forward stops the send', (tester,@@ -646,6 +662,119 @@ void main() {expect(reports, ['taken']);});+ group('recent prompts', () {+ Future<_App> withHistory(WidgetTester tester, List<String> said) async {+ final (app, _) = await _open(tester);+ for (final prompt in said.reversed) {+ await app.taskHistory.add(prompt, account: 'u1');+ }+ // The box draws them once read.+ await tester.pump();+ return app;+ }++ testWidgets('an empty box offers the latest six, newest first', (+ tester,+ ) async {+ final app = await withHistory(tester, [+ for (var i = 0; i < 8; i++) 'task $i',+ ]);+ // Reopened, so the box reads the history it now has.+ Navigator.of(tester.element(find.byType(TextField))).pop();+ await tester.pumpAndSettle();+ await tester.tap(find.text('Open'));+ await tester.pumpAndSettle();+ for (var i = 0; i < 6; i++) {+ expect(find.text('task $i'), findsOneWidget);+ }+ expect(find.text('task 6'), findsNothing);+ expect(app.payloads, isEmpty);+ });++ testWidgets('typing narrows them to the ones that fit', (tester) async {+ await withHistory(tester, [+ 'what is the d3 retention rate',+ 'also add tests for the parser',+ ]);+ await tester.enterText(find.byType(TextField), 'retention');+ await tester.pump();+ expect(find.text('what is the d3 retention rate'), findsOneWidget);+ expect(find.text('also add tests for the parser'), findsNothing);+ });++ testWidgets(+ 'a recent prompt clicked is said again, decided on the desk now',+ (tester) async {+ final app = await withHistory(tester, ['ship the retention chart']);+ app.reply = (_) => {'decided': 'session', 'id': _session, 'via': 'jev'};+ await tester.enterText(find.byType(TextField), 'ship');+ await tester.pump();+ await tester.tap(find.text('ship the retention chart'));+ await tester.pump();+ await tester.pump();+ expect(app.sent, [('m', 'a0', 'ship the retention chart')]);+ },+ );++ testWidgets(+ 'down and Return say the one picked; Return alone says what is typed',+ (tester) async {+ final app = await withHistory(tester, [+ 'plot signups by week',+ 'ship the chart',+ ]);+ app.reply = (_) => {'decided': 'session', 'id': _session, 'via': 'jev'};+ await tester.enterText(find.byType(TextField), 'by week');+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ await tester.pump();+ expect(app.sent.single.$3, 'plot signups by week');+ },+ );++ testWidgets(+ 'a prompt of several lines keeps its arrows for its own lines',+ (tester) async {+ await withHistory(tester, ['deploy the dev firmware']);+ await tester.enterText(find.byType(TextField), 'deploy\n');+ await tester.pump();+ expect(find.text('deploy the dev firmware'), findsNothing);+ },+ );++ testWidgets('another account signed in here sees none of them', (+ tester,+ ) async {+ final app = await withHistory(tester, ['a private prompt']);+ app.currentUser = const CurrentUserProfile(+ id: 'u2',+ email: '[email protected]',+ );+ Navigator.of(tester.element(find.byType(TextField))).pop();+ await tester.pumpAndSettle();+ await tester.tap(find.text('Open'));+ await tester.pumpAndSettle();+ expect(find.text('a private prompt'), findsNothing);+ });++ testWidgets(+ 'Return with nothing picked sends what is typed, and remembers it',+ (tester) async {+ final app = await withHistory(tester, ['plot signups by week']);+ app.reply = (_) => {'decided': 'session', 'id': _session, 'via': 'jev'};+ await _say(tester, 'plot');+ expect(app.sent.single.$3, 'plot');+ expect(app.taskHistory.recentFor('u1'), [+ 'plot',+ 'plot signups by week',+ ]);+ },+ );+ });+testWidgets('a daemon without the router leaves the card as it was', (tester,) async {diff --git a/desktop/test/route_screen_test.dart b/desktop/test/route_screen_test.dartindex 0b5426e53..b61ce8a87 100644--- a/desktop/test/route_screen_test.dart+++ b/desktop/test/route_screen_test.dart@@ -84,8 +84,7 @@ Future<_Connection> _routeNewWork(final _taskField = find.byWidgetPredicate((widget) =>- widget is TextField &&- widget.decoration?.hintText == 'Describe the work…',+ widget is TextField && widget.decoration?.hintText == "What's up?",);void main() {@@ -179,4 +178,37 @@ void main() {await tester.pump(const Duration(minutes: 1));},);++ testWidgets('the pane a task lands in lights once, then goes quiet', (+ tester,+ ) async {+ final app = createApp(connectionForTest: (_) => _Connection());+ app.machineStates['m']!+ ..nodeOnline = true+ ..connectionStatus = ConnectionStatus.connected;+ app.adoptSessionForTest(terminal('a0', []));+ final other = app.adoptSessionForTest(terminal('a1', []));+ await mount(tester, app);+ final lit = app.allPanes.firstWhere((p) => p.agentId == 'a0');++ app.markLanding('m', 'a0');+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 200));+ expect(find.byKey(ValueKey('pane-landing:${lit.id}')), findsOneWidget);+ // Only where it landed.+ expect(find.byKey(ValueKey('pane-landing:${other.id}')), findsNothing);++ await tester.pump(const Duration(seconds: 2));+ expect(find.byKey(ValueKey('pane-landing:${lit.id}')), findsNothing);+ // Over: a pane of it opened later does not light for words that landed long ago.+ expect(app.paneLanding.value, isNull);+ app.paneLanding.value = (+ machineId: 'm',+ agentId: 'a0',+ seq: 99,+ at: DateTime.now().subtract(const Duration(seconds: 5)),+ );+ await tester.pump();+ expect(find.byKey(ValueKey('pane-landing:${lit.id}')), findsNothing);+ });}diff --git a/desktop/test/task_history_test.dart b/desktop/test/task_history_test.dartnew file mode 100644index 000000000..09a36fb62--- /dev/null+++ b/desktop/test/task_history_test.dart@@ -0,0 +1,87 @@+import 'dart:convert';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/task_history.dart';++import 'swarm_state_test.dart' show MemoryStore;++/// ⌘B's recent prompts: newest first, said again moves to the top, kept across launches, and only ever+/// shown to the account that said them.+void main() {+ test('a prompt said again moves to the top, never twice', () async {+ final history = TaskHistory(null);+ await history.add('what is the d3 retention rate', account: 'u1');+ await history.add(' also add tests ', account: 'u1');+ await history.add('what is the d3 retention rate', account: 'u1');+ expect(history.recentFor('u1'), [+ 'what is the d3 retention rate',+ 'also add tests',+ ]);+ });++ test(+ 'keeps the newest twenty, and no empty or pasted-document prompts',+ () async {+ final history = TaskHistory(null);+ for (var i = 0; i < 25; i++) {+ await history.add('task $i', account: 'u1');+ }+ await history.add(' ', account: 'u1');+ await history.add('x' * (TaskHistory.maxChars + 1), account: 'u1');+ expect(history.recentFor('u1'), hasLength(TaskHistory.keep));+ expect(history.recentFor('u1').first, 'task 24');+ expect(history.recentFor('u1').last, 'task 5');+ },+ );++ test('is there again after the app restarts', () async {+ final store = MemoryStore();+ await TaskHistory(store).add('plot signups by week', account: 'u1');+ await TaskHistory(store).add('ship the retention chart', account: 'u1');+ final reopened = TaskHistory(store);+ await reopened.load();+ expect(reopened.recentFor('u1'), [+ 'ship the retention chart',+ 'plot signups by week',+ ]);+ });++ test(+ 'another account on this computer sees none of them, and starts its own',+ () async {+ final store = MemoryStore();+ await TaskHistory(store).add('a private prompt', account: 'u1');+ final next = TaskHistory(store);+ await next.load();+ expect(next.recentFor('u2'), isEmpty);+ expect(next.recentFor(null), isEmpty);+ await next.add('hello from u2', account: 'u2');+ expect(next.recentFor('u2'), ['hello from u2']);+ expect(next.recentFor('u1'), isEmpty);+ expect(jsonDecode(store.values['task_box_recent_v1']!), {+ 'owner': 'u2',+ 'prompts': ['hello from u2'],+ });+ },+ );++ test('nothing is kept while no account is known', () async {+ final store = MemoryStore();+ await TaskHistory(store).add('who am i', account: null);+ expect(store.values, isEmpty);+ });++ test('an unreadable history is no history', () async {+ final store = MemoryStore();+ for (final raw in [+ '{not json',+ '["a list"]',+ '{"owner": 1, "prompts": []}',+ ]) {+ await store.write('task_box_recent_v1', raw);+ final history = TaskHistory(store);+ await history.load();+ expect(history.recentFor('u1'), isEmpty, reason: raw);+ }+ });+}