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
chore(desktop): remove HomeScreen, the machine rail, the status rail and other unreachable UI (#203)
Dee7d22931e2fde
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.mdindex 46fc22e9c..272eae16b 100644--- a/desktop/CLAUDE.md+++ b/desktop/CLAUDE.md@@ -262,32 +262,18 @@ its headless debug timings do not establish native display or network latency.strings behind `LocalKeyValueStore`): connection config, skipped update version, theme, font, panelayout. `~/.harness/computer-id` is the machine identity shared with the CLI.- The window is frameless on macOS via `window_manager` (`lib/core/desktop_window.dart`, same size and- `TitleBarStyle.hidden` as Grid). The traffic lights float over the rail's head, which leaves- `railTopInset` above the wordmark and is a `DragToMoveArea`; so are the pane headers. A screen that+ `TitleBarStyle.hidden` as Grid). On macOS the tabs are native, in the title bar beside the traffic+ lights (`SwarmTitlebar.swift`); the pane headers are a `DragToMoveArea`. A screen thatfills the window goes through `FullWindowScreen` (`lib/widgets/window_chrome.dart`) for its dragstrip, and a full-width band at the top edge pads by `trafficLightClearance`.- `macos/Runner/MainFlutterWindow.swift` installs native menu items and calls into Dart over the`harness/app_menu` MethodChannel (`checkForUpdates`, `flashFirmware`, `showShortcuts`, terminal fontsize). Keep the menu in Swift; only the handler lives in `RootShell`.-- **The status rail is where the app polls** (`lib/widgets/status_rail/`): a 26px full-bleed strip- along the window's bottom edge carrying what the agent accounts have spent, right-aligned against- the key hints (`key_hints.dart`). The hover/pin surface is `rail_figure.dart` + `rail_panel.dart`.- The `UsageController` behind it is owned by `_HomeScreenState`, not by the rail, because the rail- unmounts when the sidebar folds and a poller living in it would restart on every unfold.-- **Agent-account usage is what the rail reads** (`lib/usage/`, `widgets/status_rail/usage_readout.dart`- + `usage_panel.dart`): what the Claude and Codex accounts on this machine — and on the remote- machines that answer `usage_read` — have spent. **The strip prints ONE figure per account — the WEEKLY- window** (`ProviderUsage.railWindow`, deliberately not `tightest`): Claude answers with three- windows and Codex with one, so printing them all made one account three figures wide and the- other one — two readouts that read as different KINDS of thing rather than the same thing about- two accounts. Weekly rather than the tightest, because the rail wants the figure worth a GLANCE- and the five-hour window refills all day: it is back to nothing by the time anybody reads it.- `tightest` stays for the question it actually answers, which limit stops the work first. A- provider reporting no weekly window falls back to it — one figure is the rule, and a blank strip- is a worse answer than the wrong window. `kWeeklyWindowLabel` is written down once because the- rail MATCHES on it and the two sources spell it separately; the panel behind the figure still- shows every window. The block sits at the RIGHT end of the strip, beside the key hints: furniture- you only read belongs at the edge you are not reaching for.+- **Agent-account usage is what the native Models menu reads** (`lib/usage/`,+ `usage/models_menu_controller.dart`, `SwarmSubscriptionView` in `SwarmTitlebar.swift`): what the+ Claude and Codex accounts on this machine — and on the remote machines that answer `usage_read` —+ have spent. Each account shows its `tightest` window, the limit that stops the work first. Opening+ the menu reads the cached snapshot and refreshes at most once a minute; nothing polls on startup.**Remote machines' accounts arrive through `usage_read`** (`AppNotifier.readRemoteUsage`,`usage/remote_usage.dart`, `usage/usage_accounts.dart`; CLI side `cli/src/lib/accountUsage.ts`).A remote machine may be signed in to a DIFFERENT subscription, and the only honest way to read@@ -327,12 +313,9 @@ its headless debug timings do not establish native display or network latency.That is also what keeps `flutter test` honest: `kUnderTest` (`core/test_run.dart`, shared with`AnalyticsConfig`) stops the poll auto-starting, since a `Timer.periodic` is a `pumpAndSettle` thatnever settles and these sources would otherwise shell out to `security` and open real sockets.- The rail figure and `UsageBar` share one pair of thresholds through `usagePressureOf`- (`usage/usage_pressure.dart`) — amber from 80%, red from 90% — so a window cannot be amber in the- strip and plain in the panel that expands it.- **The token ledger is the OTHER usage feature, and the two must not be merged** (`lib/usage/ledger/`,- Settings ▸ Usage in `settings/sections/usage_section.dart` + `usage_panels.dart`). The rail's readout- above asks the vendors *how much of your rate limit is left* — a percentage, scoped to an **account**,+ Settings ▸ Usage in `settings/sections/usage_section.dart` + `usage_panels.dart`). The Models menu's+ readout above asks the vendors *how much of your rate limit is left* — a percentage, scoped to an **account**,true whichever machine burned it. This counts **tokens**, scoped to **this machine**, with a history:it reads the logs the agent CLIs already wrote to this disk and calls nobody. Ported from Orca(`src/main/{claude,codex,opencode}-usage/`); keep the pricing tables in step with its@@ -354,7 +337,7 @@ its headless debug timings do not establish native display or network latency.Claude and Codex are priced from `model_pricing.dart`, and a model that matches no row leaves`hasUnpricedModel` set so the panel calls the figure a floor. A Grid session records a real `0.0`(Grid inference is free, grid ADR 0039 D-g) and that measurement must not render like an unpriced- model. Same rule as the rail: `LedgerStatus.unavailable` is kept apart from `failed`, because a+ model. Same rule as account usage: `LedgerStatus.unavailable` is kept apart from `failed`, because amachine with no OpenCode is never fixed by retrying.**Off is the resting state**, per provider, persisted through `LocalKeyValueStore`: these transcriptshold every prompt, path and branch a session touched and this feature wants only the counts, so@@ -379,7 +362,7 @@ its headless debug timings do not establish native display or network latency.per-machine source would arrive if that changes.`sqlite3` is a **Dart-only FFI** dependency (never `sqlite3_flutter_libs`): it dlopens the systemlibrary, so it registers no native plugin and leaves the macOS SPM package list alone. `kUnderTest`- keeps `UsageSection` from auto-loading, for the same reason the rail's poller does not start there.+ keeps `UsageSection` from auto-loading, for the same reason `UsageController`'s poll does not start there.⚠️ **The snapshot goes through `SnapshotStore` (`core/snapshot_store.dart`), and a test MUST pass`MemorySnapshotStore`** — this is not tidiness. A real `File.writeAsString` never completes inside`testWidgets`' fake-async zone, so a store awaiting one hangs the whole run until the shell is@@ -528,14 +511,12 @@ its headless debug timings do not establish native display or network latency.`AppSurface.recess` and `recessHover`, never a shimmer sweep, frozen at the **peak** under ReduceMotion because a block held at 40% reads as disabled. A spinner is still right where the shape isgenuinely unknown (boot, a button mid-action); a list, table, card, row or figure gets a skeleton.- Three rules the call sites keep, all guarded by `test/skeleton_test.dart` and- `test/skeleton_sites_test.dart`: a placeholder is measured from the real content (`SkeletonText`+ Three rules the call sites keep, guarded by `test/skeleton_test.dart`: a placeholder is measured from the real content (`SkeletonText`lays out the style with a `TextPainter` rather than trusting arithmetic — see `AppMenuRowMetrics`for why), it wears the real row's surface and padding, and it is never **taller** than the answerusually is, since a skeleton that shrinks jumps the page upward. **"Loading" and "answered withnothing" must not render the same** — hence `AppNotifier.machinesLoading`, which is set on the- first fetch only so a refresh keeps the rows already on screen. Same reason the status rail blanks- its figures only before the first reading.+ first fetch only so a refresh keeps the rows already on screen.- `lib/shortcuts/app_shortcuts.dart` is the one list that feeds both the live bindings and the ⌘/sheet. `shortcutRows()` there is that list as the UI prints it — one row per action, so the twoactivators on "focus the next pane" (`⌘]`, `⌃⇥`) fold into one line, and `⌘1`–`⌘9` join as one.diff --git a/desktop/lib/logging/app_log_tail.dart b/desktop/lib/logging/app_log_tail.dartdeleted file mode 100644index aa4c6064f..000000000--- a/desktop/lib/logging/app_log_tail.dart+++ /dev/null@@ -1,76 +0,0 @@-import 'dart:convert';-import 'dart:io';--import 'install.dart';-import 'log_file.dart';--/// How much of the tail of a log file is worth opening to find recent errors.-///-/// A day's log is unbounded in principle, and this runs while a screen is-/// building — so read the end of the file rather than the file. 64 KB is far-/// more than the last few error lines need and small enough to be free.-const int _tailBytes = 64 * 1024;--/// The last few `ERROR` lines from today's app log, newest last.-///-/// Best-effort by design: this only ever decorates something a person is-/// reading, so a missing directory, a log not yet written, or an unreadable file-/// all mean "nothing to show" rather than a failure the caller must handle.-///-/// [sanitize] runs over the whole tail *before* it is split and clipped, and a-/// caller that sends these lines anywhere must pass one. Before clipping on-/// purpose: a secret cut in half by the clip is still half a secret, and a-/// redactor given the fragment can no longer recognise it.-Future<List<String>> readRecentAppErrors({- int keep = 3,- String Function(String)? sanitize,-}) async {- try {- final file = File(- '${DailyLogFile.defaultDirectory.path}/'- '${dailyLogName(kAppLogBase, DateTime.now())}',- );- if (!await file.exists()) return const [];- final tail = await _readTail(file);- return recentErrorLines(- sanitize == null ? tail : sanitize(tail),- keep: keep,- );- } on Object {- return const [];- }-}--/// The last [_tailBytes] of [file], decoded leniently — a window that starts-/// mid-character would otherwise throw on an accented path in a log line.-Future<String> _readTail(File file) async {- final handle = await file.open();- try {- final length = await handle.length();- final from = length > _tailBytes ? length - _tailBytes : 0;- await handle.setPosition(from);- final bytes = await handle.read(length - from);- return const Utf8Decoder(allowMalformed: true).convert(bytes);- } finally {- await handle.close();- }-}--/// The last [keep] error lines in [log], each clipped to [clip] characters.-///-/// Matches the shape [FileAppLog] writes — `[stamp] ERROR category message` —-/// which is also why the indented stack-trace lines that follow an error are-/// left out: they carry paths from this machine, and the one-line summary is-/// what says where to look.-///-/// Pure, so what a person is shown is decided by a function that can be reasoned-/// about rather than by whatever the disk happens to hold.-List<String> recentErrorLines(String log, {int keep = 3, int clip = 200}) {- final errors = <String>[];- for (final line in const LineSplitter().convert(log)) {- if (!line.contains('] ERROR ')) continue;- errors.add(line.length > clip ? '${line.substring(0, clip)}…' : line);- }- if (errors.length <= keep) return errors;- return errors.sublist(errors.length - keep);-}diff --git a/desktop/lib/screens/home_screen.dart b/desktop/lib/screens/home_screen.dartdeleted file mode 100644index 4bb81e7e9..000000000--- a/desktop/lib/screens/home_screen.dart+++ /dev/null@@ -1,771 +0,0 @@-import 'dart:async';-import 'dart:ui' show lerpDouble;--import 'package:flutter/material.dart';-import 'package:harness/terminal/terminal_text.dart';--import '../core/desktop_window.dart';-import '../state/app_state.dart';-import '../terminal/terminal_viewport.dart';-import '../shared/theme/app_theme.dart' as grid;-import '../theme/app_theme.dart';-import '../usage/usage_controller.dart';-import '../widgets/layout_palette.dart';-import '../widgets/link_machine_screen.dart';-import '../widgets/machine_rail.dart';-import '../widgets/machine_rail_mini.dart';-import '../settings/settings_screen.dart';-import '../settings/settings_section.dart';-import '../shortcuts/app_shortcuts.dart';-import '../widgets/new_agent_dialog.dart';-import '../widgets/task_palette.dart';-import '../orchestrator/orchestrator_launcher.dart';-import '../orchestrator/orchestrator_workspace.dart';-import '../widgets/pane_grid.dart';-import '../widgets/shortcuts_sheet.dart';-import '../widgets/status_rail/status_rail.dart';-import '../widgets/window_chrome.dart';--class HomeScreen extends StatefulWidget {- final AppNotifier notifier;- const HomeScreen({super.key, required this.notifier});-- @override- State<HomeScreen> createState() => _HomeScreenState();-}--class _HomeScreenState extends State<HomeScreen> {- /// What the agent accounts on this machine have spent.- ///- /// Owned HERE rather than by the status rail that draws it, because the rail- /// unmounts whenever the sidebar folds, and a controller living in it would- /// restart its poll — and blank its figures — on every unfold.- ///- /// It also asks every connected REMOTE machine for its own accounts- /// (`AppNotifier.readRemoteUsage`), because a machine elsewhere may be signed- /// in to a different subscription — one this computer cannot read itself.- late final UsageController _usage = UsageController(- remote: widget.notifier.readRemoteUsage,- );-- /// Spoken tasks from the dial, waiting for a palette. Subscribed here because this is the lowest- /// place that has both a [BuildContext] to open a dialog on and a lifetime to cancel with.- StreamSubscription<SpokenTaskRequest>? _spokenTasks;-- /// One palette at a time. Two people cannot speak into one dial at once, but a request can arrive- /// while the previous one is still open — from a retry, or from a second daemon — and stacking two- /// dialogs would leave the one underneath answering for words nobody can see.- bool _spokenPaletteOpen = false;-- // User-dragged override. null until the resize handle is used, so the- // window-relative default below keeps applying on its own.- double? _railWidth;- bool _collapsed = false;-- // Guards against opening a second popup for the same machine while one is already up — showDialog- // itself has no such de-dup, and this rebuilds on every notifier change while the popup is open.- String? _linkDialogMachineId;-- @override- void initState() {- super.initState();- _spokenTasks = widget.notifier.spokenTasks.listen(_openSpokenTask);- }-- @override- void dispose() {- unawaited(_spokenTasks?.cancel());- // The shell made it, so the shell cancels its timer. The rail is handed it- // and deliberately does not dispose what it did not create.- _usage.dispose();- super.dispose();- }-- /// The dial spoke: raise the window and run the palette on those words.- ///- /// The raise is not a nicety. The person is looking at a dial, not at this screen, and the palette may- /// have a question for them — a route this window is not sure enough about to send in silence. Behind- /// another app, that question is never asked and the spoken sentence dies on a deadline.- Future<void> _openSpokenTask(SpokenTaskRequest request) async {- final spoken = SpokenTask(- voiceId: request.voiceId,- text: request.text,- cmd: request.cmd,- report: (voiceId, state, agentId) => widget.notifier.reportVoiceRoute(- request.machineId,- voiceId,- state,- agentId,- ),- );- // Busy: answer immediately rather than let the daemon hold the dial's overlay open for a minute- // waiting on a palette this window is never going to show.- if (_spokenPaletteOpen || !mounted) {- spoken.cancelled();- return;- }- _spokenPaletteOpen = true;- try {- await revealWindow();- if (!mounted) {- spoken.cancelled();- return;- }- await showTaskPalette(context, widget.notifier, spoken: spoken);- } finally {- _spokenPaletteOpen = false;- // Belt: showTaskPalette answers on every exit of its own, and this is a no-op after any of them.- spoken.cancelled();- }- }-- /// Pops open the link popup for whichever machine was most recently SELECTED (not- /// `activeMachineState`, which prefers whatever pane currently has a terminal focused — clicking- /// "link required" for a machine that needs linking must not get shadowed by an unrelated- /// terminal the user already has open elsewhere). Both entry points (machine_rail.dart's "link- /// required" rows and its "Remote into this machine…" menu item) already set `selectedMachineId`- /// via `selectMachineForSetup`/`showMachinePane`, so neither needs to know about this popup- /// directly; this is the one place that turns "the selected machine needs linking" into "show- /// the popup," for however that state was reached (a click, or a connection attempt that only- /// discovers NO_PEER_LINK after the fact).- void _maybeShowLinkDialog(AppNotifier notifier) {- final selectedId = notifier.selectedMachineId;- final active = selectedId == null ? null : notifier.stateOf(selectedId);- final show =- active != null &&- active.isRemote &&- !active.isLocalMachine &&- active.needsLink &&- !notifier.isLinkPromptDismissed(active.machine.machineId);- if (!show || _linkDialogMachineId == active.machine.machineId) return;- final machineId = active.machine.machineId;- _linkDialogMachineId = machineId;- WidgetsBinding.instance.addPostFrameCallback((_) async {- if (!mounted) return;- await showLinkMachineScreenDialog(context, notifier, machineId);- if (!mounted) return;- _linkDialogMachineId = null;- });- }-- /// Every agent the rail is currently showing, in the order it shows them.- ///- /// Agent traversal follows the rail's visible ordering.- List<({String machineId, String agentId})> _visibleAgents() {- final notifier = widget.notifier;- final result = <({String machineId, String agentId})>[];- for (final machine in notifier.machines) {- final state = notifier.machineStates[machine.machineId];- if (state == null) continue;- if (!notifier.expandedMachines.contains(machine.machineId)) continue;- for (final agent in state.agents) {- result.add((machineId: machine.machineId, agentId: agent.id));- }- }- return result;- }-- void _stepAgent(int delta) {- final agents = _visibleAgents();- if (agents.isEmpty) return;- final pane = widget.notifier.focusedPane;- final current = pane?.agentId == null- ? -1- : agents.indexWhere(- (a) => a.machineId == pane!.machineId && a.agentId == pane.agentId,- );- // Wraps, and starts at the top when nothing is open — the list is a ring,- // and a first press that does nothing reads as a broken key.- final next = current < 0- ? (delta > 0 ? 0 : agents.length - 1)- : (current + delta) % agents.length;- final target = agents[next];- unawaited(widget.notifier.selectAgent(target.machineId, target.agentId));- }-- void _closeFocusedPane() {- final pane = widget.notifier.focusedPane;- // No pane to close: leave ⌘W alone so macOS closes the window with it, the- // way it does in every other app.- if (pane == null) return;- unawaited(widget.notifier.closePane(pane.id));- }-- void _newAgent() {- final machineId =- widget.notifier.focusedPane?.machineId ??- widget.notifier.selectedMachineId;- if (machineId == null) return;- unawaited(- showNewAgentDialog(- context,- widget.notifier,- machineId,- source: 'shortcut',- ),- );- }-- @override- Widget build(BuildContext context) {- TerminalFontScope.watch(context);- final notifier = widget.notifier;- return ListenableBuilder(- listenable: notifier,- builder: (context, _) {- _maybeShowLinkDialog(notifier);- return CallbackShortcuts(- bindings: buildShortcutBindings(- swarmMode: false,- handlers: {- ShortcutAction.toggleRail: () =>- setState(() => _collapsed = !_collapsed),- ShortcutAction.nextAgent: () => _stepAgent(1),- ShortcutAction.previousAgent: () => _stepAgent(-1),- // All four directions read the GEOMETRY now. Left and right used- // to walk the list while up and down read the layout, so half the- // compass meant "the next one" and half meant "the one over- // there" — a scheme nobody can hold in their head, and the reason- // hjkl could not simply be aliased onto the old keys.- ShortcutAction.focusPaneLeft: () =>- notifier.focusPaneHorizontally(-1),- // BOTH directions go to the same place, and that is the fix.- //- // ⌘l used to be special-cased here — "if the rail has focus, leave- // it" — which returned before the ring in focusPaneHorizontally- // could run. So ⌘h came round and ⌘l stopped dead at the sidebar,- // and the asymmetry was invisible because the two keys looked- // symmetrical at the call site.- ShortcutAction.focusPaneRight: () =>- notifier.focusPaneHorizontally(1),- ShortcutAction.focusPaneAbove: () =>- notifier.focusPaneVertically(-1),- ShortcutAction.focusPaneBelow: () =>- notifier.focusPaneVertically(1),- ShortcutAction.movePaneLeft: () =>- notifier.movePaneDirection(dx: -1, dy: 0),- ShortcutAction.movePaneRight: () =>- notifier.movePaneDirection(dx: 1, dy: 0),- ShortcutAction.movePaneUp: () =>- notifier.movePaneDirection(dx: 0, dy: -1),- ShortcutAction.movePaneDown: () =>- notifier.movePaneDirection(dx: 0, dy: 1),- ShortcutAction.findTerminal: () =>- notifier.focusedPane?.session?.find(TerminalFindAction.open),- ShortcutAction.findNext: () =>- notifier.focusedPane?.session?.find(TerminalFindAction.next),- ShortcutAction.findPrevious: () => notifier.focusedPane?.session- ?.find(TerminalFindAction.previous),- ShortcutAction.lastPane: notifier.focusLastPane,- ShortcutAction.zoomPane: notifier.toggleZoomPane,- ShortcutAction.closePane: _closeFocusedPane,- ShortcutAction.newAgent: _newAgent,- ShortcutAction.routeTask: () =>- unawaited(showTaskPalette(context, notifier)),- ShortcutAction.orchestrate: () =>- unawaited(showOrchestratorLauncher(context, notifier)),- ShortcutAction.reload: () => unawaited(notifier.retryMachines()),- ShortcutAction.pinPane: () {- final id = notifier.focusedPaneId;- if (id != null && notifier.panes.length > 1) {- notifier.togglePinPane(id);- }- },- ShortcutAction.showLayout: () =>- unawaited(showLayoutPalette(context, notifier)),- ShortcutAction.showShortcuts: () =>- unawaited(showShortcutsSheet(context)),- // Bound whether or not this build has the screen: an unlisted- // action is simply never in the bindings (see appShortcuts()),- // so the handler costs nothing where the key does not exist.- ShortcutAction.showDebug: () => unawaited(- showSettingsScreen(- context,- notifier,- initialSection: SettingsSection.debug,- source: 'shortcut',- ),- ),- },- onSelectTabIndex: notifier.selectSwarmByIndex,- ),- child: Focus(- // This is only a shortcuts scope. If it owns keyboard focus after- // an agent-list refresh, the focused terminal can no longer open- // its native TextInput connection, which makes the whole terminal- // look locked even though its stream is still healthy.- canRequestFocus: false,- child: Scaffold(- // Not the theme's: that one is still the old terminal palette, and it- // is what showed through the seam above.- backgroundColor: grid.AppPalette.windowBg,- // THE FIELD SPANS THE BODY, so it runs behind the status rail as well as the grid.- //- // Wrapped any further in and the gradient stops where the grid stops — which is what- // made the transparent rail look unchanged: with no fill of its own it simply showed- // the scaffold's flat colour, a shade off the one it had just given up. The top bar- // paints its own opaque fill over this, so nothing changes up there.- body: GridField(- child: Column(- children: [- // The window's own strip, above the rail AND the grid. It- // exists so the content below it starts clear of the- // transparent title bar — see HarnessTopBar, which explains- // why anything drawn up there cannot be dragged by Flutter.- const HarnessTopBar(),- Expanded(- child: Stack(- children: [- Positioned.fill(- child: LayoutBuilder(- builder: (context, constraints) {- final defaultWidth =- (constraints.maxWidth * 0.18)- .clamp(252.0, 300.0)- .toDouble();- final minWidth = 220.0;- final maxWidth = (constraints.maxWidth * 0.5)- .clamp(minWidth, 520.0)- .toDouble();- final railWidth = (_railWidth ?? defaultWidth)- .clamp(minWidth, maxWidth);- // THE FIELD RUNS UNDER EVERYTHING, rail included, and one margin- // holds the lot. It used to start where the rail ended, so the two- // surfaces met along a hard seam that belonged to neither: every tile- // floated as a card while the rail alone stayed bolted to the window- // with square corners.- // The margin only. The field itself is up at the body now, so- // one gradient covers the window instead of one per region.- return Padding(- padding: const EdgeInsets.all(kPaneGap),- child: Row(- children: [- _RailFold(- notifier: notifier,- collapsed: _collapsed,- wideWidth: railWidth,- onCollapse: () =>- setState(() => _collapsed = true),- onExpand: () =>- setState(() => _collapsed = false),- ),- // Only the full rail can be dragged wider. Folded, the- // width is the fold's to decide, and a handle there- // would offer a resize that snaps back.- // Folded there is nothing to resize and nothing to divide: the- // seam that used to sit here was seven more pixels of chrome beside- // a rail that had just gone to zero, which is most of what folding- // was supposed to give back.- if (!_collapsed)- _ResizeHandle(- onDrag: (dx) => setState(() {- // Accumulate against the STATE field, not the- // `railWidth` local above: that local is a- // snapshot from the last completed rebuild, and- // several drag-update events can fire before- // Flutter gets around to rebuilding (routine- // under fast mouse movement). Basing each step- // on the same stale snapshot silently drops all- // but the last delta in that batch, which is- // exactly the lag/drift this fixes.- final current =- _railWidth ?? defaultWidth;- _railWidth = (current + dx).clamp(- minWidth,- maxWidth,- );- }),- ),- Expanded(- child:- notifier.activeSwarm.isOrchestrator- ? OrchestratorWorkspace(- key: ValueKey(- 'orchestrator:${notifier.activeSwarm.orchestratorId}',- ),- notifier: notifier,- machineId: notifier- .activeSwarm- .orchestratorMachineId!,- projectId: notifier- .activeSwarm- .orchestratorId!,- )- : PaneGrid(notifier: notifier),- ),- ],- ),- );- },- ),- ),- if (_collapsed)- Positioned(- left: 0,- top: 0,- bottom: 0,- child: _RailReveal(- notifier: notifier,- onExpand: () =>- setState(() => _collapsed = false),- ),- ),- if (notifier.lastError != null)- Positioned(- left: 0,- right: 0,- top: 0,- child: _ErrorStrip(- message: notifier.lastError!,- retryable: notifier.lastErrorRetryable,- onRetry: notifier.retryMachines,- onDismiss: notifier.dismissError,- ),- ),- ],- ),- ),- // What the accounts have spent, along the very bottom. Outside- // the Expanded above so it is full-bleed under the machine- // rail as well as the panes — a strip that started after the- // rail would put a step in the window's bottom edge.- // FOLDS WITH THE RAIL. Collapsing is a request for the whole window, and a strip- // of chrome left running along the bottom answers half of it — the terminals get- // the width and keep paying forty pixels of height for figures nobody folded the- // rail to read.- //- // AnimatedSize rather than a plain `if`: the rail takes AppMotion.fold to get out- // of the way, and a bar that vanished on the first frame of that would read as- // two separate things happening, not one window opening up.- AnimatedSize(- duration: grid.AppMotion.fold,- curve: grid.AppMotion.curve,- alignment: Alignment.topCenter,- child: _collapsed- ? const SizedBox(width: double.infinity, height: 0)- : StatusRail(- notifier: notifier,- // The shell's — see [_usage].- usage: _usage,- ),- ),- ],- ),- ),- ),- ),- );- },- );- }-}--/// A draggable divider between the machine rail and the terminal pane. Wider-/// than the 1px line it draws so the hit target is actually grabbable.-/// The rail, and the fold between its two widths.-///-/// It owns the rail's SURFACE while the two rails own only what is drawn on it.-/// That split is what makes the fold one moving edge instead of two: during the-/// crossfade both rails are mounted at partial opacity, and two fills stacked-/// over the window would darken the whole rail for the length of the animation.-///-/// Neither rail animates its own contents. The wide one stays laid out at its-/// full width and is clipped by the shrinking box, because its rows are written-/// for that width — reflowing the machine tree through every width between 284-/// and 72 would be sixty frames of text rewrapping, and it would look like it.-class _RailFold extends StatelessWidget {- const _RailFold({- required this.notifier,- required this.collapsed,- required this.wideWidth,- required this.onCollapse,- required this.onExpand,- });-- final AppNotifier notifier;-- final bool collapsed;- final double wideWidth;- final VoidCallback onCollapse;- final VoidCallback onExpand;-- /// How far each rail drifts sideways as it leaves.- ///- /// A hint, not a journey. Sliding the wide rail out by its whole width would- /// drag every label across the screen and — coming back — deliver the labels- /// before their own icons. Twelve pixels reads as "this went away" while the- /// width itself carries the movement.- static const double _drift = 12;-- /// One rail's share of the crossfade. Each is alone for the first and last- /// quarter and they trade over the middle half, so neither is ever the only- /// thing on screen at half strength.- static double _fade(double t) => ((t - 0.25) / 0.5).clamp(0.0, 1.0);-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- return TweenAnimationBuilder<double>(- // No `begin`: a window that opens folded should BE folded, not unfold- // itself while the user watches.- tween: Tween(end: collapsed ? 0.0 : 1.0),- duration: grid.AppMotion.fold,- // Fast off the mark, settling at the end — the rail arrives at its new- // width rather than drifting there.- curve: grid.AppMotion.curve,- builder: (context, open, _) {- final wide = _fade(open);- return SizedBox(- // FOLDED IS ZERO NOW, not 72. The folded rail held a fold button and an avatar and nothing- // else — a column that was empty permanently, which is what made it expensive. Those two- // controls moved to the edge reveal ([_RailReveal]), so folding gives the whole width back.- width: lerpDouble(0, wideWidth, open),- child: DecoratedBox(- // A CARD, like the tiles beside it: same fill duty, same corners, same hairline. It was- // the one surface running edge to edge with square corners, which read as the app's- // chrome rather than as one more thing on the field.- decoration: BoxDecoration(- color: grid.AppGlass.sidebarFill,- borderRadius: BorderRadius.circular(kPaneRadius),- border: Border.all(color: AppColors.border, width: 1),- ),- // Rounded, not square: the rail's own rows run to its edge, and a square clip would let- // them square off the corners the rim just rounded — the same notch the panes had.- child: ClipRRect(- borderRadius: BorderRadius.circular(kPaneRadius - 1),- child: Stack(- children: [- // Both hang off the LEFT edge — the edge that doesn't move.- // Pinning the wide one right would slide its icons out of- // view first and leave a column of orphaned labels.- //- // Unmounted at zero opacity rather than merely invisible: the- // wide rail carries the whole machine tree, and a folded rail- // should not be paying for it.- if (wide > 0)- Positioned(- left: 0,- top: 0,- bottom: 0,- width: wideWidth,- child: Opacity(- opacity: wide,- child: Transform.translate(- offset: Offset(-_drift * (1 - open), 0),- child: MachineRail(- notifier: notifier,- onCollapse: onCollapse,- ),- ),- ),- ),- ],- ),- ),- ),- );- },- );- }-}--/// The seam, with nothing to drag.-///-/// Same painting as [_ResizeHandle] so folding the rail does not change the-/// line between it and the pane — only whether that line can be grabbed.-/// The folded rail, which is not on screen until you reach for it.-///-/// Folding used to leave a 72px column carrying a fold button and an avatar — permanently, on every-/// window, whether or not anyone was going to touch either. This is the same two controls with the-/// column deleted: a narrow strip along the left edge that costs nothing until the pointer arrives,-/// then slides the real [MachineRailMini] out over the grid on a scrim.-///-/// The cost of hiding a control is that a new user cannot find it, and that is answered here by the-/// keyboard: `toggleRail` is bound and listed in the shortcuts sheet as "Show or hide the sidebar", so-/// the rail is reachable without knowing this strip exists at all.-class _RailReveal extends StatefulWidget {- const _RailReveal({required this.notifier, required this.onExpand});-- final AppNotifier notifier;- final VoidCallback onExpand;-- /// How far in from the edge counts as reaching for it. Wide enough to catch a deliberate move to the- /// edge, narrow enough to sit inside the grid's own margin — so crossing it does not mean crossing- /// anything a person was aiming at.- static const double _reach = 12;-- /// What the open card occupies: the grid's own margin, then the card.- ///- /// The margin is part of the width rather than something the card is nudged- /// by, so the card lands on exactly the left edge the WIDE rail has — that- /// row sits inside `Padding(EdgeInsets.all(kPaneGap))`. Folded and unfolded- /// then start at the same pixel, and expanding is one surface growing rather- /// than two surfaces swapping places.- static const double _cardReach = kPaneGap + MachineRailMini.width;-- @override- State<_RailReveal> createState() => _RailRevealState();-}--class _RailRevealState extends State<_RailReveal> {- bool _open = false;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- return MouseRegion(- // NOT opaque, and that is the whole trick: while the strip is hidden this is twelve pixels lying- // over the first pane, and an opaque region there would quietly eat every click that landed on- // that edge — a terminal that ignores you along one stripe, with nothing on screen to explain it.- opaque: false,- onEnter: (_) => setState(() => _open = true),- onExit: (_) => setState(() => _open = false),- child: AnimatedContainer(- duration: grid.AppMotion.fold,- curve: grid.AppMotion.curve,- width: _open ? _RailReveal._cardReach : _RailReveal._reach,- child: IgnorePointer(- // The buttons still hit-test at zero opacity, so they are taken out of the tree's reach- // rather than merely faded — otherwise the hidden strip would swallow clicks the same way an- // opaque region would, just less obviously.- ignoring: !_open,- child: AnimatedOpacity(- duration: grid.AppMotion.fold,- curve: grid.AppMotion.curve,- opacity: _open ? 1 : 0,- child: ClipRect(- child: OverflowBox(- // Laid out at its full width even while the container is 12px, so the icons inside do- // not reflow on the way in — they slide out already in their final places.- alignment: Alignment.centerLeft,- minWidth: _RailReveal._cardReach,- maxWidth: _RailReveal._cardReach,- child: Padding(- // Left, top and bottom only. The right side is where the card- // meets the pane it is floating over, and a margin there would- // be a gap between two things that are not beside each other.- padding: const EdgeInsets.fromLTRB(- kPaneGap,- kPaneGap,- 0,- kPaneGap,- ),- child: DecoratedBox(- // A CARD, the same one the tiles and the wide rail are: the- // rail's own fill, the same hairline, the same corners.- //- // It replaces a black gradient ramp, which was the only- // surface in the window that was neither a card nor the- // field — so it read as a smudge over the first pane rather- // than as part of the app, and its darkest end landed on- // that pane's title.- //- // The ramp also took the blame for a centring bug that was- // never there. MachineRailMini puts its button in a Center,- // so the button always sat on the strip's middle; the RAMP- // was the lopsided thing, heaviest at the edge and gone by- // the far side, and the eye lines an icon up against the- // mass it can see. A bounded surface has a middle you can- // find, which is why this fixes the look without moving the- // icon a pixel.- decoration: BoxDecoration(- color: grid.AppGlass.sidebarFill,- borderRadius: BorderRadius.circular(kPaneRadius),- border: Border.all(color: AppColors.border, width: 1),- ),- // Inside the rim, like the wide rail: the account row runs- // to the card's edge and a square clip would square off the- // corners the border just rounded.- child: ClipRRect(- borderRadius: BorderRadius.circular(kPaneRadius - 1),- child: MachineRailMini(- notifier: widget.notifier,- onExpand: widget.onExpand,- ),- ),- ),- ),- ),- ),- ),- ),- ),- );- }-}--class _ResizeHandle extends StatelessWidget {- final ValueChanged<double> onDrag;- const _ResizeHandle({required this.onDrag});-- @override- Widget build(BuildContext context) {- TerminalFontScope.watch(context);- return MouseRegion(- cursor: SystemMouseCursors.resizeLeftRight,- child: GestureDetector(- behavior: HitTestBehavior.translucent,- onHorizontalDragUpdate: (details) => onDrag(details.delta.dx),- // UNPAINTED, and that is the point: it is the gap between two cards, so what belongs in it is- // the field, the same as every gap inside the grid.- //- // It used to paint the pane's colour with a hairline down its left edge — a seam, drawn back- // when the rail was chrome butted against the grid and something had to divide them. Two cards- // do not need dividing; the space already does it. All that survives is the width and the- // drag, which is all this was ever for.- child: const SizedBox(width: kPaneGap, height: double.infinity),- ),- );- }-}--class _ErrorStrip extends StatelessWidget {- final String message;- final bool retryable;- final VoidCallback onRetry;- final VoidCallback onDismiss;-- const _ErrorStrip({- required this.message,- required this.retryable,- required this.onRetry,- required this.onDismiss,- });-- @override- Widget build(BuildContext context) {- TerminalFontScope.watch(context);- // Pinned to the window's top edge, where the traffic lights float — so- // the text starts past them, and the strip drags the window like the rest- // of that edge.- return WindowDragArea(- child: Container(- constraints: const BoxConstraints(minHeight: 34),- color: const Color(0xff26131b),- padding: EdgeInsets.fromLTRB(12 + trafficLightClearance, 7, 12, 7),- child: Row(- children: [- Icon(Icons.error_outline, size: 15, color: AppColors.danger),- const SizedBox(width: 8),- Expanded(- child: Text(- message,- maxLines: 2,- overflow: TextOverflow.ellipsis,- style: terminalTextStyle(color: AppColors.textSoft),- ),- ),- // A failure already finished (an agent's launch) has nothing left- // for a retry to redo — reloading the machine list will not- // install the engine that just failed to. Offer to dismiss it- // instead of a button that only looks like it did something.- if (retryable)- TextButton(onPressed: onRetry, child: const Text('RETRY'))- else- TextButton(onPressed: onDismiss, child: const Text('CLOSE')),- ],- ),- ),- );- }-}diff --git a/desktop/lib/settings/appearance/system_fonts.dart b/desktop/lib/settings/appearance/system_fonts.dartdeleted file mode 100644index dafc8055c..000000000--- a/desktop/lib/settings/appearance/system_fonts.dart+++ /dev/null@@ -1,52 +0,0 @@-import '../../shared/widgets/app_select_field.dart';--/// The faces the app's UI can be set in.-///-/// ⚠️ A curated list, not the machine's installed fonts — for now. Enumerating-/// what is installed needs a native `MethodChannel`, and this ships without one-/// on purpose: the platform side is the part that a headless `flutter test`-/// cannot verify (the test font manager resolves every family to one face and-/// reports monospace metrics for all of them), so a channel written now would be-/// a feature nobody could prove works until it was already in front of a user.-///-/// The cost is stated plainly rather than hidden: someone whose favourite face-/// is installed but not listed cannot pick it yet.-///-/// [load] is async and returns a future today for no reason other than this: the-/// day the channel lands, only the body of this function changes, and no widget-/// that awaits it has to be rewritten.-abstract final class SystemFonts {- /// `null` is the system font. It is FIRST because it is the default and the- /// answer most people want, and it is spelled with a note rather than with its- /// real name — `.AppleSystemUIFont` is a private CoreText name, correct to- /// resolve against and wrong to show a person.- static const List<SelectOption<String?>> _uiFamilies = [- SelectOption(value: null, label: 'System', note: 'SF Pro'),- SelectOption(value: 'Helvetica Neue', label: 'Helvetica Neue'),- SelectOption(value: 'Avenir Next', label: 'Avenir Next'),- SelectOption(value: 'Optima', label: 'Optima'),- SelectOption(value: 'Georgia', label: 'Georgia'),- SelectOption(value: 'Menlo', label: 'Menlo'),- ];-- /// The list to show, given what is currently chosen.- ///- /// ⚠️ A saved family that is not in the list is ADDED rather than dropped,- /// carrying a note. A picker that silently forgets the user's setting — and- /// then shows a different font as if it were the choice — is a worse failure- /// than an entry that explains itself. This is also what will keep a setting- /// alive across a machine where the face is genuinely missing.- static Future<List<SelectOption<String?>>> load({String? selected}) async {- if (selected == null || _uiFamilies.any((o) => o.value == selected)) {- return _uiFamilies;- }- return [- ..._uiFamilies,- SelectOption(- value: selected,- label: selected,- note: 'not in the list on this Mac',- ),- ];- }-}diff --git a/desktop/lib/settings/sections/usage_section.dart b/desktop/lib/settings/sections/usage_section.dartindex 3e3f7180e..f4839676a 100644--- a/desktop/lib/settings/sections/usage_section.dart+++ b/desktop/lib/settings/sections/usage_section.dart@@ -9,7 +9,7 @@/// agent CLIs' own logs. Off until switched on, per provider, because those/// logs hold every prompt and path a session touched.///-/// Its sibling readout on the status rail (`widgets/status_rail/usage_panel.dart`)+/// Its sibling readout in the native Models menu (`usage/models_menu_controller.dart`)/// answers a third question — *how much of your rate limit is left* — which is/// an account fact and a percentage. All three are true at once and none/// substitutes for another.diff --git a/desktop/lib/shared/layouts/widgets/sidebar_show_more.dart b/desktop/lib/shared/layouts/widgets/sidebar_show_more.dartdeleted file mode 100644index bffdfe8e9..000000000--- a/desktop/lib/shared/layouts/widgets/sidebar_show_more.dart+++ /dev/null@@ -1,157 +0,0 @@-import 'package:flutter/material.dart';--import '../../theme/app_theme.dart';-import 'sidebar_item.dart';--/// How many rows a *nested* sidebar section shows before the rest sit behind-/// "Show more".-///-/// Small on purpose: the rail is a way back to the chat you were just in, and a-/// section that opens at twenty rows buries the three that matter under-/// seventeen that don't.-///-/// One number for both of them — the project list, and the chats inside a-/// project — so those two can't grow differently-sized pages. The loose chats-/// are the exception and page at [kSidebarChatsFirstPage]; see there for why-/// that one list earns a longer opening.-const int kSidebarFirstPage = 5;--/// How many chats the rail's "Chats" section shows before the rest sit behind-/// "Show more".-///-/// Four times [kSidebarFirstPage], because nothing else in the rail stands in-/// for this list. A project's chats are one click away inside a folder you can-/// already see, so cutting that list short costs you nothing you can't find;-/// a chat that belongs to no project is in this list or nowhere. Opening it at-/// five made "Show more" the row a person clicked most.-///-/// It doubles as the threshold, which is the point of stating it as the first-/// page rather than as a separate rule: a section is truncated only when it has-/// more rows than it shows, so nineteen loose chats are simply all drawn and-/// "Show more" is never built.-const int kSidebarChatsFirstPage = 20;--/// How many more rows each click of "Show more" reveals.-///-/// **Bigger than [kSidebarFirstPage], deliberately.** The two answer different-/// questions. That first page is what the rail volunteers, so it stays short;-/// a click is someone saying "I don't see it, show me more", and answering that-/// five at a time makes them click four times to reach a chat from last week.-/// Whoever asked has already told you they want a longer list.-///-/// One step for every section, including the one that opens at-/// [kSidebarChatsFirstPage] and so reveals *fewer* rows per click than it began-/// with: what a click is worth doesn't change with how much the rail chose to-/// show before it.-const int kSidebarNextPage = 10;--/// How many rows a section shows once it has been paged open [pages] times:-/// [firstPage], then [kSidebarNextPage] more for every click after.-///-/// A function rather than the arithmetic at each call site, so the three-/// sections can't drift apart on the *step* even where they deliberately differ-/// on the opening page, and so the count is always clamped to what's actually-/// there: a section expanded past a list that later shrank (a chat archived, a-/// project removed) must not keep claiming there's more to see.-int sidebarPageCount(- int pages,- int total, {- int firstPage = kSidebarFirstPage,-}) {- final shown = pages <= 1- ? firstPage- : firstPage + kSidebarNextPage * (pages - 1);- return shown < total ? shown : total;-}--/// The row that closes a truncated sidebar section: quiet text that reveals the-/// next [kSidebarNextPage] rows, and stops being built once the list is fully-/// shown.-///-/// Deliberately lighter than a [SidebarItem] — shorter, smaller, faint until you-/// reach for it. It's chrome *about* the list, not an entry *in* it, so it must-/// not read as one more chat you could open.-class SidebarShowMore extends StatefulWidget {- const SidebarShowMore({- super.key,- required this.remaining,- required this.onTap,- this.indented = false,- });-- /// How many rows are still hidden — carried in the tooltip, so the row itself- /// stays the same two words at every list length.- final int remaining;-- final VoidCallback onTap;-- /// Line the label up with the chats it follows: a project's chats, and the- /// loose ones, are indented one step. The row under the project *list* stays- /// out at the rail's edge, which is what tells you it belongs to the section- /// rather than to the chats of the last project above it.- final bool indented;-- @override- State<SidebarShowMore> createState() => _SidebarShowMoreState();-}--class _SidebarShowMoreState extends State<SidebarShowMore> {- bool _hovered = false;-- void _setHovered(bool value) {- if (_hovered == value) return;- setState(() => _hovered = value);- }-- @override- Widget build(BuildContext context) {- // Reads AppPalette/AppSurface from inside the rail's lazy list — watch here- // or this row keeps the palette it was first painted with.- AppTheme.watch(context);- final hot = _hovered;- // Rests at the hint ink so a truncated section stays quiet, and climbs to- // the primary ink under the pointer: an affordance that stays dim while- // you're aiming at it reads as a caption, not a control.- final ink = hot ? AppPalette.textPrimary : AppPalette.textFaint;-- return Padding(- // The same 28px step a chat row takes, plus the 1px of vertical breathing- // room every rail row keeps, so neighbouring highlights never touch.- padding: EdgeInsets.only(- left: widget.indented ? 28 : 0,- top: 1,- bottom: 1,- ),- child: Semantics(- button: true,- label: 'Show more',- child: Tooltip(- message: '${widget.remaining} more',- child: MouseRegion(- cursor: SystemMouseCursors.click,- onEnter: (_) => _setHovered(true),- onExit: (_) => _setHovered(false),- child: GestureDetector(- behavior: HitTestBehavior.opaque,- onTap: widget.onTap,- child: AnimatedContainer(- duration: AppMotion.hover,- curve: AppMotion.curve,- height: 30,- alignment: Alignment.centerLeft,- padding: const EdgeInsets.symmetric(- horizontal: SidebarItem.iconGutter,- ),- decoration: BoxDecoration(- color: hot ? AppSurface.hoverFill : Colors.transparent,- borderRadius: BorderRadius.circular(8),- ),- child: Text('Show more', style: AppType.label(color: ink)),- ),- ),- ),- ),- ),- );- }-}diff --git a/desktop/lib/shared/layouts/widgets/sidebar_timeline.dart b/desktop/lib/shared/layouts/widgets/sidebar_timeline.dartdeleted file mode 100644index 4d1d59f89..000000000--- a/desktop/lib/shared/layouts/widgets/sidebar_timeline.dart+++ /dev/null@@ -1,79 +0,0 @@-import 'package:flutter/material.dart';--import '../../widgets/timeline_guide.dart';-import 'sidebar_item.dart';--/// Where the trunk runs: dead centre of a project row's folder icon, so the-/// icons read as nodes threaded onto one line rather than as a list that-/// happens to have a rule beside it.-///-/// Derived from [SidebarItem.iconGutter] plus half an 18px glyph rather than-/// typed as `19`, so changing the rail's inset moves the guide with it instead-/// of leaving it pointing at nothing.-const double _trunkX = SidebarItem.iconGutter + 9;--/// How far the arm reaches out of the trunk towards a nested row.-///-/// A nested row's own box starts 28px in, so the arm stops 2px short of it:-/// touching the row's hover fill would make the guide read as part of the row-/// instead of as the thing holding it.-const double _armLength = 7;--/// How wide a berth the trunk gives a project's folder icon.-///-/// An 18px glyph centred in a 38px band leaves 10px clear at each end; 13-/// clears the glyph by 4px, which is what keeps the line from looking like it-/// is striking the icon out. What's left either side is ~6px of trunk — short,-/// but that is the point: enough to say the line passes behind the node.-const double _nodeGap = 13;--/// What a row is to the guide line running down the rail's Projects block.-///-/// The shared [TimelineRole] under the rail's own name: the transcript's step-/// list draws the same guide with the same three roles, and one enum is what-/// keeps a change to the line landing on both.-typedef SidebarTimelineRole = TimelineRole;--/// The guide line that ties the rail's projects and the chats inside them into-/// one tree.-///-/// The rail already says which chats belong to which project by indenting them,-/// but indentation alone goes quiet the moment a project's chats run long-/// enough that its folder row has scrolled away — the eye has nothing left to-/// follow back up. One continuous line through the whole block answers "what am-/// I still inside?" without the user having to scroll to find out.-///-/// The drawing itself is [TimelineGuide]; what lives here is the rail's own-/// geometry, which is derived from [SidebarItem]'s and belongs beside it.-class SidebarTimeline extends StatelessWidget {- const SidebarTimeline({- super.key,- required this.role,- required this.child,- this.above = true,- this.below = true,- });-- final SidebarTimelineRole role;- final Widget child;-- /// Whether the trunk arrives from the row above. False on the first project —- /// a line dangling up towards the "Projects" header would point at nothing.- final bool above;-- /// Whether the trunk carries on into the row below. False on the last row of- /// the block, where the tree ends and the line has to stop rather than run- /// out into the "Chats" section, which isn't part of this tree.- final bool below;-- @override- Widget build(BuildContext context) => TimelineGuide(- role: role,- trunkX: _trunkX,- above: above,- below: below,- nodeGap: _nodeGap,- armLength: _armLength,- child: child,- );-}diff --git a/desktop/lib/shared/layouts/window_size.dart b/desktop/lib/shared/layouts/window_size.dartdeleted file mode 100644index 33bb29101..000000000--- a/desktop/lib/shared/layouts/window_size.dart+++ /dev/null@@ -1,49 +0,0 @@-import 'package:flutter/widgets.dart';--/// The width bands the shell branches on.-///-/// One definition, in one place, so "narrow" means the same number to every-/// piece of chrome rather than each one inventing its own threshold.-///-/// These are WINDOW widths, not device classes. A desktop window dragged down-/// to 500pt is [compact] for the same reason a phone is, and is laid out the-/// same way — there is no separate mobile build to branch on, and a rule that-/// asked "is this a phone?" would leave the narrow desktop window broken.-///-/// The lower edge is Material's 600. The upper one is this app's own: the pane-/// grid's floor for a usable terminal tile is about 336pt (`_MinTile` in-/// `widgets/pane_grid.dart`, 40 columns at the default font), and [expanded]-/// is meant to mean "two of those side by side, with the chrome around them" —-/// which 840 does not buy and 1024 does.-enum WindowSizeClass {- /// One thing at a time. Chrome that cannot earn its width collapses.- compact,-- /// Everything is present, with less room around it.- medium,-- /// The size the app is drawn for.- expanded;-- /// First width that is no longer [compact].- static const double compactMax = 600;-- /// First width that is [expanded].- static const double mediumMax = 1024;-- static WindowSizeClass fromWidth(double width) => switch (width) {- < compactMax => WindowSizeClass.compact,- < mediumMax => WindowSizeClass.medium,- _ => WindowSizeClass.expanded,- };-- /// The class of the WINDOW.- ///- /// Prefer [fromWidth] with a `LayoutBuilder`'s own constraint for anything- /// laid out narrower than the window: a strip inside a split should answer- /// for the box it was given, not for the screen it happens to sit on.- static WindowSizeClass of(BuildContext context) =>- fromWidth(MediaQuery.sizeOf(context).width);-- bool get isCompact => this == WindowSizeClass.compact;-}diff --git a/desktop/lib/shared/theme/app_theme.dart b/desktop/lib/shared/theme/app_theme.dartindex e0aada73b..d37d11d8c 100644--- a/desktop/lib/shared/theme/app_theme.dart+++ b/desktop/lib/shared/theme/app_theme.dart@@ -669,12 +669,13 @@ abstract final class AppGlass {/// menuTheme / popupMenuTheme #1E1E1E 8 6 no/// appMenuStyle() #2A2A2A 12 10 yes/// tooltipTheme #1E1E1E — 10 yes-/// AccountFooter, inline cardBg 18 8 yes+/// the account footer, inline cardBg 18 8 yes/// ```////// The cost was exactly what a second recipe always costs: the account footer's-/// `MenuAnchor` passed no style at all, so it opened the rimless themed default-/// — the surface `appMenuStyle` had been written to replace.+/// `MenuAnchor` (since removed with the machine rail) passed no style at all, so+/// it opened the rimless themed default — the surface `appMenuStyle` had been+/// written to replace.////// ⚠️ The fill is deliberately **not** the themed default. `#1E1E1E` sits within/// 1.02:1 of a raised block ([AppGlass.surfaceFill], `#202020`), and in lightdiff --git a/desktop/lib/shared/widgets/app_checkbox.dart b/desktop/lib/shared/widgets/app_checkbox.dartdeleted file mode 100644index 54d6aa910..000000000--- a/desktop/lib/shared/widgets/app_checkbox.dart+++ /dev/null@@ -1,83 +0,0 @@-import 'package:flutter/material.dart';--import '../theme/app_theme.dart';--/// A square tick box that fills with the accent when it is on.-///-/// Material's [Checkbox] is unusable raw here for the same reason [IconButton]-/// is (see [AppIconButton]): the app defines no `checkboxTheme`, so a bare one-/// takes Material's defaults — and the loudest of those is an **ink overlay-/// that is a circle**, laid over a square box on hover, focus and press. A round-/// wash bleeding out past the corners of the thing it belongs to is the single-/// clearest tell that a control was never looked at; on macOS a checkbox has no-/// hover halo at all, it just deepens.-///-/// It also brings a 48px tap target, a 2px corner where this app's controls sit-/// at 4–8, and a resting rim from `colorScheme.onSurfaceVariant` that reads far-/// darker than any other unfilled surface here.-///-/// So: the app's own formula instead — [MouseRegion] + [AnimatedContainer] on-/// [AppMotion.hover], depth from fill (§1), and a hover state that stays inside-/// the box's own edges.-///-/// ⚠️ This draws the BOX only. The label beside it belongs to the caller, and-/// so does the tap target that covers both — a checkbox whose text is not-/// clickable is a smaller target than it looks, and every row in this app that-/// carries one wraps the pair in its own [GestureDetector].-class AppCheckbox extends StatelessWidget {- const AppCheckbox({- super.key,- required this.value,- required this.onChanged,- this.hovered = false,- });-- final bool value;- final ValueChanged<bool>? onChanged;-- /// Whether the pointer is on the ROW this box belongs to.- ///- /// Passed in rather than sensed here, because the box is a 16px target inside- /// a row that is the real one: a box that only warmed when the pointer was- /// literally on it would stay cold through almost every hover the user- /// actually performs.- final bool hovered;-- /// Matches the cap height of the [AppControl.fontSize] label beside it, so- /// the two sit on one line rather than the box floating above the text.- static const double _box = 16;-- /// A step tighter than [AppControl.radius]. A checkbox reads as square — at- /// the button's 8 on a 16px box the corners eat a quarter of each edge and it- /// turns into a rounded chip.- static const double _radius = 4;-- @override- Widget build(BuildContext context) {- AppTheme.watch(context);- final enabled = onChanged != null;-- return AnimatedContainer(- duration: AppMotion.hover,- curve: AppMotion.curve,- width: _box,- height: _box,- alignment: Alignment.center,- decoration: BoxDecoration(- borderRadius: BorderRadius.circular(_radius),- // Ticked, the accent carries it. Unticked, it is a recessed well like- // every other empty control surface in the app — a step lighter under- // the pointer, which is the whole of the hover treatment.- color: value- ? (enabled ? AppPalette.accent : AppPalette.accentMuted)- : (hovered && enabled ? AppSurface.recessHover : AppSurface.recess),- ),- child: AnimatedOpacity(- duration: AppMotion.hover,- curve: AppMotion.curve,- opacity: value ? 1 : 0,- child: const Icon(Icons.check_rounded, size: 12, color: Colors.white),- ),- );- }-}diff --git a/desktop/lib/shared/widgets/timeline_guide.dart b/desktop/lib/shared/widgets/timeline_guide.dartdeleted file mode 100644index f34196082..000000000--- a/desktop/lib/shared/widgets/timeline_guide.dart+++ /dev/null@@ -1,165 +0,0 @@-import 'package:flutter/material.dart';--import '../theme/app_theme.dart';--/// What a row is to the guide line running down a timeline beside it.-enum TimelineRole {- /// The row carries a mark the line runs *through*. The trunk breaks around- /// it, so the mark reads as a node threaded onto the line rather than as an- /// icon the line happens to strike out.- node,-- /// Something living under the row above. The trunk passes by and an arm- /// reaches out to it.- branch,-- /// Neither — the trunk simply crosses this band. What a step's opened payload- /// sits beside: the line has to carry on past it to reach the next row, and- /// there is no mark down there to break around.- through,-}--/// The line that ties a run of rows into one thing.-///-/// Two surfaces draw one: the rail's projects and the chats inside them, and a-/// turn's steps between two passages of an agent's answer. Both are answering-/// the same question — *what is this stretch of rows, and where does it end?* —-/// and indentation alone answers it only while the whole group is on screen.-///-/// **Drawn per row rather than as one line behind the block**, so nothing here-/// has to know how tall a row is: each row paints the segment crossing its own-/// band, and [above]/[below] stitch those segments into one line. That is also-/// what lets a row in a lazy list draw its own share without the list having to-/// measure anything.-///-/// [trunkX] is the caller's, because the whole point is that the line runs-/// through the middle of something — a folder icon in the rail, a tool's glyph-/// in a step row — and only the caller knows where that sits.-class TimelineGuide extends StatelessWidget {- const TimelineGuide({- super.key,- required this.role,- required this.trunkX,- required this.child,- this.above = true,- this.below = true,- this.nodeGap = 13,- this.armLength = 7,- });-- final TimelineRole role;-- /// Where the trunk runs, from the child's left edge.- final double trunkX;-- final Widget child;-- /// Whether the trunk arrives from the row above. False on the first row —- /// a line dangling up towards a heading points at nothing.- final bool above;-- /// Whether the trunk carries on into the row below. False on the last row,- /// where the run ends and the line has to stop rather than run out into- /// whatever follows it.- final bool below;-- /// How wide a berth [TimelineRole.node] gives the mark it runs through.- /// Enough to clear the glyph by a few pixels: any less and the line reads as- /// striking it out.- final double nodeGap;-- /// How far a [TimelineRole.branch]'s arm reaches out of the trunk. Stop it- /// short of the row's own box — touching a hover fill makes the guide read as- /// part of the row instead of as the thing holding it.- final double armLength;-- @override- Widget build(BuildContext context) {- // Reads AppPalette.guide from inside a lazy list, where an ancestor's- // rebuild never lands — watch here or the guide keeps the palette it was- // first painted with.- AppTheme.watch(context);- return CustomPaint(- // In front of the child, not behind it: a row's hover and selection fills- // run its full width, and painting under them would swallow the two short- // segments carrying the trunk past its mark on exactly the row the- // pointer is on.- foregroundPainter: _TimelinePainter(- role: role,- trunkX: trunkX,- above: above,- below: below,- nodeGap: nodeGap,- armLength: armLength,- color: AppPalette.guide,- ),- child: child,- );- }-}--/// A hairline, like every other rule in the app. This is chrome about the rows,-/// not an entry among them.-const double _stroke = 1;--/// One row's share of the guide: the trunk crossing its band, broken around a-/// node's mark, plus the arm out to a nested row.-class _TimelinePainter extends CustomPainter {- const _TimelinePainter({- required this.role,- required this.trunkX,- required this.above,- required this.below,- required this.nodeGap,- required this.armLength,- required this.color,- });-- final TimelineRole role;- final double trunkX;- final bool above;- final bool below;- final double nodeGap;- final double armLength;- final Color color;-- @override- void paint(Canvas canvas, Size size) {- final line = Paint()- ..color = color- ..strokeWidth = _stroke;- final centerY = size.height / 2;- // A node breaks the line around its mark; everything else lets it run- // straight through, which is also what turns the last branch's two segments- // into one clean elbow.- final gap = role == TimelineRole.node ? nodeGap : 0.0;-- if (above) {- canvas.drawLine(Offset(trunkX, 0), Offset(trunkX, centerY - gap), line);- }- if (below) {- canvas.drawLine(- Offset(trunkX, centerY + gap),- Offset(trunkX, size.height),- line,- );- }- if (role == TimelineRole.branch) {- canvas.drawLine(- Offset(trunkX, centerY),- Offset(trunkX + armLength, centerY),- line,- );- }- }-- @override- bool shouldRepaint(_TimelinePainter old) =>- role != old.role ||- trunkX != old.trunkX ||- above != old.above ||- below != old.below ||- nodeGap != old.nodeGap ||- armLength != old.armLength ||- color != old.color;-}diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 5c3868c1d..462cc7785 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -7947,7 +7947,7 @@ class AppNotifier extends ChangeNotifier {/// take over the whole content area would blank three working terminals/// belonging to two other machines. The one exception is a machine that/// already needs linking: that state now surfaces as a blocking popup- /// (HomeScreen._maybeShowLinkDialog / showLinkMachineScreenDialog) rather+ /// (showLinkMachineScreenDialog, from SwarmScreen) rather/// than a tile, so opening one here too would just be a redundant "not/// linked" pane sitting behind it. Selecting is still worth doing — it's/// what makes the popup's gate notice this machine — the tile is not.diff --git a/desktop/lib/usage/usage_pressure.dart b/desktop/lib/usage/usage_pressure.dartdeleted file mode 100644index 7002cd48b..000000000--- a/desktop/lib/usage/usage_pressure.dart+++ /dev/null@@ -1,34 +0,0 @@-import 'usage_window.dart';--/// How close a rate-limit window is to being spent.-///-/// Two thresholds, one step each: [warn] turns a figure amber and [critical]-/// turns it red. A third shade between them would be one nobody could name.-enum UsagePressure {- calm,-- /// Amber. The window is worth noticing on the way past.- warn,-- /// Red. The window is nearly spent.- critical,-}--/// Where a window starts reading amber.-///-/// The figure beside it is already exact, so this number is not carrying the-/// quantity — it is carrying the moment the quantity starts to matter.-const double kUsageWarnPercent = 80;--/// Where a window starts reading red.-const double kUsageCriticalPercent = 90;--UsagePressure usagePressureOf(double usedPercent) {- if (usedPercent >= kUsageCriticalPercent) return UsagePressure.critical;- if (usedPercent >= kUsageWarnPercent) return UsagePressure.warn;- return UsagePressure.calm;-}--extension UsageWindowPressure on UsageWindow {- UsagePressure get pressure => usagePressureOf(usedPercent);-}diff --git a/desktop/lib/usage/usage_window.dart b/desktop/lib/usage/usage_window.dartindex 6ea8e1a93..4548595c6 100644--- a/desktop/lib/usage/usage_window.dart+++ b/desktop/lib/usage/usage_window.dart@@ -2,17 +2,15 @@////// The vendors answer in different shapes — Claude names its windows, Codex/// numbers them — so both are mapped onto this one model before anything draws-/// them. A rail that had to know which provider it was printing would grow a-/// branch per provider in every widget.+/// them. A readout that had to know which provider it was printing would grow+/// a branch per provider in every widget.library;/// What both vendors call their seven-day window.////// Claude names it outright; Codex's label is derived from/// `limit_window_seconds` and lands on the same word at seven days. Written-/// down once because the rail MATCHES on it — see [ProviderUsage.railWindow] —-/// and a match against a string spelled in two files is a match that breaks-/// silently the day one of them is reworded.+/// down once so the two sources cannot spell it differently.const String kWeeklyWindowLabel = 'Weekly';/// Which account a reading belongs to.@@ -136,27 +134,6 @@ class ProviderUsage {if (windows.isEmpty) return null;return windows.reduce((a, b) => b.usedPercent > a.usedPercent ? b : a);}-- /// The ONE window the status rail prints.- ///- /// The weekly one. Claude reports three windows and Codex usually one, so- /// printing them all made one account three figures wide and the other one —- /// two readouts that looked like different KINDS of thing rather than the- /// same thing about two accounts. Weekly is also the figure worth a glance:- /// the five-hour window refills all day and is back to nothing by the time- /// anyone reads it, while the week is the budget somebody actually plans- /// against.- ///- /// Falls back to [tightest] for a provider that reports no weekly window at- /// all — one figure is the rule, and an empty strip would be a worse answer- /// than the wrong window. The panel behind the figure still shows every- /// window, which is where the detail belongs.- UsageWindow? get railWindow {- for (final window in windows) {- if (window.label == kWeeklyWindowLabel) return window;- }- return tightest;- }}/// Reads a vendor's reset timestamp, which arrives as an ISO string, epochdiff --git a/desktop/lib/widgets/account_footer.dart b/desktop/lib/widgets/account_footer.dartdeleted file mode 100644index b54039f13..000000000--- a/desktop/lib/widgets/account_footer.dart+++ /dev/null@@ -1,357 +0,0 @@-import 'dart:async';--import 'package:flutter/material.dart';-import 'package:lucide_icons_flutter/lucide_icons.dart';-import 'package:harness/terminal/terminal_text.dart';--import '../state/app_state.dart';-import '../shared/theme/app_theme.dart' as grid;-import '../shared/widgets/app_menu.dart';-import 'link_machine_dialog.dart';-import '../settings/settings_screen.dart';--class AccountFooter extends StatefulWidget {- final AppNotifier notifier;-- /// Draw the avatar alone, for the folded rail.- ///- /// Not the pill with the email hidden: at 72px a recessed pill would be a- /// rounded box hugging a circle, which reads as a second ring around the- /// avatar rather than as a button.- final bool compact;-- const AccountFooter({- super.key,- required this.notifier,- this.compact = false,- });-- @override- State<AccountFooter> createState() => _AccountFooterState();-}--class _AccountFooterState extends State<AccountFooter> {- /// Held here because [AppMenuItem] does not close the panel for you — unlike- /// `MenuItemButton`, which used to and was the only thing it did right.- final _menu = MenuController();-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- final profile = widget.notifier.currentUser;- final isLocal = widget.notifier.localManualFixture != null;- final primary =- profile?.email ?? (isLocal ? 'local terminal' : 'signed in');- final secondary = isLocal ? 'LOCAL SESSION' : null;-- return MenuAnchor(- controller: _menu,- alignmentOffset: const Offset(8, -8),- // The app's one panel recipe, with only the two things that are specific- // to *this* menu passed in.- //- // The width is one of them: this panel holds an email address, and a menu- // that resized itself to the signed-in account would move its own rows- // between one user and the next. The height is the other — the summary- // block plus three rows and their rules run past the 240 a plain menu is- // capped at, and this one opens *upward*, so a cap that clipped it would- // also lift it clear of the pill it hangs off.- style: grid.AppMenu.style(minWidth: 276, maxWidth: 292, maxHeight: 420),- // The same rows the machine and agent ⋯ menus use.- //- // These were raw `MenuItemButton`s, which take Material's M3 defaults and- // land wrong on four counts at once: radius 0, a 14pt label, a grey- // `onSurface`-8% hover and an ink ripple every other menu here has turned- // off — plus a 48px tap target. The visible tell was the highlight: a- // full-bleed band touching both panel edges, running square into a panel- // rounded at 10. [AppMenuItem] carries a 6px gutter, so the hover reads as- // a pill INSET in the panel, which is what the ⋯ menus already looked like.- //- // Icons come from the same set as those menus too. Two glyph families for- // the same kind of row is a boundary nobody can see the logic of.- menuChildren: [- _AccountSummary(notifier: widget.notifier),- const AppMenuDivider(),- AppMenuItem(- key: const Key('link-a-machine-menu-item'),- icon: LucideIcons.link2300,- label: 'Remote into another machine…',- onPressed: () {- _menu.close();- unawaited(showLinkMachineDialog(context, widget.notifier));- },- ),- AppMenuItem(- key: const Key('settings-menu-item'),- icon: LucideIcons.settings300,- label: 'Settings',- onPressed: () {- _menu.close();- unawaited(- showSettingsScreen(- context,- widget.notifier,- source: 'account_menu',- ),- );- },- ),- const AppMenuDivider(),- AppMenuItem(- key: const Key('sign-out-menu-item'),- icon: LucideIcons.logOut300,- label: isLocal ? 'Disconnect local session' : 'Sign out',- // The one row here that ENDS something. It sat in a group of its own- // already, which said "this is different" — but drew in the same ink- // as Settings, which said the opposite louder. [AppMenuItem] has- // carried the treatment all along; this row simply never asked.- danger: true,- onPressed: () {- _menu.close();- widget.notifier.logout();- },- ),- ],- builder: (context, controller, child) => Padding(- // The pill floats inside the rail rather than spanning it. A full-width- // band with a rule above it reads as a second surface bolted to the- // bottom; a recessed pill reads as part of the column it sits in.- padding: const EdgeInsets.fromLTRB(10, 6, 10, 10),- child: widget.compact- ? Center(- child: _AvatarButton(- onTap: controller.isOpen ? controller.close : controller.open,- initials: profile?.initials ?? (isLocal ? 'L' : '?'),- ),- )- : _AccountPill(- open: controller.isOpen,- onTap: controller.isOpen ? controller.close : controller.open,- initials: profile?.initials ?? (isLocal ? 'L' : '?'),- primary: primary,- secondary: secondary,- ),- ),- );- }-}--/// The row you press to reach the account menu.-///-/// Its own widget so the hover state belongs to the thing that shows it: an-/// InkWell `hoverColor` tinted the whole 66px band instead, which read as the-/// rail highlighting rather than the row.-/// The avatar as a button, for the folded rail.-class _AvatarButton extends StatelessWidget {- const _AvatarButton({required this.onTap, required this.initials});-- final VoidCallback onTap;- final String initials;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- return Tooltip(- message: 'Account',- child: MouseRegion(- cursor: SystemMouseCursors.click,- child: GestureDetector(- key: const Key('account-menu-button'),- onTap: onTap,- behavior: HitTestBehavior.opaque,- child: _Avatar(initials: initials),- ),- ),- );- }-}--class _AccountPill extends StatefulWidget {- const _AccountPill({- required this.open,- required this.onTap,- required this.initials,- required this.primary,- this.secondary,- });-- final bool open;- final VoidCallback onTap;- final String initials;- final String primary;- final String? secondary;-- @override- State<_AccountPill> createState() => _AccountPillState();-}--class _AccountPillState extends State<_AccountPill> {- bool _hovered = false;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- final lit = _hovered || widget.open;- return MouseRegion(- onEnter: (_) => setState(() => _hovered = true),- onExit: (_) => setState(() => _hovered = false),- cursor: SystemMouseCursors.click,- child: GestureDetector(- key: const Key('account-menu-button'),- onTap: widget.onTap,- behavior: HitTestBehavior.opaque,- child: AnimatedContainer(- duration: grid.AppMotion.hover,- curve: grid.AppMotion.curve,- padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),- decoration: BoxDecoration(- color: lit ? grid.AppSurface.recessHover : grid.AppSurface.recess,- borderRadius: BorderRadius.circular(11),- ),- child: Row(- children: [- _Avatar(initials: widget.initials),- const SizedBox(width: 10),- Expanded(- child: Column(- mainAxisAlignment: MainAxisAlignment.center,- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(- widget.primary,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: terminalTextStyle(- color: grid.AppPalette.textPrimary,- fontWeight: grid.AppFont.medium,- ),- ),- if (widget.secondary != null)- Text(- widget.secondary!,- style: terminalTextStyle(- color: grid.AppPalette.textFaint,- fontWeight: grid.AppFont.medium,- ),- ),- ],- ),- ),- Icon(- Icons.more_horiz,- size: 18,- color: grid.AppPalette.textSecondary,- ),- ],- ),- ),- ),- );- }-}--class _AccountSummary extends StatelessWidget {- final AppNotifier notifier;-- const _AccountSummary({required this.notifier});-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- final profile = notifier.currentUser;- final isLocal = notifier.localManualFixture != null;- return Padding(- // 15 = the row gutter (6) plus a row's own inner padding (9), so this- // block starts on the same left edge as the glyphs under it instead of- // one pixel off it.- padding: const EdgeInsets.fromLTRB(15, 10, 15, 8),- child: Row(- children: [- _Avatar(- initials: profile?.initials ?? (isLocal ? 'L' : '?'),- large: true,- ),- const SizedBox(width: 12),- Expanded(- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(- profile?.displayName ??- (isLocal ? 'Local session' : 'Autonomous user'),- maxLines: 1,- overflow: TextOverflow.ellipsis,- // Semibold, not w700: the weight ladder has three steps and- // this is the top one. A fourth weight for one line makes it- // shout at the rows it is introducing.- style: terminalTextStyle(- color: grid.AppPalette.textPrimary,- // 1.25, not the 1.2 a row uses: this line has a second line- // under it, and a name and its address set solid read as one- // block of text rather than as a heading and its subtitle.- height: 1.25,- // From the ladder, like the address under it — not a hand- // -picked value. Two lines this close with tracking set on- // only one of them drift apart at the right edge.- letterSpacing: grid.AppFont.trackingFor(13.5),- fontWeight: grid.AppFont.semibold,- ),- ),- const SizedBox(height: 3),- Text(- profile?.email ??- (isLocal ? 'loopback backend' : 'profile unavailable'),- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: terminalTextStyle(- color: grid.AppPalette.textSecondary,- height: 1.25,- letterSpacing: grid.AppFont.trackingFor(12),- ),- ),- ],- ),- ),- ],- ),- );- }-}--class _Avatar extends StatelessWidget {- final String initials;- final bool large;-- const _Avatar({required this.initials, this.large = false});-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- final size = large ? 36.0 : 32.0;- return Container(- // Keyed so the rows that stand on this pill's column can prove, in a- // test, that they do — the device row above it measures its mark- // against this centre.- key: const Key('account-avatar'),- width: size,- height: size,- alignment: Alignment.center,- decoration: BoxDecoration(- // A filled disc, not a ring. The ring read as a third border stacked- // inside the pill's own rounding; a solid mark is what makes an avatar- // look like a person rather than like another control.- color: grid.AppPalette.avatarFill,- shape: BoxShape.circle,- ),- child: Text(- initials,- style: terminalTextStyle(- // White on the accent disc — the token pair the palette is built for- // (5.5:1). The page ink would be near-black in Light and vanish.- color: Colors.white,- fontWeight: FontWeight.w700,- ),- ),- );- }-}diff --git a/desktop/lib/widgets/agent_switcher.dart b/desktop/lib/widgets/agent_switcher.dartdeleted file mode 100644index fdab702cd..000000000--- a/desktop/lib/widgets/agent_switcher.dart+++ /dev/null@@ -1,369 +0,0 @@-import 'dart:async';--import 'package:flutter/material.dart';-import 'package:flutter/services.dart';--import '../core/models.dart';-import '../core/fuzzy_match.dart';-import '../shared/theme/app_theme.dart' as grid;-import '../shared/widgets/app_dialog.dart';-import '../state/app_state.dart';-import 'engine_identity.dart';--export '../core/fuzzy_match.dart' show subsequenceSpread;--/// ⌘P — go to an agent by name, on any machine.-///-/// THE KEY THAT WAS MISSING, and it was missing for the main verb of the-/// product. Before this, a hand that never touched the mouse could reach an-/// agent three ways and none of them did this job: ⌘1…⌘9 address TILES, so they-/// only find agents already on the grid; ⌘[ / ⌘] walk that same short list; ⌘B-/// takes a task and lets a model choose who gets it. Open the eleventh agent by-/// name — the thing tmux answers with `prefix s` and vim with telescope — and-/// the only answer was the sidebar, with a pointer.-///-/// A FILTER, NOT A MENU. Every agent on every machine is in the list, and typing-/// narrows it; that is the shape of the motion terminal people already have, and-/// it is the only shape that stays usable at thirty agents. The match is-/// subsequence, not substring — `frn` finds `frontend`, the way fzf and every-/// editor's go-to-file does — and it runs over the machine's name too, so-/// "mini auth" reaches the Auth agent on the mac mini.-///-/// Built on the same bones as [showLayoutPalette]: a dialog that takes focus at-/// once, walks on the arrow keys, commits on Enter. That palette proved the-/// pattern works in this app; this one adds a field in front of it.--/// Guards a second ⌘P while the switcher is already up — the same stacking-/// failure `showLayoutPalette` documents, where every press laid another-/// barrier over the last and the window appeared to fade to black.-bool _switcherOpen = false;--Future<void> showAgentSwitcher(BuildContext context, AppNotifier notifier) {- if (_switcherOpen) return Future<void>.value();- _switcherOpen = true;- return showDialog<void>(- context: context,- barrierColor: kDialogVeilTint,- builder: (context) => _AgentSwitcher(notifier: notifier),- ).whenComplete(() => _switcherOpen = false);-}--/// One agent, with everything the list needs to draw and rank it.-@immutable-class SwitcherEntry {- const SwitcherEntry({- required this.machineId,- required this.machineName,- required this.agent,- required this.onGrid,- });-- final String machineId;- final String machineName;- final Agent agent;-- /// Already has a tile. Shown, not hidden: "where is it" and "is it open" are- /// different questions, and a switcher that omitted the open ones would make- /// ⌘P useless for the very agents being worked on.- final bool onGrid;-- /// What the filter reads — the agent's name and its machine's, so a query can- /// name either.- String get haystack => '${agent.name} $machineName'.toLowerCase();-}--/// The agents this window can reach, ranked against [query].-///-/// Pulled out of the widget so the ranking can be tested without a screen —-/// which matters more here than usual, because "why did it not find my agent"-/// is the one bug report a fuzzy list reliably generates.-List<SwitcherEntry> rankAgentsForSwitcher(- List<SwitcherEntry> all,- String query,-) {- final needle = query.trim().toLowerCase();- if (needle.isEmpty) {- // No query: the ones NOT on the grid first. Someone who opened this with an- // empty field is looking for something they cannot already see, and the- // agents in front of them are the least likely answer.- return [...all]..sort((a, b) {- if (a.onGrid != b.onGrid) return a.onGrid ? 1 : -1;- return a.agent.name.toLowerCase().compareTo(b.agent.name.toLowerCase());- });- }- final scored = <({SwitcherEntry entry, int spread})>[];- for (final entry in all) {- final spread = subsequenceSpread(entry.haystack, needle);- if (spread != null) scored.add((entry: entry, spread: spread));- }- scored.sort((a, b) {- if (a.spread != b.spread) return a.spread.compareTo(b.spread);- return a.entry.agent.name.toLowerCase().compareTo(- b.entry.agent.name.toLowerCase(),- );- });- return [for (final row in scored) row.entry];-}--class _AgentSwitcher extends StatefulWidget {- const _AgentSwitcher({required this.notifier});-- final AppNotifier notifier;-- @override- State<_AgentSwitcher> createState() => _AgentSwitcherState();-}--class _AgentSwitcherState extends State<_AgentSwitcher> {- final _query = TextEditingController();- final _field = FocusNode();- int _cursor = 0;-- @override- void dispose() {- _query.dispose();- _field.dispose();- super.dispose();- }-- List<SwitcherEntry> _entries() {- final out = <SwitcherEntry>[];- for (final state in widget.notifier.machineStates.values) {- for (final agent in state.agents) {- // An agent with no terminal cannot be opened, so offering it is a row- // that answers a keystroke with nothing.- if (!agent.terminalAvailable) continue;- out.add(- SwitcherEntry(- machineId: state.machine.machineId,- machineName: state.machine.displayName,- agent: agent,- onGrid:- widget.notifier.paneOfAgent(- state.machine.machineId,- agent.id,- ) !=- null,- ),- );- }- }- return out;- }-- void _open(SwitcherEntry entry, {required bool newTile}) {- Navigator.of(context).pop();- if (newTile && !entry.onGrid) {- unawaited(- widget.notifier.assignAgentToPane(- null,- entry.machineId,- entry.agent.id,- ),- );- return;- }- // selectAgent focuses the tile this agent already has, or opens one. Both- // are "take me there", which is the only promise this list makes.- unawaited(widget.notifier.selectAgent(entry.machineId, entry.agent.id));- }-- KeyEventResult _onKey(- FocusNode node,- KeyEvent event,- List<SwitcherEntry> rows,- ) {- if (event is! KeyDownEvent && event is! KeyRepeatEvent) {- return KeyEventResult.ignored;- }- final key = event.logicalKey;- final ctrl = HardwareKeyboard.instance.isControlPressed;-- // Ctrl-n / Ctrl-p walk the list as well as the arrows. Inside a text field- // those two are readline's "next line" / "previous line", which is exactly- // what they are being asked to do here, and they are what a terminal user's- // hand does without being told. They cost nothing: the field is this app's,- // not a pty, so no shell is waiting for them.- final down =- key == LogicalKeyboardKey.arrowDown ||- (ctrl && key == LogicalKeyboardKey.keyN);- final up =- key == LogicalKeyboardKey.arrowUp ||- (ctrl && key == LogicalKeyboardKey.keyP);- if (down || up) {- if (rows.isEmpty) return KeyEventResult.handled;- setState(() {- // Wraps, unlike the layout palette's strip: this is a LIST, and a list- // that runs off its own end is the one place wrapping reads as correct.- _cursor = (_cursor + (down ? 1 : -1) + rows.length) % rows.length;- });- return KeyEventResult.handled;- }- if (key == LogicalKeyboardKey.enter ||- key == LogicalKeyboardKey.numpadEnter) {- if (rows.isEmpty) return KeyEventResult.handled;- _open(- rows[_cursor.clamp(0, rows.length - 1)],- newTile: HardwareKeyboard.instance.isShiftPressed,- );- return KeyEventResult.handled;- }- if (key == LogicalKeyboardKey.escape) {- Navigator.of(context).pop();- return KeyEventResult.handled;- }- return KeyEventResult.ignored;- }-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- return ListenableBuilder(- listenable: widget.notifier,- builder: (context, _) {- final rows = rankAgentsForSwitcher(_entries(), _query.text);- final at = rows.isEmpty ? 0 : _cursor.clamp(0, rows.length - 1);- return Dialog(- alignment: Alignment.topCenter,- insetPadding: const EdgeInsets.only(top: 96, left: 24, right: 24),- backgroundColor: grid.AppGlass.surfaceFill,- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(13),- side: BorderSide(color: grid.AppGlass.hair),- ),- child: ConstrainedBox(- constraints: const BoxConstraints(maxWidth: 620),- child: Focus(- onKeyEvent: (node, event) => _onKey(node, event, rows),- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- Padding(- padding: const EdgeInsets.fromLTRB(16, 14, 16, 12),- child: TextField(- controller: _query,- focusNode: _field,- autofocus: true,- style: grid.AppType.mono(- color: grid.AppPalette.textPrimary,- ),- decoration: InputDecoration(- border: InputBorder.none,- isDense: true,- hintText: 'Find a harness',- hintStyle: grid.AppType.mono(- color: grid.AppPalette.textFaint,- ),- ),- // Rebuilt on every keystroke, and the cursor goes home- // with it: after narrowing the list, row 4 is a different- // agent than it was, and landing on it would open- // something nobody chose.- onChanged: (_) => setState(() => _cursor = 0),- ),- ),- Divider(height: 1, color: grid.AppGlass.hair),- if (rows.isEmpty)- Padding(- padding: const EdgeInsets.fromLTRB(16, 18, 16, 20),- child: Text(- 'No agent matches that.',- style: grid.AppType.monoLabel(- fontWeight: FontWeight.w400,- color: grid.AppPalette.textFaint,- ),- ),- )- else- Flexible(- child: ListView.builder(- shrinkWrap: true,- padding: const EdgeInsets.symmetric(vertical: 6),- itemCount: rows.length,- itemBuilder: (context, i) => _Row(- entry: rows[i],- selected: i == at,- onTap: () => _open(rows[i], newTile: false),- ),- ),- ),- Divider(height: 1, color: grid.AppGlass.hair),- Padding(- padding: const EdgeInsets.fromLTRB(16, 9, 16, 10),- child: Text(- '↑↓ or ⌃n ⌃p to move · ⏎ to go · ⇧⏎ in a new tile · esc',- style: grid.AppType.monoMeta(- color: grid.AppPalette.textFaint,- ),- ),- ),- ],- ),- ),- ),- );- },- );- }-}--class _Row extends StatelessWidget {- const _Row({- required this.entry,- required this.selected,- required this.onTap,- });-- final SwitcherEntry entry;- final bool selected;- final VoidCallback onTap;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- return InkWell(- onTap: onTap,- child: Container(- color: selected ? grid.AppGlass.surfaceHoverFill : null,- padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 9),- child: Row(- children: [- EngineMark.forAgent(entry.agent, size: 15),- const SizedBox(width: 11),- Expanded(- child: Text(- entry.agent.name,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: grid.AppType.monoLabel(- color: grid.AppPalette.textPrimary,- ),- ),- ),- const SizedBox(width: 12),- Text(- entry.machineName,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: grid.AppType.monoMeta(color: grid.AppPalette.textFaint),- ),- // A dot, not the word "open": the list is read at a glance and a- // second column of text would compete with the machine's name.- if (entry.onGrid) ...[- const SizedBox(width: 10),- Container(- width: 5,- height: 5,- decoration: BoxDecoration(- shape: BoxShape.circle,- color: grid.AppPalette.textSecondary,- ),- ),- ],- ],- ),- ),- );- }-}diff --git a/desktop/lib/widgets/device_row.dart b/desktop/lib/widgets/device_row.dartdeleted file mode 100644index a51ceda6d..000000000--- a/desktop/lib/widgets/device_row.dart+++ /dev/null@@ -1,405 +0,0 @@-import 'dart:async';--import 'package:flutter/material.dart';-import 'package:url_launcher/url_launcher.dart';-import 'package:harness/terminal/terminal_text.dart';--import '../shared/theme/app_theme.dart' as grid;-import '../shared/widgets/app_dialog.dart';-import '../state/app_state.dart';-import '../state/dial_status.dart';--/// Where to get one. The product page, and the same page the app's own Quick Setup card points at.-const String kDeviceStoreUrl = 'https://www.autonomous.ai/harness';--/// The dial's row on the rail's floor, above the account.-///-/// One row, never absent, saying one of three things — because the row is the SAME thing to three-/// different people. Someone who has never owned a dial is shown the way to get one; someone whose dial-/// is on the desk gets a way to its status; someone whose dial is in a drawer is told it is unplugged,-/// and is not sold a second one every time they glance at the rail. The three are told apart by two-/// facts the daemon and a remembered bit already carry ([DialState]), so nothing here guesses.-///-/// Drawn in the account pill's own idiom — same fill, radius and padding — so the floor reads as one-/// piece. Settings are NOT here: they live on the device (its last screen), and a second copy in the-/// window would be two places for one fact.-class DeviceRow extends StatefulWidget {- const DeviceRow({super.key, required this.notifier});-- final AppNotifier notifier;-- @override- State<DeviceRow> createState() => _DeviceRowState();-}--class _DeviceRowState extends State<DeviceRow> {- bool _hovered = false;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- return ListenableBuilder(- listenable: widget.notifier.dial,- builder: (context, _) {- final dial = widget.notifier.dial;- final status = dial.status;- // What the row offers is decided by what the person HAS, not by what they might buy.- final invite = !status.attached && !dial.seen;- return Padding(- padding: const EdgeInsets.fromLTRB(10, 0, 10, 4),- child: MouseRegion(- onEnter: (_) => setState(() => _hovered = true),- onExit: (_) => setState(() => _hovered = false),- cursor: SystemMouseCursors.click,- child: GestureDetector(- key: const Key('device-row'),- behavior: HitTestBehavior.opaque,- onTap: () => invite- ? unawaited(- launchUrl(- Uri.parse(kDeviceStoreUrl),- mode: LaunchMode.externalApplication,- ),- )- : unawaited(_showStatus(context)),- child: AnimatedContainer(- duration: grid.AppMotion.hover,- curve: grid.AppMotion.curve,- // The account pill's own metrics, so the two rows share a left column: a 32px- // leading box — the avatar's real size, measured in _Avatar, not the 26 the pill- // looks like — and a 10px gap put this row's mark and text exactly under the avatar- // and the email. Off by six the first time, from reading the size off a screenshot.- padding: const EdgeInsets.all(8),- decoration: BoxDecoration(- color: _hovered- ? grid.AppSurface.recessHover- : grid.AppSurface.recess,- borderRadius: BorderRadius.circular(11),- ),- child: Row(- children: [- _Dot(live: status.attached),- const SizedBox(width: 10),- Expanded(- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(- 'DEVICE',- style: terminalTextStyle(- color: grid.AppPalette.textFaint,- fontWeight: grid.AppFont.semibold,- letterSpacing: 0.7,- ),- ),- const SizedBox(height: 1),- _line(status, invite),- ],- ),- ),- if (!invite)- Icon(- Icons.chevron_right,- size: 16,- color: grid.AppPalette.textSecondary,- ),- ],- ),- ),- ),- ),- );- },- );- }-- /// The value line, in its three readings.- Widget _line(DialStatus status, bool invite) {- final base = terminalTextStyle(color: grid.AppPalette.textSecondary);- if (invite) {- return Text.rich(- TextSpan(- style: base,- children: [- const TextSpan(text: 'Harness device · '),- TextSpan(- text: 'Get the device →',- style: TextStyle(- color: grid.AppPalette.accentOnSurface,- fontWeight: grid.AppFont.medium,- ),- ),- ],- ),- maxLines: 1,- overflow: TextOverflow.ellipsis,- );- }- if (status.attached) {- // The name alone. Version and port belong to the card this opens — on the row they were two- // more things to read for a fact the green ring already tells.- return Text(- 'Harness device',- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: base.copyWith(- color: grid.AppPalette.textPrimary,- fontWeight: grid.AppFont.medium,- ),- );- }- return Text(- 'Harness device · unplugged',- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: base,- );- }-- Future<void> _showStatus(BuildContext context) {- return showDialog<void>(- context: context,- barrierColor: kDialogVeilTint,- builder: (context) => _DeviceStatusCard(notifier: widget.notifier),- );- }-}--/// The mark: a solid dot in the avatar's 32px box, so it sits on the account row's column.-///-/// Solid, not a ring — a ring read as "empty", which is the opposite of a device that is on. Lit, it-/// wears a soft halo out to 20px so it carries about the avatar's weight beside it; unplugged, the halo-/// goes and the dot turns the rail's faint grey. Same dot, two states, nothing to re-learn.-class _Dot extends StatelessWidget {- const _Dot({required this.live});-- final bool live;-- @override- Widget build(BuildContext context) {- TerminalFontScope.watch(context);- final color = live ? grid.AppPalette.online : grid.AppPalette.textFaint;- return SizedBox(- width: 32,- height: 32,- child: Center(- child: Container(- key: const Key('device-dot'),- width: 12,- height: 12,- decoration: BoxDecoration(- shape: BoxShape.circle,- color: color,- boxShadow: live- ? [- BoxShadow(- color: color.withValues(alpha: 0.2),- spreadRadius: 4,- ),- ]- : null,- ),- ),- ),- );- }-}--/// What the row opens: the dial's status, three lines, and where the settings are.-///-/// Deliberately not a settings screen. The device keeps its own (brightness, voice language, reset —-/// its last screen), and the window saying so is worth more than the window copying them.-class _DeviceStatusCard extends StatelessWidget {- const _DeviceStatusCard({required this.notifier});-- final AppNotifier notifier;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- return ListenableBuilder(- listenable: notifier.dial,- builder: (context, _) {- final status = notifier.dial.status;- final updating = status.updating;- final sub = terminalTextStyle(- color: grid.AppPalette.textSecondary,- height: 1.45,- );- return Dialog(- backgroundColor: grid.AppGlass.surfaceFill,- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(13),- side: BorderSide(color: grid.AppGlass.hair),- ),- child: ConstrainedBox(- constraints: const BoxConstraints(maxWidth: 400),- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- Padding(- padding: const EdgeInsets.fromLTRB(20, 18, 20, 14),- child: Row(- children: [- _Dial(live: status.attached),- const SizedBox(width: 14),- Expanded(- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(- 'Harness device',- style: terminalTextStyle(- color: grid.AppPalette.textPrimary,- fontWeight: grid.AppFont.semibold,- ),- ),- const SizedBox(height: 3),- Text.rich(- TextSpan(- style: sub,- children: [- TextSpan(- text: status.attached- ? 'Connected via USB'- : 'Unplugged',- ),- if (status.fw != null) ...[- const TextSpan(text: ' · firmware '),- TextSpan(- text: status.fw,- style: TextStyle(- color: grid.AppPalette.textPrimary,- ),- ),- ],- if (status.hw != null) ...[- TextSpan(text: ' · ${status.hw}'),- ],- if (updating != null) ...[- const TextSpan(text: ' · '),- TextSpan(- text: 'updating to $updating…',- style: TextStyle(- color: grid.AppPalette.warn,- ),- ),- ],- ],- ),- ),- ],- ),- ),- ],- ),- ),- Divider(height: 1, color: grid.AppGlass.hair),- Padding(- padding: const EdgeInsets.fromLTRB(20, 12, 20, 12),- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(- // The one minute in which people unplug the thing — said instead of the usual- // line while it is running.- updating != null- ? 'Keep it plugged in'- : 'Settings are on the device',- style: terminalTextStyle(- color: grid.AppPalette.textPrimary,- ),- ),- const SizedBox(height: 2),- Text(- updating != null- ? 'The update goes over the cable and takes about a minute.'- : 'Swipe to its last screen: brightness, voice language, reset.',- style: terminalTextStyle(- color: grid.AppPalette.textFaint,- height: 1.4,- ),- ),- ],- ),- ),- Container(- padding: const EdgeInsets.fromLTRB(20, 11, 20, 13),- decoration: BoxDecoration(- color: grid.AppPalette.cardBg,- border: Border(top: BorderSide(color: grid.AppGlass.hair)),- ),- child: Row(- children: [- Expanded(- child: Text(- status.attached- ? 'Want one for another desk?'- : 'Plug it into this Mac to use it.',- style: terminalTextStyle(- color: grid.AppPalette.textFaint,- ),- ),- ),- InkWell(- onTap: () => unawaited(- launchUrl(- Uri.parse(kDeviceStoreUrl),- mode: LaunchMode.externalApplication,- ),- ),- child: Text(- 'Get the device →',- style: terminalTextStyle(- color: grid.AppPalette.accentOnSurface,- fontWeight: grid.AppFont.medium,- ),- ),- ),- ],- ),- ),- ],- ),- ),- );- },- );- }-}--/// The dial, as a mark: a dark disc with the bezel drawn in and a small ring at its centre.-class _Dial extends StatelessWidget {- const _Dial({required this.live});-- final bool live;-- @override- Widget build(BuildContext context) {- TerminalFontScope.watch(context);- return Container(- width: 56,- height: 56,- decoration: BoxDecoration(- shape: BoxShape.circle,- color: const Color(0xFF0C0C0E),- border: Border.all(color: const Color(0xFF2C2C31), width: 3),- ),- child: Center(- child: Container(- width: 14,- height: 14,- decoration: BoxDecoration(- shape: BoxShape.circle,- border: Border.all(- width: 2,- color: live ? grid.AppPalette.online : const Color(0xFF3A3A3E),- ),- ),- ),- ),- );- }-}diff --git a/desktop/lib/widgets/harness_entry_actions.dart b/desktop/lib/widgets/harness_entry_actions.dartdeleted file mode 100644index 3a68f100c..000000000--- a/desktop/lib/widgets/harness_entry_actions.dart+++ /dev/null@@ -1,104 +0,0 @@-import 'package:flutter/material.dart';-import 'package:flutter/services.dart';--import '../shared/theme/app_theme.dart' as grid;-import '../shortcuts/app_keymap.dart';-import '../shortcuts/keymap.dart';-import 'agent_action_icons.dart';--/// Separate Open Agent and New Agent actions on the Harness start page.-class HarnessEntryActions extends StatelessWidget {- const HarnessEntryActions({- super.key,- required this.onOpen,- required this.onNew,- required this.openKey,- required this.newKey,- this.filledOpen = false,- });- final VoidCallback? onOpen, onNew;- final Key openKey, newKey;- final bool filledOpen;-- Widget _keyboardAction(- BuildContext context,- VoidCallback? onPressed,- Widget child,- ) {- final region = KeymapRegion.of(context);- if (region?.contextKind == KeymapContext.picker) {- child = KeymapRegion(- contextKind: KeymapContext.picker,- actions: {- ...?region?.actions,- 'picker.accept': () => onPressed?.call(),- 'picker.add_here': () => onPressed?.call(),- },- child: child,- );- }- return CallbackShortcuts(- bindings: {- const SingleActivator(LogicalKeyboardKey.enter): () =>- onPressed?.call(),- const SingleActivator(LogicalKeyboardKey.numpadEnter): () =>- onPressed?.call(),- },- child: child,- );- }-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- const size = Size(140, 48);- const padding = EdgeInsets.symmetric(horizontal: 20);- return Wrap(- spacing: 12,- runSpacing: 12,- children: [- _keyboardAction(- context,- onOpen,- OutlinedButton.icon(- key: openKey,- onPressed: onOpen,- style: OutlinedButton.styleFrom(- enabledMouseCursor: SystemMouseCursors.click,- minimumSize: size,- padding: padding,- backgroundColor: filledOpen- ? grid.AppPalette.swarmSearchSurface- : Colors.transparent,- foregroundColor: Colors.white,- side: filledOpen- ? BorderSide.none- : const BorderSide(color: Colors.white24),- shape: const StadiumBorder(),- ),- icon: const Icon(AgentActionIcons.open, size: 18),- label: const Text('Open Harness'),- ),- ),- _keyboardAction(- context,- onNew,- FilledButton.icon(- key: newKey,- onPressed: onNew,- icon: const Icon(AgentActionIcons.create, size: 18),- label: const Text('New Harness'),- style: FilledButton.styleFrom(- enabledMouseCursor: SystemMouseCursors.click,- minimumSize: size,- padding: padding,- backgroundColor: grid.AppPalette.swarmAccent,- foregroundColor: grid.AppPalette.swarmTabBar,- shape: const StadiumBorder(),- ),- ),- ),- ],- );- }-}diff --git a/desktop/lib/widgets/machine_rail.dart b/desktop/lib/widgets/machine_rail.dartdeleted file mode 100644index 4595f70e8..000000000--- a/desktop/lib/widgets/machine_rail.dart+++ /dev/null@@ -1,1827 +0,0 @@-import 'dart:async';--import 'package:flutter/material.dart';-import 'package:flutter/services.dart';-import 'package:lucide_icons_flutter/lucide_icons.dart';-import 'package:harness/terminal/terminal_text.dart';--import 'window_chrome.dart';--import '../core/models.dart';-import '../shared/layouts/widgets/sidebar_item.dart';-import '../shared/layouts/widgets/sidebar_timeline.dart';-import '../shared/theme/app_theme.dart' as grid;-import '../shared/widgets/app_icon_button.dart';-import '../shared/widgets/app_menu.dart';-import '../shared/widgets/skeleton.dart';-import '../shortcuts/app_shortcuts.dart';-import '../state/app_state.dart';-import 'agent_drag.dart';-import 'machine_actions.dart';-import 'delete_agent_dialog.dart';-import 'fork_agent_dialog.dart';-import 'restart_agent_action.dart';-import 'rename_agent_dialog.dart';-import 'account_footer.dart';-import 'device_row.dart';-import 'engine_identity.dart';-import 'link_machine_dialog.dart';-import 'new_agent_dialog.dart';-import 'machines_manager.dart';--/// The machine caption's type.-///-/// A function rather than a constant so its skeleton can borrow the exact-/// metrics: `skeleton_sites_test.dart` measures a placeholder machine row-/// against a real one, and a caption whose type drifts from its placeholder-/// makes the rail resize the moment the list lands.-TextStyle _machineCaptionStyle(Color color) => terminalTextStyle(- color: color,- fontWeight: grid.AppFont.semibold,- letterSpacing: 0.3,-);--/// The caption's own box: 18px mark at the rail's gutter, 22px of line, and-/// symmetric padding so the mark lands on [SidebarTimeline]'s trunk break.-/// Shared with the placeholder for the same reason as the type above.-const EdgeInsets _machineCaptionPadding = EdgeInsets.fromLTRB(10, 7, 6, 7);-const double _machineCaptionHeight = 22;-const double _machineMarkSize = 18;--class MachineRail extends StatefulWidget {- final AppNotifier notifier;-- /// Fold the rail away. Null hides the control — a button that collapses- /// nothing is worse than no button.- final VoidCallback? onCollapse;-- const MachineRail({super.key, required this.notifier, this.onCollapse});-- @override- State<MachineRail> createState() => _MachineRailState();-}--class _MachineRailState extends State<MachineRail> {- /// The node that holds the keyboard while the cursor is in the rail.- ///- /// A real Flutter focus node rather than a flag the rail reads, because focus- /// is EXCLUSIVE: taking it here is what makes the terminal let go, and that is- /// the whole reason plain `j` and `k` can mean something in this column while- /// they are ordinary characters two pixels to the right.- final FocusNode _railFocus = FocusNode(debugLabel: 'rail');-- @override- void dispose() {- _railFocus.dispose();- super.dispose();- }-- /// The keys the rail answers while it holds them.- ///- /// PLAIN LETTERS, no ⌘. Everywhere else in this app a bare key belongs to the- /// terminal (see app_shortcuts.dart's header), and that rule is exactly why it- /// can be broken here: the rail is not a pty, and while it has focus no shell- /// is waiting for anything. This is the one surface where vim's own keys can- /// be vim's own keys.- KeyEventResult _onRailKey(FocusNode node, KeyEvent event) {- if (event is! KeyDownEvent && event is! KeyRepeatEvent) {- return KeyEventResult.ignored;- }- final notifier = widget.notifier;- final key = event.logicalKey;-- // BARE KEYS ONLY. `h` and `l` mean two different things two pixels apart:- // plain, they are the rail's own — close this machine, open this agent —- // and with ⌘ they are the window's ring, which seats the rail between the- // last tile and the first. Without this guard the rail swallows ⌘h and the- // ring has no way out of the sidebar.- if (HardwareKeyboard.instance.isMetaPressed ||- HardwareKeyboard.instance.isControlPressed ||- HardwareKeyboard.instance.isAltPressed) {- return KeyEventResult.ignored;- }-- if (key == LogicalKeyboardKey.keyJ || key == LogicalKeyboardKey.arrowDown) {- notifier.moveRailCursor(1);- return KeyEventResult.handled;- }- if (key == LogicalKeyboardKey.keyK || key == LogicalKeyboardKey.arrowUp) {- notifier.moveRailCursor(-1);- return KeyEventResult.handled;- }- if (key == LogicalKeyboardKey.keyH || key == LogicalKeyboardKey.arrowLeft) {- notifier.railCollapseOrExit();- return KeyEventResult.handled;- }- if (key == LogicalKeyboardKey.keyL ||- key == LogicalKeyboardKey.arrowRight ||- key == LogicalKeyboardKey.enter ||- key == LogicalKeyboardKey.numpadEnter ||- key == LogicalKeyboardKey.space) {- unawaited(notifier.activateRailRow());- return KeyEventResult.handled;- }- if (key == LogicalKeyboardKey.escape) {- notifier.unfocusRail();- return KeyEventResult.handled;- }- // Everything else — including ⌘ chords — goes up to the app's own bindings,- // so ⌘P and ⌘N still work with the cursor parked in here.- return KeyEventResult.ignored;- }-- /// The wordmark strip. The same 46px the terminal panes draw, so the- /// wordmark and a pane's title sit on one baseline.- static const _headerHeight = 46.0;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- // No fill here. The fold above draws one surface under whichever rail is- // showing: during the crossfade both are mounted, and two translucent fills- // stacked over the window would darken the whole rail for the length of the- // animation.- return ListenableBuilder(- listenable: widget.notifier,- builder: (context, _) {- // Requested during the build that turns it on, not from the handler that- // set the flag: the node has to be mounted to take focus, and on the- // first ⌘h of a session the rail may have only just been laid out.- if (widget.notifier.railFocused && !_railFocus.hasFocus) {- WidgetsBinding.instance.addPostFrameCallback((_) {- if (mounted && widget.notifier.railFocused) {- _railFocus.requestFocus();- }- });- }- // Keep the current computer immediately reachable while preserving- // the backend order for every other machine.- final machines = <Machine>[- ...widget.notifier.machines.where(- (machine) =>- widget.notifier.stateOf(machine.machineId)?.isLocalMachine ==- true,- ),- ...widget.notifier.machines.where(- (machine) =>- widget.notifier.stateOf(machine.machineId)?.isLocalMachine !=- true,- ),- ];- return Focus(- focusNode: _railFocus,- onKeyEvent: _onRailKey,- // Losing focus to a click in a terminal must put the cursor away too,- // or the rail keeps a highlight that no key will move.- onFocusChange: (has) {- if (!has && widget.notifier.railFocused) {- widget.notifier.unfocusRail();- }- },- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- // The rail's head is a TOOLBAR, and it is built to look like one:- // its own surface and its own bottom edge.- //- // It used to be a wordmark and three glyphs on the same fill as the- // list, with no edge under them — so "Harness" read as the first- // entry in the rail rather than as the thing above the entries, and- // the three buttons bunched into the right corner 2px apart.- //- // [grid.AppSurface.recess] over the rail's own fill, not a colour- // of its own: it is an overlay, so it separates in BOTH themes —- // lighter than the charcoal rail in dark, a touch greyer than the- // near-white one in light, the way a Finder toolbar sits over its- // list.- DecoratedBox(- decoration: BoxDecoration(- color: grid.AppSurface.recess,- border: Border(- bottom: BorderSide(color: grid.AppPalette.divider),- ),- ),- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- // Still the window's drag handle — the title bar is hidden,- // see configureDesktopWindow. `WindowDragArea` rather than- // window_manager's own `DragToMoveArea`: main introduced one- // for the whole app when `HarnessTopBar` took over the- // traffic-light row, and two ways to drag the same window is- // one too many.- //- // No top inset for the traffic lights here — that bar sits- // above the window now, and an inset would push the wordmark- // down twice.- WindowDragArea(- child: SizedBox(- height: _headerHeight,- child: Padding(- // 16 left against 8 right, so the wordmark's stem and- // the last button's CENTRE both land 20px from their- // own edge. Matching the two paddings instead would- // push the buttons visibly further in than the text.- padding: const EdgeInsets.fromLTRB(16, 0, 8, 0),- child: Row(- children: [- Expanded(- child: Text(- 'Harness',- style: terminalTextStyle(- color: grid.AppPalette.textPrimary,- // Semibold, not bold. A wordmark at this size- // already out-ranks everything below it.- fontWeight: grid.AppFont.semibold,- letterSpacing: -0.1,- ),- ),- ),- AppIconButton(- icon: LucideIcons.refreshCw300,- size: 17,- // A step up from the default resting ink. At- // textSecondary these two hairline glyphs read as- // half-loaded next to a semibold wordmark.- color: grid.AppPalette.textPrimary.withValues(- alpha: 0.72,- ),- tooltip: withShortcutHint(- 'Reload machines',- ShortcutAction.reload,- ),- // The glyph turns for as long as the reload runs- // and the button refuses presses meanwhile — a- // reload is a REST call plus an `agents_list` per- // open machine, long enough that a button which- // just sat there read as not having registered- // the click.- spinning: widget.notifier.machinesRefreshing,- onPressed: () =>- unawaited(widget.notifier.retryMachines()),- ),- if (widget.onCollapse != null) ...[- // 6, not 2. Two glyphs a hair apart read as one- // smudge; this is the smallest gap that still- // says "two buttons".- const SizedBox(width: 6),- AppIconButton(- icon: LucideIcons.panelLeft300,- size: 17,- color: grid.AppPalette.textPrimary.withValues(- alpha: 0.72,- ),- tooltip: withShortcutHint(- 'Collapse sidebar',- ShortcutAction.toggleRail,- swarmMode: false,- ),- onPressed: widget.onCollapse!,- ),- ],- ],- ),- ),- ),- ),- ],- ),- ),- // Says out loud that these rows are a cached copy. Without it a backend outage looks- // identical to a healthy list, and the only clue is machines whose state never changes.- if (widget.notifier.machinesAreStale && machines.isNotEmpty)- Padding(- padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),- child: Row(- children: [- Icon(- LucideIcons.cloudOff300,- size: 13,- color: grid.AppPalette.textSecondary,- ),- const SizedBox(width: 6),- Expanded(- child: Text(- 'Offline copy — backend unreachable',- style: terminalTextStyle(- color: grid.AppPalette.textSecondary,- ),- ),- ),- ],- ),- ),- Expanded(- child: machines.isEmpty- // Two kinds of empty, and they must not look the same: the- // list has not answered yet, or it answered with nothing.- ? widget.notifier.machinesLoading- ? const _MachineListSkeleton(- key: ValueKey('machines-loading'),- )- : Center(- child: Text(- 'no remote machines',- style: terminalTextStyle(- color: grid.AppPalette.textFaint,- ),- ),- )- : ListView.builder(- itemCount: machines.length,- itemBuilder: (context, index) => _MachineNode(- notifier: widget.notifier,- machine: machines[index],- isFirst: index == 0,- ),- ),- ),- // The dial's row stands on the rail's floor, above the account. It is- // not a setting, it is a thing on the desk — present, absent, or on its- // way — and the one place someone without one is told where to get one.- DeviceRow(notifier: widget.notifier),- AccountFooter(notifier: widget.notifier),- ],- ),- );- },- );- }-}--/// A machine's actions, revealed on hover: `⋯` first, then `+` to its right.-///-/// Both hide at rest, so a rail full of machines is a list of hostnames rather-/// than a column of buttons — and the hostname, which is the part you read, has-/// the whole row until you reach for something.-///-/// The `+` sits at the far right, nearest the rail's edge and furthest from the-/// name: it is the one you press, so it gets the end of the row where the hand-/// is already travelling, with the housekeeping menu tucked behind it.-///-/// Two things move at once, deliberately on one curve. The pair FADES up and-/// slides in a few pixels from the right, so it reads as arriving from off the-/// row's edge rather than blinking into place. And the row makes room as it-/// comes: [Align.widthFactor] runs 0 → 1, so the hostname shortens under the-/// buttons instead of the buttons landing on a name that never moved.-///-/// A slot held permanently open would avoid that reflow, but it costs every row-/// in the rail ~50px of nothing for the sake of the one row under the pointer —-/// and the hostname is exactly the thing that was running out of width.-class _CaptionActions extends StatelessWidget {- const _CaptionActions({- required this.shown,- required this.onNewAgent,- required this.menu,- });-- /// Whether the pointer is on the row — or the menu it opened is still up,- /// which is the case a plain hover test gets wrong: the pointer has left the- /// row for the panel, and the button the panel hangs off must not vanish- /// under it.- final bool shown;-- final VoidCallback onNewAgent;-- /// The ⋯ and its panel, built by the caller because the menu's controller and- /// its open/close state belong to the row, not to this animation.- final Widget menu;-- /// How far the pair drifts in from the right. A hint, not a journey: enough- /// to read as movement, short enough that the two buttons never separate.- static const double _drift = 10;-- @override- Widget build(BuildContext context) {- TerminalFontScope.watch(context);- return TweenAnimationBuilder<double>(- // No `begin`: a row built already hovered is settled, not animating in.- tween: Tween(end: shown ? 1.0 : 0.0),- duration: grid.AppMotion.hover,- curve: grid.AppMotion.curve,- builder: (context, t, child) => ClipRect(- child: Align(- // Pinned right, so the pair grows out of the row's edge rather than- // sliding along it — and clipped, so nothing is clickable while it is- // still folded away.- alignment: Alignment.centerRight,- widthFactor: t,- child: Opacity(- opacity: t,- child: Transform.translate(- offset: Offset((1 - t) * _drift, 0),- child: child,- ),- ),- ),- ),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- menu,- const SizedBox(width: 2),- AppIconButton(- icon: LucideIcons.plus300,- size: 16,- tooltip: 'New Harness here…',- onPressed: onNewAgent,- ),- ],- ),- );- }-}--class _MachineNode extends StatefulWidget {- /// Whether the guide line arrives from a row above. False on the first- /// machine, where a line dangling up towards the Create Agent button would point- /// at nothing.- final bool isFirst;-- final AppNotifier notifier;- final Machine machine;-- const _MachineNode({- required this.notifier,- required this.machine,- required this.isFirst,- });-- @override- State<_MachineNode> createState() => _MachineNodeState();-}--class _MachineNodeState extends State<_MachineNode> {- final MenuController _machineMenu = MenuController();- bool _menuOpen = false;- bool _hovered = false;-- AppNotifier get notifier => widget.notifier;- Machine get machine => widget.machine;-- Future<void> _showRenameDialog() => showMachineRenameDialog(- context,- notifier,- machine.machineId,- machine.displayName,- );-- Future<void> _confirmDeleteMachine() => confirmDeleteMachine(- context,- notifier,- machineId: machine.machineId,- displayName: machine.displayName,- );-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- final expanded = notifier.expandedMachines.contains(machine.machineId);- final state = notifier.stateOf(machine.machineId)!;- // The relay's local WS session can stay `connected` for a beat after the backend has already- // reported the underlying node offline (two independently-polled signals) — never show green here- // while the offline-guide panel is (or is about to be) blocking the same machine.- final connectionColor = state.nodeOnline == false- ? grid.AppPalette.textFaint- : state.needsLink- // Unlinked, our socket never reaches this machine: NO_PEER_LINK is the- // local CLI's own peer table saying no, before anything is dialled, and- // the link-retry loop then bounces connecting/disconnected every few- // seconds — none of which is a fact about the other computer. Only the- // REST status is, so green needs an explicit `true` from it; unknown- // stays grey rather than promising a machine that may be off. Offline,- // above, still wins.- ? (state.nodeOnline == true- ? grid.AppPalette.online- : grid.AppPalette.textFaint)- : switch (state.connectionStatus) {- ConnectionStatus.connected => grid.AppPalette.online,- ConnectionStatus.connecting ||- ConnectionStatus.reconnecting => grid.AppPalette.warn,- ConnectionStatus.disconnected => grid.AppPalette.textFaint,- };- // One clock for the whole node, and it has to be one: the trunk under the- // caption, the agent count beside the name and the rows themselves all- // change at the moment the machine opens. Run on three timers they arrive- // in three stages 30ms apart and the row reads as sluggish even though- // nothing is slow.- //- // No `begin` on the tween: a rail that mounts with this machine already- // open is *settled*, not unfolding itself while the user watches.- //- // Leaving is the shorter half — the user has already decided to close it,- // and waiting on the rows to go is what makes a fold feel heavy.- return TweenAnimationBuilder<double>(- tween: Tween(end: expanded ? 1.0 : 0.0),- duration: MediaQuery.disableAnimationsOf(context)- ? Duration.zero- : expanded- ? grid.AppMotion.fold- : grid.AppMotion.swap,- curve: grid.AppMotion.curve,- // Hoisted so the rows are not rebuilt on every frame of the fold. Built- // here but only *mounted* below while `fold > 0`, so a closed machine- // costs nothing.- child: _AgentTree(notifier: notifier, state: state),- builder: (context, fold, tree) =>- _node(context, fold, tree!, state, connectionColor),- );- }-- Widget _node(- BuildContext context,- double fold,- Widget tree,- MachineState state,- Color connectionColor,- ) {- return Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- // The machine is a CAPTION over its agents, not a row among them.- //- // Quiet micro-type is what makes that read at a glance: the eye sorts- // the rail into "things I open" and "labels saying where they live"- // without having to decode the indent alone. It used to be a full- // SidebarItem, which gave a machine exactly the weight, the height and- // the hover of the agents under it.- //- // Not upper-cased, though the type is sized for it: a hostname is 26- // characters of shouting by the time it reaches the ellipsis, and the- // case of `MacBooks-MacBook-Pro.local` is information.- //- // It is still a NODE on the guide line, and that is why the glyph sits- // on [SidebarTimeline]'s trunk with nothing in front of it: the line- // runs THROUGH the mark it breaks around, so anything to its left- // pushes the mark off the line. Which is also why there is no chevron —- // the trunk carrying on down into the agents already says the machine- // is open, and says it better than a glyph pointing at itself.- SidebarTimeline(- role: SidebarTimelineRole.node,- above: !widget.isFirst,- // While the rows are on their way out too: a trunk that vanished at- // frame one would leave them hanging off nothing.- below: fold > 0 && state.agents.isNotEmpty,- child: MouseRegion(- onEnter: (_) => setState(() => _hovered = true),- onExit: (_) => setState(() => _hovered = false),- child: GestureDetector(- behavior: HitTestBehavior.translucent,- // Same menu the ⋯ opens — one shape for one set of actions.- onSecondaryTap: _machineMenu.open,- onTap: () => notifier.toggleExpand(machine.machineId),- child: _RailCursor(- on:- notifier.railFocused &&- notifier.railRowAt(notifier.railCursor) ==- RailRow(machineId: machine.machineId),- child: Padding(- key: ValueKey('machine-row-${machine.machineId}'),- // Symmetric top and bottom on purpose: [TimelineGuide] breaks- // the trunk around the middle of the band it is given, so an- // off-centre glyph would sit beside the gap left for it.- padding: _machineCaptionPadding,- child: SizedBox(- height: _machineCaptionHeight,- child: Row(- children: [- // 18px at the rail's 10px gutter puts this glyph's centre- // at x=19, which is exactly where SidebarTimeline runs- // its trunk. Change either and they part company.- Semantics(- label: state.isLocalMachine- ? 'This computer'- : 'Remote machine',- child: SizedBox(- width: _machineMarkSize,- height: _machineMarkSize,- child: Icon(- state.isLocalMachine- ? LucideIcons.laptopMinimal300- : LucideIcons.network300,- key: const ValueKey('machine-connection-icon'),- size: _machineMarkSize,- color: connectionColor,- ),- ),- ),- // The same 10px SidebarItem puts between its own icon and- // label, so the caption and the agents under it start in- // one column.- const SizedBox(width: 10),- Expanded(- child: Text(- machine.displayName,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: _machineCaptionStyle(- _hovered- ? grid.AppPalette.textSecondary- : grid.AppPalette.textFaint,- ),- ),- ),- // A computer that is not answering, said once, where the- // computer is named. It replaces two lines of red further- // down: a machine being off is a STATE, and red is for- // something that went wrong. Mutually exclusive with the- // link affordance below: a daemon that is not running- // cannot shake hands, so offline still wins (see- // _AgentTree's own "OFFLINE WINS").- if (state.nodeOnline == false)- const _OfflineWord()- else ...[- // Presence and link state are two independent slots,- // the same split the native Machines menu uses.- // "Online" is said for every reachable machine, so an- // unlinked-but-running one reads "Online" AND still- // offers the link beside it — the link state no longer- // masks the fact that the computer is up. Offline,- // above, still wins (a daemon that is not running- // cannot shake hands — see "OFFLINE WINS").- if (state.nodeOnline == true) const _OnlineWord(),- if (state.needsLink)- // The one click that fixes it, ALWAYS visible rather- // than hidden behind hover like _CaptionActions: that- // was the whole reason an unlinked-but-alive machine- // read as unreachable. Same gate as _LinkMachineRow.- Padding(- padding: const EdgeInsets.only(left: 6),- child: AppIconButton(- key: const ValueKey('machine-link-affordance'),- icon: LucideIcons.link2300,- size: 13,- color: grid.AppPalette.accentOnSurface,- hoverColor: grid.AppPalette.accentOnSurface,- tooltip: 'Link this machine…',- onPressed: () => notifier.selectMachineForSetup(- machine.machineId,- ),- ),- ),- ],- // How many agents are inside something you have closed.- // Only when closed: with the list open you can count- // them, and a number beside a list you can see is noise.- if (fold < 1 && state.agents.isNotEmpty)- // Width as well as opacity, so the name beside it- // lengthens into the space the number gives up rather- // than snapping wider the instant the fold starts.- Align(- alignment: Alignment.centerLeft,- widthFactor: 1 - fold,- child: Opacity(- opacity: 1 - fold,- child: Padding(- padding: const EdgeInsets.only(left: 6),- child: Text(- '${state.agents.length}',- style: terminalTextStyle(- color: grid.AppPalette.textFaint,- fontFeatures: const [- FontFeature.tabularFigures(),- ],- ),- ),- ),- ),- ),- // Both of this machine's actions, on this machine's own- // row. The `+` is what the rail's big Create Agent button- // used to be: that button had to guess which machine you- // meant, and this one cannot be wrong about it.- if (!machine.isShared)- _CaptionActions(- shown: _hovered || _menuOpen,- onNewAgent: () => showNewAgentDialog(- context,- notifier,- machine.machineId,- source: 'machine_row',- ),- menu: MenuAnchor(- controller: _machineMenu,- onOpen: () => setState(() => _menuOpen = true),- onClose: () => setState(() => _menuOpen = false),- menuChildren: [- // Where the empty state's refresh went. It used to hang off a status line- // that only existed while a machine had no agents, so the one machine you- // could not reload was a machine whose list had gone stale WITH agents in- // it. A per-machine action belongs with the machine's other ones.- AppMenuItem(- icon: LucideIcons.refreshCw300,- label: 'Reload agents',- onPressed: () {- _machineMenu.close();- notifier.reloadMachineData(- machine.machineId,- );- },- ),- AppMenuItem(- icon: LucideIcons.pencil300,- label: 'Rename Machine',- onPressed: () {- _machineMenu.close();- _showRenameDialog();- },- ),- if (state.isLocalMachine) ...[- const AppMenuDivider(),- AppMenuItem(- icon: LucideIcons.keyRound300,- label: 'Set remote password',- onPressed: () {- _machineMenu.close();- unawaited(- showLinkMachineDialog(- context,- notifier,- ),- );- },- ),- ],- if (!state.isLocalMachine) ...[- const AppMenuDivider(),- AppMenuItem(- icon: LucideIcons.link2300,- label: 'Remote into this machine…',- onPressed: () {- _machineMenu.close();- notifier.selectMachineForSetup(- machine.machineId,- );- },- ),- const AppMenuDivider(),- AppMenuItem(- icon: LucideIcons.trash2300,- label: 'Delete machine',- danger: true,- onPressed: () {- _machineMenu.close();- _confirmDeleteMachine();- },- ),- ],- ],- builder: (context, controller, child) =>- AppIconButton(- icon: LucideIcons.ellipsis300,- size: 16,- tooltip: 'Machine options',- onPressed: () => controller.isOpen- ? controller.close()- : controller.open(),- ),- ),- ),- ],- ),- ),- ),- ),- ),- ),- ),- if (fold > 0)- // Clipped, not re-laid out. The rows keep their full height and the- // box in front of them grows — laying the list out again at every- // height in between would be a dozen frames of rows reflowing, and it- // would look like it.- ClipRect(- child: Align(- alignment: Alignment.topLeft,- heightFactor: fold,- // `Align` hands its child loose constraints, which would drop the- // stretch this Column gives everything else and let the rows- // shrink-wrap mid-fold. This puts the width back.- child: SizedBox(width: double.infinity, child: tree),- ),- ),- ],- );- }-}--class _AgentTree extends StatelessWidget {- final AppNotifier notifier;- final MachineState state;-- const _AgentTree({required this.notifier, required this.state});-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- if (state.agents.isEmpty) {- switch (state.agentLoadStatus) {- case AgentLoadStatus.idle:- return _AgentStatusRow(- icon: Icons.sync,- label: state.connectionStatus == ConnectionStatus.connected- ? 'preparing harness list…'- : 'connecting…',- );- case AgentLoadStatus.needsLink:- // OFFLINE WINS. Linking is a PAKE handshake with the daemon on the- // other computer, and a daemon that is not running cannot shake- // hands — so a machine that is both unlinked and offline gets the- // offline note, not an invitation to do the impossible. The retry- // poll that already runs for an unlinked machine turns this into the- // link row by itself once the computer comes back.- if (state.nodeOnline == false) {- return _MachineOfflineNote(state: state, linkPending: true);- }- return _LinkMachineRow(notifier: notifier, state: state);- case AgentLoadStatus.loading:- // Rows, not a sentence: "loading agents…" is one line tall, so- // everything under the machine dropped when the real rows arrived.- return const _AgentRowsSkeleton(key: ValueKey('agents-loading'));- case AgentLoadStatus.error:- // A machine with no agents AND no connection fails HERE, not on the- // branch below — that one only runs once some agents are known. This- // is the path the rail actually took for an offline computer, and the- // reason the red block outlived the first attempt to replace it.- if (state.nodeOnline == false) {- return _MachineOfflineNote(state: state);- }- return _AgentLoadError(notifier: notifier, state: state);- case AgentLoadStatus.loaded:- return _EmptyAgents(notifier: notifier, state: state);- }- }-- final byParent = <String?, List<Agent>>{};- final ids = state.agents.map((agent) => agent.id).toSet();- for (final agent in state.agents) {- final parent = ids.contains(agent.parentAgentId)- ? agent.parentAgentId- : null;- byParent.putIfAbsent(parent, () => []).add(agent);- }- final visible = state.agents.map((agent) => agent.id).toSet();-- final rows = <Widget>[- for (final root in byParent[null] ?? const <Agent>[])- ..._rows(root, byParent, visible, 0, <String>{}),- // …and the invitation, last, as a row of the same list. Adding an agent to a machine that already- // has some was reachable only through a `+` revealed on hover of the machine's caption — a control- // nobody finds who does not already know it. Put where a new row would actually appear, it needs no- // discovering. It joins `rows` rather than being appended after the loop so the guide's trunk runs- // down to it and closes there, exactly as it would on a real last agent.- if (!state.machine.isShared)- _NewAgentRow(- notifier: notifier,- machineId: state.machine.machineId,- source: 'rail_tail',- ),- ];-- return Column(- children: [- if (state.agentsRefreshing) const LinearProgressIndicator(minHeight: 1),- // The guide arm reaches out to each agent from the trunk running down- // through its machine's mark. `below` closes the line on the last row:- // a trunk carrying on past the end would point at whatever section- // happens to follow, which is not part of this tree.- for (var i = 0; i < rows.length; i++)- SidebarTimeline(- role: SidebarTimelineRole.branch,- below: i < rows.length - 1,- child: rows[i],- ),- // Only while the machine can answer — see the empty-tree branch. An- // offline machine already shows its note below.- if (state.agentLoadStatus == AgentLoadStatus.needsLink &&- state.nodeOnline != false)- _LinkMachineRow(notifier: notifier, state: state),- // OFFLINE IS NOT AN ERROR, so it does not get the error's treatment.- //- // The red row told an app user to "run harness start on that machine" —- // an instruction for a terminal, given to somebody who opened a window,- // about a computer they may not be sitting at. The chip on the row above- // already says the machine is off; this says why its agents are missing,- // in the rail's ordinary grey, once.- if (state.nodeOnline == false)- _MachineOfflineNote(state: state)- else if (state.agentsLoadError != null)- _AgentLoadError(notifier: notifier, state: state),- if (state.terminalCapabilityLoaded &&- !state.terminalCapabilityAvailable)- Padding(- padding: const EdgeInsets.fromLTRB(38, 2, 12, 8),- child: Text(- state.terminalCapabilityError ?? 'terminal unavailable',- style: terminalTextStyle(color: grid.AppPalette.dangerFill),- ),- ),- ],- );- }-- List<Widget> _rows(- Agent agent,- Map<String?, List<Agent>> byParent,- Set<String> visible,- int depth,- Set<String> ancestors,- ) {- if (ancestors.contains(agent.id)) return const [];- final children = byParent[agent.id] ?? const <Agent>[];- final descendantVisible = children.any(- (child) => visible.contains(child.id),- );- if (!visible.contains(agent.id) && !descendantVisible) return const [];- final nextAncestors = {...ancestors, agent.id};- return [- _AgentRow(- notifier: notifier,- state: state,- agent: agent,- depth: depth,- hasChildren: children.isNotEmpty,- ),- for (final child in children)- ..._rows(child, byParent, visible, depth + 1, nextAncestors),- ];- }-}--/// The keyboard's place in the rail, drawn as a rim rather than a fill.-///-/// A FILL would compete with `selected`, which the rail already spends on "this-/// agent is the one the window is looking at" — two different facts that are-/// true at different times, and shading both would make the column ambiguous in-/// exactly the state where it has to be clear: cursor on one row, selection on-/// another.-///-/// It also only ever shows while the rail HOLDS the keyboard. A cursor left-/// behind on a column nobody is driving is a highlight that no key will move,-/// which reads as the app having lost track of itself.-class _RailCursor extends StatelessWidget {- const _RailCursor({required this.on, required this.child});-- final bool on;- final Widget child;-- @override- Widget build(BuildContext context) {- if (!on) return child;- grid.AppTheme.watch(context);- return DecoratedBox(- decoration: BoxDecoration(- borderRadius: BorderRadius.circular(7),- border: Border.all(color: grid.AppPalette.accentOnSurface, width: 1),- ),- child: child,- );- }-}--class _AgentRow extends StatefulWidget {- final AppNotifier notifier;- final MachineState state;- final Agent agent;- final int depth;- final bool hasChildren;-- const _AgentRow({- required this.notifier,- required this.state,- required this.agent,- required this.depth,- required this.hasChildren,- });-- @override- State<_AgentRow> createState() => _AgentRowState();-}--class _AgentRowState extends State<_AgentRow> {- final MenuController _agentMenu = MenuController();- bool _menuOpen = false;-- AppNotifier get notifier => widget.notifier;- MachineState get state => widget.state;- Agent get agent => widget.agent;- int get depth => widget.depth;- bool get hasChildren => widget.hasChildren;-- /// The row's own way into the shared dialog — see rename_agent_dialog.dart.- Future<void> _showRenameDialog() => showAgentRenameDialog(- context,- notifier,- state.machine.machineId,- agent.id,- agent.displayName,- );-- /// The row's way into the shared confirmation — see delete_agent_dialog.dart.- Future<void> _confirmDelete() => confirmDeleteAgent(- context,- notifier,- state.machine.machineId,- agent.id,- agent.displayName,- engine: agent.engine,- );-- Future<void> _restartAgent() =>- restartHarness(context, notifier, state.machine.machineId, agent.id);-- Future<void> _forkAgent() => forkHarness(- context,- notifier,- state.machine.machineId,- agent.id,- agent.displayName,- engine: agent.engine,- );-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- final machineId = state.machine.machineId;- // Two different facts, and the grid is why they had to separate. "Selected"- // used to be the only terminal there was. Now a row can be on screen in a- // tile the keyboard is not in — still worth showing, but not as the current- // one, or four rows would claim to be current at once.- final focusedHere =- notifier.focusedPane?.machineId == machineId &&- notifier.focusedPane?.agentId == agent.id;- final inAnotherPane =- !focusedHere && notifier.isAgentInPane(machineId, agent.id);- final selected = focusedHere;- // Cached agents remain selectable while the adapter is offline so the- // user gets the actionable `harness login` guide instead of a dead row.- final offlineSelectable =- state.nodeOnline == false && agent.terminalAvailable;- final enabled =- (state.machine.isShared && agent.terminalAvailable) ||- offlineSelectable ||- // `connected` never arrives until the local CLI has finished terminating E2EE for this- // machine (or confirmed none is needed, for its own) — no separate readiness check left.- state.connectionStatus == ConnectionStatus.connected &&- state.terminalCapabilityAvailable &&- agent.terminalAvailable;- // A cached agent under an offline machine stays clickable (`offlineSelectable`, above) so the- // login guide is reachable — but it should still LOOK offline, not bright/normal. Decouple the- // visual state from `enabled` (which only governs tap-ability) so the row dims whenever the- // machine itself is offline, regardless of whether it's still selectable.- final visuallyEnabled = enabled && state.nodeOnline != false;- final reason = !agent.terminalAvailable- ? agent.terminalUnavailableReason- : offlineSelectable- ? 'Harness is offline — run harness login'- : !state.terminalCapabilityAvailable- ? state.terminalCapabilityError- : null;- final identity = agentIdentity(agent);- final processing = state.processingAgentIds.contains(agent.id);- // Right-click wraps the row rather than fighting it: SidebarItem owns the- // primary tap and the press/hover states that go with it, and exposes no- // secondary gesture.- final row = GestureDetector(- behavior: HitTestBehavior.translucent,- // Right-click opens the SAME menu the ⋯ does. Two menus carrying the same- // two actions in two different shapes is the drift this avoids; the only- // thing lost is opening at the cursor rather than at the button.- onSecondaryTap: state.machine.isShared ? null : _agentMenu.open,- child: Padding(- // 28px is where a nested row's box starts, which is what the guide's- // arm is drawn to reach (trunk at 19, arm 7 long, stopping 2px short of- // the row's own hover fill). Without it the agents line up under the- // machine's own mark and the arm points at nothing. Sub-agents step in- // further from there.- padding: EdgeInsets.only(left: 28 + depth * 14.0),- child: _RailCursor(- on:- notifier.railFocused &&- notifier.railRowAt(notifier.railCursor) ==- RailRow(- machineId: state.machine.machineId,- agentId: agent.id,- ),- child: SidebarItem(- label: agent.displayName,- selected: selected,- enabled: enabled,- dimmed: !visuallyEnabled,- // ⌘-click opens a NEW tile, the same meaning it has on a link in- // every browser. A plain click stays navigation — it replaces the- // focused tile — because that rule is what keeps four glances at the- // rail from becoming four terminals. But until this existed, ADDING a- // tile was only possible by dragging a row onto the grid, so the- // ceiling of nine was unreachable for anyone who did not know the- // drag: a cap nobody can climb to is the same as no cap being raised.- onTap: () {- final machineId = state.machine.machineId;- if (HardwareKeyboard.instance.isMetaPressed &&- notifier.canAddPane &&- notifier.paneOfAgent(machineId, agent.id) == null) {- unawaited(- notifier.assignAgentToPane(null, machineId, agent.id),- );- return;- }- unawaited(notifier.selectAgent(machineId, agent.id));- },- // The same "Edit name" the row's own menu opens — a double click is- // just the shorter way to it, and the place a hand reaches first.- onDoubleTap: notifier.stateOf(machineId)?.machine.isShared == true- ? null- : _showRenameDialog,-- // No tooltip on a row that works. "Claude engine" only repeated what- // the mark beside it already says, and it followed the pointer down- // the whole list. A row that CANNOT be used keeps one, because then- // it carries the reason — which is the only thing here the row- // itself cannot show.- tooltip: enabled ? null : (reason ?? 'machine not ready'),- // The engine's mark in a well, which is what carries the row now- // that the guide line is gone. A bare 16px logo floating at the head- // of a flat list left the column no left edge to sit on; the well is- // a translucent overlay (see [grid.AppSurface.wellFill]) so it keeps- // its edge on the hovered and the selected row too.- leading: Container(- width: 24,- height: 24,- alignment: Alignment.center,- decoration: BoxDecoration(- color: grid.AppSurface.wellFill,- borderRadius: BorderRadius.circular(7),- ),- child: SizedBox(- width: 15,- height: 15,- child: Semantics(- label: '${identity.label} engine',- image: true,- child: EngineMark.forAgent(- agent,- enabled: visuallyEnabled,- size: 15,- ),- ),- ),- ),- // A turn in flight is a FACT about the row, so it goes in the badge- // slot, which never hides. Reaching for the row must not take away- // the only sign that it is busy.- badge: SizedBox(- width: 16,- height: 16,- child: AnimatedSwitcher(- duration: grid.AppMotion.hover,- child: processing- ? Padding(- key: const ValueKey('processing'),- padding: const EdgeInsets.all(2),- child: CircularProgressIndicator(- key: const ValueKey('agent-processing-indicator'),- strokeWidth: 1.6,- color: grid.AppPalette.online,- ),- )- : inAnotherPane- ? Tooltip(- key: const ValueKey('in-pane'),- message: 'Open in another pane',- child: Icon(- Icons.crop_square,- size: 12,- color: grid.AppPalette.textFaint,- ),- )- : const SizedBox.shrink(key: ValueKey('idle')),- ),- ),- // The ⋯ is an ACTION, so it arrives with the pointer — except while- // its own menu is open, where a button that vanished under the menu- // it opened would leave the panel pointing at nothing.- trailingAlwaysVisible: _menuOpen,- trailing: notifier.stateOf(machineId)?.machine.isShared == true- ? const Icon(Icons.visibility_outlined, size: 14)- : MenuAnchor(- controller: _agentMenu,- onOpen: () => setState(() => _menuOpen = true),- onClose: () => setState(() => _menuOpen = false),- menuChildren: [- AppMenuItem(- icon: LucideIcons.pencil300,- label: 'Edit name',- onPressed: () {- _agentMenu.close();- _showRenameDialog();- },- ),- const AppMenuDivider(),- AppMenuItem(- icon: LucideIcons.refreshCw300,- label: isTerminalEngine(agent.engine)- ? 'Restart Terminal'- : 'Restart Harness',- onPressed: () {- _agentMenu.close();- _restartAgent();- },- ),- if (agent.canFork)- AppMenuItem(- icon: LucideIcons.gitFork300,- label: 'Fork Harness',- onPressed: () {- _agentMenu.close();- _forkAgent();- },- ),- const AppMenuDivider(),- AppMenuItem(- icon: Icons.stop_rounded,- label: 'Stop Harness',- danger: true,- onPressed: () {- _agentMenu.close();- _confirmDelete();- },- ),- ],- builder: (context, controller, child) => AppIconButton(- icon: LucideIcons.ellipsis300,- size: 16,- onPressed: () => controller.isOpen- ? controller.close()- : controller.open(),- ),- ),- ),- ),- ),- );-- // A row that cannot be opened cannot be dropped either: dragging it would- // promise a tile that assignAgentToPane would then refuse to fill, and the- // grid would answer a deliberate gesture with nothing at all.- if (!enabled) return row;-- return Draggable<AgentDragRef>(- data: AgentDragRef(- machineId: machineId,- agentId: agent.id,- name: agent.displayName,- ),- // Horizontal only, and the rail is a scrolling list — that is the whole- // reason. An unrestricted Draggable competes with the list's own vertical- // drag, so trying to scroll past a row would pick the row up instead. The- // tiles are to the RIGHT of the rail, so the gesture that means "take- // this there" is horizontal anyway, and the two never contend.- affinity: Axis.horizontal,- dragAnchorStrategy: pointerDragAnchorStrategy,- onDragStarted: () => agentDrag.value = AgentDragRef(- machineId: machineId,- agentId: agent.id,- name: agent.displayName,- ),- onDragEnd: (_) => agentDrag.value = null,- onDraggableCanceled: (_, _) => agentDrag.value = null,- feedback: _DragChip(- name: agent.displayName,- engine: agent.identityEngine,- ),- // The row stays put and dims. Removing it would reflow the list under the- // pointer mid-drag, moving every other row out from under the place the- // hand had already aimed at.- childWhenDragging: Opacity(opacity: 0.4, child: row),- child: row,- );- }-}--/// What travels with the pointer: enough to recognise the row it came from,-/// small enough not to cover the tile being aimed at.-class _DragChip extends StatelessWidget {- const _DragChip({required this.name, required this.engine});-- final String name;- final String? engine;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- return Material(- color: Colors.transparent,- child: Container(- padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7),- decoration: BoxDecoration(- color: grid.AppPalette.windowBg,- border: Border.all(color: grid.AppPalette.divider),- borderRadius: BorderRadius.circular(6),- boxShadow: const [- BoxShadow(- color: Color(0x33000000),- blurRadius: 10,- offset: Offset(0, 3),- ),- ],- ),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- EngineMark(engine: engine, size: 14),- const SizedBox(width: 7),- Text(- name,- style: terminalTextStyle(- color: grid.AppPalette.textPrimary,- fontWeight: FontWeight.w600,- ),- ),- ],- ),- ),- );- }-}--/// The machine list before the backend has answered: three rows on the guide-/// line, at a [SidebarItem]'s exact geometry.-///-/// Three because the rail is a list pane and most accounts have a few-/// machines; a skeleton taller than the answer jumps up when it lands.-class _MachineListSkeleton extends StatelessWidget {- const _MachineListSkeleton({super.key});-- static const _labels = [0.56, 0.42, 0.64];-- @override- Widget build(BuildContext context) {- TerminalFontScope.watch(context);- return SkeletonList(- rows: 3,- semanticsLabel: 'Loading machines',- itemBuilder: (context, i) => SidebarTimeline(- role: SidebarTimelineRole.node,- above: i > 0,- below: false,- child: _MachineCaptionSkeleton(labelFactor: _labels[i]),- ),- );- }-}--/// A machine caption with nothing in it yet.-///-/// Not [_SidebarRowSkeleton]: that one stands in for a [SidebarItem], which is-/// what an AGENT row is. A machine is a caption at half the label size in a-/// shorter box, and a placeholder built to the wrong one resizes the rail as-/// the answer lands — which is the whole thing a skeleton exists to avoid.-class _MachineCaptionSkeleton extends StatelessWidget {- const _MachineCaptionSkeleton({required this.labelFactor});-- final double labelFactor;-- @override- Widget build(BuildContext context) {- TerminalFontScope.watch(context);- return Padding(- padding: _machineCaptionPadding,- child: SizedBox(- height: _machineCaptionHeight,- child: Row(- children: [- Skeleton(- width: _machineMarkSize,- height: _machineMarkSize,- radius: 5,- ),- const SizedBox(width: 10),- Expanded(- child: SkeletonText(- style: _machineCaptionStyle(grid.AppPalette.textFaint),- widthFactor: labelFactor,- ),- ),- ],- ),- ),- );- }-}--/// A machine's agents before `agents_list` has answered: two rows where the-/// agents will go, threaded onto the same guide line they will hang from.-class _AgentRowsSkeleton extends StatelessWidget {- const _AgentRowsSkeleton({super.key});-- static const _rows = 2;- static const _labels = [0.48, 0.36];-- @override- Widget build(BuildContext context) {- TerminalFontScope.watch(context);- return SkeletonList(- rows: _rows,- fadeDepth: skeletonFadeLight,- semanticsLabel: 'Loading agents',- itemBuilder: (context, i) => SidebarTimeline(- role: SidebarTimelineRole.branch,- below: i < _rows - 1,- child: Padding(- // Where a nested row's box starts — see [_AgentRow].- padding: const EdgeInsets.only(left: 28),- child: _SidebarRowSkeleton(- leading: 16,- leadingRadius: 4,- labelFactor: _labels[i],- ),- ),- ),- );- }-}--/// A [SidebarItem] with nothing in it yet: the same 1px margin, 36px box,-/// icon gutter and label strut, so a placeholder row and a real one measure-/// the same to the pixel — the row's label pins its metrics with a strut, and-/// a bar measured without it comes out a pixel short.-class _SidebarRowSkeleton extends StatelessWidget {- const _SidebarRowSkeleton({- required this.leading,- required this.leadingRadius,- required this.labelFactor,- });-- final double leading;- final double leadingRadius;- final double labelFactor;-- @override- Widget build(BuildContext context) {- TerminalFontScope.watch(context);- return Padding(- padding: const EdgeInsets.symmetric(vertical: 1),- child: SizedBox(- height: 36,- child: Padding(- padding: const EdgeInsets.fromLTRB(SidebarItem.iconGutter, 0, 5, 0),- child: Row(- children: [- Skeleton(width: leading, height: leading, radius: leadingRadius),- const SizedBox(width: 10),- Expanded(- child: SkeletonText(- style: terminalTextStyle(height: 1.25),- strutStyle: StrutStyle(- fontSize: terminalFontStore.size,- fontFamily: terminalFontStore.value.fontFamily,- fontFamilyFallback:- terminalFontStore.value.fontFamilyFallback,- height: 1.25,- forceStrutHeight: true,- ),- widthFactor: labelFactor,- ),- ),- ],- ),- ),- ),- );- }-}--class _AgentStatusRow extends StatelessWidget {- final IconData icon;- final String label;-- /// A quiet line of fact under a machine — "connecting…", "preparing agent- /// list…". Never a control: the one tappable thing that used to share this- /// shape ("link required") is a row of its own now, see [_LinkMachineRow].- const _AgentStatusRow({required this.icon, required this.label});-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- return Padding(- padding: const EdgeInsets.fromLTRB(38, 3, 12, 9),- child: Row(- children: [- Icon(icon, size: 12, color: grid.AppPalette.textFaint),- const SizedBox(width: 7),- Expanded(- child: Text(- label,- style: terminalTextStyle(color: grid.AppPalette.textFaint),- ),- ),- ],- ),- );- }-}--/// The word for a machine that is not answering, on the machine's own row.-///-/// A word, not a chip. It was a filled pill, and it was the only filled thing-/// in a column that says everything else in plain text — so it read as a-/// control, on the one row where there is nothing to press. The grey mark-/// beside the name already carries the fact; this just names it.-class _OfflineWord extends StatelessWidget {- const _OfflineWord();-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- return Padding(- padding: const EdgeInsets.only(left: 8),- child: Text(- 'offline',- style: terminalTextStyle(- color: grid.AppPalette.textFaint,- letterSpacing: 0.2,- ),- ),- );- }-}--/// The counterpart to [_OfflineWord]: the machine's node is up. Same quiet-/// treatment so online/offline read as the same kind of thing — the green-/// connection dot beside the name already carries the colour; this is the word.-class _OnlineWord extends StatelessWidget {- const _OnlineWord();-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- return Padding(- padding: const EdgeInsets.only(left: 8),- child: Text(- 'online',- style: terminalTextStyle(- color: grid.AppPalette.textFaint,- letterSpacing: 0.2,- ),- ),- );- }-}--/// Why an offline machine has no agents under it.-///-/// One sentence, in the colour every other quiet line in the rail uses. No icon,-/// because the chip beside the machine name is already the marker; no command,-/// because the person reading it opened an application.-class _MachineOfflineNote extends StatelessWidget {- const _MachineOfflineNote({required this.state, this.linkPending = false});-- final MachineState state;-- /// True when the machine also has no link yet — then the note says what- /// comes next, so the person is not left wondering why the link row they- /// saw on another machine is missing on this one.- final bool linkPending;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- // "it", not the machine's name: the name is the caption directly above- // this line, and repeating it doubled the note to two lines on every host- // with a hostname-shaped name. The local computer keeps "this computer",- // because "it" for the machine you are sitting at reads as somewhere else.- final where = state.isLocalMachine ? 'this computer' : 'it';- return Padding(- padding: const EdgeInsets.fromLTRB(38, 0, 12, 8),- child: Text(- linkPending- ? "Harness isn't running on $where · link when it's back"- : "Harness isn't running on $where.",- maxLines: 2,- overflow: TextOverflow.ellipsis,- style: terminalTextStyle(color: grid.AppPalette.textFaint, height: 1.4),- ),- );- }-}--class _AgentLoadError extends StatelessWidget {- final AppNotifier notifier;- final MachineState state;-- const _AgentLoadError({required this.notifier, required this.state});-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- return Padding(- padding: const EdgeInsets.fromLTRB(38, 2, 8, 8),- child: Row(- children: [- Icon(- Icons.error_outline,- size: 12,- color: grid.AppPalette.dangerFill,- ),- const SizedBox(width: 7),- Expanded(- child: Text(- state.agentsLoadError ?? 'Could not load agents',- maxLines: 2,- overflow: TextOverflow.ellipsis,- style: terminalTextStyle(color: grid.AppPalette.dangerFill),- ),- ),- IconButton(- icon: const Icon(Icons.refresh, size: 14),- color: grid.AppPalette.textSecondary,- tooltip: 'Retry agents',- onPressed: () =>- notifier.reloadMachineData(state.machine.machineId),- ),- ],- ),- );- }-}--/// "New Harness", drawn as the row it would create.-///-/// The rail is a LIST, and every framed control put in it has read as a foreign object — there is-/// nothing else in this column with a border or a fill of its own. So this is not a button placed in a-/// list; it is a row of the list that happens to be empty. Same indent, same well, same label type, same-/// hover fill: what changes is that the well is drawn in dashes and holds a `+`, which is the shared-/// vocabulary for "this one is not real yet".-///-/// It replaces two things that were louder and said less. A sentence — "no running agents" — set at-/// 13.5px under an 11px machine caption, so the status line was bigger than its own heading and the eye-/// landed on the least useful words on screen. And an accent-washed button, which in a rail holding no-/// other framed control read as the primary action of the whole window for a machine that is merely-/// idle. Neither said the thing that matters, which is that a row can be added here.-///-/// It also stands at the END of a machine that already has agents, and that is not scope creep — it is-/// the same problem one row further down. Adding an agent to a machine that has some is only offered by-/// a `+` revealed on hover of the machine caption, which cannot be found by anyone who does not already-/// know it is there. One shape now answers both.-class _NewAgentRow extends StatelessWidget {- const _NewAgentRow({- required this.notifier,- required this.machineId,- required this.source,- });-- final AppNotifier notifier;- final String machineId;-- /// Which of the two places this row is standing in, so the dialog's own telemetry can tell an empty- /// machine's first agent from a fifth one added to a busy machine — different moments, different- /// answers to "did this get found".- final String source;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- return Padding(- // The same 28 an agent row takes, so the guide's arm reaches this row exactly as it reaches a real- // one. A different indent here would bend the trunk at the last branch.- padding: const EdgeInsets.only(left: 28),- child: SidebarItem(- label: 'New Harness',- // Dimmed rather than a colour of its own: this row is a placeholder until it is reached for, and- // the hover state SidebarItem already owns is what says it is live.- dimmed: true,- tooltip: 'Start a harness on this machine',- onTap: () =>- showNewAgentDialog(context, notifier, machineId, source: source),- // The agent row's well, in dashes. Same 24px box and same 7px radius, so the column of marks- // stays a column — only the border and the glyph say this one is an invitation.- leading: CustomPaint(- painter: _DashedWellPainter(color: grid.AppPalette.textFaint),- child: SizedBox(- width: 24,- height: 24,- child: Icon(- LucideIcons.plus300,- size: 13,- color: grid.AppPalette.textFaint,- ),- ),- ),- ),- );- }-}--/// "Link this machine…", drawn as the row the link would unlock.-///-/// The same shape as [_NewAgentRow], on purpose: linking is the step BEFORE-/// adding an agent to this machine, and a row that looks like the one it leads-/// to says so without a sentence. It replaces a status line — "link required",-/// grey text with an accent icon and a chevron — that was a fact dressed as a-/// command: it named a condition and then behaved like a button, and its three-/// tones (accent icon, secondary text, faint chevron) agreed on nothing.-///-/// Only ever built for a machine that is ONLINE — the callers check, because-/// the handshake behind this needs the other daemon awake.-class _LinkMachineRow extends StatelessWidget {- const _LinkMachineRow({required this.notifier, required this.state});-- final AppNotifier notifier;- final MachineState state;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- return SidebarTimeline(- role: SidebarTimelineRole.branch,- below: false,- child: Padding(- padding: const EdgeInsets.only(left: 28),- child: SidebarItem(- label: 'Link this machine…',- dimmed: true,- tooltip:- 'Link ${state.machine.displayName} so its agents show up here',- onTap: () => notifier.selectMachineForSetup(state.machine.machineId),- leading: CustomPaint(- painter: _DashedWellPainter(color: grid.AppPalette.textFaint),- child: SizedBox(- width: 24,- height: 24,- child: Icon(- LucideIcons.link2300,- size: 13,- color: grid.AppPalette.textFaint,- ),- ),- ),- ),- ),- );- }-}--/// The agent well's 7px rounded square, drawn as a dashed outline.-///-/// Hand-drawn because Flutter has no dashed border: the path is walked in fixed steps and every other-/// step is stroked. Cheap enough for a row — it is one rounded rect — and it keeps the well's exact-/// geometry, which a substitute icon would not.-class _DashedWellPainter extends CustomPainter {- const _DashedWellPainter({required this.color});-- final Color color;-- @override- void paint(Canvas canvas, Size size) {- final paint = Paint()- ..style = PaintingStyle.stroke- ..strokeWidth = 1- ..color = color.withValues(alpha: 0.55);- final rect = RRect.fromRectAndRadius(- Rect.fromLTWH(0.5, 0.5, size.width - 1, size.height - 1),- const Radius.circular(7),- );- final path = Path()..addRRect(rect);- for (final metric in path.computeMetrics()) {- var distance = 0.0;- while (distance < metric.length) {- canvas.drawPath(metric.extractPath(distance, distance + 2.5), paint);- distance += 5;- }- }- }-- @override- bool shouldRepaint(_DashedWellPainter old) => old.color != color;-}--class _EmptyAgents extends StatelessWidget {- final AppNotifier notifier;- final MachineState state;- const _EmptyAgents({required this.notifier, required this.state});-- @override- Widget build(BuildContext context) {- TerminalFontScope.watch(context);- // No sentence, and nothing framed. An empty list says it is empty by being empty; what it cannot say- // on its own is that a row can be added, and that is exactly what this row is. See [_NewAgentRow] for- // what it replaces and why.- //- // The reload the old sentence carried moved to the machine's own menu. It was a 40px icon button- // living on a status line, reachable only while a machine happened to be empty — a per-machine action- // belongs with the machine's other per-machine actions, where it is reachable in every state.- // Wrapped in the timeline like any other row, and that is the whole claim: the guide's arm reaches- // this row from the machine's trunk exactly as it reaches a real agent, so the rail reads as a list- // with one row in it rather than as a message where a list should be. `below: false` closes the- // trunk here — there is nothing after it.- return SidebarTimeline(- role: SidebarTimelineRole.branch,- below: false,- child: _NewAgentRow(- notifier: notifier,- machineId: state.machine.machineId,- source: 'rail_empty',- ),- );- }-}diff --git a/desktop/lib/widgets/machine_rail_mini.dart b/desktop/lib/widgets/machine_rail_mini.dartdeleted file mode 100644index e6cd5d207..000000000--- a/desktop/lib/widgets/machine_rail_mini.dart+++ /dev/null@@ -1,68 +0,0 @@-import 'package:flutter/material.dart';-import 'package:lucide_icons_flutter/lucide_icons.dart';--import 'window_chrome.dart';--import '../shared/theme/app_theme.dart' as grid;-import '../shared/widgets/app_icon_button.dart';-import '../state/app_state.dart';-import 'account_footer.dart';--/// The rail, folded.-///-/// It is a narrow column rather than nothing at all, and that is the whole-/// point: the control that folds the rail has to still be there to unfold it.-/// Hiding the rail outright would leave the button that did it nowhere on-/// screen, and the only way back would be a shortcut nobody was told about.-///-/// What survives the fold is what still means something at this width — the way-/// back, and who you are signed in as. A machine's name does not fit in 72px,-/// and a truncated one says less than no name at all.-class MachineRailMini extends StatelessWidget {- const MachineRailMini({- super.key,- required this.notifier,- required this.onExpand,- });-- final AppNotifier notifier;- final VoidCallback onExpand;-- /// The same width Grid's folded rail uses, so the two apps fold to the same- /// shape on a desk where both are open.- static const double width = 72;- static const double _headerHeight = 46;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- // No fill: the fold draws the surface — see MachineRail for why.- return SizedBox(- width: width,- child: Column(- children: [- // Same inset and drag handle as the wide rail's head, for the same- // reason: the traffic lights float over this corner.- WindowDragArea(- child: SizedBox(- height: _headerHeight,- child: Center(- child: AppIconButton(- icon: LucideIcons.panelLeft300,- size: 18,- tooltip: 'Expand sidebar ⌘\\',- onPressed: onExpand,- ),- ),- ),- ),- const Spacer(),- Padding(- padding: const EdgeInsets.only(bottom: 10),- child: AccountFooter(notifier: notifier, compact: true),- ),- ],- ),- );- }-}diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dartindex 90e57008b..0d10b708e 100644--- a/desktop/lib/widgets/pane_grid.dart+++ b/desktop/lib/widgets/pane_grid.dart@@ -2224,7 +2224,7 @@ class _EmptyGrid extends StatelessWidget {final machineId = _machineId;// Holds the keyboard while there is no terminal to hold it.//- // App shortcuts are bound above this screen (home_screen.dart) and, like+ // App shortcuts are bound above this screen (swarm_screen.dart) and, like// every Flutter shortcut, they are delivered along the focus chain — from// whatever has focus up through its ancestors. With no pane open nothing// inside the screen has any, so the chain starts at the route's own scope,diff --git a/desktop/lib/widgets/status_rail/key_hints.dart b/desktop/lib/widgets/status_rail/key_hints.dartdeleted file mode 100644index 67990832a..000000000--- a/desktop/lib/widgets/status_rail/key_hints.dart+++ /dev/null@@ -1,108 +0,0 @@-import 'package:flutter/widgets.dart';-import 'package:harness/terminal/terminal_text.dart';--import '../../shared/theme/app_theme.dart' as grid;-import '../../state/app_state.dart';--/// The keys that mean something RIGHT NOW, along the bottom of the window.-///-/// ⌘/ already prints every shortcut this app has, and it is the wrong shape for-/// the problem it was given: a modal is something you go and look up, so it-/// teaches only the people who already suspect there is something to learn. The-/// keys nobody discovers are the ones nobody goes looking for.-///-/// zellij answers this with a strip along the bottom that changes with the mode,-/// and vim users answer it with which-key. Both work for the same reason — the-/// hint is in the corner of the eye during the work, not behind a gesture — and-/// both are read hundreds of times before they stop being read at all, which is-/// the mark of a good one: it teaches itself out of a job.-///-/// IT CHANGES WITH WHERE THE KEYBOARD IS, and that is most of its value. With-/// the cursor in the rail, `j` and `k` are live and plain — the one surface in-/// this app where an unmodified letter does something — and nothing else on-/// screen says so. A strip that printed the same six chords in both states-/// would be decoration.-///-/// It rides the strip that was already there rather than adding a second one.-/// That strip carries two usage figures and has the whole width to itself; a-/// row of hints costs no height and gives the surface a second reason to exist.-class KeyHints extends StatelessWidget {- const KeyHints({super.key, required this.notifier});-- final AppNotifier notifier;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- return ListenableBuilder(- listenable: notifier,- builder: (context, _) {- final hints = notifier.railFocused ? _railHints : _gridHints(notifier);- return Row(- mainAxisSize: MainAxisSize.min,- children: [- for (final hint in hints) ...[- _Hint(keys: hint.$1, what: hint.$2),- const SizedBox(width: 14),- ],- ],- );- },- );- }-- /// In the rail: the four vim keys, unmodified, and the way out.- static const List<(String, String)> _railHints = [- ('j k', 'move'),- ('⏎', 'open'),- ('h', 'back'),- ('esc', 'grid'),- ];-- /// On the grid, and it is DELIBERATELY SHORT.- ///- /// Six chords is a strip people read; twelve is a wall they stop seeing, and- /// then it has cost height and taught nothing. These are the ones that answer- /// "what can I do from here" — go somewhere, make something, and the two that- /// change the shape of the window.- ///- /// The zoom hint says which way it will go, because a key whose label does not- /// match what it is about to do is worse than no label.- static List<(String, String)> _gridHints(AppNotifier notifier) => [- ('⌘hjkl', 'panes'),- ('⌘N', 'add an agent'),- ('⌘⏎', notifier.zoomedPaneId != null ? 'unzoom' : 'zoom'),- ('⌘;', 'last'),- ('⌘N', 'new'),- ('⌘/', 'keys'),- ];-}--class _Hint extends StatelessWidget {- const _Hint({required this.keys, required this.what});-- final String keys;- final String what;-- @override- Widget build(BuildContext context) {- TerminalFontScope.watch(context);- return Row(- mainAxisSize: MainAxisSize.min,- children: [- Text(- keys,- style: terminalTextStyle(- // The chord is the brighter half. Someone scanning this is looking- // for a key, not reading a sentence — the word after it only has to- // confirm what they guessed.- color: grid.AppPalette.textSecondary,- fontWeight: grid.AppFont.medium,- ),- ),- const SizedBox(width: 5),- Text(what, style: terminalTextStyle(color: grid.AppPalette.textFaint)),- ],- );- }-}diff --git a/desktop/lib/widgets/status_rail/rail_figure.dart b/desktop/lib/widgets/status_rail/rail_figure.dartdeleted file mode 100644index f7feb542f..000000000--- a/desktop/lib/widgets/status_rail/rail_figure.dart+++ /dev/null@@ -1,83 +0,0 @@-import 'package:flutter/material.dart';--/// What a status-rail panel hangs from: the link that places it under its-/// figure, and the key that says where that figure sits.-///-/// Both, because the link alone cannot answer whether the panel it places still-/// fits inside the window — see `RailPanel`.-typedef RailFigureAnchor = ({LayerLink link, GlobalKey key});--/// A fresh anchor. One per figure: a [LayerLink] can only be attached to a-/// single target, so figures cannot share.-RailFigureAnchor newRailFigureAnchor() => (link: LayerLink(), key: GlobalKey());--/// One figure on the status rail, and the panel it opens.-///-/// The regions touch: the gap between figures is each figure's own padding-/// rather than a spacer between them. A bare `SizedBox` would be dead ground —-/// the pointer crossing it belongs to nothing, so an open panel would close on-/// the way past and reopen on landing.-///-/// Generic over what a figure opens: the figure hands back whatever its panel-/// is looked up by.-class RailHoverTarget<T> extends StatelessWidget {- const RailHoverTarget({- super.key,- required this.kind,- required this.anchor,- required this.semantics,- required this.child,- required this.onEnter,- required this.onExit,- this.enabled = true,- });-- final T kind;- final RailFigureAnchor anchor;- final String semantics;- final Widget child;- final void Function(T) onEnter;- final void Function(T) onExit;-- /// False while there is nothing to open — the figure is then still readable- /// and simply inert.- final bool enabled;-- /// Half the space between two figures. Each side owns its own half, so the- /// two regions meet with nothing between them.- static const double gap = 9;-- @override- Widget build(BuildContext context) {- return CompositedTransformTarget(- link: anchor.link,- child: KeyedSubtree(- key: anchor.key,- child: Semantics(- label: semantics,- child: MouseRegion(- cursor: enabled- ? SystemMouseCursors.click- : SystemMouseCursors.basic,- onEnter: enabled ? (_) => onEnter(kind) : null,- onExit: enabled ? (_) => onExit(kind) : null,- child: Padding(- // Full height, so the pointer entering the rail anywhere over a- // figure is already on it — a region inset from the strip's own- // edges leaves a lane above and below that closes the panel.- padding: const EdgeInsets.symmetric(horizontal: gap),- // ⚠️ No `Center` here, and that is deliberate. It used to wrap- // this child, and `Center` LOOSENS the width constraint on the- // way through — the child could then take whatever it wanted and- // hand the overflow up, which made every `Flexible` inside a- // figure inert. The vertical centring it was here for is already- // done by the rail's own `SizedBox(height: 26)` and the Row's- // default cross-axis centre.- child: child,- ),- ),- ),- ),- );- }-}diff --git a/desktop/lib/widgets/status_rail/rail_panel.dart b/desktop/lib/widgets/status_rail/rail_panel.dartdeleted file mode 100644index 2ae1b7d16..000000000--- a/desktop/lib/widgets/status_rail/rail_panel.dart+++ /dev/null@@ -1,161 +0,0 @@-import 'dart:math' as math;--import 'package:flutter/material.dart';--import '../../shared/theme/app_theme.dart';-import 'rail_figure.dart';--/// The panel behind one figure on the status rail.-///-/// Anchored under its own figure rather than the rail as a whole, so it points-/// at the number it belongs to. The frame only: placement, the shared surface,-/// and the hover plumbing that keeps it open while the pointer crosses from the-/// figure to it. What goes inside is the caller's.-class RailPanel extends StatelessWidget {- const RailPanel({- super.key,- required this.anchor,- required this.tapGroupId,- required this.onEnter,- required this.onExit,- required this.width,- required this.child,- });-- /// The figure this panel hangs from. Its link places the panel; its key says- /// where on screen that is, which is what decides whether the panel still- /// fits (see [_slide]).- final RailFigureAnchor anchor;-- /// Shared with the rail so a click inside the panel isn't the "click outside"- /// that dismisses a pinned one — the panel lives in an overlay, outside the- /// rail's own subtree.- final Object tapGroupId;-- final VoidCallback onEnter;- final VoidCallback onExit;-- final double width;- final Widget child;-- /// The surface's own padding, undone on the left so the panel's text sits- /// under the figure's text rather than being inset from it by a rim's width.- static const double _inset = 13;-- /// How close to the window's edge the panel may come once it has had to move- /// to stay on screen.- static const double _edgeMargin = 10;-- @override- Widget build(BuildContext context) {- final windowWidth = MediaQuery.sizeOf(context).width;- // Never wider than the window it opens over — a clamp that only bites on a- // window narrower than any the app can be resized to, but the slide below- // needs a width it can trust.- final panelWidth = math.min(width, windowWidth - _edgeMargin * 2);- return Positioned(- width: panelWidth,- child: CompositedTransformFollower(- link: anchor.link,- // Upward: the rail is the window's bottom edge, so a panel dropped- // below its anchor would open off the window.- targetAnchor: Alignment.topLeft,- followerAnchor: Alignment.bottomLeft,- offset: Offset(-_inset + _slide(windowWidth, panelWidth), -8),- child: MouseRegion(- onEnter: (_) => onEnter(),- onExit: (_) => onExit(),- child: TapRegion(- groupId: tapGroupId,- child: _Entrance(child: RailPanelSurface(child: child)),- ),- ),- ),- );- }-- /// How far the panel has to slide sideways to stay inside the window — zero,- /// the usual case, when it already fits where its figure puts it.- ///- /// The figures sit at the rail's RIGHT end, so a panel hung from the left of- /// its figure and grown rightwards runs off the window's edge. Sliding beats- /// re-anchoring to the figure's right edge, which would park the panel well- /// left of the number it belongs to even when there was room to sit under it.- double _slide(double windowWidth, double panelWidth) {- final box = anchor.key.currentContext?.findRenderObject() as RenderBox?;- if (box == null || !box.hasSize) return 0;- final left = box.localToGlobal(Offset.zero).dx - _inset;- final limit = windowWidth - panelWidth - _edgeMargin;- return left.clamp(_edgeMargin, math.max(_edgeMargin, limit)) - left;- }-}--/// The glass box a rail panel is drawn on.-class RailPanelSurface extends StatelessWidget {- const RailPanelSurface({super.key, required this.child});-- final Widget child;-- @override- Widget build(BuildContext context) {- AppTheme.watch(context);- return Material(- type: MaterialType.transparency,- child: DecoratedBox(- decoration: BoxDecoration(- color: AppGlass.surfaceFill,- borderRadius: BorderRadius.circular(AppCard.radius),- border: Border.all(color: AppGlass.hair),- boxShadow: AppGlass.shadow,- ),- child: Padding(- padding: const EdgeInsets.all(RailPanel._inset),- child: child,- ),- ),- );- }-}--/// The panel arriving: a short fade while it settles the last few pixels up from-/// the rail it hangs off.-///-/// Six pixels and 160ms, which is under the threshold at which a movement reads-/// as *travel* — the panel should look like it was already there and is coming-/// into focus, not like it flew in. These open on hover, so whatever this costs-/// is paid every time the pointer crosses a figure.-///-/// Only on the way in. There is no exit animation because there is nothing to-/// animate: [OverlayPortal] takes the panel out of the tree the moment it hides,-/// and holding it there to fade would keep a dead popover over the transcript.-///-/// Runs once per mount, so swapping figures under an open panel replaces the-/// contents in place without re-playing this.-class _Entrance extends StatelessWidget {- const _Entrance({required this.child});-- final Widget child;-- @override- Widget build(BuildContext context) {- // Reduce Motion means no motion, not less of it — the fade goes too, since- // an opacity ramp is the part that reads as movement on a surface this size.- final instant = MediaQuery.disableAnimationsOf(context);- return TweenAnimationBuilder<double>(- tween: Tween<double>(begin: 0, end: 1),- duration: instant ? Duration.zero : AppMotion.swap,- curve: AppMotion.curve,- builder: (context, t, child) => Opacity(- opacity: t,- child: Transform.translate(- // Positive, so it rises into place: the panel travels *away* from the- // rail it opens off, and a fall would read as arriving from the wrong- // side of its own anchor.- offset: Offset(0, (1 - t) * 6),- child: child,- ),- ),- child: child,- );- }-}diff --git a/desktop/lib/widgets/status_rail/status_rail.dart b/desktop/lib/widgets/status_rail/status_rail.dartdeleted file mode 100644index ee6840f44..000000000--- a/desktop/lib/widgets/status_rail/status_rail.dart+++ /dev/null@@ -1,83 +0,0 @@-import 'package:flutter/material.dart';--import '../../shared/theme/app_theme.dart' as grid;-import '../../state/app_state.dart';-import '../../usage/usage_controller.dart';-import 'key_hints.dart';-import 'usage_rail.dart';--/// The strip along the bottom of the window: what the agent accounts have-/// spent, and the keys that mean something right now.-///-/// It exists because the top of the window is where the things you *press*-/// live — the rail, the panes, the menus — and none of these figures is a call-/// to action. **The top is what you press, the bottom is what you know.**-///-/// Full-bleed, under the machine rail as well as the panes, so the window-/// closes on one unbroken line. A strip that started after the rail would put a-/// step in the bottom edge and read as part of the pane rather than the window.-class StatusRail extends StatefulWidget {- const StatusRail({super.key, required this.notifier, this.usage});-- /// Read by [KeyHints] for where the keyboard is, and by the usage panel for- /// what the sidebar calls this computer.- final AppNotifier notifier;-- /// The agent accounts' rate limits.- ///- /// Handed down by the shell, which owns it so that folding the sidebar —- /// which unmounts this strip — does not restart the poll. Null only in a test- /// that wants the rail on its own, where the rail makes — and disposes — one- /// for itself.- final UsageController? usage;-- /// Tall enough for an 11.5pt figure with a hit target around it, short enough- /// to stay furniture.- static double get height =>- (grid.AppFont.codeSize * 1.35 + 8).clamp(26, double.infinity);-- @override- State<StatusRail> createState() => _StatusRailState();-}--class _StatusRailState extends State<StatusRail> {- late final UsageController _usage = widget.usage ?? UsageController();-- @override- void dispose() {- if (widget.usage == null) _usage.dispose();- super.dispose();- }-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- // NO FILL, NO RULE — the strip is its text and nothing else. The rail above- // it and every pane are floating cards on the gradient field, and a flat- // slab laid across the bottom of the window would be the one surface that- // did not belong to anything.- return SizedBox(- height: StatusRail.height,- child: Padding(- padding: const EdgeInsets.symmetric(horizontal: 12),- child: Row(- children: [- Expanded(- child: UsageRail(usage: _usage, notifier: widget.notifier),- ),- // The keys had nowhere to live that was not a modal. See [KeyHints]- // for why a strip beats a sheet for the ones nobody knows to go- // looking for.- Flexible(- flex: 3,- child: SingleChildScrollView(- scrollDirection: Axis.horizontal,- child: KeyHints(notifier: widget.notifier),- ),- ),- ],- ),- ),- );- }-}diff --git a/desktop/lib/widgets/status_rail/usage_ink.dart b/desktop/lib/widgets/status_rail/usage_ink.dartdeleted file mode 100644index fe0ee7d4d..000000000--- a/desktop/lib/widgets/status_rail/usage_ink.dart+++ /dev/null@@ -1,22 +0,0 @@-import 'package:flutter/widgets.dart';--import '../../shared/theme/app_theme.dart' as grid;-import '../../theme/app_theme.dart';-import '../../usage/usage_pressure.dart';--/// The colour a nearly-spent window is drawn in, over the [calm] colour it-/// wears the rest of the time.-///-/// One function for the rail's figure and the panel's bar, so a window cannot-/// be amber in one place and plain in the other — the strip prints a summary of-/// the very numbers the panel expands, and two thresholds would make the pair-/// disagree at exactly the moment they matter.-///-/// ⚠️ [AppColors.danger] rather than `AppPalette.dangerFill`: this is ink on a-/// surface, and the fill is tuned to carry white lettering ON it.-Color usagePressureInk(UsagePressure pressure, Color calm) =>- switch (pressure) {- UsagePressure.calm => calm,- UsagePressure.warn => grid.AppPalette.warn,- UsagePressure.critical => AppColors.danger,- };diff --git a/desktop/lib/widgets/status_rail/usage_panel.dart b/desktop/lib/widgets/status_rail/usage_panel.dartdeleted file mode 100644index 4a4b79598..000000000--- a/desktop/lib/widgets/status_rail/usage_panel.dart+++ /dev/null@@ -1,364 +0,0 @@-import 'package:flutter/material.dart';-import 'package:harness/terminal/terminal_text.dart';--import '../../shared/theme/app_theme.dart' as grid;-import '../../usage/usage_accounts.dart';-import '../../usage/usage_pressure.dart';-import '../../usage/usage_window.dart';-import '../engine_identity.dart';-import 'usage_ink.dart';--/// What a panel calls this computer when neither the sidebar nor the OS has a-/// name for it.-const String _kThisComputer = 'This computer';--/// What one account has spent, window by window.-///-/// The panel behind a figure on the status rail: the same numbers the strip-/// prints, given the room to say which window each belongs to and when it-/// starts over.-class UsagePanelContent extends StatelessWidget {- const UsagePanelContent({- super.key,- required this.accounts,- this.machineName,- });-- /// Every account of ONE provider, this computer's first- /// (`groupUsageAccounts`). With a single account — the common case, and every- /// case where the remote machines share this computer's subscription — the- /// panel is exactly the one it always was: captions appear only once there is- /// something to tell apart.- final List<UsageAccount> accounts;-- /// What to call THIS computer — the sidebar's own name for it, from- /// `AppNotifier.thisMachineName`.- ///- /// Replaces the words "This computer", which were right while that was the- /// only machine a panel could be about and are a wasted line now: a reader- /// with two machines signed in sees one caption naming a host and another- /// naming none, and has to work out that the nameless one is the one they- /// are sitting at. The name says it and matches the rail above it.- ///- /// Null falls back to those words rather than printing a blank caption.- final String? machineName;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- final captioned = accounts.length > 1;- return Column(- crossAxisAlignment: CrossAxisAlignment.start,- mainAxisSize: MainAxisSize.min,- children: [- _Header(reading: accounts.first.reading),- // Whose spend this is. The rail can carry other machines' accounts- // as well as this one's, so a panel that named no scope would leave- // the reader to infer it.- //- // Only when there is ONE account: past that the per-account captions- // below already name every machine, and a heading claiming this- // computer over a list including two others would be wrong.- if (!captioned) ...[- const SizedBox(height: 4),- _PanelScope(name: machineName),- ],- for (final (index, account) in accounts.indexed) ...[- if (captioned) ...[- SizedBox(height: index == 0 ? 12 : 16),- _AccountCaption(account: account, machineName: machineName),- ],- ..._accountBody(account.reading),- ],- ],- );- }-- /// One account's windows — or, when it has none, the sentence its source- /// wrote about why, because the source is what knows whether signing in or- /// retrying is the way out.- static List<Widget> _accountBody(ProviderUsage reading) {- if (!reading.hasFigures) {- return [- const SizedBox(height: 10),- Text(- reading.message ?? 'No usage to show',- style: terminalTextStyle(- color: grid.AppPalette.textFaint,- height: 1.35,- ),- ),- ];- }- return [- for (final window in reading.windows) ...[- const SizedBox(height: 12),- _WindowRow(- window: window,- color: engineIdentity(reading.provider.engineId).color,- ),- ],- ];- }-}--/// Whose subscription a block of windows is, once a provider has more than one.-class _AccountCaption extends StatelessWidget {- const _AccountCaption({required this.account, this.machineName});-- final UsageAccount account;-- /// This computer's own name, for the local block — see- /// [UsagePanelContent.machineName].- final String? machineName;-- @override- Widget build(BuildContext context) {- TerminalFontScope.watch(context);- return Text(- _caption,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: terminalTextStyle(- color: grid.AppPalette.textSecondary,- fontWeight: grid.AppFont.medium,- ),- );- }-- String get _caption {- if (!account.isLocal) return account.machines.join(', ');- // The machine's own name, falling back to [_kThisComputer] when the rail- // has none to give — a caption is worth more than a blank line.- final own = machineName?.trim();- final here = own == null || own.isEmpty ? _kThisComputer : own;- return account.machines.isEmpty- ? here- : '$here · also ${account.machines.join(', ')}';- }-}--/// Whose spend a single-account panel is showing: this computer, named.-class _PanelScope extends StatelessWidget {- const _PanelScope({required this.name});-- final String? name;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- final style = terminalTextStyle(- height: 1.35,- color: grid.AppPalette.textSecondary,- );- final own = name?.trim();- return RichText(- // One line: a hostname can be long and this panel is 248px across.- maxLines: 1,- overflow: TextOverflow.ellipsis,- text: TextSpan(- style: style,- children: [- TextSpan(text: 'Computer · ', style: style),- TextSpan(- text: own == null || own.isEmpty ? _kThisComputer : own,- style: style.copyWith(- color: grid.AppPalette.textPrimary,- fontWeight: grid.AppFont.medium,- ),- ),- ],- ),- );- }-}--/// The account this panel is about, and how fresh its figures are.-class _Header extends StatelessWidget {- const _Header({required this.reading});-- final ProviderUsage reading;-- @override- Widget build(BuildContext context) {- TerminalFontScope.watch(context);- final fetchedAt = reading.fetchedAt;- return Row(- children: [- // The mark the machine rail already draws beside every agent of this- // engine — the account's own logo, in its own colour. Drawing a second- // glyph here would make one account look like two things.- EngineMark(engine: reading.provider.engineId, size: 13),- const SizedBox(width: 7),- Text(- reading.provider.label,- style: terminalTextStyle(- color: grid.AppPalette.textPrimary,- fontWeight: grid.AppFont.semibold,- ),- ),- const Spacer(),- if (fetchedAt != null)- // Flexible, not bare: the account's name is the header's point and- // must never be pushed out by the freshness note beside it, which is- // the half that can afford to shorten.- Flexible(- child: Text(- _freshness(fetchedAt),- maxLines: 1,- overflow: TextOverflow.ellipsis,- textAlign: TextAlign.right,- style: terminalTextStyle(color: grid.AppPalette.textFaint),- ),- ),- ],- );- }-- /// How long ago the figures were read, at the granularity the poll actually- /// has. Anything finer would be a precision the once-a-minute refresh behind- /// it cannot back up.- static String _freshness(DateTime at) {- final since = DateTime.now().difference(at);- if (since.inMinutes < 1) return 'Updated just now';- if (since.inMinutes < 60) return 'Updated ${since.inMinutes}m ago';- return 'Updated ${since.inHours}h ago';- }-}--/// One window: what it is, how full it is, and when it empties.-class _WindowRow extends StatelessWidget {- const _WindowRow({required this.window, required this.color});-- final UsageWindow window;-- /// The account's own colour, so the bar and the mark at the top of the panel- /// are visibly the same account's.- final Color color;-- @override- Widget build(BuildContext context) {- TerminalFontScope.watch(context);- final resetsIn = window.resetsInLabel();- return Column(- crossAxisAlignment: CrossAxisAlignment.start,- mainAxisSize: MainAxisSize.min,- children: [- Text(- window.label,- style: terminalTextStyle(- color: grid.AppPalette.textPrimary,- fontWeight: grid.AppFont.medium,- ),- ),- const SizedBox(height: 6),- UsageBar(usedPercent: window.usedPercent, color: color),- const SizedBox(height: 5),- Row(- children: [- Text(- '${window.usedPercent.round()}% used',- style: terminalTextStyle(color: grid.AppPalette.textSecondary),- ),- const Spacer(),- // No reset time means no countdown — never "resets in 0m", which- // would read as a measurement rather than as the silence it is.- if (resetsIn != null)- Text(- 'Resets in $resetsIn',- style: terminalTextStyle(color: grid.AppPalette.textFaint),- ),- ],- ),- ],- );- }-}--/// How full one window is.-///-/// Drawn 6px and fully rounded, in the **account's own colour** — the same-/// colour as the mark at the top of the panel. The first version was a 3px grey sliver on a recessed-/// track, and at the single-digit percentages these windows actually sit at for-/// most of their life it was invisible: the figure beside it was doing all the-/// work and the bar was decoration that could not be seen.-///-/// Turns amber past [kUsageWarnPercent] and red past [kUsageCriticalPercent].-/// The figure is already exact, so the colour is not carrying the number — it-/// is carrying the moment the number starts to matter, which a bar that never-/// changes hue cannot. Both thresholds come from `usage_pressure.dart`, shared-/// with the rail figure this panel expands: a bar that went amber at a-/// different number from the figure above it would make one window look like-/// two readings.-class UsageBar extends StatelessWidget {- const UsageBar({- super.key,- required this.usedPercent,- required this.color,- this.height = 6,- });-- final double usedPercent;-- /// The account's colour. Overridden once the window is nearly spent, because- /// "which account" matters less at that point than "how close".- final Color color;-- final double height;-- /// The narrowest the filled part may be drawn.- ///- /// Below this a band of colour reads as a rendering artefact rather than a- /// quantity, so a small percentage is over-represented on purpose. A window at 2% is *not* a- /// window at 0%, and the bar has to be able to say so — the exact figure is- /// printed directly underneath, so nothing is lost by rounding up here.- static const double _minFill = 4;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- final fill = usagePressureInk(usagePressureOf(usedPercent), color);- return ClipRRect(- borderRadius: BorderRadius.circular(height / 2),- child: SizedBox(- height: height,- child: LayoutBuilder(- builder: (context, constraints) {- final full = constraints.maxWidth;- final measured = full * (usedPercent / 100).clamp(0.0, 1.0);- // Zero stays zero: an untouched window draws no colour at all, or- // the bar would claim usage nobody has spent.- final width = measured <= 0- ? 0.0- : measured.clamp(_minFill, full).toDouble();- // BOTH children are positioned, deliberately. A Stack takes its- // size from its non-positioned children, so an unpositioned fill- // made the Stack as narrow as the fill itself — dragging the track- // in with it — while the fill's own ColoredBox, left with loose- // height, collapsed to nothing. The result drew the *track* at the- // fill's width: the right length in the wrong colour, which is- // exactly the bug this bar was rewritten to fix.- return Stack(- children: [- Positioned.fill(- child: ColoredBox(color: grid.AppSurface.recess),- ),- Positioned(- // Keyed so a test can measure what was actually painted:- // this bar's whole failure mode is being present in the- // widget tree and invisible on screen.- key: const Key('usage-bar-fill'),- left: 0,- top: 0,- bottom: 0,- width: width,- child: ColoredBox(color: fill),- ),- ],- );- },- ),- ),- );- }-}diff --git a/desktop/lib/widgets/status_rail/usage_rail.dart b/desktop/lib/widgets/status_rail/usage_rail.dartdeleted file mode 100644index e2573b8f4..000000000--- a/desktop/lib/widgets/status_rail/usage_rail.dart+++ /dev/null@@ -1,206 +0,0 @@-import 'package:flutter/material.dart';--import '../../shared/theme/app_theme.dart' as grid;-import '../../state/app_state.dart';-import '../../usage/usage_accounts.dart';-import '../../usage/usage_controller.dart';-import '../../usage/usage_window.dart';-import 'rail_figure.dart';-import 'rail_panel.dart';-import 'usage_panel.dart';-import 'usage_readout.dart';--/// The status rail's usage figures, each opening the panel that spells it out.-///-/// Owns only the hover-and-pin behaviour around [UsageReadout]: which figure-/// the pointer is on, whose panel is showing, and whether a click is holding-/// it open. The figures are the readout's, and the panel's content is-/// [UsagePanelContent]'s.-class UsageRail extends StatefulWidget {- const UsageRail({super.key, required this.usage, required this.notifier});-- final UsageController usage;-- /// For what the sidebar calls this computer, which the panel names its own- /// account by.- final AppNotifier notifier;-- @override- State<UsageRail> createState() => _UsageRailState();-}--class _UsageRailState extends State<UsageRail> {- /// One anchor per provider, made up front rather than per build: an anchor- /// rebuilt mid-hover would hand the open panel a [LayerLink] its target no- /// longer holds, and the panel would jump to the window's origin.- final Map<UsageProvider, RailFigureAnchor> _anchors = {- for (final provider in UsageProvider.values)- provider: newRailFigureAnchor(),- };- final _portal = OverlayPortalController();-- /// Ties the rail and its panel into one tap region, so a click inside either- /// is not the "click outside" that dismisses a pinned panel.- final _tapGroup = Object();-- /// What the pointer is over right now, or null when it is over none of it.- ///- /// Moving between two figures sets this to the new one *before* the old one's- /// delayed close runs, which is what lets the panel swap in place instead of- /// blinking shut and reopening. It is also what carries the pointer across- /// the gap between a figure and the panel above it: the panel sets this to- /// the provider it is showing, so leaving the figure finds it already- /// claimed.- UsageProvider? _hovered;-- /// Whose panel is showing, or null before any has opened.- UsageProvider? _panel;-- /// Held open by a click, rather than by the pointer resting on the rail.- ///- /// Hover alone cannot hold a panel still for reading: the pointer wanders on- /// its way to anything else, and a panel that closes the moment it does has- /// to be summoned again to finish a line. A pinned panel closes on a second- /// click, or on a click anywhere outside it.- bool _pinned = false;-- /// What a click pins when the pointer is on no figure: the first account- /// with figures to show.- UsageProvider? get _firstWithFigures => widget.usage.accounts- .where((account) => account.reading.hasFigures)- .firstOrNull- ?.provider;-- void _hide() {- _pinned = false;- if (_portal.isShowing) _portal.hide();- }-- /// The pointer settled on [provider] — a figure, or the open panel itself.- ///- /// With a panel already open the swap is immediate: the pointer has crossed- /// from one figure to the next inside a surface it never left, and re-serving- /// the wait there would make the rail feel like it had to be re-asked. The- /// wait is for *opening*, so a pointer crossing the rail on its way elsewhere- /// does not flash a panel open behind it.- void _onEnter(UsageProvider provider) {- _hovered = provider;- if (_portal.isShowing) {- if (_panel != provider) setState(() => _panel = provider);- return;- }- Future<void>.delayed(const Duration(milliseconds: 180), () {- if (!mounted || _hovered != provider) return;- setState(() => _panel = provider);- _portal.show();- });- }-- /// The pointer left [provider]. Closes only if it has not landed on another- /// figure or on the panel — the guard is the *current* hover, not this one,- /// so figure-to-figure and figure-to-panel both survive the gap.- void _onExit(UsageProvider provider) {- if (_hovered == provider) _hovered = null;- // A beat of grace so the pointer can cross the gap between the rail and the- // panel without the panel closing out from under it.- Future<void>.delayed(const Duration(milliseconds: 120), () {- if (!mounted || _hovered != null || _pinned) return;- _hide();- });- }-- /// A click pins whatever the pointer is on, so the panel can be read without- /// the pointer having to stay put.- void _toggle() {- if (_pinned) {- _hide();- return;- }- final target = _hovered ?? _firstWithFigures;- if (target == null) return;- _pinned = true;- setState(() => _panel = target);- _portal.show();- }-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- return ListenableBuilder(- listenable: widget.usage,- builder: (context, _) => _figures(),- );- }-- Widget _figures() {- final usage = widget.usage;- // No account signed in here: the strip keeps its key hints and says- // nothing else, rather than drawing a figure-shaped blank that will never- // fill.- if (!usage.loading && usage.answered.isEmpty) {- return const SizedBox.shrink();- }- return TapRegion(- groupId: _tapGroup,- onTapOutside: (_) {- if (_pinned) _hide();- },- child: OverlayPortal(- controller: _portal,- overlayChildBuilder: (context) {- final provider = _panel;- return provider == null- ? const SizedBox.shrink()- : _panelFor(provider);- },- child: GestureDetector(- // Defer, not opaque: a click on the empty rail beside the figures- // must not pin a panel.- behavior: HitTestBehavior.deferToChild,- onTap: _toggle,- child: UsageReadout(- accounts: usage.accounts,- loading: usage.loading,- anchorFor: (provider) => _anchors[provider]!,- onEnter: _onEnter,- onExit: _onExit,- ),- ),- ),- );- }-- /// One provider's accounts, under the figure that summarises them.- ///- /// Narrow: every row is a label, a bar and two short figures, and extra width- /// would go to the bar alone — the one thing here that carries no reading of- /// its own.- Widget _panelFor(UsageProvider provider) {- final accounts = [- for (final account in widget.usage.accounts)- if (account.provider == provider) account,- ];- return RailPanel(- anchor: _anchors[provider]!,- tapGroupId: _tapGroup,- onEnter: () => _onEnter(provider),- onExit: () => _onExit(provider),- width: 248,- child: UsagePanelContent(- // A pinned panel can outlive its account: the next poll may drop it- // from the grouped list. This computer's own reading — a loading one,- // if need be — stands in rather than an empty panel.- accounts: accounts.isNotEmpty- ? accounts- : [UsageAccount(reading: _localReading(provider), isLocal: true)],- machineName: widget.notifier.thisMachineName,- ),- );- }-- ProviderUsage _localReading(UsageProvider provider) =>- widget.usage.readings.firstWhere(- (reading) => reading.provider == provider,- orElse: () => ProviderUsage.loading(provider),- );-}diff --git a/desktop/lib/widgets/status_rail/usage_readout.dart b/desktop/lib/widgets/status_rail/usage_readout.dartdeleted file mode 100644index 44f5ce437..000000000--- a/desktop/lib/widgets/status_rail/usage_readout.dart+++ /dev/null@@ -1,243 +0,0 @@-import 'package:flutter/material.dart';-import 'package:harness/terminal/terminal_text.dart';--import '../../shared/theme/app_theme.dart' as grid;-import '../../shared/widgets/skeleton.dart';-import '../../usage/usage_accounts.dart';-import '../../usage/usage_pressure.dart';-import '../../usage/usage_window.dart';-import '../engine_identity.dart';-import 'rail_figure.dart';-import 'usage_ink.dart';--/// What the agent accounts have spent, along the status rail.-///-/// True whichever machine the agents run on, because a rate limit belongs to an-/// *account* rather than to a machine — see `UsageController`.-class UsageReadout extends StatelessWidget {- const UsageReadout({- super.key,- required this.accounts,- required this.loading,- required this.anchorFor,- required this.onEnter,- required this.onExit,- });-- /// One per ACCOUNT, this computer's first — see `groupUsageAccounts`. A- /// remote machine on this same subscription is folded into this computer's- /// figure; one on a different subscription is a figure of its own.- final List<UsageAccount> accounts;-- /// The first cycle has not landed yet and nothing has ever been shown.- final bool loading;-- final RailFigureAnchor Function(UsageProvider) anchorFor;- final void Function(UsageProvider) onEnter;- final void Function(UsageProvider) onExit;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- // Blank at the size of the answer, so the strip does not assemble itself- // one account at a time. Only before the first reading: once figures exist- // they stay through every refresh.- if (loading) {- return const Align(- alignment: Alignment.centerRight,- child: _UsageSkeleton(),- );- }- // One hover target per PROVIDER, holding a figure for each of its- // accounts. The rail's panels are keyed by provider, and one Claude panel- // that lists two accounts reads better than two Claude panels fighting over- // one anchor.- final byProvider = <UsageProvider, List<UsageAccount>>{};- for (final account in accounts) {- // An account nobody signed into is left out rather than printed as a row- // of blanks: the rail is for figures, and the reason there are none- // belongs in the panel, where there is room to say it.- if (!account.reading.hasFigures) continue;- byProvider.putIfAbsent(account.provider, () => []).add(account);- }- if (byProvider.isEmpty) return const SizedBox.shrink();- // Right, at the strip's far end beside the key hints: furniture you only- // read belongs at the edge you are not reaching for.- return Align(- alignment: Alignment.centerRight,- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- for (final MapEntry(key: provider, value: shown)- in byProvider.entries)- // Loose, so a provider gives width back instead of overflowing:- // two providers' worth of `92% used · resets in 12d 8h` beside the- // key hints is wider than a narrow window leaves.- Flexible(- child: RailHoverTarget<UsageProvider>(- kind: provider,- anchor: anchorFor(provider),- semantics: _semantics(provider, shown),- onEnter: onEnter,- onExit: onExit,- child: _ProviderFigures(provider: provider, accounts: shown),- ),- ),- ],- ),- );- }-- static String _semantics(UsageProvider provider, List<UsageAccount> shown) {- final figures = [- for (final account in shown)- '${account.reading.railWindow?.usedPercent.round() ?? 0} percent used'- '${account.isLocal ? '' : ' on ${account.machines.join(', ')}'}',- ];- return '${provider.label} usage, ${figures.join('; ')}';- }-}--/// One provider's accounts, as the strip prints them: its mark once, then a-/// figure per account.-class _ProviderFigures extends StatelessWidget {- const _ProviderFigures({required this.provider, required this.accounts});-- final UsageProvider provider;- final List<UsageAccount> accounts;-- @override- Widget build(BuildContext context) {- TerminalFontScope.watch(context);- final style = terminalTextStyle(color: grid.AppPalette.textSecondary);- return Row(- mainAxisSize: MainAxisSize.min,- children: [- EngineMark(engine: provider.engineId, size: 12),- const SizedBox(width: 5),- for (final (index, account) in accounts.indexed) ...[- if (index > 0)- Text(- ' · ',- style: style.copyWith(color: grid.AppPalette.textFaint),- ),- // Loose, so the bound the rail put on this whole block reaches the- // one `Flexible` inside the figure. `_AccountFigure`'s Row is `min`- // and a `min` Row inside a `min` Row passes its parent's constraint- // down unchanged — but only to children that can take it, and a- // bare child here cannot. Without this the figures measured at- // their natural width and overflowed the cap rather than trimming.- Flexible(- child: _AccountFigure(account: account, style: style),- ),- ],- ],- );- }-}--/// One account's figure: its weekly window, and — when it is not this-/// computer's — the machine it was read on.-class _AccountFigure extends StatelessWidget {- const _AccountFigure({required this.account, required this.style});-- final UsageAccount account;- final TextStyle style;-- /// A hostname can be long, and the strip is 26px of furniture. The panel- /// behind the figure names every machine in full.- static const double _labelMaxWidth = 110;-- @override- Widget build(BuildContext context) {- TerminalFontScope.watch(context);- // ⚠️ ONE window, not every window this account reports — see- // [ProviderUsage.railWindow]. Claude answers with three and Codex with one,- // so printing them all made one account three figures wide and the other- // one: two readouts that read as different KINDS of thing rather than the- // same thing about two accounts.- final window = account.reading.railWindow;- if (window == null) return const SizedBox.shrink();- final faint = style.copyWith(color: grid.AppPalette.textFaint);- return Row(- mainAxisSize: MainAxisSize.min,- children: [- Text(- '${window.usedPercent.round()}% used',- // Amber past 80, red past 90. The figure is exact either way, so the- // colour is not carrying the number — it is carrying the moment the- // number starts to matter, which is the whole reason somebody would- // look down here unprompted. `19% used` and `92% used` used to print- // identically.- style: style.copyWith(- fontWeight: grid.AppFont.medium,- color: usagePressureInk(- window.pressure,- grid.AppPalette.textSecondary,- ),- ),- ),- const SizedBox(width: 4),- // The countdown when there is one, and the window's own name when there- // is not — so the figure is always followed by something that says- // which limit it belongs to.- //- // Flexible, and the only part of the figure that is: this readout- // shares the strip with the key hints, and something has to give when- // two accounts' worth of it will not fit. The percentage is what a- // person came here to read and must never be clipped; `resets in 12d- // 8h` still means something half-ellipsised.- Flexible(- child: Text(- window.resetsInLabel() ?? window.label,- maxLines: 1,- overflow: TextOverflow.ellipsis,- softWrap: false,- style: faint,- ),- ),- // This computer's figure is never labelled: it is the one a person- // reads as "mine" without being told. Every OTHER account is, because- // two Claude figures side by side are a riddle without it.- if (!account.isLocal && account.machines.isNotEmpty) ...[- const SizedBox(width: 6),- ConstrainedBox(- constraints: const BoxConstraints(maxWidth: _labelMaxWidth),- child: Text(- account.machines.length == 1- ? account.machines.first- : '${account.machines.first} +${account.machines.length - 1}',- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: faint,- ),- ),- ],- ],- );- }-}--/// The readout before the first answer: the same padding a live figure's hover-/// region takes, so the strip is the same width before and after.-class _UsageSkeleton extends StatelessWidget {- const _UsageSkeleton();-- @override- Widget build(BuildContext context) {- TerminalFontScope.watch(context);- return Padding(- padding: const EdgeInsets.symmetric(- horizontal: RailHoverTarget.gap,- vertical: 4,- ),- child: SkeletonText(- // Measured against what lands here — one figure per account, an engine- // mark and a countdown each. A placeholder wider than its answer is the- // jump a skeleton exists to prevent, in the other direction.- style: terminalTextStyle(fontWeight: grid.AppFont.medium),- width: 84,- ),- );- }-}diff --git a/desktop/lib/widgets/swarm_project_agents.dart b/desktop/lib/widgets/swarm_project_agents.dartdeleted file mode 100644index ddb9eae98..000000000--- a/desktop/lib/widgets/swarm_project_agents.dart+++ /dev/null@@ -1,143 +0,0 @@-import 'swarm_search_field.dart';--import 'package:flutter/material.dart';-import 'package:harness/shared/theme/app_type.dart';--import '../shared/widgets/app_dialog.dart';-import '../state/app_state.dart';-import '../state/swarm_catalog.dart';--Future<SavedSwarmProject?> showSwarmProjectAgents(- BuildContext context,- AppNotifier app,- SwarmProjectGroup group,-) => showAppDialog<SavedSwarmProject>(- context: context,- transitionDuration: Duration.zero,- veilBlur: 0,- builder: (_) => _ProjectAgents(app: app, group: group),-);--class _ProjectAgents extends StatefulWidget {- const _ProjectAgents({required this.app, required this.group});- final AppNotifier app;- final SwarmProjectGroup group;- @override- State<_ProjectAgents> createState() => _ProjectAgentsState();-}--class _ProjectAgentsState extends State<_ProjectAgents> {- late final _members = {...?widget.group.saved?.members};- late final _automatic = {- for (final a in widget.group.agents)- if (a.project?.identity(a.machineId) == widget.group.id)- (machineId: a.machineId, agentId: a.agent.id),- };- String _query = '';-- void _save() {- final original = widget.group.saved;- final anchor = widget.group.agents- .where((a) => a.project != null)- .firstOrNull;- if (original == null && anchor == null) return;- Navigator.pop(- context,- SavedSwarmProject(- machineId: original?.machineId ?? anchor!.machineId,- path: original?.path ?? anchor!.project!.root ?? anchor!.project!.cwd,- name: original?.name ?? widget.group.name,- members: List.unmodifiable(_members),- ),- );- }-- @override- Widget build(BuildContext context) {- return Dialog(- child: SizedBox(- width: 620,- height: 520,- child: Padding(- padding: const EdgeInsets.all(20),- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- Text(widget.group.name, style: AppType.heading()),- const SizedBox(height: 8),- Text(- 'Include agents from any machine. Matching repositories are included automatically.',- style: AppType.body(),- ),- const SizedBox(height: 16),- SwarmSearchField(- autofocus: true,- hintText: 'Find a harness or machine',- onChanged: (value) => setState(() => _query = value),- ),- const SizedBox(height: 12),- Expanded(- child: ListenableBuilder(- listenable: widget.app,- builder: (context, _) {- final rows = swarmAgents(widget.app, _query);- if (rows.isEmpty) {- return const Center(child: Text('No matching harnesses'));- }- return ListView.builder(- itemCount: rows.length,- itemBuilder: (context, index) {- final agent = rows[index];- final id = (- machineId: agent.machineId,- agentId: agent.agent.id,- );- final automatic = _automatic.contains(id);- return CheckboxListTile(- controlAffinity: ListTileControlAffinity.leading,- contentPadding: EdgeInsets.zero,- value: automatic || _members.contains(id),- title: Text(- agent.agent.name,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: AppType.label(),- ),- subtitle: Text(- '${agent.machine.machine.displayName}${automatic ? ' · Repository match' : ''}',- style: AppType.body(),- ),- onChanged: automatic- ? null- : (selected) => setState(() {- if (selected == true) {- _members.add(id);- } else {- _members.remove(id);- }- }),- );- },- );- },- ),- ),- const SizedBox(height: 12),- Row(- mainAxisAlignment: MainAxisAlignment.end,- children: [- TextButton(- onPressed: () => Navigator.pop(context),- child: const Text('Cancel'),- ),- const SizedBox(width: 8),- FilledButton(onPressed: _save, child: const Text('Save')),- ],- ),- ],- ),- ),- ),- );- }-}diff --git a/desktop/test/account_footer_test.dart b/desktop/test/account_footer_test.dartdeleted file mode 100644index f4b6d5080..000000000--- a/desktop/test/account_footer_test.dart+++ /dev/null@@ -1,126 +0,0 @@-import 'package:flutter/material.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/shared/theme/app_theme.dart';-import 'package:harness/shared/widgets/app_menu.dart';-import 'package:harness/state/app_state.dart';-import 'package:harness/widgets/account_footer.dart';--/// The account menu's rows.-///-/// Only the destructive treatment is asserted here, and deliberately so: it is-/// the one property of this menu that carries *meaning* rather than taste. Sign-/// out ends the session, and it sat for a long time in exactly the same ink as-/// Settings — the row above it, which does nothing of the kind. A test that-/// pinned the padding or the font size would fail on every future tune-up-/// without ever catching that.-void main() {- TestWidgetsFlutterBinding.ensureInitialized();-- Future<AppNotifier> pumpMenu(- WidgetTester tester, {- required Brightness brightness,- }) async {- final notifier = AppNotifier(- config: AppConfig.dev,- authSession: AuthSession(),- configStore: null,- );- notifier.currentUser = const CurrentUserProfile(- name: 'Avery Example',- email: '[email protected]',- );- addTearDown(notifier.dispose);-- tester.view.physicalSize = const Size(900 * 2, 700 * 2);- tester.view.devicePixelRatio = 2;- addTearDown(tester.view.reset);-- await tester.pumpWidget(- MaterialApp(- theme: buildAppTheme(brightness: brightness),- home: Scaffold(- // The footer sits at the bottom of a rail; the menu opens upward, so- // it needs room above it to land in.- body: Align(- alignment: Alignment.bottomLeft,- child: SizedBox(- width: 240,- child: AccountFooter(notifier: notifier),- ),- ),- ),- ),- );- await tester.tap(find.byKey(const Key('account-menu-button')));- await tester.pumpAndSettle();- return notifier;- }-- AppMenuItem itemByKey(WidgetTester tester, String key) =>- tester.widget<AppMenuItem>(find.byKey(Key(key)));-- for (final brightness in Brightness.values) {- final label = brightness == Brightness.dark ? 'dark' : 'light';-- testWidgets('sign out is the only destructive row ($label)', (- tester,- ) async {- await pumpMenu(tester, brightness: brightness);-- expect(itemByKey(tester, 'sign-out-menu-item').danger, isTrue);- // The two rows that merely NAVIGATE must not borrow the treatment — a- // menu where everything is red says nothing is.- expect(itemByKey(tester, 'settings-menu-item').danger, isFalse);- expect(itemByKey(tester, 'link-a-machine-menu-item').danger, isFalse);- });-- testWidgets('sign out draws in the error ink ($label)', (tester) async {- await pumpMenu(tester, brightness: brightness);-- final context = tester.element(- find.byKey(const Key('sign-out-menu-item')),- );- final error = Theme.of(context).colorScheme.error;- final text = tester.widget<Text>(- find.descendant(- of: find.byKey(const Key('sign-out-menu-item')),- matching: find.text('Sign out'),- ),- );-- expect(text.style?.color, error);- // Not the ink every other row takes — the assertion above would pass by- // accident if the two ever resolved to the same value.- expect(text.style?.color, isNot(AppPalette.textPrimary));- });- }-- // The provider pill used to stand on the rail's floor; a row here briefly- // replaced it, and that went too. Settings is the one door onto the pane —- // two rows opening one screen, one directly above the other, is two rows that- // are both right and neither of which says which to press.- testWidgets('no provider row: Settings is the only way to that pane', (- tester,- ) async {- await pumpMenu(tester, brightness: Brightness.dark);-- expect(find.byKey(const Key('providers-menu-item')), findsNothing);- expect(find.text('Where new agents run…'), findsNothing);- expect(find.text('Providers'), findsNothing);- expect(find.byKey(const Key('settings-menu-item')), findsOneWidget);- });-- testWidgets('the summary names the account above its address', (- tester,- ) async {- await pumpMenu(tester, brightness: Brightness.dark);-- expect(find.text('Avery Example'), findsOneWidget);- // Twice: once in the pill that opened the menu, once in the panel's summary.- expect(find.text('[email protected]'), findsNWidgets(2));- });-}diff --git a/desktop/test/agent_switcher_test.dart b/desktop/test/agent_switcher_test.dartdeleted file mode 100644index 756a36f85..000000000--- a/desktop/test/agent_switcher_test.dart+++ /dev/null@@ -1,124 +0,0 @@-// ⌘P — the ranking behind "go to an agent by name".-//-// Pinned here rather than through the widget, because "why did it not find my-// agent" is the one bug report a fuzzy list reliably generates, and the answer-// is always in these two functions.-import 'package:flutter_test/flutter_test.dart';-import 'package:harness/core/models.dart';-import 'package:harness/widgets/agent_switcher.dart';--Agent _agent(String id, String name) => Agent(- id: id,- sessionId: null,- name: name,- engine: 'claude',- engineDisplayName: null,- engineIconHint: null,- codexHome: null,- parentAgentId: null,- status: 'running',- launchState: 'ready',- launchError: null,- launchDetail: null,- terminalAvailable: true,-);--SwitcherEntry _entry(- String name, {- String machine = 'MacBook-Pro.local',- bool onGrid = false,- String? id,-}) => SwitcherEntry(- machineId: 'm1',- machineName: machine,- agent: _agent(id ?? name, name),- onGrid: onGrid,-);--void main() {- group('subsequenceSpread', () {- test('an exact run is the tightest possible', () {- expect(subsequenceSpread('frontend', 'front'), 4);- });-- test('matches letters that are apart — this is fzf, not a substring', () {- // The whole reason to use a subsequence: `frn` is what a hand types when- // it is going fast, and a substring matcher answers "no such agent".- expect(subsequenceSpread('frontend', 'frn'), isNotNull);- });-- test('is null when a letter is missing, or out of order', () {- expect(subsequenceSpread('frontend', 'frx'), isNull);- expect(subsequenceSpread('frontend', 'nof'), isNull);- });-- test('an empty query matches everything at zero', () {- expect(subsequenceSpread('anything', ''), 0);- });-- test('a tight match scores lower than a scattered one', () {- // Which is the ranking: lower spread sorts first.- final tight = subsequenceSpread('auth', 'ath')!;- final scattered = subsequenceSpread('a big ugly thing', 'ath')!;- expect(tight, lessThan(scattered));- });- });-- group('rankAgentsForSwitcher', () {- test('with no query, the agents NOT on the grid come first', () {- // Someone who opened this with an empty field is looking for something- // they cannot already see.- final rows = rankAgentsForSwitcher([- _entry('alpha', onGrid: true),- _entry('beta'),- ], '');- expect(rows.map((r) => r.agent.name), ['beta', 'alpha']);- });-- test('drops what does not match at all', () {- final rows = rankAgentsForSwitcher([- _entry('frontend'),- _entry('billing'),- ], 'front');- expect(rows.map((r) => r.agent.name), ['frontend']);- });-- test('ranks the tighter match first', () {- final rows = rankAgentsForSwitcher([- _entry('a big ugly thing'),- _entry('auth'),- ], 'ath');- expect(rows.first.agent.name, 'auth');- });-- test('a query can name the MACHINE instead', () {- // "mini auth" has to reach the Auth agent on the mac mini — two agents- // with the same name on two computers are told apart by nothing else.- final rows = rankAgentsForSwitcher([- _entry('auth', machine: 'MacBook-Pro.local', id: 'a1'),- _entry('auth', machine: 'mac-mini', id: 'a2'),- ], 'mini');- expect(rows, hasLength(1));- expect(rows.first.agent.id, 'a2');- });-- test('is case- and whitespace-insensitive', () {- final rows = rankAgentsForSwitcher([_entry('Frontend')], ' FRONT ');- expect(rows, hasLength(1));- });-- test('keeps agents that are already on the grid', () {- // Hiding them would make ⌘P useless for the very agents being worked on:- // "where is it" and "is it open" are different questions.- final rows = rankAgentsForSwitcher([- _entry('auth', onGrid: true),- ], 'auth');- expect(rows, hasLength(1));- expect(rows.first.onGrid, isTrue);- });-- test('an empty roster is an empty list, not a throw', () {- expect(rankAgentsForSwitcher(const [], 'anything'), isEmpty);- });- });-}diff --git a/desktop/test/app_log_test.dart b/desktop/test/app_log_test.dartindex b9c69f3ae..98486332a 100644--- a/desktop/test/app_log_test.dart+++ b/desktop/test/app_log_test.dart@@ -5,7 +5,6 @@ import 'dart:io';import 'package:flutter_test/flutter_test.dart';import 'package:harness/logging/app_log.dart';-import 'package:harness/logging/app_log_tail.dart';import 'package:harness/logging/error_burst_filter.dart';import 'package:harness/logging/log_file.dart';@@ -140,32 +139,4 @@ void main() {expect('\n'.allMatches(sink.currentFile.readAsStringSync()).length, 5);});});-- group('recentErrorLines', () {- const log = '''-[2026-09-07 08:00:00] INFO app launched-[2026-09-07 08:00:01] ERROR ws first failure- #0 a stack frame that must not be picked up-[2026-09-07 08:00:02] WARN cli a warning-[2026-09-07 08:00:03] ERROR api second failure-''';-- test('keeps only ERROR lines, newest last, without their stacks', () {- expect(recentErrorLines(log), [- '[2026-09-07 08:00:01] ERROR ws first failure',- '[2026-09-07 08:00:03] ERROR api second failure',- ]);- });-- test('keeps at most `keep`, taking the newest', () {- expect(recentErrorLines(log, keep: 1), [- '[2026-09-07 08:00:03] ERROR api second failure',- ]);- });-- test('a very long line is clipped', () {- final wide = '[2026-09-07 08:00:00] ERROR api ${'x' * 400}';- expect(recentErrorLines(wide, clip: 60).single.length, 61);- });- });}diff --git a/desktop/test/attention_surfaces_test.dart b/desktop/test/attention_surfaces_test.dartindex 4ee30208a..890b3c2d8 100644--- a/desktop/test/attention_surfaces_test.dart+++ b/desktop/test/attention_surfaces_test.dart@@ -1,11 +1,6 @@-// Where a blocked agent may and may NOT show itself.-//-// The rail deliberately says nothing: its badge means "a turn is running", and-// that is the only thing it is for. An agent waiting on an answer is a fact-// about the TILE you are looking at, so the tile rings itself and the list-// stays quiet. These pin that split, because the tempting change is to let the-// rail speak too.-import 'package:flutter/material.dart';+// Where a blocked agent shows itself: the tile it is in reads its question+// from the notifier and rings itself.+import 'package:flutter_test/flutter_test.dart';import 'package:harness/auth/auth_session.dart';@@ -13,7 +8,6 @@ import 'package:harness/core/config.dart';import 'package:harness/core/models.dart';import 'package:harness/state/app_state.dart';import 'package:harness/state/pending_question.dart';-import 'package:harness/widgets/machine_rail.dart';const _machine = Machine(machineId: 'm1',@@ -59,57 +53,8 @@ PendingQuestion question({String agentId = 'a1'}) => PendingQuestion(multi: false,since: DateTime.now(),);--Future<void> pumpRail(WidgetTester tester, AppNotifier notifier) async {- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SizedBox(width: 320, child: MachineRail(notifier: notifier)),- ),- ),- );- await tester.pump();-}-void main() {- testWidgets('a blocked agent keeps the rail exactly as it was', (- tester,- ) async {- final notifier = notifierWithAgents([_agent('a1', 'payments')]);- final state = notifier.machineStates['m1']!;- state.processingAgentIds.add('a1');- // Both are true at once — the turn stays open while the dialog waits — and- // the row shows only the one it has always shown.- state.blockedAgents['a1'] = question();-- await pumpRail(tester, notifier);-- expect(- find.byKey(const ValueKey('agent-processing-indicator')),- findsOneWidget,- reason: 'the spinner is the rail badge, blocked or not',- );- expect(- find.text('Which colour theme do you want?'),- findsNothing,- reason: 'the question belongs to the tile, not to the list',- );- });-- testWidgets('and an idle blocked agent adds no mark either', (tester) async {- final notifier = notifierWithAgents([_agent('a1', 'payments')]);- notifier.machineStates['m1']!.blockedAgents['a1'] = question();-- await pumpRail(tester, notifier);-- expect(find.text('payments'), findsOneWidget);- expect(- find.byKey(const ValueKey('agent-processing-indicator')),- findsNothing,- );- });-- test('the tile can see what the rail will not', () {+ test('the tile can read a blocked agent\'s question', () {// The one reader. If this goes, nothing draws the ring and the whole// question path becomes dead weight.final notifier = notifierWithAgents([_agent('a1', 'payments')]);diff --git a/desktop/test/device_align_test.dart b/desktop/test/device_align_test.dartdeleted file mode 100644index db24dfa20..000000000--- a/desktop/test/device_align_test.dart+++ /dev/null@@ -1,52 +0,0 @@-// The device row's column is the account row's column — measured, not eyeballed.-import 'package:flutter/material.dart';-import 'package:flutter_test/flutter_test.dart';-import 'package:harness/auth/auth_session.dart';-import 'package:harness/core/config.dart';-import 'package:harness/state/app_state.dart';-import 'package:harness/state/dial_status.dart';-import 'package:harness/widgets/account_footer.dart';-import 'package:harness/widgets/device_row.dart';--void main() {- testWidgets('the dot and the text sit on the avatar and the email', (- tester,- ) async {- // The two pills share a left column or they read as two row types. The first cut put the mark- // in a 26px box because that is what the account pill LOOKS like; the avatar is 32, and the- // six-pixel miss was visible from across the room. So this measures, in pixels.- final n = AppNotifier(- config: AppConfig.dev,- authSession: AuthSession(),- configStore: null,- )..dial.apply(const DialStatus(attached: true));- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: Column(- children: [- SizedBox(width: 264, child: DeviceRow(notifier: n)),- SizedBox(width: 264, child: AccountFooter(notifier: n)),- ],- ),- ),- ),- );- await tester.pump();- final dot = tester.getCenter(find.byKey(const Key('device-dot')));- final avatar = tester.getCenter(find.byKey(const Key('account-avatar')));- expect(- dot.dx,- closeTo(avatar.dx, 0.5),- reason: 'mark centre vs avatar centre',- );- final label = tester.getTopLeft(find.text('Harness device'));- // Signed out in a test, the pill prints its fallback where the email goes; same column.- final email = tester.getTopLeft(find.text('signed in'));- expect(- label.dx,- closeTo(email.dx, 0.5),- reason: 'label left vs email left',- );- });-}diff --git a/desktop/test/device_row_test.dart b/desktop/test/device_row_test.dartdeleted file mode 100644index 42a6746ef..000000000--- a/desktop/test/device_row_test.dart+++ /dev/null@@ -1,134 +0,0 @@-// The dial's row on the rail's floor: one row, three readings, decided by two facts.-import 'package:flutter/material.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/local_key_value_store.dart';-import 'package:harness/state/app_state.dart';-import 'package:harness/state/dial_status.dart';-import 'package:harness/widgets/device_row.dart';--class _MemoryStore implements LocalKeyValueStore {- final values = <String, String>{};- @override- Future<String?> read(String key) async => values[key];- @override- Future<void> write(String key, String value) async => values[key] = value;- @override- Future<void> delete(String key) async => values.remove(key);-}--AppNotifier _notifier() => AppNotifier(- config: AppConfig.dev,- authSession: AuthSession(),- configStore: null,-);--Future<void> _pump(WidgetTester tester, AppNotifier notifier) async {- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SizedBox(width: 264, child: DeviceRow(notifier: notifier)),- ),- ),- );- await tester.pump();-}--void main() {- testWidgets('never seen one: the row is the way to get one', (tester) async {- final notifier = _notifier();- await _pump(tester, notifier);- expect(find.textContaining('Get the device'), findsOneWidget);- expect(find.byIcon(Icons.chevron_right), findsNothing);- });-- testWidgets('plugged in: the name alone, and a way to its status', (- tester,- ) async {- // No version, no port on the row — the green ring already says "here", and- // the card this opens carries the rest.- final notifier = _notifier();- notifier.dial.apply(const DialStatus(attached: true, fw: '0.0.58'));- await _pump(tester, notifier);- expect(find.text('Harness device'), findsOneWidget);- expect(find.textContaining('0.0.58'), findsNothing);- expect(find.textContaining('Get the device'), findsNothing);- expect(find.byIcon(Icons.chevron_right), findsOneWidget);-- await tester.tap(find.byKey(const Key('device-row')));- await tester.pumpAndSettle();- // One rich line: state, then the version in a heavier ink.- expect(- find.textContaining('Connected via USB', findRichText: true),- findsOneWidget,- );- expect(find.textContaining('0.0.58', findRichText: true), findsOneWidget);- expect(find.text('Settings are on the device'), findsOneWidget);- });-- testWidgets('unplugged after being seen: told so, not sold another', (- tester,- ) async {- final notifier = _notifier();- notifier.dial.apply(const DialStatus(attached: true, fw: '0.0.58'));- notifier.dial.apply(DialStatus.none);- await _pump(tester, notifier);- expect(find.text('Harness device · unplugged'), findsOneWidget);- expect(find.textContaining('Get the device'), findsNothing);- });-- testWidgets('an update in flight says the one thing that matters', (- tester,- ) async {- final notifier = _notifier();- notifier.dial.apply(- const DialStatus(attached: true, fw: '0.0.57', updating: '0.0.58'),- );- await _pump(tester, notifier);- await tester.tap(find.byKey(const Key('device-row')));- await tester.pumpAndSettle();- expect(find.text('Keep it plugged in'), findsOneWidget);- expect(- find.textContaining('updating to 0.0.58', findRichText: true),- findsOneWidget,- );- });-- test(- '"seen" is remembered across launches, and only ever set by a real dial',- () async {- final store = _MemoryStore();- final state = DialState(store);- await state.restore();- expect(state.seen, isFalse);-- state.apply(DialStatus.none);- expect(store.values, isEmpty, reason: 'nothing seen yet');-- state.apply(const DialStatus(attached: true));- await Future<void>.delayed(Duration.zero);- expect(store.values['dial_seen'], '1');-- final later = DialState(store);- await later.restore();- expect(later.seen, isTrue);- },- );-- test('the frame is read with is, never as', () {- expect(- DialStatus.fromJson({'attached': true, 'fw': '0.0.58'}).fw,- '0.0.58',- );- final junk = DialStatus.fromJson({- 'attached': 'yes',- 'fw': 7,- 'updating': '',- });- expect(junk.attached, isFalse);- expect(junk.fw, isNull);- expect(junk.updating, isNull);- });-}diff --git a/desktop/test/dial_status_test.dart b/desktop/test/dial_status_test.dartnew file mode 100644index 000000000..7e9e1cd06--- /dev/null+++ b/desktop/test/dial_status_test.dart@@ -0,0 +1,53 @@+// What the app remembers about the dial, and how it reads the dial's status frame.+import 'package:flutter_test/flutter_test.dart';++import 'package:harness/core/local_key_value_store.dart';+import 'package:harness/state/dial_status.dart';++class _MemoryStore implements LocalKeyValueStore {+ final values = <String, String>{};+ @override+ Future<String?> read(String key) async => values[key];+ @override+ Future<void> write(String key, String value) async => values[key] = value;+ @override+ Future<void> delete(String key) async => values.remove(key);+}++void main() {+ test(+ '"seen" is remembered across launches, and only ever set by a real dial',+ () async {+ final store = _MemoryStore();+ final state = DialState(store);+ await state.restore();+ expect(state.seen, isFalse);++ state.apply(DialStatus.none);+ expect(store.values, isEmpty, reason: 'nothing seen yet');++ state.apply(const DialStatus(attached: true));+ await Future<void>.delayed(Duration.zero);+ expect(store.values['dial_seen'], '1');++ final later = DialState(store);+ await later.restore();+ expect(later.seen, isTrue);+ },+ );++ test('the frame is read with is, never as', () {+ expect(+ DialStatus.fromJson({'attached': true, 'fw': '0.0.58'}).fw,+ '0.0.58',+ );+ final junk = DialStatus.fromJson({+ 'attached': 'yes',+ 'fw': 7,+ 'updating': '',+ });+ expect(junk.attached, isFalse);+ expect(junk.fw, isNull);+ expect(junk.updating, isNull);+ });+}diff --git a/desktop/test/machine_tree_widget_test.dart b/desktop/test/machine_tree_widget_test.dartindex 9a10c52f0..3f36a2119 100644--- a/desktop/test/machine_tree_widget_test.dart+++ b/desktop/test/machine_tree_widget_test.dart@@ -3,11 +3,7 @@ import 'package:harness/core/config.dart';import 'package:harness/core/models.dart';import 'package:harness/state/app_state.dart';import 'package:harness/terminal/terminal_session.dart';-import 'package:harness/widgets/machine_rail.dart';-import 'package:flutter/gestures.dart';-import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';-import 'package:harness/shared/theme/app_theme.dart';class ReloadTrackingNotifier extends AppNotifier {int machineRefreshes = 0;@@ -111,29 +107,18 @@ void main() {return notifier;}- AppNotifier notifierWithLoadState(- AgentLoadStatus loadStatus, {- String? error,- }) {- final notifier = AppNotifier(- config: AppConfig.dev,- authSession: AuthSession(),- configStore: null,- );- final state = MachineState(machine)- ..connectionStatus = ConnectionStatus.connected- ..agentLoadStatus = loadStatus- // In production these two are always set together — see onLocalFailure- // in app_state.dart — so a needsLink fixture must carry both, or the- // caption row's link affordance (which reads the raw bool, the same- // signal the root-cause fix operates on) would never see it.- ..needsLink = loadStatus == AgentLoadStatus.needsLink- ..agentsLoadError = error;- notifier.machines = [machine];- notifier.machineStates[machine.machineId] = state;- notifier.expandedMachines.add(machine.machineId);- return notifier;- }+ test('offline agent selection keeps the agent pending', () async {+ final notifier = notifierWithTree();+ final state = notifier.machineStates[machine.machineId]!;+ state.nodeOnline = false;++ await notifier.selectAgent(machine.machineId, 'parent');++ expect(state.activeAgentId, 'parent');+ expect(state.pendingOfflineAgentId, 'parent');+ expect(notifier.activeTerminal, isNull);+ notifier.dispose();+ });test('reselecting the active agent keeps its terminal controller', () async {final notifier = notifierWithTree();@@ -158,476 +143,6 @@ void main() {notifier.dispose();});- testWidgets('an empty machine offers a row, not a sentence and a button', (- tester,- ) async {- // The empty state IS the list, with one row in it that would become an agent. What it must NOT be is- // what it was: a 13.5px status line under an 11px machine caption — a sentence outranking its own- // heading — over an accent-washed button that read as the primary action of the whole window for a- // machine that is merely idle.- final notifier = notifierWithLoadState(AgentLoadStatus.loaded);- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SizedBox(width: 320, child: MachineRail(notifier: notifier)),- ),- ),- );- await tester.pump();-- expect(find.text('New Harness'), findsOneWidget);- expect(find.text('no running agents'), findsNothing);- // Keep one quiet list action rather than the old prominent button.- expect(find.widgetWithText(TextButton, 'New Harness'), findsNothing);- });-- testWidgets('a machine that HAS agents is offered the same row, last', (- tester,- ) async {- // The same problem one row further down: adding to a machine that already has agents was reachable- // only through a `+` revealed on hover of the machine's caption, which nobody finds who does not- // already know it is there.- final notifier = notifierWithTree();- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SizedBox(width: 320, child: MachineRail(notifier: notifier)),- ),- ),- );- await tester.pump();-- expect(find.text('backend-api'), findsOneWidget);- expect(find.text('New Harness'), findsOneWidget);- // …and LAST, because a row that would create the next agent has to stand where the next agent would.- final rowY = tester.getTopLeft(find.text('New Harness')).dy;- for (final name in ['backend-api', 'future-worker', 'herdr-session']) {- expect(- tester.getTopLeft(find.text(name)).dy,- lessThan(rowY),- reason: '$name should sit above the invitation',- );- }- });-- testWidgets('renders one-line agent rows with engine identity', (- tester,- ) async {- final notifier = notifierWithTree();- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SizedBox(width: 320, child: MachineRail(notifier: notifier)),- ),- ),- );- await tester.pump();-- expect(find.text('prod-mac'), findsOneWidget);- final machineIcon = tester.widget<Icon>(- find.byKey(const ValueKey('machine-connection-icon')),- );- expect(machineIcon.color, AppPalette.online);- expect(find.text('backend-api'), findsOneWidget);- expect(find.text('future-worker'), findsOneWidget);- expect(find.byKey(const ValueKey('engine-icon-codex')), findsOneWidget);- expect(- find.byKey(- const ValueKey('engine-fallback-engine-added-after-app-release'),- ),- findsOneWidget,- );- expect(find.text('herdr-session'), findsOneWidget);- expect(find.text('CTRL'), findsNothing);- expect(find.text('active'), findsNothing);- expect(find.text('busy'), findsNothing);- expect(find.text('NO TMUX'), findsNothing);- await tester.tap(find.text('herdr-session'));- await tester.pump();- expect(notifier.activeTerminal, isNull);- expect(notifier.machineStates['machine-1']!.activeAgentId, isNull);- notifier.dispose();- });-- testWidgets('shows a gray computer icon when the machine is offline', (- tester,- ) async {- final notifier = notifierWithTree();- notifier.machineStates[machine.machineId]!.connectionStatus =- ConnectionStatus.disconnected;- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SizedBox(width: 320, child: MachineRail(notifier: notifier)),- ),- ),- );- await tester.pump();-- final machineIcon = tester.widget<Icon>(- find.byKey(const ValueKey('machine-connection-icon')),- );- expect(machineIcon.color, AppPalette.textFaint);- notifier.dispose();- });-- testWidgets(- 'shows a gray computer icon when nodeOnline is false even if the relay WS reports connected',- (tester) async {- final notifier = notifierWithTree();- notifier.machineStates[machine.machineId]!- ..connectionStatus = ConnectionStatus.connected- ..nodeOnline = false;- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SizedBox(width: 320, child: MachineRail(notifier: notifier)),- ),- ),- );- await tester.pump();-- final machineIcon = tester.widget<Icon>(- find.byKey(const ValueKey('machine-connection-icon')),- );- expect(machineIcon.color, AppPalette.textFaint);- notifier.dispose();- },- );-- testWidgets(- 'shows a green icon and an always-visible link button when reachable but not yet linked',- (tester) async {- // The backend says the machine is up; only our own link to it is- // missing. That reads as online — our socket bouncing off NO_PEER_LINK- // says nothing about the other computer — and the fix is one click away- // on the row itself, not hidden behind hover or a Link this machine… row- // nobody expanded to.- final notifier = notifierWithLoadState(AgentLoadStatus.needsLink);- notifier.machineStates[machine.machineId]!- ..nodeOnline = true- ..connectionStatus = ConnectionStatus.disconnected;- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SizedBox(width: 320, child: MachineRail(notifier: notifier)),- ),- ),- );- await tester.pump();-- final machineIcon = tester.widget<Icon>(- find.byKey(const ValueKey('machine-connection-icon')),- );- expect(machineIcon.color, AppPalette.online);- expect(find.text('offline'), findsNothing);- final linkButton = find.byKey(const ValueKey('machine-link-affordance'));- expect(linkButton, findsOneWidget);-- await tester.tap(linkButton);- await tester.pump();- expect(notifier.selectedMachineId, machine.machineId);- notifier.dispose();- },- );-- testWidgets(- 'an unlinked machine of unknown reachability is offered a link but not called online',- (tester) async {- // NO_PEER_LINK is the local CLI's peer table saying no before anything is- // dialled, so with no REST verdict yet there is nothing to paint green —- // the machine may well be off. The link is still offered, as- // _LinkMachineRow does, because "unknown" is not "off".- final notifier = notifierWithLoadState(AgentLoadStatus.needsLink);- notifier.machineStates[machine.machineId]!- ..nodeOnline = null- ..connectionStatus = ConnectionStatus.disconnected;- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SizedBox(width: 320, child: MachineRail(notifier: notifier)),- ),- ),- );- await tester.pump();-- final machineIcon = tester.widget<Icon>(- find.byKey(const ValueKey('machine-connection-icon')),- );- expect(machineIcon.color, AppPalette.textFaint);- expect(find.text('offline'), findsNothing);- expect(- find.byKey(const ValueKey('machine-link-affordance')),- findsOneWidget,- );- notifier.dispose();- },- );-- testWidgets('marks and prioritizes this computer', (tester) async {- const localMachine = Machine(- machineId: 'machine-local',- apiKey: '',- authMode: MachineAuthMode.remote,- name: 'this-mac',- status: 'offline',- );- final notifier = AppNotifier(- config: AppConfig.dev,- authSession: AuthSession(),- configStore: null,- );- notifier.machines = [machine, localMachine];- notifier.machineStates[machine.machineId] = MachineState(machine);- notifier.machineStates[localMachine.machineId] = MachineState(localMachine)- ..localOnly = true;-- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SizedBox(width: 320, child: MachineRail(notifier: notifier)),- ),- ),- );- await tester.pump();-- final localRow = find.byKey(const ValueKey('machine-row-machine-local'));- final remoteRow = find.byKey(const ValueKey('machine-row-machine-1'));- expect(- tester.getTopLeft(localRow).dy,- lessThan(tester.getTopLeft(remoteRow).dy),- );- // This computer and a machine across the network must not draw the same- // mark — telling them apart is the whole job of the glyph, and a rail where- // every row looks alike makes the user read names to find their own box.- Icon markOf(Finder row) => tester.widget<Icon>(- find.descendant(- of: row,- matching: find.byKey(const ValueKey('machine-connection-icon')),- ),- );- expect(markOf(localRow).icon, isNot(markOf(remoteRow).icon));- // The glyph carries the fact, so it still has to say so out loud for a- // screen reader — the visible 'This computer' tooltip it replaced is gone.- expect(- tester- .widget<Semantics>(- find- .ancestor(- of: find.descendant(- of: localRow,- matching: find.byKey(- const ValueKey('machine-connection-icon'),- ),- ),- matching: find.byType(Semantics),- )- .first,- )- .properties- .label,- 'This computer',- );- notifier.dispose();- });-- testWidgets('offline agent selection keeps the agent pending', (- tester,- ) async {- final notifier = notifierWithTree();- final state = notifier.machineStates[machine.machineId]!;- state.nodeOnline = false;- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SizedBox(width: 320, child: MachineRail(notifier: notifier)),- ),- ),- );- await tester.tap(find.text('backend-api'));- // Past the double-tap window, not just one frame: an agent row also takes a- // double click (rename), so its single tap is only resolved once the second- // one can no longer arrive. A bare pump() lands inside that window and sees- // a row that has apparently done nothing.- await tester.pump(kDoubleTapTimeout);-- expect(state.activeAgentId, 'parent');- expect(state.pendingOfflineAgentId, 'parent');- expect(notifier.activeTerminal, isNull);- notifier.dispose();- });-- testWidgets('turn lifecycle drives only the processing spinner', (- tester,- ) async {- final notifier = AppNotifier(- config: AppConfig.dev,- authSession: AuthSession(),- configStore: null,- turnActivityTimeout: const Duration(milliseconds: 100),- );- final seeded = notifierWithTree();- notifier.machines = seeded.machines;- notifier.machineStates.addAll(seeded.machineStates);- notifier.expandedMachines.addAll(seeded.expandedMachines);- seeded.machineStates.clear();- seeded.dispose();-- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SizedBox(width: 320, child: MachineRail(notifier: notifier)),- ),- ),- );-- await notifier.handleEventForTest('machine-1', {- 'type': 'turn_heartbeat',- 'dbSessionId': 'session-parent',- 'payload': {'sessionId': 'session-parent'},- });- await tester.pump();- expect(- find.byKey(const ValueKey('agent-processing-indicator')),- findsOneWidget,- );-- await notifier.handleEventForTest('machine-1', {- 'type': 'turn_ended',- 'agentId': 'parent',- 'payload': {'agentId': 'parent'},- });- await tester.pump();- await tester.pump(const Duration(milliseconds: 150));- expect(- find.byKey(const ValueKey('agent-processing-indicator')),- findsNothing,- );-- await notifier.handleEventForTest('machine-1', {- 'type': 'turn_started',- 'agentId': 'parent',- 'payload': {'agentId': 'parent'},- });- await tester.pump();- expect(- find.byKey(const ValueKey('agent-processing-indicator')),- findsOneWidget,- );- await tester.pump(const Duration(milliseconds: 250));- await tester.pump(const Duration(milliseconds: 150));- expect(- find.byKey(const ValueKey('agent-processing-indicator')),- findsNothing,- );- notifier.dispose();- });-- testWidgets(- 'retains lifecycle activity that arrives before the agent snapshot',- (tester) async {- final notifier = AppNotifier(- config: AppConfig.dev,- authSession: AuthSession(),- configStore: null,- turnActivityTimeout: const Duration(seconds: 1),- );- final state = MachineState(machine)- ..connectionStatus = ConnectionStatus.connected- ..terminalCapabilityLoaded = true- ..terminalCapabilityAvailable = true- ..agentLoadStatus = AgentLoadStatus.loaded;- notifier.machines = [machine];- notifier.machineStates[machine.machineId] = state;- notifier.expandedMachines.add(machine.machineId);-- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SizedBox(width: 320, child: MachineRail(notifier: notifier)),- ),- ),- );-- await notifier.handleEventForTest(machine.machineId, {- 'type': 'turn_heartbeat',- 'dbSessionId': 'session-before-list',- 'payload': {'sessionId': 'session-before-list'},- });- await notifier.handleEventForTest(machine.machineId, {- 'type': 'agent_synced',- 'payload': {- 'agent': {- 'id': 'agent-before-list',- 'sessionId': 'session-before-list',- 'name': 'late-agent',- 'engine': 'claude',- 'terminal': {- 'runtimes': [- {'backend': 'tmux', 'paneId': '%8'},- ],- },- },- },- });- await tester.pump();- expect(- find.byKey(const ValueKey('agent-processing-indicator')),- findsOneWidget,- );- notifier.dispose();- },- );-- testWidgets('agent lifecycle updates rows without replacing the tree', (- tester,- ) async {- final notifier = notifierWithTree();- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SizedBox(width: 320, child: MachineRail(notifier: notifier)),- ),- ),- );-- await notifier.handleEventForTest('machine-1', {- 'type': 'agent_synced',- 'payload': {- 'agent': {- 'id': 'new-agent',- 'sessionId': 'new-session',- 'name': 'new-worker',- 'engine': 'claude',- 'terminal': {- 'runtimes': [- {'backend': 'tmux', 'paneId': '%9'},- ],- },- },- },- });- await tester.pump();- expect(find.text('new-worker'), findsOneWidget);- expect(find.byKey(const ValueKey('engine-icon-claude')), findsNWidgets(2));-- await notifier.handleEventForTest('machine-1', {- 'type': 'agent_renamed',- 'payload': {'agentId': 'new-agent', 'name': 'renamed-worker'},- });- await tester.pump();- expect(find.text('new-worker'), findsNothing);- expect(find.text('renamed-worker'), findsOneWidget);-- await notifier.handleEventForTest('machine-1', {- 'type': 'agent_deleted',- 'payload': {'agentId': 'new-agent'},- });- await tester.pump();- expect(find.text('renamed-worker'), findsNothing);- notifier.dispose();- });-test('decrypted events preserve session correlation metadata', () {final clear = eventWithClearPayload({@@ -843,136 +358,6 @@ void main() {notifier.dispose();});- testWidgets('an unlinked machine that is offline is not offered a link', (- tester,- ) async {- // Linking is a handshake with the daemon on the other computer. A daemon- // that is not running cannot shake hands, so the row that starts it must- // not exist while the machine is off — it would be a button for the- // impossible. What shows instead names the state and what comes next.- final notifier = notifierWithLoadState(AgentLoadStatus.needsLink);- notifier.machineStates[machine.machineId]!.nodeOnline = false;- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SizedBox(width: 320, child: MachineRail(notifier: notifier)),- ),- ),- );- await tester.pump();-- expect(find.text('Link this machine…'), findsNothing);- expect(- find.text("Harness isn't running on it · link when it's back"),- findsOneWidget,- );- // …and the offline mark is a word on the caption, not a chip.- expect(find.text('offline'), findsOneWidget);- // Offline wins on the caption row too: no link button pretending the- // handshake is one click away, and the icon reads exactly as offline.- expect(find.byKey(const ValueKey('machine-link-affordance')), findsNothing);- final machineIcon = tester.widget<Icon>(- find.byKey(const ValueKey('machine-connection-icon')),- );- expect(machineIcon.color, AppPalette.textFaint);- notifier.dispose();- });-- testWidgets(- 'shows link-required, loading, and retryable agent error states',- (tester) async {- var notifier = notifierWithLoadState(AgentLoadStatus.needsLink);- notifier.machineStates[machine.machineId]!.nodeOnline = true;- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SizedBox(width: 320, child: MachineRail(notifier: notifier)),- ),- ),- );- // A row, not a status line: the link is the step before this machine's- // first agent, and it wears that row's shape. The old "link required" was- // a condition dressed as a command.- expect(find.text('Link this machine…'), findsOneWidget);- expect(find.text('link required'), findsNothing);- // The same fact is also on the caption row itself, not just the- // expanded tree — a machine the backend calls up, merely unlinked, reads- // as online, with its own one-click way to fix it right beside the name.- final machineIcon = tester.widget<Icon>(- find.byKey(const ValueKey('machine-connection-icon')),- );- expect(machineIcon.color, AppPalette.online);- expect(- find.byKey(const ValueKey('machine-link-affordance')),- findsOneWidget,- );- final otherPane = notifier.adoptSessionForTest(- TerminalSession(- machineId: 'other-machine',- agentId: 'other-agent',- agentName: 'other-agent',- engineId: 'codex',- send: (_, _) async => true,- sendBinary: (_) async => true,- ),- );- await tester.tap(find.text('Link this machine…'));- await tester.pump();- expect(notifier.selectedMachineId, machine.machineId);- // showMachinePane's own doc comment: a needsLink machine gets no tile- // of its own (the blocking link dialog is the surface for it instead),- // so selecting it must not steal focus from whatever pane is already- // open — it stays the unrelated session adopted above.- expect(notifier.activeTerminal, same(otherPane.session));- notifier.dispose();-- notifier = notifierWithLoadState(AgentLoadStatus.loading);- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SizedBox(width: 320, child: MachineRail(notifier: notifier)),- ),- ),- );- // Rows-shaped placeholders, not a sentence: the real rows land where- // these are, so nothing under the machine moves.- expect(find.byKey(const ValueKey('agents-loading')), findsOneWidget);- expect(find.text('loading agents…'), findsNothing);- notifier.dispose();-- notifier = notifierWithLoadState(- AgentLoadStatus.error,- error: 'Could not load agents: disconnected',- );- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SizedBox(width: 320, child: MachineRail(notifier: notifier)),- ),- ),- );- expect(find.textContaining('Could not load agents'), findsOneWidget);- expect(find.byTooltip('Retry agents'), findsOneWidget);- notifier.dispose();- },- );-- testWidgets('keeps existing agents visible while refreshing', (tester) async {- final notifier = notifierWithTree();- notifier.machineStates[machine.machineId]!.agentsRefreshing = true;- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SizedBox(width: 320, child: MachineRail(notifier: notifier)),- ),- ),- );-- expect(find.text('backend-api'), findsOneWidget);- expect(find.byType(LinearProgressIndicator), findsOneWidget);- notifier.dispose();- });-test('global reload refreshes machines and every expanded agent tree',() async {diff --git a/desktop/test/rail_agents_first_test.dart b/desktop/test/rail_agents_first_test.dartdeleted file mode 100644index a1dba5836..000000000--- a/desktop/test/rail_agents_first_test.dart+++ /dev/null@@ -1,212 +0,0 @@-import 'package:flutter/gestures.dart';-import 'package:flutter/material.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/shared/layouts/widgets/sidebar_item.dart';-import 'package:harness/state/app_state.dart';-import 'package:harness/widgets/machine_rail.dart';--/// The rail leads with the agents; a machine is the caption over them.-///-/// These guard what that redesign turned on: every action on a machine sits on-/// that machine's own row and stays out of the way until you point at it, and-/// the two numbers the guide line is built from — the trunk at 19 and the rows-/// at 28 — stay in step with each other.-void main() {- const machine = Machine(- machineId: 'machine-1',- apiKey: '',- authMode: MachineAuthMode.remote,- name: 'prod-mac',- status: 'online',- );-- Agent agent(String id, String name, String engine) => Agent.fromJson({- 'id': id,- 'sessionId': 'session-$id',- 'name': name,- 'engine': engine,- 'status': 'active',- 'terminal': {- 'runtimes': [- {'backend': 'tmux', 'paneId': '%1'},- ],- },- });-- AppNotifier railNotifier({bool expanded = true}) {- final notifier = AppNotifier(- config: AppConfig.dev,- authSession: AuthSession(),- configStore: null,- );- final state = MachineState(machine)- ..connectionStatus = ConnectionStatus.connected- ..terminalCapabilityLoaded = true- ..terminalCapabilityAvailable = true- ..agentLoadStatus = AgentLoadStatus.loaded- ..agents = [- agent('a', 'Ban làm được gì', 'claude'),- agent('b', '9989 · Folder10', 'codex'),- agent('c', 'Claude Code', 'claude'),- ];- notifier.machines = [machine];- notifier.machineStates[machine.machineId] = state;- if (expanded) notifier.expandedMachines.add(machine.machineId);- return notifier;- }-- Future<void> pumpRail(- WidgetTester tester,- AppNotifier notifier, {- double width = 264,- }) async {- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SizedBox(- width: width,- child: MachineRail(notifier: notifier),- ),- ),- ),- );- await tester.pump();- }-- testWidgets('the rail lays out at every width it can be dragged to', (- tester,- ) async {- // 220 is the rail's floor and 520 its ceiling (see home_screen.dart). A- // RenderFlex overflow at either end fails this test on its own — which is- // the point of pumping both rather than only the default.- for (final width in [220.0, 264.0, 520.0]) {- final notifier = railNotifier();- await pumpRail(tester, notifier, width: width);-- expect(- find.text('prod-mac'),- findsOneWidget,- reason: 'the rail did not render at ${width}px',- );- expect(find.text('Ban làm được gì'), findsOneWidget);- notifier.dispose();- }- });-- testWidgets('a machine hides ⋯ and + until you point at its row', (- tester,- ) async {- final notifier = railNotifier();- await pumpRail(tester, notifier);-- // Folded, not merely faded: the pair is clipped to zero width, so the- // hostname has the whole row and nothing invisible sits there to be clicked- // by accident. Measured on the clip box, not on a button — each button- // keeps its own 24px inside it either way.- final menu = find.byTooltip('Machine options');- final plus = find.byTooltip('New Harness here…');- expect(menu, findsOneWidget);- expect(plus, findsOneWidget);- Size actionsBox() => tester.getSize(- find.ancestor(of: plus, matching: find.byType(ClipRect)).first,- );- expect(actionsBox().width, 0);-- final gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);- await gesture.addPointer(location: Offset.zero);- addTearDown(gesture.removePointer);- await gesture.moveTo(tester.getCenter(find.text('prod-mac')));- await tester.pumpAndSettle();-- // Opened out, both on the machine's own row, with + at the far end —- // nearest the rail's edge, where the hand is already going.- expect(actionsBox().width, greaterThan(40));- expect(- tester.getCenter(plus).dx,- greaterThan(tester.getCenter(menu).dx),- reason: 'the + sits to the right of the ⋯',- );- notifier.dispose();- });-- testWidgets('an agent row starts where the guide line reaches for it', (- tester,- ) async {- final notifier = railNotifier();- await pumpRail(tester, notifier);-- // 28px, and it is not a free number: SidebarTimeline runs its trunk at 19- // and reaches 7px out of it, so a row starting anywhere else leaves the arm- // pointing at a gap. Moving one without the other is the bug this catches.- final row = find- .ancestor(- of: find.text('9989 · Folder10'),- matching: find.byType(SidebarItem),- )- .first;- expect(tester.getTopLeft(row).dx, 28);- notifier.dispose();- });-- testWidgets('the machine mark sits on the trunk the agents hang off', (- tester,- ) async {- final notifier = railNotifier();- await pumpRail(tester, notifier);-- // The line runs THROUGH this glyph, so its centre has to land on the trunk.- // A chevron or any other mark to its left is what breaks this.- final mark = find.byKey(const ValueKey('machine-connection-icon'));- expect(tester.getCenter(mark).dx, 19);- notifier.dispose();- });-- testWidgets('a closed machine says how many agents are inside it', (- tester,- ) async {- final notifier = railNotifier(expanded: false);- await pumpRail(tester, notifier);-- // Closed: the count is the only thing left saying the machine has anything.- expect(find.text('prod-mac'), findsOneWidget);- expect(find.text('3'), findsOneWidget);- expect(find.text('Claude Code'), findsNothing);-- // Open: the count goes away, because a number beside a list you can see is- // noise. It leaves on the same clock as the rows arrive on, though — cut at- // frame one it would be a second stage of a change that is meant to read as- // one.- notifier.toggleExpand(machine.machineId);- await tester.pump();- await tester.pump(const Duration(milliseconds: 60));- expect(find.text('3'), findsOneWidget);-- await tester.pumpAndSettle();- expect(find.text('3'), findsNothing);- expect(find.text('Claude Code'), findsOneWidget);- notifier.dispose();- });-- testWidgets('the machine caption opens and closes its own agents', (- tester,- ) async {- final notifier = railNotifier();- await pumpRail(tester, notifier);- expect(find.text('Claude Code'), findsOneWidget);-- await tester.tap(find.text('prod-mac'));- await tester.pump();-- expect(notifier.expandedMachines, isNot(contains(machine.machineId)));- // Still mounted, and that is the point: the rows are clipped away by a- // shrinking box rather than deleted the instant the caption is tapped.- expect(find.text('Claude Code'), findsOneWidget);-- await tester.pumpAndSettle();- expect(find.text('Claude Code'), findsNothing);- notifier.dispose();- });-}diff --git a/desktop/test/rail_fold_test.dart b/desktop/test/rail_fold_test.dartdeleted file mode 100644index 53bd684ad..000000000--- a/desktop/test/rail_fold_test.dart+++ /dev/null@@ -1,107 +0,0 @@-// Folding the rail must never strand the user.-//-// The control that folds it is IN it, so hiding the rail outright would take-// the way back with it — the failure this guards is a window with no visible-// route to its own sidebar. Both routes are checked: the button that appears in-// the folded rail, and the shortcut its tooltip promises.-import 'package:flutter/material.dart';-import 'package:flutter/services.dart';-import 'package:flutter_riverpod/flutter_riverpod.dart';-import 'package:flutter_test/flutter_test.dart';-import 'package:package_info_plus/package_info_plus.dart';--import 'package:harness/auth/auth_session.dart';-import 'package:harness/core/config.dart';-import 'package:harness/core/models.dart';-import 'package:harness/screens/home_screen.dart';-import 'package:harness/shared/theme/app_theme.dart';-import 'package:harness/state/app_state.dart';--void main() {- TestWidgetsFlutterBinding.ensureInitialized();- PackageInfo.setMockInitialValues(- appName: 'Harness',- packageName: 'ai.autonomous.harness',- version: '1.0.0',- buildNumber: '1',- buildSignature: '',- );-- testWidgets('folding the rail leaves a way back', (tester) async {- const machine = Machine(- machineId: 'm1',- apiKey: '',- authMode: MachineAuthMode.remote,- name: 'MacBook-Pro.local',- status: 'online',- );- final notifier = AppNotifier(- config: AppConfig.dev,- authSession: AuthSession(),- configStore: null,- );- final state = MachineState(machine)- ..connectionStatus = ConnectionStatus.connected- ..nodeOnline = true- ..terminalCapabilityLoaded = true- ..terminalCapabilityAvailable = true- ..agentLoadStatus = AgentLoadStatus.loaded- ..agents = [- Agent.fromJson({- 'id': 'a1',- 'name': 'Worldcup dc to chuc',- 'engine': 'claude',- 'terminal': {- 'runtimes': [- {'backend': 'tmux', 'paneId': '%1'},- ],- },- }),- ];- notifier.machines = [machine];- notifier.machineStates[machine.machineId] = state;- notifier.expandedMachines.add(machine.machineId);-- tester.view.physicalSize = const Size(760 * 2, 560 * 2);- tester.view.devicePixelRatio = 2;- addTearDown(tester.view.reset);-- await tester.pumpWidget(- ProviderScope(- child: MaterialApp(- theme: buildAppTheme(brightness: Brightness.dark),- home: Builder(- builder: (context) {- AppTheme.brightness.value = Brightness.dark;- return BrightnessScope(child: HomeScreen(notifier: notifier));- },- ),- ),- ),- );- await tester.pump(const Duration(milliseconds: 300));-- final collapse = find.byTooltip('Collapse sidebar ⌘\\');- expect(collapse, findsOneWidget, reason: 'nút thu gọn phải có mặt');- await tester.tap(collapse);- // settle, not a fixed pump: the fold is animated now, and a single frame- // lands mid-crossfade where both rails are mounted.- await tester.pumpAndSettle();-- expect(- find.byTooltip('Expand sidebar ⌘\\'),- findsOneWidget,- reason: 'gấp rồi vẫn phải còn đường mở lại',- );- // Phím tắt phải chạy thật: tooltip đang hứa ⌘\\- await tester.sendKeyDownEvent(LogicalKeyboardKey.meta);- await tester.sendKeyEvent(LogicalKeyboardKey.backslash);- await tester.sendKeyUpEvent(LogicalKeyboardKey.meta);- await tester.pumpAndSettle();- expect(- find.byTooltip('Collapse sidebar ⌘\\'),- findsOneWidget,- reason: '⌘\\ phải mở lại rail',- );- });-}diff --git a/desktop/test/rail_header_test.dart b/desktop/test/rail_header_test.dartdeleted file mode 100644index 08d22a866..000000000--- a/desktop/test/rail_header_test.dart+++ /dev/null@@ -1,127 +0,0 @@-import 'package:flutter/material.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/state/app_state.dart';-import 'package:harness/widgets/machine_rail.dart';--/// The rail's head is a toolbar: its own surface and its own bottom edge, so it-/// reads as the thing ABOVE the list rather than as the list's first row.-///-/// What these hold: the reload glyph reports a run in flight by turning, the-/// two buttons stay far enough apart to read as two, and the list starts below-/// the toolbar's rule.-void main() {- const machine = Machine(- machineId: 'machine-1',- apiKey: '',- authMode: MachineAuthMode.remote,- name: 'prod-mac',- status: 'online',- );-- AppNotifier railNotifier() {- final notifier = AppNotifier(- config: AppConfig.dev,- authSession: AuthSession(),- configStore: null,- );- final state = MachineState(machine)- ..connectionStatus = ConnectionStatus.connected- ..terminalCapabilityLoaded = true- ..terminalCapabilityAvailable = true- ..agentLoadStatus = AgentLoadStatus.loaded- ..agents = [- Agent.fromJson({- 'id': 'a',- 'sessionId': 'session-a',- 'name': 'Ban làm được gì',- 'engine': 'claude',- 'status': 'active',- 'terminal': {- 'runtimes': [- {'backend': 'tmux', 'paneId': '%1'},- ],- },- }),- Agent.fromJson({- 'id': 'b',- 'sessionId': 'session-b',- 'name': 'Claude Code',- 'engine': 'claude',- 'status': 'active',- 'terminal': {- 'runtimes': [- {'backend': 'tmux', 'paneId': '%2'},- ],- },- }),- ];- notifier.machines = [machine];- notifier.machineStates[machine.machineId] = state;- notifier.expandedMachines.add(machine.machineId);- return notifier;- }-- Future<void> pumpRail(- WidgetTester tester,- AppNotifier notifier, {- double width = 264,- }) async {- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SizedBox(- width: width,- child: MachineRail(notifier: notifier, onCollapse: () {}),- ),- ),- ),- );- await tester.pump();- }-- testWidgets('the reload button reports a run in flight by turning', (- tester,- ) async {- final notifier = railNotifier();- await pumpRail(tester, notifier);-- final reload = find.byTooltip('Reload machines');- RotationTransition glyph() => tester.widget<RotationTransition>(- find.descendant(of: reload, matching: find.byType(RotationTransition)),- );-- // At rest the mark is upright and stays there — the transition is always in- // the tree, so "not spinning" has to be read off the angle, not off which- // widgets exist.- final resting = glyph().turns.value;- await tester.pump(const Duration(milliseconds: 300));- expect(glyph().turns.value, resting);-- notifier.dispose();- });-- testWidgets('the toolbar keeps its two buttons apart, and its bottom edge', (- tester,- ) async {- final notifier = railNotifier();- await pumpRail(tester, notifier);-- // 2px between glyphs was the old spacing and it read as one smudge. The- // gap is measured between the buttons' boxes, so it survives a change of- // glyph size.- final reload = tester.getRect(find.byTooltip('Reload machines'));- final collapse = tester.getRect(find.byTooltip('Collapse sidebar ⌘\\'));- expect(collapse.left - reload.right, greaterThanOrEqualTo(6));-- // The list starts below the toolbar's rule, not level with it — the whole- // point of the block is that the head is not the first row of the rail.- expect(- tester.getTopLeft(find.text('prod-mac')).dy,- greaterThan(reload.bottom),- );- notifier.dispose();- });-}diff --git a/desktop/test/remote_usage_test.dart b/desktop/test/remote_usage_test.dartindex ee16549fb..24f19e6b2 100644--- a/desktop/test/remote_usage_test.dart+++ b/desktop/test/remote_usage_test.dart@@ -43,8 +43,10 @@ void main() {expect(claude.account, 'k1');// Claude's `seven_day` is the Weekly window here exactly as it is for// this computer's own reading — one mapper, two sources.- expect(claude.railWindow?.label, kWeeklyWindowLabel);- expect(claude.railWindow?.usedPercent, 42);+ final weekly = claude.windows.singleWhere(+ (window) => window.label == kWeeklyWindowLabel,+ );+ expect(weekly.usedPercent, 42);});test('a vendor refusal is read the way this computer reads one', () {diff --git a/desktop/test/skeleton_sites_test.dart b/desktop/test/skeleton_sites_test.dartdeleted file mode 100644index ec7ed5510..000000000--- a/desktop/test/skeleton_sites_test.dart+++ /dev/null@@ -1,113 +0,0 @@-// Every screen that waits on a call now waits in the SHAPE of its answer.-//-// These guard the property that makes a skeleton worth having and a spinner-// not: the placeholder occupies the same room as the content it stands in-// for, so nothing on the page moves when the answer lands. They also guard-// the two states that must never look alike — "still loading" and "answered-// with nothing" — which is the bug a bare empty list always has.-import 'package:flutter/material.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/shared/theme/app_theme.dart';-import 'package:harness/shared/widgets/skeleton.dart';-import 'package:harness/state/app_state.dart';-import 'package:harness/widgets/machine_rail.dart';--Widget _themed(Widget child) => MaterialApp(- home: Builder(- builder: (context) {- AppTheme.brightness.value = Brightness.light;- return BrightnessScope(child: Scaffold(body: child));- },- ),-);--const _machine = Machine(- machineId: 'm-1',- apiKey: '',- authMode: MachineAuthMode.remote,- name: 'prod-mac',- status: 'online',-);--void main() {- TestWidgetsFlutterBinding.ensureInitialized();-- group('the machine rail', () {- AppNotifier notifier() => AppNotifier(- config: AppConfig.dev,- authSession: AuthSession(),- configStore: null,- );-- testWidgets('an empty list that is still loading does not say "none"', (- tester,- ) async {- final app = notifier()..status = AppStatus.authenticated;- addTearDown(app.dispose);- app.machinesLoading = true;-- await tester.pumpWidget(- _themed(SizedBox(width: 320, child: MachineRail(notifier: app))),- );- await tester.pump();-- expect(find.byKey(const ValueKey('machines-loading')), findsOneWidget);- // The sentence that means something else entirely.- expect(find.text('no remote machines'), findsNothing);- });-- testWidgets('an empty list that has answered says so', (tester) async {- final app = notifier()..status = AppStatus.authenticated;- addTearDown(app.dispose);-- await tester.pumpWidget(- _themed(SizedBox(width: 320, child: MachineRail(notifier: app))),- );- await tester.pump();-- expect(find.byKey(const ValueKey('machines-loading')), findsNothing);- expect(find.text('no remote machines'), findsOneWidget);- });-- testWidgets('a placeholder machine row is the height of a real one', (- tester,- ) async {- final loading = notifier()..status = AppStatus.authenticated;- addTearDown(loading.dispose);- loading.machinesLoading = true;- await tester.pumpWidget(- _themed(SizedBox(width: 320, child: MachineRail(notifier: loading))),- );- await tester.pump();- final placeholder = tester- .getRect(- find- .descendant(- of: find.byKey(const ValueKey('machines-loading')),- matching: find.byType(SkeletonText),- )- .first,- )- .height;-- final ready = notifier()..status = AppStatus.authenticated;- addTearDown(ready.dispose);- ready.machines = [_machine];- ready.machineStates[_machine.machineId] = MachineState(_machine);- await tester.pumpWidget(- _themed(SizedBox(width: 320, child: MachineRail(notifier: ready))),- );- await tester.pump();-- // Rows are 36px boxes either way, so the rail does not resize under the- // pointer when the list lands.- expect(- tester.getSize(find.text('prod-mac')).height,- closeTo(placeholder, 0.01),- );- });- });-}diff --git a/desktop/test/status_rail_test.dart b/desktop/test/status_rail_test.dartdeleted file mode 100644index 6bf72b137..000000000--- a/desktop/test/status_rail_test.dart+++ /dev/null@@ -1,270 +0,0 @@-// The strip along the window's bottom edge: one figure per agent account, a-// colour once a window is nearly spent, and a panel behind each figure that-// stays open long enough to be read.-import 'package:flutter/gestures.dart';-import 'package:flutter/material.dart';-import 'package:flutter_test/flutter_test.dart';-import 'package:harness/auth/auth_session.dart';-import 'package:harness/core/config.dart';-import 'package:harness/shared/theme/app_theme.dart' as grid;-import 'package:harness/state/app_state.dart';-import 'package:harness/theme/app_theme.dart';-import 'package:harness/usage/usage_controller.dart';-import 'package:harness/usage/usage_source.dart';-import 'package:harness/usage/usage_window.dart';-import 'package:harness/widgets/status_rail/rail_panel.dart';-import 'package:harness/widgets/status_rail/status_rail.dart';--/// One agent account's rate limits, fixed, so the strip can be read without-/// shelling out to a vendor CLI.-class _StubUsageSource implements UsageSource {- _StubUsageSource(this.reading);-- final ProviderUsage reading;-- @override- UsageProvider get provider => reading.provider;-- @override- Future<ProviderUsage> read() async => reading;-}--/// A Claude account answering with all three of its windows.-const _claude = ProviderUsage(- provider: UsageProvider.claude,- status: UsageStatus.ok,- windows: [- UsageWindow(label: 'Session', usedPercent: 12),- UsageWindow(label: 'Weekly', usedPercent: 42),- UsageWindow(label: 'Fable', usedPercent: 7),- ],-);--/// The rail at the foot of an empty [window], reading [readings].-///-/// A window the app can actually be: its own minimum is 880px, narrower than-/// the test's default of 800, and the key hints share this strip.-///-/// `autoStart: false` and one explicit [UsageController.refresh]: the live-/// controller starts a periodic timer, and a timer is a `pumpAndSettle` that-/// never settles.-Future<void> _pump(- WidgetTester tester,- List<ProviderUsage> readings, {- Size window = const Size(1280, 720),-}) async {- tester.view.physicalSize = window;- tester.view.devicePixelRatio = 1;- addTearDown(tester.view.reset);- final usage = UsageController(- sources: [for (final reading in readings) _StubUsageSource(reading)],- autoStart: false,- );- addTearDown(usage.dispose);- await usage.refresh();- final notifier = AppNotifier(- config: AppConfig.dev,- authSession: AuthSession(),- configStore: null,- );- addTearDown(notifier.dispose);- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: Column(- children: [- const Spacer(),- StatusRail(notifier: notifier, usage: usage),- ],- ),- ),- ),- );- await tester.pumpAndSettle();-}--/// Rests a mouse on the Claude figure long enough for its panel to open.-Future<TestGesture> _hoverFigure(WidgetTester tester) async {- final gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);- await gesture.addPointer(location: Offset.zero);- addTearDown(gesture.removePointer);- await gesture.moveTo(tester.getCenter(find.text('42% used')));- await tester.pump(const Duration(milliseconds: 200));- await tester.pumpAndSettle();- return gesture;-}--void main() {- testWidgets('the strip reads the agent accounts', (tester) async {- await _pump(tester, const [- ProviderUsage(- provider: UsageProvider.claude,- status: UsageStatus.ok,- windows: [UsageWindow(label: 'Session', usedPercent: 12)],- ),- ]);-- expect(find.text('12% used'), findsOneWidget);- // No reset time came back, so the window's own name says which limit the- // figure belongs to.- expect(find.text('Session'), findsOneWidget);- });-- testWidgets('each account prints ONE figure — its weekly window', (- tester,- ) async {- // Claude answers with three windows and Codex with one, so printing them- // all made one account three figures wide and the other one: two readouts- // that read as different KINDS of thing rather than the same thing about- // two accounts. The panel behind the figure still carries every window.- await _pump(tester, const [_claude]);-- expect(find.text('42% used'), findsOneWidget);- expect(find.text('12% used'), findsNothing);- expect(find.text('7% used'), findsNothing);- });-- testWidgets('a nearly-spent window colours its own figure', (tester) async {- // The whole point of looking down here unprompted. `19% used` and- // `92% used` used to print in exactly the same ink, which made the strip- // useless for the one question it can answer at a glance.- await _pump(tester, const [- ProviderUsage(- provider: UsageProvider.claude,- status: UsageStatus.ok,- windows: [UsageWindow(label: 'Weekly', usedPercent: 92)],- ),- ProviderUsage(- provider: UsageProvider.codex,- status: UsageStatus.ok,- windows: [UsageWindow(label: 'Weekly', usedPercent: 12)],- ),- ]);-- Color inkOf(String text) =>- tester.widget<Text>(find.text(text)).style!.color!;- expect(inkOf('12% used'), grid.AppPalette.textSecondary);- expect(inkOf('92% used'), AppColors.danger);- });-- testWidgets('and warns in amber before it turns red', (tester) async {- await _pump(tester, const [- ProviderUsage(- provider: UsageProvider.claude,- status: UsageStatus.ok,- windows: [UsageWindow(label: 'Weekly', usedPercent: 84)],- ),- ]);-- expect(- tester.widget<Text>(find.text('84% used')).style!.color,- grid.AppPalette.warn,- );- });-- testWidgets('an account nobody signed into here leaves the strip empty', (- tester,- ) async {- await _pump(tester, const [- ProviderUsage(- provider: UsageProvider.claude,- status: UsageStatus.signedOut,- message: 'Sign in to Claude to see usage',- ),- ]);-- // A figure-shaped blank that will never fill is worse than nothing, so an- // account with no session contributes no figures at all — the reason there- // are none belongs in the panel, where there is room to say it.- expect(find.textContaining('% used'), findsNothing);- });-- group('the panel behind a figure', () {- testWidgets('opens on hover, with every window the strip left out', (- tester,- ) async {- await _pump(tester, const [_claude]);- await _hoverFigure(tester);-- expect(find.byType(RailPanelSurface), findsOneWidget);- expect(find.text('Claude'), findsOneWidget);- // The strip prints the weekly window alone; the panel is where the rest- // are.- expect(find.text('Session'), findsOneWidget);- expect(find.text('Fable'), findsOneWidget);- });-- testWidgets('is a card, not the window', (tester) async {- // The bug this pins: an OverlayEntry whose `Positioned` has no offsets is- // a NON-positioned overlay child, and those are laid out with tight- // constraints — the panel then covered the whole window and its own- // width was ignored.- await _pump(tester, const [_claude], window: const Size(1000, 460));- await _hoverFigure(tester);-- final panel = tester.getRect(find.byType(RailPanelSurface));- expect(panel.width, 248);- // Its own height, not the window's — which is what the bug looked like.- final window = tester.getRect(find.byType(MaterialApp));- expect(panel.height, lessThan(window.height));- // It opens UPWARD: there is nothing below a strip on the window's bottom- // edge.- final rail = tester.getRect(find.byType(StatusRail));- expect(panel.bottom, lessThanOrEqualTo(rail.top + 1));- });-- testWidgets('the pointer survives the gap between figure and panel', (- tester,- ) async {- // The panel hangs 8px above the rail, and a pointer reaching it crosses- // that band — which belongs to neither. Without a beat of grace the panel- // closed there, so nothing inside it could be reached.- await _pump(tester, const [_claude], window: const Size(1000, 460));- final gesture = await _hoverFigure(tester);- expect(find.byType(RailPanelSurface), findsOneWidget);-- // Into the dead band between the two.- final rail = tester.getRect(find.byType(StatusRail));- final panel = tester.getRect(find.byType(RailPanelSurface));- await gesture.moveTo(- Offset(panel.center.dx, (panel.bottom + rail.top) / 2),- );- await tester.pump(const Duration(milliseconds: 60));- expect(find.byType(RailPanelSurface), findsOneWidget);-- // And onto the panel, which claims it before the grace runs out.- await gesture.moveTo(panel.center);- await tester.pump(const Duration(milliseconds: 200));- await tester.pumpAndSettle();- expect(find.byType(RailPanelSurface), findsOneWidget);- });-- testWidgets('a pointer that keeps going closes it', (tester) async {- // The grace is a beat, not a latch.- await _pump(tester, const [_claude]);- final gesture = await _hoverFigure(tester);- expect(find.byType(RailPanelSurface), findsOneWidget);-- await gesture.moveTo(const Offset(500, 20));- await tester.pump(const Duration(milliseconds: 200));- await tester.pumpAndSettle();- expect(find.byType(RailPanelSurface), findsNothing);- });-- testWidgets('a click pins it, so the pointer can leave', (tester) async {- await _pump(tester, const [_claude]);- // Measured before the panel opens: the panel prints the same figure, and- // the tap has to land on the rail's.- final figure = tester.getCenter(find.text('42% used'));- final gesture = await _hoverFigure(tester);- await tester.tapAt(figure);- await tester.pumpAndSettle();-- // Pointer well away, panel still up.- await gesture.moveTo(const Offset(500, 20));- await tester.pump(const Duration(milliseconds: 400));- await tester.pumpAndSettle();- expect(find.byType(RailPanelSurface), findsOneWidget);- });- });-}diff --git a/desktop/test/swarm_project_members_test.dart b/desktop/test/swarm_project_members_test.dartdeleted file mode 100644index 205f05200..000000000--- a/desktop/test/swarm_project_members_test.dart+++ /dev/null@@ -1,130 +0,0 @@-import 'package:harness/widgets/swarm_switcher.dart';-import 'package:flutter/services.dart';--import 'swarm_interactions_test.dart' show chord;--import 'package:harness/state/swarm_navigation.dart';-import 'package:flutter/material.dart';-import 'package:harness/widgets/swarm_project_agents.dart';-import 'package:flutter_test/flutter_test.dart';-import 'package:harness/core/models.dart';-import 'package:harness/screens/swarm_screen.dart';-import 'package:harness/state/app_state.dart';-import 'package:harness/state/swarm_catalog.dart';-import 'package:harness/ws/local_cli_discovery.dart';--import 'swarm_state_test.dart' show createApp, MemoryStore;--void main() {- testWidgets(- 'project membership includes an older remote daemon and survives reopening',- (tester) async {- tester.view.physicalSize = const Size(1280, 900);- tester.view.devicePixelRatio = 1;- addTearDown(tester.view.resetPhysicalSize);- addTearDown(tester.view.resetDevicePixelRatio);- final app = createApp();- app.machineStates['m']!.localEndpoint = LocalCliEndpoint(- computerId: 'local',- wsUri: Uri.parse('ws://fixture.invalid'),- protocolVersion: 1,- terminalProtocolVersion: 3,- agentProjects: const {- 'a0': AgentProject(name: 'Solid', cwd: '/work/workshop'),- 'a1': AgentProject(name: 'Solid', cwd: '/work/workshop'),- },- );- app.machineStates['remote'] =- MachineState(- const Machine(- machineId: 'remote',- name: 'iMac Home',- authMode: MachineAuthMode.remote,- ),- )- ..agents = [- const Agent(- id: 'chess',- name: 'Chess Set',- terminalAvailable: true,- ),- const Agent(- id: 'unrelated',- name: 'Other work',- terminalAvailable: true,- ),- ];- final memory = MemoryStore();- final projects = SwarmProjectStore(storage: memory);- await projects.load();- await tester.pumpWidget(- MaterialApp(- home: SwarmScreen(- notifier: app,- nativeTabs: false,- projectStore: projects,- ),- ),- );- await tester.pump();- final editing = showSwarmProjectAgents(- tester.element(find.byType(SwarmScreen)),- app,- swarmProjects(app, projects.projects).single,- );- await tester.pumpAndSettle();- await tester.enterText(- find.byWidgetPredicate(- (w) =>- w is TextField &&- w.decoration?.hintText == 'Find a harness or machine',- ),- 'Chess Set',- );- await tester.pump();- await tester.tap(find.widgetWithText(CheckboxListTile, 'Chess Set'));- await tester.tap(find.text('Save'));- await tester.pumpAndSettle();- final saved = await editing;- expect(saved, isNotNull);- await projects.add(saved!);- final restored = SwarmProjectStore(storage: memory);- await restored.load();- final group = swarmProjects(app, restored.projects).single;- expect(group.agents.map((a) => a.agent.id), ['a0', 'a1', 'chess']);- expect(- app.panes,- isEmpty,- reason:- 'Editing project membership does not attach or take over terminals',- );- await chord(tester, LogicalKeyboardKey.keyP);- await tester.pump();- await tester.enterText(- find.byKey(const ValueKey('swarm-search-input')),- 'Solid',- );- await tester.pump();- expect(- tester- .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))- .search- .rows- .where((row) => row.isProject),- isEmpty,- );- await tester.tap(- find.byKey(ValueKey(agentDestinationId('remote', 'chess'))),- );- await tester.pump(const Duration(milliseconds: 100));- expect(app.panes.map((p) => (p.machineId, p.agentId)), [- ('remote', 'chess'),- ]);- expect(app.panes.single.machineId, 'remote');- await tester.pumpWidget(const SizedBox());- app.dispose();- projects.dispose();- restored.dispose();- },- );-}diff --git a/desktop/test/usage_accounts_test.dart b/desktop/test/usage_accounts_test.dartindex 66e62d2a0..f30c0d597 100644--- a/desktop/test/usage_accounts_test.dart+++ b/desktop/test/usage_accounts_test.dart@@ -61,7 +61,7 @@ void main() {final claude = _claude(accounts);expect(claude.map((a) => a.isLocal), [true, false]);expect(claude.last.machines, ['box']);- expect(claude.last.reading.railWindow?.usedPercent, 71);+ expect(claude.last.reading.windows.single.usedPercent, 71);});test('two remote machines on one other account are one figure', () {diff --git a/desktop/test/usage_test.dart b/desktop/test/usage_test.dartindex 82c890d70..1772599ed 100644--- a/desktop/test/usage_test.dart+++ b/desktop/test/usage_test.dart@@ -1,16 +1,12 @@import 'dart:io';import 'package:dio/dio.dart';-import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';-import 'package:harness/widgets/engine_identity.dart';-import 'package:harness/widgets/status_rail/usage_panel.dart';import 'package:harness/usage/claude_usage_source.dart';import 'package:harness/usage/codex_usage_source.dart';import 'package:harness/usage/usage_credentials.dart';import 'package:harness/usage/usage_controller.dart';import 'package:harness/usage/usage_source.dart';-import 'package:harness/usage/usage_accounts.dart';import 'package:harness/usage/usage_window.dart';/// A Dio that answers every request with one canned payload, so a source can be@@ -144,42 +140,7 @@ void main() {expect(reading.tightest?.label, 'Weekly');});- test('the rail prints the weekly window, not the tightest one', () {- // Two different questions. `tightest` is the limit that will stop the work- // first; the rail wants the one worth a GLANCE, and the five-hour window- // refills all day — it is back to nothing by the time anybody reads it.- const reading = ProviderUsage(- provider: UsageProvider.claude,- status: UsageStatus.ok,- windows: [- UsageWindow(label: 'Session', usedPercent: 88),- UsageWindow(label: kWeeklyWindowLabel, usedPercent: 42),- ],- );- expect(reading.tightest?.label, 'Session');- expect(reading.railWindow?.label, kWeeklyWindowLabel);- });- test('a provider with no weekly window still prints one figure', () {- // One figure is the rule, and a blank strip would be a worse answer than- // the wrong window.- const reading = ProviderUsage(- provider: UsageProvider.codex,- status: UsageStatus.ok,- windows: [- UsageWindow(label: '5h', usedPercent: 30),- UsageWindow(label: '30d', usedPercent: 61),- ],- );- expect(reading.railWindow?.label, '30d');- expect(- const ProviderUsage(- provider: UsageProvider.codex,- status: UsageStatus.ok,- ).railWindow,- isNull,- );- });group('Claude source', () {test('maps the three windows the CLI itself shows', () async {@@ -327,105 +288,6 @@ void main() {});});- group('the bar', () {- /// Pumps one window's row and hands back the fill as it was actually- /// LAID OUT — [WidgetTester.getSize], not the `width` property of the- /// widget that asked for it.- ///- /// The difference is the whole point. An earlier version of these tests- /// read the properties, and passed against a bar whose fill was laid out- /// zero pixels tall and therefore never appeared on screen: the tree said- /// coral, the window drew nothing. A property is a request; only the size- /// is an outcome.- Future<({Size size, Color color})> fill(- WidgetTester tester,- double percent,- ) async {- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: Center(- child: SizedBox(- // The width the rail actually opens this panel at.- width: 248,- child: UsagePanelContent(- accounts: [- UsageAccount(- isLocal: true,- reading: ProviderUsage(- provider: UsageProvider.claude,- status: UsageStatus.ok,- windows: [- UsageWindow(label: 'Session', usedPercent: percent),- ],- fetchedAt: DateTime.now(),- ),- ),- ],- ),- ),- ),- ),- ),- );- final finder = find.byKey(const Key('usage-bar-fill'));- final painted = tester.widget<ColoredBox>(- find.descendant(of: finder, matching: find.byType(ColoredBox)),- );- return (size: tester.getSize(finder), color: painted.color);- }-- testWidgets('a single-digit window still shows a band of colour', (- tester,- ) async {- // The bug this guards: at the percentages these windows sit at for most- // of their life, a strictly proportional fill is a couple of pixels and- // reads as nothing at all.- final small = await fill(tester, 2);- expect(small.size.width, greaterThanOrEqualTo(4));- // And it has to be tall enough to see, which is the half that silently- // went missing: a fill laid out flat is present, correct and invisible.- expect(small.size.height, 6);- });-- testWidgets('an untouched window draws no fill at all', (tester) async {- // Zero is the one case that must NOT be over-represented: a bar claiming- // usage nobody spent is worse than a bar that is hard to see.- expect((await fill(tester, 0)).size.width, 0);- });-- testWidgets('the fill wears the account colour, and never a grey', (- tester,- ) async {- final claude = await fill(tester, 30);- expect(claude.color, engineIdentity('claude').color);- // The mark at the top of the panel is drawn from the same source, so the- // two cannot drift into two colours for one account.- expect(- claude.color.r == claude.color.g && claude.color.g == claude.color.b,- isFalse,- );- });-- testWidgets('a nearly spent window stops wearing the account colour', (- tester,- ) async {- final spent = await fill(tester, 92);- expect(spent.color, isNot(engineIdentity('claude').color));- });-- testWidgets('a full window fills the bar exactly, not past it', (- tester,- ) async {- // The bar spans the panel, so a spent window's fill is the panel's own- // width — and the clamp that widens small fills must not widen this one- // past the track it sits in.- final full = await fill(tester, 100);- expect(full.size.width, 248);- expect(full.size.height, 6);- });- });-group('controller', () {test('a controller nobody started is not loading', () {// A rail that drew a skeleton for it would promise an answer that was