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
hn: Set up signs in and sets grid up; a sign-in elsewhere signs in alone — and the desktop follows it (#1108)
scholes-autonomous576ae724619a
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex f9624304d..fbd982d0c 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -5181,6 +5181,7 @@ class AppNotifier extends ChangeNotifier {void _updateLocalProjectSnapshot(LocalCliEndpoint endpoint) {if (_disposed) return;+ _followDaemonAccount(endpoint);// Every five seconds the daemon answers ready: the one steady witness that this computer's// machine is up, whatever a timeout or a missed probe said. It used to skip a row whose endpoint// had been cleared — the very row that needed it.@@ -5237,6 +5238,115 @@ class AppNotifier extends ChangeNotifier {/// Deliberately says nothing about WHY. The daemon clears its session identically whether the/// machine was deleted from another machine or the SSO token simply expired, and guessing between/// them in the copy would sometimes be wrong. Signing in again is the answer to both.+ /// A sign-in or sign-out made somewhere else on this computer — hn, a terminal's `harness login` or+ /// `harness logout` — that this window has not seen. The daemon says which on every ready probe+ /// (`/api/status.signedIn`), and the window follows it as it does its own: a guest window takes the+ /// sign-in ([_adoptSignInFromElsewhere]), a signed-in one becomes a guest ([_signedOutAtRuntime]).+ /// It used to learn the account only at launch and from its own buttons, so a sign-in from hn left+ /// Settings › Account saying "Not signed in" over a daemon that was signed in.+ ///+ /// Only on the CLI's own word (`harness auth status`), which owns the sign-in; asked at most every+ /// [_daemonAccountRecheck] while the two disagree, and never during this window's own sign-in or out.+ void _followDaemonAccount(LocalCliEndpoint endpoint) {+ final daemonSignedIn = endpoint.signedIn;+ if (daemonSignedIn == null ||+ viewer != null ||+ signingIn ||+ signingOut ||+ _followingDaemonAccount ||+ status != AppStatus.authenticated) {+ return;+ }+ final disagree = daemonSignedIn ? isGuest : signedIn;+ if (!disagree) return;+ final now = DateTime.now();+ if (_daemonAccountCheckedAt case final at?+ when now.difference(at) < _daemonAccountRecheck) {+ return;+ }+ _daemonAccountCheckedAt = now;+ unawaited(+ daemonSignedIn+ ? _adoptSignInFromElsewhere()+ : _followSignOutFromElsewhere(),+ );+ }++ static const _daemonAccountRecheck = Duration(seconds: 30);+ DateTime? _daemonAccountCheckedAt;+ bool _followingDaemonAccount = false;++ /// This computer was signed in elsewhere while this window was a guest: it ends as this window's own+ /// [login] does — the account's workspace built on the daemon the sign-in restarted.+ Future<void> _adoptSignInFromElsewhere() async {+ _followingDaemonAccount = true;+ int? revision;+ try {+ final confirmed = await cliLogin.checkStatus();+ if (_disposed ||+ !confirmed.loggedIn ||+ !isGuest ||+ signingIn ||+ signingOut) {+ return;+ }+ revision = _invalidateAuthWork();+ _closedHistory.clear();+ _monitorHarnesses.clear();+ _lastError = null;+ status = AppStatus.bootstrapping;+ notifyListeners();+ if (_workspaceCleanup case final cleanup?) {+ await cleanup;+ if (!_authWorkCurrent(revision)) return;+ }+ signedIn = true;+ await _finishBootstrapSignedIn();+ if (!_authWorkCurrent(revision) || status != AppStatus.authenticated) {+ return;+ }+ _guestDeskRestorePending = false;+ } catch (error) {+ debugPrint('AppNotifier: following a sign-in made elsewhere: $error');+ if (revision != null && _authWorkCurrent(revision)) {+ status = AppStatus.authenticated;+ }+ } finally {+ _followingDaemonAccount = false;+ if (!_disposed) notifyListeners();+ }+ }++ /// This computer was signed out elsewhere (hn, `harness logout`): this window becomes a guest, as it+ /// does when the account is lost under it.+ Future<void> _followSignOutFromElsewhere() async {+ _followingDaemonAccount = true;+ try {+ final confirmed = await cliLogin.checkStatus();+ if (_disposed ||+ confirmed.loggedIn ||+ !signedIn ||+ signingIn ||+ signingOut) {+ return;+ }+ _signedOutAtRuntime(_signedOutMessage);+ } catch (error) {+ debugPrint('AppNotifier: following a sign-out made elsewhere: $error');+ } finally {+ _followingDaemonAccount = false;+ }+ }++ /// Lets the next probe ask the CLI at once, as [_daemonAccountRecheck] later would.+ @visibleForTesting+ void debugForgetDaemonAccountCheckForTest() => _daemonAccountCheckedAt = null;++ /// Feeds [endpoint] to the daemon-account follower, as a ready probe does.+ @visibleForTesting+ void followDaemonAccountForTest(LocalCliEndpoint endpoint) =>+ _followDaemonAccount(endpoint);+static const _signedOutMessage ='You were signed out on this computer. This computer\'s agents keep ''running; sign in again to reach your other machines.';diff --git a/desktop/lib/ws/local_cli_discovery.dart b/desktop/lib/ws/local_cli_discovery.dartindex 6535d6156..cd342a26b 100644--- a/desktop/lib/ws/local_cli_discovery.dart+++ b/desktop/lib/ws/local_cli_discovery.dart@@ -33,6 +33,11 @@ class LocalCliEndpoint {/// does. False means remote machines and the profile are unavailable for now, nothing more.final bool backendOnline;+ /// Whether this computer is signed in to an account, as the daemon reads its sign-in right now+ /// (`/api/status.signedIn`); null from a daemon too old to say. A sign-in or sign-out made somewhere+ /// else on this computer — hn, a terminal — shows here first (AppNotifier `_followDaemonAccount`).+ final bool? signedIn;+/// Older daemons report local working folders in status before they support/// project metadata in agent frames. This snapshot never describes a peer.final Map<String, AgentProject> agentProjects;@@ -55,6 +60,7 @@ class LocalCliEndpoint {required this.terminalProtocolVersion,this.machineId,this.backendOnline = true,+ this.signedIn,this.agentProjects = const {},this.socketPath,this.scanning = false,@@ -668,6 +674,7 @@ class LocalCliDiscovery {? machineId: null,backendOnline: backendOnline,+ signedIn: body['signedIn'] is bool ? body['signedIn'] as bool : null,agentProjects: _localAgentProjects(body['sessions'],identity.environment,diff --git a/desktop/test/desktop_account_transition_test.dart b/desktop/test/desktop_account_transition_test.dartindex c2f827917..da6275e1f 100644--- a/desktop/test/desktop_account_transition_test.dart+++ b/desktop/test/desktop_account_transition_test.dart@@ -13,6 +13,7 @@ import 'package:harness/state/app_state.dart';import 'package:harness/state/pane_layout_store.dart';import 'package:harness/terminal/terminal_session.dart';import 'package:harness/viewer/device_log_sync.dart' show DeviceLogDeparted;+import 'package:harness/ws/local_cli_discovery.dart';import 'swarm_state_test.dart' show MemoryStore;@@ -21,6 +22,16 @@ class _Login extends CliLogin {Completer<void>? pending;bool fail = false;+ /// What `harness auth status` says: the sign-in as the CLI holds it.+ bool loggedIn = true;+ var statusChecks = 0;++ @override+ Future<CliAuthStatus> checkStatus() async {+ statusChecks++;+ return CliAuthStatus(loggedIn: loggedIn);+ }+@overrideFuture<void> logout() async {}@@ -166,7 +177,72 @@ Future<void> _settle() async {}}+/// A ready probe of this computer's daemon, signed in or not as it says.+LocalCliEndpoint _probe({required bool signedIn}) => LocalCliEndpoint(+ computerId: 'computer-local',+ wsUri: Uri.parse('ws://127.0.0.1:1/ws'),+ protocolVersion: 1,+ terminalProtocolVersion: 3,+ signedIn: signedIn,+);+void main() {+ test('a sign-in made elsewhere (hn, a terminal) is followed, not left as "Not signed in"', () async {+ final login = _Login();+ final app = _Desktop(MemoryStore(), login);+ addTearDown(app.dispose);+ await app.arrange();+ await app.logout();+ await _settle();+ expect(app.isGuest, isTrue);++ // The daemon says signed in, but the CLI does not (yet): nothing changes.+ login.loggedIn = false;+ app.followDaemonAccountForTest(_probe(signedIn: true));+ await _settle();+ expect(app.isGuest, isTrue);++ // Asked again only after a while, then on the CLI's word the window is signed in — without+ // a sign-in of its own.+ login.loggedIn = true;+ app.followDaemonAccountForTest(_probe(signedIn: true));+ await _settle();+ expect(login.statusChecks, 1, reason: 'at most one check per pause');+ app.debugForgetDaemonAccountCheckForTest();+ app.followDaemonAccountForTest(_probe(signedIn: true));+ await _settle();+ expect(app.isGuest, isFalse);+ expect(app.signedIn, isTrue);+ expect(app.status, AppStatus.authenticated);+ expect(login.logins, 0);+ expect(app.allPanes.map((p) => (p.machineId, p.agentId)), [+ ('account-local', 'local-agent'),+ ]);++ // A daemon that agrees asks nothing.+ final checks = login.statusChecks;+ app.debugForgetDaemonAccountCheckForTest();+ app.followDaemonAccountForTest(_probe(signedIn: true));+ await _settle();+ expect(login.statusChecks, checks);+ });++ test('a sign-out made elsewhere turns the window into a guest', () async {+ final login = _Login();+ final app = _Desktop(MemoryStore(), login);+ addTearDown(app.dispose);+ await app.arrange();+ expect(app.isGuest, isFalse);+ login.loggedIn = false;+ app.followDaemonAccountForTest(_probe(signedIn: false));+ await _settle();+ expect(app.isGuest, isTrue);+ expect(app.status, AppStatus.authenticated);+ expect(app.allPanes.map((p) => (p.machineId, p.agentId)), [+ ('computer-local', 'local-agent'),+ ]);+ });+test('a failed guest layout write preserves the old identity and can retry',() async {diff --git a/tui/src/account.rs b/tui/src/account.rsindex 9f39d3552..4ba5654f3 100644--- a/tui/src/account.rs+++ b/tui/src/account.rs@@ -60,6 +60,11 @@ pub fn open(app: &mut App) {refresh(app, true);}+/// A sign-in is under way: the browser or phone asked, or the account it chose being committed.+pub fn signing_in(app: &App) -> bool {+ app.account.driver.is_some() || matches!(app.account.phase, Phase::Starting | Phase::Browser(_) | Phase::Phone { .. } | Phase::Completing | Phase::Committed)+}+fn visible(app: &App) -> bool { matches!(app.modal, Some(Modal::Picker { kind: PickerKind::Account, .. })) }pub(crate) fn identity_changed(app: &mut App) {@@ -111,6 +116,7 @@ pub fn refresh(app: &mut App, force: bool) {let email = match &app.account.status { Status::SignedIn { email, .. } => email.clone(), _ => None };app.account.status = Status::SignedIn { offline: status["offline"] == true, email };load_email(app, generation);+ crate::models::signed_in(app);}None => {}}@@ -317,8 +323,18 @@ pub fn choose(app: &mut App, mut picker: Picker, id: &str) {}}+/// hn's own sign-in, chosen and finished — what the browser and `harness login` would do.+#[cfg(test)]+pub(crate) fn sign_in_for_test(app: &mut App) {+ start(app, "google");+ let generation = app.account.generation;+ finished(app, generation, true, None);+}+fn cancel(app: &mut App) {if matches!(app.account.phase, Phase::Committed | Phase::Completing) { return }+ // A sign-in that a Set up asked for, given up: nothing waits to set grid up behind a later one.+ if (app.account.driver.is_some() || app.account.status == Status::SignedOut) && !app.models_view.set_up_signed_in { app.models_view.set_up_after_sign_in = false }if let Some(driver) = app.account.driver.take() {let _ = driver.send(Driver::Cancel);app.account.generation += 1;@@ -473,6 +489,8 @@ fn finished(app: &mut App, generation: u64, committed: bool, error: Option<Strinapp.account.driver = None;if committed {app.account.phase = error.map(Phase::Failed).unwrap_or(Phase::Ready);+ // This sign-in is hn's own: a Set up that asked for it goes on (only that one sets grid up).+ crate::models::own_sign_in_done(app);// The CLI commits credentials and restarts its daemon before it exits.reconnect(app);refresh(app, true);diff --git a/tui/src/account_scope.rs b/tui/src/account_scope.rsindex 6c70f143d..9d06819d7 100644--- a/tui/src/account_scope.rs+++ b/tui/src/account_scope.rs@@ -241,7 +241,9 @@ impl App {if self.session_desk { self.session_alias = None; self.session_path = None; }for session in &mut self.sessions { if session.desk { session.alias = None; session.path = None; } }}- if !matches!(self.modal, Some(Modal::NewHarness(_)) | Some(Modal::Picker { kind:crate::modal::PickerKind::Account, .. })) { self.modal = None; }+ // (The Models view a Set up's sign-in brought back stays: its Set up goes on under the new account.)+ let setting_up = matches!(self.modal, Some(Modal::Picker { kind: crate::modal::PickerKind::Models, .. })) && self.models_view.set_up_after_sign_in;+ if !setting_up && !matches!(self.modal, Some(Modal::NewHarness(_)) | Some(Modal::Picker { kind:crate::modal::PickerKind::Account, .. })) { self.modal = None; }crate::account::identity_changed(self);crate::models::account_changed(self);self.fit_panes(); self.redraw_all = true; self.server_dirty = true;@@ -465,6 +467,25 @@ mod tests {assert!(crate::agent_switch::preserves(&app, 1), "local view stays until the new desk confirms it");}+ /// The sign-in a Set up asked for can land before the daemon answers to the account: the Models view+ /// it brought back stays open through that, where the Set up goes on. Any other view still closes.+ #[test]+ fn a_set_up_s_models_view_stays_through_the_sign_in() {+ use crate::modal::{Modal, PickerKind};+ let mut app = app("computer", false);+ app.modal = Some(Modal::Picker { kind: PickerKind::Models, picker: crate::picker::Picker::new("models", "") });+ app.models_view.set_up_after_sign_in = true;+ app.models_view.set_up_signed_in = true;+ app.adopt_daemon_identity(&status("account-a", true));+ assert!(matches!(app.modal, Some(Modal::Picker { kind: PickerKind::Models, .. })));+ assert!(app.models_view.set_up_after_sign_in, "the Set up carries over to the account's machine id");++ let mut app = super::tests::app("computer", false);+ app.modal = Some(Modal::Picker { kind: PickerKind::Models, picker: crate::picker::Picker::new("models", "") });+ app.adopt_daemon_identity(&status("account-a", true));+ assert!(app.modal.is_none(), "without a Set up, the old account's view closes");+ }+#[test]fn changing_accounts_drops_old_views_and_requests_but_never_stops_a_local_pty() {let mut app = app("account-a", true);diff --git a/tui/src/app.rs b/tui/src/app.rsindex 09f5a1a4a..3c507c98b 100644--- a/tui/src/app.rs+++ b/tui/src/app.rs@@ -6112,14 +6112,18 @@ impl App {// The accounts' rate limits, from each machine that holds one (every five minutes; the// first a few seconds in).if self.started.elapsed() > Duration::from_secs(4) && self.usage_checked.map(|t| t.elapsed() > Duration::from_secs(300)).unwrap_or(true) {+ // (Half a minute, not five, after a machine that could not be asked or whose first read+ // failed — this computer's connection is not up yet a few seconds after a signed-in start.)+ let soon = || Instant::now().checked_sub(Duration::from_secs(270));self.usage_checked = Some(Instant::now());let ids: Vec<String> = self.fleet.machines.iter().filter(|m| m.usable()).map(|m| m.id.clone()).collect();+ if ids.is_empty() { self.usage_checked = soon() }for id in ids {- let Some(link) = self.link(&id) else { continue };+ let Some(link) = self.link(&id) else { self.usage_checked = soon(); continue };let generation = link.generation;self.spawn(async move { link.rpc("usage_read", json!({}), Duration::from_secs(30)).await }, move |app, reply| {if app.connection_generation(&id) != Some(generation) { return }- let Ok(reply) = reply else { return };+ let Ok(reply) = reply else { if !app.usage.contains_key(&id) { app.usage_checked = soon() } return };let readings: Vec<fleet::Usage> = reply.get("providers").and_then(Value::as_array).map(|p| p.iter().filter_map(fleet::usage_from).collect()).unwrap_or_default();app.usage.insert(id, readings);});diff --git a/tui/src/input.rs b/tui/src/input.rsindex 3048d8895..93f03b24c 100644--- a/tui/src/input.rs+++ b/tui/src/input.rs@@ -3128,6 +3128,8 @@ fn choose(app: &mut App, kind: PickerKind, mut picker: Picker, choice: Choice) {PickerKind::Models if id.as_deref().is_some_and(crate::models::is_row) => {if !matches!(choice, Choice::Enter | Choice::SplitDown) { return keep(app, kind, picker) }crate::models::choose(app, &mut picker, id.as_deref().unwrap_or(""), choice == Choice::SplitDown);+ // (Set up signed out opened the account page: the sign-in is shown, not this list.)+ if matches!(app.modal, Some(Modal::Picker { kind: PickerKind::Account, .. })) { return }fill(app, &kind, &mut picker);return keep(app, kind, picker);}diff --git a/tui/src/models.rs b/tui/src/models.rsindex 6aacc4700..e9c791372 100644--- a/tui/src/models.rs+++ b/tui/src/models.rs@@ -108,9 +108,11 @@ impl LocalModel {}/// What `grid_fleet_models_list` answers: the models, the machine's memory and free disk, and-/// whether an operation is under way.+/// whether an operation is under way. `grid_setup_needed`: grid is not set up here, so local and+/// shared models are one Set up row (the desktop's); `grid_setup_error`: why the last Set up failed.#[derive(Clone, Debug, Default, PartialEq)]-pub struct Snapshot { pub models: Vec<LocalModel>, pub memory: Option<f64>, pub free_disk: Option<f64>, pub hardware: Option<String>, pub notice: Option<String>, pub busy: bool, pub supports_download: bool }+pub struct Snapshot { pub models: Vec<LocalModel>, pub memory: Option<f64>, pub free_disk: Option<f64>, pub hardware: Option<String>, pub notice: Option<String>, pub busy: bool, pub supports_download: bool,+ pub grid_setup_needed: bool, pub grid_setup_error: Option<String> }/// None when there is no list — a daemon too old for it, or a reply that failed.pub fn parse_local(reply: &Value) -> Option<Snapshot> {@@ -119,6 +121,7 @@ pub fn parse_local(reply: &Value) -> Option<Snapshot> {models, memory: num(&reply["memoryBytes"]).filter(|m| *m > 0.0), free_disk: num(&reply["freeDiskBytes"]), hardware: text(&reply["hardware"]),// A sentence beside the list, never a failure (an `error` fails the whole request).notice: text(&reply["notice"]), busy: reply["busy"] == true, supports_download: reply["supportsDownload"] == true,+ grid_setup_needed: reply["gridSetupNeeded"] == true, grid_setup_error: text(&reply["gridSetupError"]),})}@@ -360,10 +363,18 @@ pub struct Models {pub grids_reading: HashSet<String>,/// This computer's saved APIs, each API's models, and those unfolded under their API.pub apis: Option<Result<Vec<Api>, String>>,+ /// When the APIs were last answered: a failed answer is asked again after [APIS_RETRY].+ pub apis_at: Option<Instant>,pub api_models: HashMap<String, Result<Vec<ApiModel>, String>>,pub api_open: HashSet<String>,/// "More models": the whole catalog shown, not its first five.pub more: bool,+ /// A Set up asked of this computer's daemon and not yet answered; one that waits on a sign-in+ /// first, and whether that sign-in — hn's own, started from Set up — has landed (continued by the+ /// first read after it). Only that sign-in sets grid up: one made anywhere else signs in alone.+ pub setting_up: bool,+ pub set_up_after_sign_in: bool,+ pub set_up_signed_in: bool,/// A download, start or stop asked and not yet answered (machine, model, action), then its/// acknowledgement, until a read shows the daemon's own receipt.pub pending: Option<(String, String, &'static str)>,@@ -479,7 +490,7 @@ pub fn no_target_why(app: &App) -> String {if p.agent_id.is_empty() { return "The focused pane is a shell, not a harness — start one with New harness".into() }match app.fleet.agent(&p.machine_id, &p.agent_id) {None => format!("This pane's harness ({}) is not in the list yet — try again in a moment", p.agent_id.chars().take(8).collect::<String>()),- Some(a) if a.engine == "terminal" => "The focused pane is a terminal — its model can not be switched; a harness's can".into(),+ Some(a) if a.engine == "terminal" => "The focused pane is a terminal. Focus a harness to move it onto a model.".into(),Some(_) => NO_HARNESS.into(),}}@@ -497,8 +508,11 @@ fn served_in(grids: Option<&Grids>, m: &LocalModel) -> Option<(String, String)>}/// The model running on this computer besides [m]: the one a Use of [m] stops first.+/// Another chat model running here — the one to stop before [m] can run. Never a Jev model: it runs+/// beside chat models (the desktop's `otherRunningModel`).fn other_running(app: &App, m: &LocalModel) -> Option<LocalModel> {- app.models_view.local.get(&app.fleet.local_id)?.models.iter().find(|o| o.can_stop && o.id != m.id).cloned()+ if m.decision { return None }+ app.models_view.local.get(&app.fleet.local_id)?.models.iter().find(|o| o.can_stop && o.id != m.id && !o.decision).cloned()}/// The harnesses answering with [m] besides [t], by name: what stopping it leaves without a model@@ -637,6 +651,24 @@ fn note(key: &str, words: &str, group: &str) -> Row {Row::new(format!("mv:note:{key}"), words.to_string()).group(group.to_string()).lead(vec![span(" ", Style::default())]).extra("note")}+/// The row that sets grid up here (the desktop's `model:grid-setup`), and the note over an empty+/// Your models whose Enter goes to the models to get.+const SET_UP: &str = "mv:setup";+const NONE_YET: &str = "mv:note:none";++/// Grid is not set up on this computer (or its Set up is under way): the view offers to set it up.+fn needs_set_up(app: &App) -> bool {+ app.models_view.setting_up || app.models_view.local.get(&app.fleet.local_id).is_some_and(|s| s.grid_setup_needed)+}++fn signed_out(app: &App) -> bool { app.account.status == crate::account::Status::SignedOut }++/// The Set up row's word: what Enter does, or what it is doing.+fn set_up_word(app: &App) -> &'static str {+ let v = &app.models_view;+ if v.setting_up { "Setting up…" } else if v.set_up_after_sign_in && crate::account::signing_in(app) { "Signing in…" } else if signed_out(app) { "Sign in" } else { "Set up" }+}+fn local_row(app: &App, m: &LocalModel, t: Option<&Target>, group: &str) -> Row {let f = facts(app, m, t);let word = f.word(m);@@ -719,9 +751,14 @@ fn jev_local_row(app: &App, m: &LocalModel, group: &str) -> Row {fn jev_local_grid(app: &App, m: &LocalModel) -> Option<String> {if !m.running() { return None }let g = app.models_view.grids.get(&app.fleet.local_id)?;- g.sections.iter().find(|s| s.own && s.models.iter().any(|x| x.decision && x.id.eq_ignore_ascii_case(&m.name))).map(|s| s.name.clone())+ g.sections.iter().find(|s| s.own && s.models.iter().any(|x| x.decision && x.id.eq_ignore_ascii_case(&m.name)))+ // (A resting own grid lists nothing: the engine here is parked on it, and the first request wakes it.)+ .or_else(|| g.sections.iter().find(|s| s.own && resting(s))).map(|s| s.name.clone())}+/// A grid asleep or waking: it lists nothing until a request wakes it.+fn resting(s: &Section) -> bool { matches!(s.state.as_str(), "asleep" | "waking") }+/// How to call the Jev model [model] on [grid] from a terminal: load the grid's address and key with/// `harness grid env` (the harness's own `grid`, so none of one's own is needed, nor one new enough to/// call a resting grid), then ask one decision. The key is never in it; the shell reads the variable.@@ -825,6 +862,14 @@ pub fn rows(app: &App, query: &str) -> Vec<Row> {_ => {}}+ // Grid not set up here: local and shared models are this one row, as on the desktop — a download+ // or a shared model cannot be used before then, and listed beside "Set up" they read as if they could.+ if needs_set_up(app) {+ out.push(Row::new(SET_UP, "Set up local & shared models").group(YOUR_MODELS).extra("setup grid local shared download")+ .lead(vec![span("+ ", fg(theme::accent()))]).right(set_up_word(app)));+ return out;+ }+// Your models: this computer's — being started, running, downloaded, in the daemon's order// within each — then the own grid's models the account's other machines serve.if let Some(t) = t.filter(|t| v.grids.contains_key(&machine) && !can_run(app, &t.engine)) {@@ -855,7 +900,9 @@ pub fn rows(app: &App, query: &str) -> Vec<Row> {let theirs: Vec<Row> = v.grids.get(&machine).map(own).unwrap_or_default().into_iter().filter(|(_, x)| !here.iter().any(|m| x.id.eq_ignore_ascii_case(&m.id) || x.id.eq_ignore_ascii_case(&m.name))).map(|(s, x)| grid_row(app, &s, &x, t, YOUR_MODELS)).collect();- if mine.is_empty() && theirs.is_empty() && !searching { out.push(note("none", "No models here yet — get one below", YOUR_MODELS)) }+ // (Only with something below to get: Enter goes to it.)+ let to_get = s.models.iter().any(|m| !m.downloaded() && !m.can_stop && !m.decision);+ if mine.is_empty() && theirs.is_empty() && !searching && to_get { out.push(note("none", "No models here yet — get one below", YOUR_MODELS)) }out.extend(mine.into_iter().map(|(_, _, r)| r));out.extend(theirs);}@@ -962,6 +1009,10 @@ pub enum Plan {Api(String),/// Put [text] on the clipboard (and in a paste buffer): how to call a Jev model.Copy(String),+ /// Set grid up here, signing in first when signed out ([set_up]).+ SetUp,+ /// The cursor to row [0] (from the empty Your models' note to the first model to get).+ Select(String),}fn local_model(app: &App, id: &str) -> Option<LocalModel> { app.models_view.local.get(&app.fleet.local_id)?.models.iter().find(|m| m.id == id).cloned() }@@ -996,6 +1047,11 @@ pub fn plan_enter(app: &App, id: &str) -> Plan {let v = &app.models_view;let say = |s: &str| Plan::Say(s.to_string());if id == "mv:more" { return Plan::More }+ if id == SET_UP { return if v.setting_up { say("Setting up…") } else { Plan::SetUp } }+ if id == NONE_YET {+ let head = catalog_heading(v.local.get(&app.fleet.local_id));+ return rows(app, "").into_iter().find(|r| r.id.starts_with("mv:local:") && r.group.as_deref() == Some(head.as_str())).map_or(Plan::Nothing, |r| Plan::Select(r.id));+ }if let Some(name) = id.strip_prefix("mv:wake:") { return if v.asking.contains(name) { say(STARTING_UP_WAIT) } else { Plan::Wake(name.to_string()) } }if let Some(key) = id.strip_prefix("mv:api:") { return Plan::Api(key.to_string()) }if let Some(rest) = id.strip_prefix("mv:jev:") {@@ -1009,7 +1065,11 @@ pub fn plan_enter(app: &App, id: &str) -> Plan {if let Some(grid) = jev_local_grid(app, &m) { return Plan::Copy(jev_request(&grid, &m.name)) }if m.running() { return say("It is starting on your grid — Enter copies how to call it once the grid lists it.") }// Get is the whole of it: the download, an engine new enough to serve it, and the model on the grid.- return if m.can_start { Plan::Act { model: m.id.clone(), action: "start" } } else { say("Wait for the current model operation to finish.") };+ // A download asks first, as a chat model's Get does: a click is Enter here, and it is gigabytes.+ if !m.can_start { return say("Wait for the current model operation to finish.") }+ let go = Plan::Act { model: m.id.clone(), action: "start" };+ let size = m.size.map(gb).map(|s| format!(" ({s})")).unwrap_or_default();+ return if m.downloaded() { go } else { Plan::Arm(format!("Get {}{size}? Enter · Esc", m.name), Box::new(go)) };}if let Some(rest) = id.strip_prefix("mv:apimodel:") {let Some((api, model)) = rest.split_once('\t') else { return Plan::Nothing };@@ -1115,7 +1175,7 @@ fn run(app: &mut App, picker: &mut Picker, plan: Plan, key: &str) {app.models_view.confirm = None;if picker.armed.as_deref() == Some(key) { picker.armed = None; run(app, picker, *then, key) }// Enter on a local model asks in its preview, where it stays until answered.- else if let Some(row) = key.strip_suffix("\u{1f}enter").filter(|id| id.starts_with("mv:local:")) { picker.armed = Some(key.to_string()); app.models_view.confirm = Some((row.to_string(), words)) }+ else if let Some(row) = key.strip_suffix("\u{1f}enter").filter(|id| id.starts_with("mv:local:") || id.starts_with("mv:jevlocal:")) { picker.armed = Some(key.to_string()); app.models_view.confirm = Some((row.to_string(), words)) }else { picker.armed = Some(key.to_string()); picker.say(words) }}Plan::Retarget { machine, payload, name } => {@@ -1127,7 +1187,13 @@ fn run(app: &mut App, picker: &mut Picker, plan: Plan, key: &str) {Plan::Use { model, download } => start_use(app, &model, download),Plan::Act { model, action } => { picker.say(format!("{}…", pending_word(action))); act(app, &model, action) }Plan::Wake(name) => { wake(app, &name); picker.say(STARTING_UP_WAIT) }- Plan::More => app.models_view.more = !app.models_view.more,+ Plan::More => {+ let before: std::collections::HashSet<String> = rows(app, "").into_iter().map(|r| r.id).collect();+ app.models_view.more = !app.models_view.more;+ // (Opened, the cursor goes to the first model it shows, as the desktop's does — not to Show+ // fewer at the end of the list. The list is filled again after this, keeping the cursor's row.)+ if app.models_view.more { if let Some(r) = rows(app, "").into_iter().find(|r| !before.contains(&r.id)) { picker.selected_id = Some(r.id) } }+ }Plan::Api(key) => {let v = &mut app.models_view;if !v.api_open.remove(&key) { v.api_open.insert(key.clone()); if !v.api_models.contains_key(&key) { read_api_models(app, &key) } }@@ -1138,7 +1204,67 @@ fn run(app: &mut App, picker: &mut Picker, plan: Plan, key: &str) {app.paste.add(text, limit);picker.say(JEV_COPIED);}+ Plan::SetUp => set_up(app),+ Plan::Select(id) => picker.select(&id),+ }+}++/// Set up, as the desktop's: signed out, it starts with signing in (the account page) and finishes+/// itself once that sign-in lands ([own_sign_in_done], [on_local]); signed in, it is a list read that+/// sets grid up (`setup`).+fn set_up(app: &mut App) {+ if signed_out(app) {+ app.models_view.set_up_after_sign_in = true;+ app.models_view.set_up_signed_in = false;+ crate::account::open(app);+ return;+ }+ send_set_up(app);+}++fn send_set_up(app: &mut App) {+ app.models_view.set_up_after_sign_in = false;+ app.models_view.set_up_signed_in = false;+ app.models_view.setting_up = true;+ let machine = app.fleet.local_id.clone();+ let m = machine.clone();+ if !read_rpc(app, &machine, "setup", "grid_fleet_models_list", json!({ "refresh": true, "setup": true }), Duration::from_secs(180), move |app, r| on_set_up(app, &m, r)) {+ app.models_view.setting_up = false;+ app.say("This computer is not connected", theme::WARN);+ }+}++/// hn's own sign-in, started from Set up, landed: the Set up goes on — back in the Models view it was+/// asked from, whose read of this computer's list carries it on ([on_local]).+pub(crate) fn own_sign_in_done(app: &mut App) {+ if !app.models_view.set_up_after_sign_in { return }+ app.models_view.set_up_signed_in = true;+ if matches!(app.modal, Some(crate::modal::Modal::Picker { kind: crate::modal::PickerKind::Account, .. })) { crate::input::run(app, "models"); return }+ let machine = app.fleet.local_id.clone();+ if !machine.is_empty() && !app.models_view.reading.contains(&machine) { read_local(app, &machine) }+}++/// This computer is signed in. Not by hn's own sign-in (that is [own_sign_in_done], and one still+/// under way decides there): it was signed in somewhere else — the desktop, a terminal — which signs+/// in alone, so a Set up left waiting is dropped rather than carried out.+pub(crate) fn signed_in(app: &mut App) {+ let v = &app.models_view;+ if !v.set_up_after_sign_in || v.set_up_signed_in || crate::account::signing_in(app) { return }+ app.models_view.set_up_after_sign_in = false;+}++/// The Set up answered: the list it read (its `gridSetupError` says why it could not), and the+/// shared grids read again once grid is set up.+pub fn on_set_up(app: &mut App, machine: &str, reply: Result<Value, RpcError>) {+ app.models_view.setting_up = false;+ match reply {+ Ok(r) => on_local(app, machine, Ok(r)),+ Err(e) => {+ if let Some(s) = app.models_view.local.get_mut(machine) { s.grid_setup_error = Some(why(&e)) }+ crate::input::refill(app);+ }}+ if !needs_set_up(app) { read_grids(app, machine) }}/// What a Use is doing, for the footer: `Downloading 42%…`, `Starting…`, `Moving it…`.@@ -1219,6 +1345,7 @@ fn release_read(app: &mut App, machine: &str, kind: &str) {"local" => { app.models_view.reading.remove(machine); },"grids" => { app.models_view.grids_reading.remove(machine); },"act" => { app.models_view.pending = None; },+ "setup" => { app.models_view.setting_up = false; },_ => if let Some(name) = kind.strip_prefix("wake:") { app.models_view.asking.remove(name); },}}@@ -1230,7 +1357,9 @@ fn reconcile_reads(app: &mut App) {if app.models_view.owner.as_ref().is_some_and(|old| old != &owner) {let switch_generation = app.models_view.switch_generation.wrapping_add(1);let panel_generation = app.models_view.panel_generation.wrapping_add(1);- app.models_view = Models { switch_generation, panel_generation, ..Default::default() };+ // (A Set up waiting on the sign-in that changed the owner continues on the new one.)+ let (set_up_after_sign_in, set_up_signed_in) = (app.models_view.set_up_after_sign_in, app.models_view.set_up_signed_in);+ app.models_view = Models { switch_generation, panel_generation, set_up_after_sign_in, set_up_signed_in, ..Default::default() };}app.models_view.owner = Some(owner.clone());let stale: Vec<_> = app.models_view.reads.iter().filter(|((machine, _), read)| read.owner != owner || read.connection != app.connection_generation(machine))@@ -1296,6 +1425,17 @@ pub fn on_local(app: &mut App, machine: &str, reply: Result<Value, RpcError>) {}None => { v.local_error.insert(machine.to_string(), "Models are unavailable. Try again.".into()); }}+ // A Set up that waited on hn's own sign-in: that landed, so it continues — or is done, when the list+ // says grid is set up. No list (a read that failed while the daemon restarted for the sign-in)+ // decides nothing: the next read does.+ let v = &app.models_view;+ if machine == app.fleet.local_id && v.set_up_after_sign_in && v.set_up_signed_in && !v.setting_up {+ match v.local.get(machine).map(|s| s.grid_setup_needed) {+ Some(true) => send_set_up(app),+ Some(false) => { app.models_view.set_up_after_sign_in = false; app.models_view.set_up_signed_in = false }+ None => {}+ }+ }advance(app);crate::input::refill(app);crate::workspace_controls::refresh_workspace(app);@@ -1370,6 +1510,18 @@ pub fn on_wake(app: &mut App, machine: &str, name: &str, reply: Result<Value, Rpcrate::input::refill(app);}+/// How soon an open view asks again for APIs it could not read (the daemon restarting for a sign-in).+const APIS_RETRY: Duration = Duration::from_secs(10);++/// The saved APIs are read when the view opens — and, open, whenever it has no list and asks for+/// none: one that opened before this computer's connection was up, or whose owner changed under it —+/// or its last answer failed a while ago.+fn apis_due(app: &App, open: bool) -> bool {+ let v = &app.models_view;+ let failed = matches!(v.apis, Some(Err(_))) && due(v.apis_at.as_ref(), APIS_RETRY, Instant::now());+ open && (v.apis.is_none() || failed) && !v.reads.contains_key(&(app.fleet.local_id.clone(), "apis".to_string()))+}+fn read_apis(app: &mut App) {let machine = app.fleet.local_id.clone();read_rpc(app, &machine, "apis", "api_connections", json!({ "action": "list" }), Duration::from_secs(20), on_apis);@@ -1379,6 +1531,7 @@ pub fn on_apis(app: &mut App, reply: Result<Value, RpcError>) {let list = match reply { Ok(r) => parse_apis(&r), Err(e) => Err(if e.detail.is_empty() { "APIs are unavailable. Try again.".into() } else { e.detail.clone() }) };let serving: Vec<String> = list.as_ref().map(|l| l.iter().filter(|a| a.serves_models()).map(|a| a.id.clone()).collect()).unwrap_or_default();app.models_view.apis = Some(list);+ app.models_view.apis_at = Some(Instant::now());for id in serving { if !app.models_view.api_models.contains_key(&id) { read_api_models(app, &id) } }crate::input::refill(app);}@@ -1629,9 +1782,11 @@ pub fn tick(app: &mut App) {let serving = v.using.as_ref().is_some_and(|u| u.step == Step::Serve);let waking = v.follow_until.is_some_and(|t| now < t) && v.grids.get(&machine).is_some_and(Grids::waking);let grids_due = !v.grids_reading.contains(&machine) && grids_every(open, serving, waking).is_some_and(|e| due(v.grids_at.get(&machine), e, now));+ let apis_due = apis_due(app, open);if !waking { app.models_view.follow_until = None }if local_due { read_local(app, &machine) }if grids_due { read_grids(app, &machine) }+ if apis_due { read_apis(app) }advance(app);}@@ -1814,11 +1969,17 @@ pub fn preview(app: &App, id: &str) -> Vec<Line<'static>> {_ => Some(Line::raw("Get downloads it and runs it on your grid.")),};if let Some(status) = status { out.push(Line::raw("")); out.push(status) }+ // (The first Enter's question, until Enter, Esc or the cursor leaves the row.)+ if let Some((_, words)) = v.confirm.as_ref().filter(|(row, _)| row == id) { out.push(Line::raw("")); out.push(Line::from(span(words.clone(), theme::bold(theme::accent())))) }out.push(Line::raw(""));if let Some(size) = m.size { out.push(kv("Size", gb(size))) }// A decision model another app downloaded (Ollama's tev1) runs in that app.out.push(kv("Runs in", match m.app.as_deref() { None | Some("Grid") => "Grid's llama.cpp".to_string(), Some(a) => a.to_string() }));if let Some(grid) = &grid {+ if v.grids.get(&machine).and_then(|g| g.sections.iter().find(|s| &s.name == grid)).is_some_and(resting) {+ out.push(Line::raw(""));+ out.push(Line::raw("Its grid is resting. Your first request wakes it, which takes a few seconds."));+ }out.push(Line::raw(""));out.push(Line::raw("Call it from a terminal:"));out.extend(jev_request(grid, &m.name).lines().map(|l| Line::from(span(l.to_string(), fg(theme::SOFT)))));@@ -1904,10 +2065,34 @@ pub fn preview(app: &App, id: &str) -> Vec<Line<'static>> {return out;}if id == "mv:more" {- let n = v.local.get(&machine).map(|s| s.models.iter().filter(|m| !m.downloaded()).count()).unwrap_or(0);+ // (The models the row folds: not the decision models, listed apart, nor one running here.)+ let n = v.local.get(&machine).map(|s| s.models.iter().filter(|m| !m.downloaded() && !m.can_stop && !m.decision).count()).unwrap_or(0);return vec![bold(format!("{n} models that fit {}", this_computer())), Line::raw(""), Line::from(span(if v.more { "Enter shows the first five." } else { "Enter lists them all." }, fg(theme::accent())))];}- id.strip_prefix("mv:note:").map(|_| vec![]).unwrap_or_default()+ if id == SET_UP {+ let here = this_computer();+ let mut out = vec![bold("Local & shared models"), Line::raw(format!("Download models to run on {here}, and use the models other people share with you.")), Line::raw("")];+ let signed_out = signed_out(app);+ if signed_out { out.push(Line::raw("They belong to your Harness account, so you need to sign in to use them.")); out.push(Line::raw("")) }+ // (Under way, it says so in place of what Enter would do.)+ match set_up_word(app) {+ "Setting up…" => out.push(Line::raw("Setting up…")),+ "Signing in…" => out.push(Line::raw("Signing in… Finish in your browser, and setup continues here.")),+ _ => {+ let said = if signed_out { "Enter opens sign-in. Setup finishes here once you're signed in.".to_string() } else { format!("Enter gets {here} ready for them with your Harness account.") };+ out.push(Line::from(span(said, fg(theme::accent()))));+ if let Some(e) = v.local.get(&machine).and_then(|s| s.grid_setup_error.clone()).filter(|_| !signed_out) { out.push(Line::raw("")); out.push(warn(format!("Could not set up: {e}"))) }+ }+ }+ return out;+ }+ if id == NONE_YET { return vec![bold("No models here yet"), Line::raw(""), Line::from(span("Enter goes to the models to get, below.", fg(theme::accent())))] }+ // A note (a grid not answering, a list that could not be read) has nothing to choose: its panel says+ // it again, whole, rather than standing blank as if something failed to load.+ if id.starts_with("mv:note:") {+ return rows(app, "").into_iter().find(|r| r.id == id).map(|r| vec![Line::raw(r.label)]).unwrap_or_default();+ }+ vec![]}#[cfg(test)]@@ -2893,7 +3078,7 @@ mod tests {assert_eq!(row(&rows, id).right_narrow.as_deref(), Some("Get"));assert!(rows.iter().filter(|r| r.label == "laya-english").count() == 1, "never also offered among the downloads");assert!(text(&preview(&app, id)).contains("Get downloads it and runs it on your grid."));- assert_eq!(plan_enter(&app, id), Plan::Act { model: "jev:ggml-org/Laya-GGUF".into(), action: "start" });+ assert_eq!(plan_enter(&app, id), Plan::Arm("Get laya-english (0.4 GB)? Enter · Esc".into(), Box::new(Plan::Act { model: "jev:ggml-org/Laya-GGUF".into(), action: "start" })));// Its engine being updated says so, on the row and in the panel.let mut updating = reply.clone();@@ -2919,4 +3104,249 @@ mod tests {assert!(text(&preview(&app, id)).contains(&jev_request("own-grid", "laya-english")));assert!(matches!(plan_stop(&app, id), Plan::Arm(_, ref then) if **then == Plan::Act { model: "jev:ggml-org/Laya-GGUF".into(), action: "stop" }));}++ /// Grid not set up here (`gridSetupNeeded`): Your models is the desktop's one Set up row — no+ /// "Sign in to find models" sentence, nothing to get. Signed out, Enter opens the sign-in and the+ /// Set up waits on it: hn's own sign-in lands — the daemon restarted under the account's machine+ /// id, its first read failing — and the view comes back and the Set up goes on by itself.+ #[test]+ fn set_up_signed_out_signs_in_then_sets_up_by_itself() {+ use crate::account::Status;+ use crate::devices::{Reply, Req};+ use crate::modal::{Modal, PickerKind};+ let mut app = app();+ let needed = json!({ "models": [], "notice": "Sign in to find models for this computer.", "busy": false, "gridSetupNeeded": true });+ on_local(&mut app, "local", Ok(needed.clone()));+ let rows = super::rows(&app, "");+ let mine: Vec<&str> = rows.iter().filter(|r| r.group.as_deref() == Some(YOUR_MODELS)).map(|r| r.id.as_str()).collect();+ assert_eq!(mine, vec![SET_UP]);+ assert!(!rows.iter().any(|r| r.label.contains("Sign in to find") || r.id == NONE_YET), "{:?}", rows.iter().map(|r| &r.label).collect::<Vec<_>>());++ app.account.status = Status::SignedOut;+ assert_eq!(row(&super::rows(&app, ""), SET_UP).right, "Sign in");+ assert!(text(&preview(&app, SET_UP)).contains("Enter opens sign-in"));+ let before = app.models_view.sent.len();+ let mut picker = Picker::new("models", "");+ choose(&mut app, &mut picker, SET_UP, false);+ assert!(matches!(app.modal, Some(Modal::Picker { kind: PickerKind::Account, .. })), "the sign-in is shown");+ assert!(app.models_view.set_up_after_sign_in);+ assert_eq!(app.models_view.sent.len(), before, "nothing is set up signed out");+ crate::account::tick(&mut app);+ assert!(app.models_view.set_up_after_sign_in, "the account page is open: still waiting");++ // hn's own sign-in: the daemon answers to the account's machine id now, and its first read fails.+ app.devices.runner = Some(Box::new(|req| Some(match req {+ Req::Cli { .. } => Reply::Cli { ok: true, out: "{\"loggedIn\":true}".into(), err: String::new() },+ _ => Reply::Http(Err(("TEST".into(), "no daemon in tests".into()))),+ })));+ app.fleet.local_id = "acct".into();+ app.fleet.machines[0].id = "acct".into();+ account_changed(&mut app);+ crate::account::sign_in_for_test(&mut app);+ assert_eq!(app.account.status, Status::SignedIn { offline: false, email: None });+ assert!(matches!(app.modal, Some(Modal::Picker { kind: PickerKind::Models, .. })), "back in Models, where it was asked");+ on_local(&mut app, "acct", Ok(json!({})));+ assert!(app.models_view.set_up_after_sign_in, "a read with no list decides nothing");+ crate::account::tick(&mut app);+ assert!(app.models_view.set_up_after_sign_in, "signed in: leaving the account page gives nothing up");++ on_local(&mut app, "acct", Ok(needed));+ assert_eq!(last_sent(&app), ("acct".into(), "grid_fleet_models_list".into(), json!({ "refresh": true, "setup": true })));+ assert!(!app.models_view.set_up_after_sign_in);+ assert_eq!(row(&super::rows(&app, ""), SET_UP).right, "Setting up…");+ assert_eq!(plan_enter(&app, SET_UP), Plan::Say("Setting up…".into()));++ on_set_up(&mut app, "acct", Ok(local_reply(qwen("running", Value::Null), false)));+ assert_eq!(last_sent(&app).1, "grid_models_list", "the shared grids are read again");+ let rows = super::rows(&app, "");+ assert!(!rows.iter().any(|r| r.id == SET_UP));+ assert!(rows.iter().any(|r| r.id == "mv:local:qwen-35b"));+ }++ /// Only Set up signs in AND sets grid up. A sign-in anywhere else signs in alone: from hn's account+ /// page, or the desktop — even with a Set up left waiting — or after a Set up's sign-in was given up.+ #[test]+ fn a_sign_in_for_anything_else_sets_nothing_up() {+ use crate::account::Status;+ use crate::devices::{Reply, Req};+ use crate::modal::{Modal, PickerKind};+ let needed = json!({ "models": [], "busy": false, "gridSetupNeeded": true });+ let signed_in = || -> crate::devices::Runner { Box::new(|req| Some(match req {+ Req::Cli { .. } => Reply::Cli { ok: true, out: "{\"loggedIn\":true}".into(), err: String::new() },+ _ => Reply::Http(Err(("TEST".into(), "no daemon in tests".into()))),+ })) };+ let nothing_set_up = |app: &mut App| {+ let before = app.models_view.sent.len();+ on_local(app, "local", Ok(json!({ "models": [], "busy": false, "gridSetupNeeded": true })));+ assert_eq!(app.models_view.sent.len(), before, "nothing is set up");+ assert_eq!(row(&super::rows(app, ""), SET_UP).right, "Set up");+ };++ // hn's own sign-in from its account page, no Set up asked: it signs in alone.+ let mut app = app();+ on_local(&mut app, "local", Ok(needed.clone()));+ app.account.status = Status::SignedOut;+ crate::account::open(&mut app);+ app.devices.runner = Some(signed_in());+ crate::account::sign_in_for_test(&mut app);+ assert!(matches!(app.modal, Some(Modal::Picker { kind: PickerKind::Account, .. })), "no view is opened for it");+ nothing_set_up(&mut app);++ // A Set up waiting on the sign-in page, and the computer signed in elsewhere (the desktop).+ let mut app = super::tests::app();+ on_local(&mut app, "local", Ok(needed.clone()));+ app.account.status = Status::SignedOut;+ let mut picker = Picker::new("models", "");+ choose(&mut app, &mut picker, SET_UP, false);+ assert!(app.models_view.set_up_after_sign_in);+ app.devices.runner = Some(signed_in());+ crate::account::refresh(&mut app, true);+ assert!(!app.models_view.set_up_after_sign_in, "signed in elsewhere: the Set up is dropped");+ nothing_set_up(&mut app);++ // A Set up whose sign-in was given up (the page left), then a sign-in later.+ let mut app = super::tests::app();+ on_local(&mut app, "local", Ok(needed));+ app.account.status = Status::SignedOut;+ let mut picker = Picker::new("models", "");+ choose(&mut app, &mut picker, SET_UP, false);+ app.modal = None;+ crate::account::tick(&mut app);+ assert!(!app.models_view.set_up_after_sign_in, "the sign-in was given up");+ app.devices.runner = Some(signed_in());+ crate::account::open(&mut app);+ crate::account::sign_in_for_test(&mut app);+ nothing_set_up(&mut app);+ }++ /// A Set up that fails says why in its preview, and Enter tries again.+ #[test]+ fn a_failed_set_up_says_why_and_enter_tries_again() {+ let mut app = app();+ app.account.status = crate::account::Status::SignedIn { offline: false, email: None };+ on_local(&mut app, "local", Ok(json!({ "models": [], "gridSetupNeeded": true })));+ let mut picker = Picker::new("models", "");+ choose(&mut app, &mut picker, SET_UP, false);+ assert_eq!(last_sent(&app).2, json!({ "refresh": true, "setup": true }));+ on_set_up(&mut app, "local", Ok(json!({ "models": [], "gridSetupNeeded": true, "gridSetupError": "Grid could not be set up on this computer. Try again." })));+ assert!(text(&preview(&app, SET_UP)).contains("Could not set up: Grid could not be set up"));+ assert_eq!(row(&super::rows(&app, ""), SET_UP).right, "Set up");+ assert_eq!(plan_enter(&app, SET_UP), Plan::SetUp);+ }++ /// "No models here yet — get one below" only with something below to get, and Enter goes to it.+ #[test]+ fn the_empty_note_points_at_the_models_to_get() {+ let mut app = app();+ on_local(&mut app, "local", Ok(json!({ "models": [model("first", "available", 4.0), model("second", "available", 4.0)], "memoryBytes": 64.0 * GIB, "supportsDownload": true })));+ assert!(super::rows(&app, "").iter().any(|r| r.id == NONE_YET));+ assert_eq!(plan_enter(&app, NONE_YET), Plan::Select("mv:local:first".into()));+ on_local(&mut app, "local", Ok(json!({ "models": [], "notice": "The model catalog is unavailable." })));+ let rows = super::rows(&app, "");+ assert!(!rows.iter().any(|r| r.id == NONE_YET), "nothing below to get");+ assert!(rows.iter().any(|r| r.label == "The model catalog is unavailable."));+ }++ /// An open view with no saved APIs listed asks for them — opened before this computer's+ /// connection was up, or after the sign-in that changed its owner — and only once at a time.+ #[test]+ fn an_open_view_without_the_apis_reads_them() {+ let mut app = app();+ reconcile_reads(&mut app);+ assert!(!apis_due(&app, false), "closed, it reads nothing");+ assert!(apis_due(&app, true));+ read_apis(&mut app);+ assert_eq!(last_sent(&app).1, "api_connections");+ assert!(!apis_due(&app, true), "one read at a time");+ let read = app.models_view.reads[&("local".to_string(), "apis".to_string())].clone();+ assert!(finish_read(&mut app, "local", "apis", &read));+ on_apis(&mut app, Ok(json!({ "connections": [] })));+ assert!(!apis_due(&app, true), "listed");+ // A failed answer (the daemon restarting for a sign-in) is asked again a little later.+ on_apis(&mut app, Err(RpcError::new("start the Harness daemon to use this feature", "")));+ assert!(!apis_due(&app, true), "not at once");+ app.models_view.apis_at = Some(Instant::now() - APIS_RETRY);+ assert!(apis_due(&app, true));+ app.fleet.local_id = "acct".into();+ app.fleet.machines[0].id = "acct".into();+ reconcile_reads(&mut app);+ assert!(apis_due(&app, true), "a new owner's are read again");+ }++ /// The own grid asleep lists nothing, but a Jev model running here is parked on it: Enter still+ /// copies how to call it on that grid, and its panel says the first request wakes it.+ #[test]+ fn a_jev_model_on_a_resting_own_grid_still_copies_its_request() {+ let mut app = app();+ on_local(&mut app, "local", Ok(json!({ "models": [{ "id": "tev1", "name": "tev1", "state": "running", "kind": "decision", "app": "Ollama", "canStop": true, "sizeBytes": 4.1 * GIB }] })));+ on_grids(&mut app, "local", Ok(json!({ "gridName": "own-grid", "grids": [{ "name": "own-grid", "own": true, "state": "asleep", "models": [] }] })));+ let id = "mv:jevlocal:tev1";+ assert_eq!(row(&super::rows(&app, ""), id).right_narrow.as_deref(), Some("Serving"));+ assert_eq!(plan_enter(&app, id), Plan::Copy(jev_request("own-grid", "tev1")));+ let panel = text(&preview(&app, id));+ assert!(panel.contains("Its grid is resting. Your first request wakes it"), "{panel}");+ assert!(panel.contains("Call it from a terminal:") && panel.contains("harness grid env own-grid"), "{panel}");++ // Awake and not listing it yet: it is still starting there, and nothing is copied.+ on_grids(&mut app, "local", Ok(json!({ "gridName": "own-grid", "grids": [{ "name": "own-grid", "own": true, "state": "awake", "models": [] }] })));+ assert!(matches!(plan_enter(&app, id), Plan::Say(ref s) if s.starts_with("It is starting on your grid")));+ }++ /// A click is Enter in hn, and a Jev model's Get is gigabytes: the first asks in its panel, as a+ /// chat model's Get does, and only the second gets it.+ #[test]+ fn a_jev_model_s_get_asks_first() {+ let mut app = app();+ let mut reply = local_reply(qwen("running", Value::Null), false);+ reply["models"].as_array_mut().unwrap().push(json!({ "id": "jev:kev-4b", "name": "kev-4b", "kind": "decision", "state": "available", "sizeBytes": 4.2 * GIB, "canStart": true, "app": "Grid" }));+ on_local(&mut app, "local", Ok(reply));+ let id = "mv:jevlocal:jev:kev-4b";+ let mut picker = Picker::new("models", "");+ choose(&mut app, &mut picker, id, false);+ assert!(text(&preview(&app, id)).contains("Get kev-4b (4.2 GB)? Enter · Esc"), "{}", text(&preview(&app, id)));+ assert!(!app.models_view.sent.iter().any(|s| s.1 == "grid_fleet_model_start"), "nothing is got on the first");+ choose(&mut app, &mut picker, id, false);+ assert_eq!(last_sent(&app), ("local".into(), "grid_fleet_model_start".into(), json!({ "modelId": "jev:kev-4b" })));+ }++ /// A Jev model runs beside chat models: one running here is never the model a chat model's Get+ /// or Start says to stop first (the desktop's `otherRunningModel`).+ #[test]+ fn a_running_jev_model_is_not_the_one_to_stop() {+ let mut app = app();+ let mut reply = local_reply(qwen("available", Value::Null), false);+ reply["models"].as_array_mut().unwrap().push(json!({ "id": "jev:kev-0.8b", "name": "kev-0.8b", "kind": "decision", "state": "running", "sizeBytes": 0.8 * GIB, "canStop": true, "app": "Grid" }));+ on_local(&mut app, "local", Ok(reply));+ app.tabs[0].focus = None;+ app.panes.clear();+ let panel = text(&preview(&app, "mv:local:qwen-35b"));+ assert!(!panel.contains("kev-0.8b"), "{panel}");+ assert!(matches!(plan_enter(&app, "mv:local:qwen-35b"), Plan::Arm(ref words, _) if !words.contains("kev")));+ }++ /// More models says how many it folds — not the decision models, listed apart — and, opened,+ /// puts the cursor on the first model it shows, not on Show fewer at the end of the list.+ #[test]+ fn more_models_counts_what_it_folds_and_opens_at_the_first_it_shows() {+ let mut app = app();+ let mut reply = local_reply(qwen("available", Value::Null), false);+ reply["models"].as_array_mut().unwrap().push(json!({ "id": "jev:kev-4b", "name": "kev-4b", "kind": "decision", "state": "available", "sizeBytes": 4.2 * GIB, "canStart": true }));+ on_local(&mut app, "local", Ok(reply));+ assert_eq!(row(&super::rows(&app, ""), "mv:more").label, "More models (2)");+ assert!(text(&preview(&app, "mv:more")).starts_with("7 models that fit"), "{}", text(&preview(&app, "mv:more")));+ let mut picker = Picker::new("models", "");+ picker.set_rows(super::rows(&app, ""));+ picker.select("mv:more");+ choose(&mut app, &mut picker, "mv:more", false);+ picker.set_rows(super::rows(&app, ""));+ assert_eq!(picker.current_id().as_deref(), Some("mv:local:extra-5"));+ }++ /// A note's panel says the note again instead of standing blank.+ #[test]+ fn a_note_s_panel_says_it() {+ let mut app = app();+ on_local(&mut app, "local", Ok(json!({ "models": [], "notice": "The model catalog is unavailable." })));+ assert_eq!(text(&preview(&app, "mv:note:notice")), "The model catalog is unavailable.");+ }}