The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat(tray): Claude-style tray menu with account or engine lines (T2)
purple37e95643165c
diff --git a/src-tauri/src/commands/gpu.rs b/src-tauri/src/commands/gpu.rsindex dd1782e3..b3dc0e32 100644--- a/src-tauri/src/commands/gpu.rs+++ b/src-tauri/src/commands/gpu.rs@@ -97,6 +97,14 @@ fn run_cmd(program: &str, args: &[&str]) -> Option<String> {crate::commands::shell::output_bounded(cmd, std::time::Duration::from_secs(5))}+/// (free, total) MiB of the biggest NVIDIA card right now, for the tray+/// menu's memory line. `None` without nvidia-smi.+pub(crate) fn nvidia_memory_mib() -> Option<(u64, u64)> {+ run_cmd("nvidia-smi", &["--query-gpu=memory.free,memory.total", "--format=csv,noheader,nounits"])+ .as_deref()+ .and_then(parse_nvidia_memory)+}+/// nvidia-smi's cards alone, for a caller that needs only those (the chat/// role's engine device, gpu_roles.rs).pub(crate) fn detect_nvidia_cards() -> Vec<DetectedGpu> {diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex d9a60ada..80e28b67 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -56,6 +56,7 @@ mod e2e_remote;mod runtime_root;mod storage_move;mod system_tray;+mod tray_menu;mod state;// Test-only OS helpers (a shell, a sleeper, "is this pid alive"), shared by// the process tests in state.rs, commands/engine.rs and commands/bg_tasks.rs@@ -70,7 +71,6 @@ use tauri::Manager;#[cfg(desktop)]use tauri::{Emitter,- menu::{Menu, MenuItem},tray::TrayIconBuilder,image::Image,};@@ -302,7 +302,7 @@ fn should_offload_after_hide(visible_now: bool, hide_generation: u64, current_ge/// icon, or Cmd+Tab to the app, is the way every Mac user gets a window back,/// and macOS reports it as `RunEvent::Reopen`. Nobody handled it, so the app/// sat in the Dock without a window and looked hung; the only way back was the-/// "Show" item of the menu bar icon.+/// "Open LU" item of the menu bar icon.////// With a window on screen macOS already does the right thing by itself/// (it activates the app and raises that window), so only the case without@@ -674,6 +674,11 @@ pub fn run() {// Hugging Face "Use this model": the page takes the waiting link#[cfg(desktop)]hf_link::hf_link_take,+ // T2: the grey lines of the tray menu+ #[cfg(desktop)]+ tray_menu::tray_update,+ #[cfg(desktop)]+ tray_menu::tray_memory,// LU Cloud OAuth loopback (Google/GitHub via system browser)commands::oauth::oauth_start,commands::oauth::oauth_wait,@@ -1391,12 +1396,12 @@ pub fn run() {// Desktop only, like the two sections after it: a phone has no// tray to hide in, and no Ollama or ComfyUI to start. Each// statement carries its own gate so the code keeps its place.+ // T2: the menu is built in tray_menu.rs; it starts as "Open LU" /+ // "Quit LU" and the frontend fills in the grey lines above them.#[cfg(desktop)]- let show = MenuItem::with_id(app, "show", "Show", true, None::<&str>)?;+ app.manage(tray_menu::TrayMenuState::<tauri::Wry>::default());#[cfg(desktop)]- let quit = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?;- #[cfg(desktop)]- let menu = Menu::with_items(app, &[&show, &quit])?;+ let (menu, menu_infos) = tray_menu::build_menu(app, &tray_menu::TrayStatus::default())?;// GH #204: on Linux the tray needs libayatana-appindicator, and// building it without that library aborts the whole app. Without@@ -1419,7 +1424,7 @@ pub fn run() {let _ = tray_icon;Image::new_owned(menu_bar_template_rgba(source.rgba()), source.width(), source.height())};- let tray = TrayIconBuilder::new()+ let tray = TrayIconBuilder::with_id(tray_menu::TRAY_ID).icon(tray_icon).tooltip("LU");#[cfg(target_os = "macos")]@@ -1427,9 +1432,17 @@ pub fn run() {tray.menu(&menu).on_menu_event(|app, event| {- match event.id().as_ref() {- "show" => onboarding_window::bring_to_front(app),- "quit" => {+ let id = event.id().as_ref();+ let action = tray_menu::TrayAction::from_id(id);+ match id {+ tray_menu::OPEN_ID | "tray-plan" | "tray-models" => {+ onboarding_window::bring_to_front(app);+ // The page opens Plan & Credits or Models.+ if let Some(action) = action {+ let _ = app.emit(tray_menu::ACTION_EVENT, action.event_name());+ }+ }+ tray_menu::QUIT_ID => {// Tauri's AppState Drop doesn't fire reliably on// Windows after `app.exit(0)` — run the explicit// subprocess shutdown here so tray Quit doesn't@@ -1442,11 +1455,22 @@ pub fn run() {}}).on_tray_icon_event(|tray, event| {- if let tauri::tray::TrayIconEvent::DoubleClick { .. } = event {- onboarding_window::bring_to_front(tray.app_handle());+ match event {+ tauri::tray::TrayIconEvent::DoubleClick { .. } => {+ onboarding_window::bring_to_front(tray.app_handle());+ }+ // Fresh lines for the menu that is about to open+ // (or already is: they change in place). Enter+ // comes first on a Mac and Windows, so most of the+ // time the menu opens with them already there.+ tauri::tray::TrayIconEvent::Click { .. } | tauri::tray::TrayIconEvent::Enter { .. } => {+ let _ = tray.app_handle().emit(tray_menu::OPENED_EVENT, ());+ }+ _ => {}}}).build(app)?;+ tray_menu::remember(app.handle(), tray_menu::TrayStatus::default(), menu_infos);}// ─── Close → hide to tray instead of quit ───@@ -1573,11 +1597,11 @@ pub fn run() {android_entry::leave_process(0);}// A click on the Dock icon while the window is hidden. Same call- // as the menu bar's "Show": the window is shown again, and that is+ // as the menu bar's "Open LU": the window is shown again, and that is// also what takes back the unload after the hide. Inside// HIDE_OFFLOAD_GRACE the timer finds the window visible and does// nothing (`should_offload_after_hide`); after it, the backends- // start again on first use, exactly as after "Show".+ // start again on first use, exactly as after "Open LU".#[cfg(target_os = "macos")]if let tauri::RunEvent::Reopen { has_visible_windows, .. } = event {if reopen_needs_a_window(has_visible_windows) {@@ -1600,7 +1624,7 @@ mod tests {}/// The rule above is worth nothing unless the run loop asks it, and the- /// way back is the one "Show" takes.+ /// way back is the one "Open LU" takes.#[test]fn the_run_loop_answers_the_dock_click_the_way_show_does() {let src = include_str!("lib.rs");diff --git a/src-tauri/src/tray_menu.rs b/src-tauri/src/tray_menu.rsnew file mode 100644index 00000000..27390514--- /dev/null+++ b/src-tauri/src/tray_menu.rs@@ -0,0 +1,439 @@+// The tray menu (T2, 3.0.9): a short Claude-Desktop-style menu instead of+// "Show" / "Quit".+//+// LU Cloud · Signed in Local · LU Engine+// ● Pro plan · active ● Qwen3 8B · ready+// 1,240 credits left · … GPU memory 9.2 of 24 GB+// ───────── ─────────+// Plan & Credits… Models…+// ───────── ─────────+// Open LU Open LU+// Quit LU Quit LU+//+// The grey lines are disabled items. The frontend knows the account, the+// engine and the model, so it sends the lines (`tray_update`); this side+// only checks and lays them out. The action is one of two fixed ids with+// labels from here, so a page can change what the menu says but never what+// a click does. A click on the icon emits `lu-tray-opened`, and the frontend+// answers with fresh lines; texts change in place, so a menu that is+// already open on a Mac updates while it is open.++use serde::Deserialize;++/// The id the tray is built with, so `tray_update` finds it again.+pub(crate) const TRAY_ID: &str = "lu-tray";+/// Emitted on a click on (or the pointer entering) the tray icon.+pub(crate) const OPENED_EVENT: &str = "lu-tray-opened";+/// Emitted with "plan" or "models" when the action item is clicked.+pub(crate) const ACTION_EVENT: &str = "lu-tray-action";++pub(crate) const OPEN_ID: &str = "open";+pub(crate) const QUIT_ID: &str = "quit";+const INFO_ID_PREFIX: &str = "info-";++/// At most this many grey lines: the menu stays as short as the mock.+pub(crate) const MAX_LINES: usize = 3;+/// Longer lines are cut with "…" (a model file name can be very long).+pub(crate) const MAX_LINE_CHARS: usize = 44;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "lowercase")]+pub(crate) enum TrayDot {+ Green,+ Amber,+ Grey,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "lowercase")]+pub(crate) enum TrayAction {+ Plan,+ Models,+}++impl TrayAction {+ pub(crate) fn id(self) -> &'static str {+ match self {+ TrayAction::Plan => "tray-plan",+ TrayAction::Models => "tray-models",+ }+ }+ pub(crate) fn label(self) -> &'static str {+ match self {+ TrayAction::Plan => "Plan & Credits…",+ TrayAction::Models => "Models…",+ }+ }+ /// The payload of `lu-tray-action`.+ pub(crate) fn event_name(self) -> &'static str {+ match self {+ TrayAction::Plan => "plan",+ TrayAction::Models => "models",+ }+ }+ pub(crate) fn from_id(id: &str) -> Option<TrayAction> {+ [TrayAction::Plan, TrayAction::Models].into_iter().find(|a| a.id() == id)+ }+}++#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]+pub(crate) struct TrayLine {+ pub text: String,+ #[serde(default)]+ pub dot: Option<TrayDot>,+}++#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]+pub(crate) struct TrayStatus {+ #[serde(default)]+ pub lines: Vec<TrayLine>,+ #[serde(default)]+ pub action: Option<TrayAction>,+}++/// One line as the menu shows it: no control characters (a newline would+/// break a native menu item), no padding, cut to `MAX_LINE_CHARS`.+pub(crate) fn clean_line(text: &str) -> String {+ let flat: String = text.chars().map(|c| if c.is_control() { ' ' } else { c }).collect();+ let flat = flat.split_whitespace().collect::<Vec<_>>().join(" ");+ if flat.chars().count() <= MAX_LINE_CHARS {+ return flat;+ }+ let mut cut: String = flat.chars().take(MAX_LINE_CHARS - 1).collect();+ cut.truncate(cut.trim_end().len());+ cut.push('…');+ cut+}++/// What the frontend sent, made safe to show: empty lines dropped, at most+/// `MAX_LINES`.+pub(crate) fn sanitize(status: TrayStatus) -> TrayStatus {+ let lines = status+ .lines+ .into_iter()+ .map(|l| TrayLine { text: clean_line(&l.text), dot: l.dot })+ .filter(|l| !l.text.is_empty())+ .take(MAX_LINES)+ .collect();+ TrayStatus { lines, action: status.action }+}++/// The rows of the menu, top to bottom.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) enum Row {+ Info(TrayLine),+ Separator,+ Action(TrayAction),+ Open,+ Quit,+}++pub(crate) fn layout(status: &TrayStatus) -> Vec<Row> {+ let mut rows: Vec<Row> = status.lines.iter().cloned().map(Row::Info).collect();+ if let Some(action) = status.action {+ if !rows.is_empty() {+ rows.push(Row::Separator);+ }+ rows.push(Row::Action(action));+ }+ if !rows.is_empty() {+ rows.push(Row::Separator);+ }+ rows.push(Row::Open);+ rows.push(Row::Quit);+ rows+}++/// Two statuses with the same shape differ only in texts and dots, which+/// change in place. Anything else needs a new menu.+pub(crate) fn same_shape(a: &TrayStatus, b: &TrayStatus) -> bool {+ a.lines.len() == b.lines.len() && a.action == b.action+}++#[cfg(desktop)]+fn memory_line(label: &'static str, used_gb: f64, total_gb: f64) -> TrayMemory {+ TrayMemory { label, used_gb: used_gb.clamp(0.0, total_gb), total_gb }+}++/// A filled circle as RGBA, the dot in front of a status line.+pub(crate) fn dot_rgba(dot: TrayDot, size: u32) -> Vec<u8> {+ let (r, g, b) = match dot {+ TrayDot::Green => (0x30, 0xd1, 0x58),+ TrayDot::Amber => (0xff, 0xb3, 0x40),+ TrayDot::Grey => (0x98, 0x98, 0x9d),+ };+ // The circle sits in the middle third of the square, about the size of+ // a text bullet; the rest stays clear so the icon column keeps its width.+ let c = (size as f32 - 1.0) / 2.0;+ let radius = size as f32 * 0.22;+ let mut out = Vec::with_capacity((size * size * 4) as usize);+ for y in 0..size {+ for x in 0..size {+ let d = ((x as f32 - c).powi(2) + (y as f32 - c).powi(2)).sqrt();+ // One pixel of soft edge.+ let a = (radius + 0.5 - d).clamp(0.0, 1.0);+ out.extend_from_slice(&[r, g, b, (a * 255.0) as u8]);+ }+ }+ out+}++#[cfg(desktop)]+pub(crate) use desktop::*;++#[cfg(desktop)]+mod desktop {+ use super::*;+ use std::sync::Mutex;+ use tauri::{+ image::Image,+ menu::{IconMenuItem, Menu, MenuItem, PredefinedMenuItem},+ AppHandle, Manager, Runtime,+ };++ const DOT_SIZE: u32 = 32;++ /// The live menu: its shape and the items whose text changes.+ pub(crate) struct TrayMenuState<R: Runtime> {+ inner: Mutex<Option<Live<R>>>,+ }++ struct Live<R: Runtime> {+ status: TrayStatus,+ infos: Vec<IconMenuItem<R>>,+ }++ impl<R: Runtime> Default for TrayMenuState<R> {+ fn default() -> Self {+ Self { inner: Mutex::new(None) }+ }+ }++ fn dot_image(dot: Option<TrayDot>) -> Option<Image<'static>> {+ dot.map(|d| Image::new_owned(dot_rgba(d, DOT_SIZE), DOT_SIZE, DOT_SIZE))+ }++ /// Build the menu for `status`. Returns the menu and the info items.+ pub(crate) fn build_menu<R: Runtime, M: Manager<R>>(+ app: &M,+ status: &TrayStatus,+ ) -> tauri::Result<(Menu<R>, Vec<IconMenuItem<R>>)> {+ let menu = Menu::new(app)?;+ let mut infos = Vec::new();+ for (i, row) in layout(status).into_iter().enumerate() {+ match row {+ Row::Info(line) => {+ let item = IconMenuItem::with_id(+ app,+ format!("{INFO_ID_PREFIX}{i}"),+ &line.text,+ false,+ dot_image(line.dot),+ None::<&str>,+ )?;+ menu.append(&item)?;+ infos.push(item);+ }+ Row::Separator => menu.append(&PredefinedMenuItem::separator(app)?)?,+ Row::Action(a) => menu.append(&MenuItem::with_id(app, a.id(), a.label(), true, None::<&str>)?)?,+ Row::Open => menu.append(&MenuItem::with_id(app, OPEN_ID, "Open LU", true, None::<&str>)?)?,+ Row::Quit => {+ // ⌘Q next to Quit, as in every Mac menu. On Windows and+ // Linux a tray menu has no shortcuts.+ #[cfg(target_os = "macos")]+ let accel = Some("CmdOrCtrl+Q");+ #[cfg(not(target_os = "macos"))]+ let accel = None::<&str>;+ menu.append(&MenuItem::with_id(app, QUIT_ID, "Quit LU", true, accel)?)?+ }+ }+ }+ Ok((menu, infos))+ }++ /// Show `status` in the tray menu. Same shape: texts and dots change in+ /// place. Otherwise a new menu is set. No tray (Linux without+ /// AppIndicator, GH #204): nothing happens.+ pub(crate) fn apply<R: Runtime>(app: &AppHandle<R>, status: TrayStatus) -> tauri::Result<()> {+ let Some(tray) = app.tray_by_id(TRAY_ID) else { return Ok(()) };+ let Some(state) = app.try_state::<TrayMenuState<R>>() else { return Ok(()) };+ let status = sanitize(status);+ let mut live = state.inner.lock().unwrap_or_else(|e| e.into_inner());+ if let Some(cur) = live.as_mut().filter(|cur| same_shape(&cur.status, &status)) {+ for (item, (old, new)) in cur.infos.iter().zip(cur.status.lines.iter().zip(&status.lines)) {+ if old.text != new.text {+ item.set_text(&new.text)?;+ }+ if old.dot != new.dot {+ item.set_icon(dot_image(new.dot))?;+ }+ }+ cur.status = status;+ return Ok(());+ }+ let (menu, infos) = build_menu(app, &status)?;+ tray.set_menu(Some(menu))?;+ *live = Some(Live { status, infos });+ Ok(())+ }++ /// Record the menu the tray was built with, so the first update can+ /// change it in place.+ pub(crate) fn remember<R: Runtime>(app: &AppHandle<R>, status: TrayStatus, infos: Vec<IconMenuItem<R>>) {+ if let Some(state) = app.try_state::<TrayMenuState<R>>() {+ *state.inner.lock().unwrap_or_else(|e| e.into_inner()) = Some(Live { status, infos });+ }+ }++ /// Memory in use for the menu's third line, measured where it can be:+ /// an NVIDIA card through nvidia-smi ("GPU memory"), a Mac's unified+ /// memory through sysinfo ("Memory": the model lives there). Elsewhere+ /// nothing measures the card, and the line is left out.+ #[derive(Debug, Clone, PartialEq, serde::Serialize)]+ #[serde(rename_all = "camelCase")]+ pub(crate) struct TrayMemory {+ pub label: &'static str,+ pub used_gb: f64,+ pub total_gb: f64,+ }++ #[tauri::command]+ pub(crate) async fn tray_memory() -> Option<TrayMemory> {+ tauri::async_runtime::spawn_blocking(measure_memory).await.ok().flatten()+ }++ fn measure_memory() -> Option<TrayMemory> {+ const GIB: f64 = 1024.0 * 1024.0 * 1024.0;+ if let Some((free, total)) = crate::commands::gpu::nvidia_memory_mib() {+ return Some(memory_line("GPU memory", (total - free) as f64 / 1024.0, total as f64 / 1024.0));+ }+ #[cfg(target_os = "macos")]+ {+ let mut sys = sysinfo::System::new();+ sys.refresh_memory();+ let total = sys.total_memory() as f64 / GIB;+ if total > 0.0 {+ return Some(memory_line("Memory", sys.used_memory() as f64 / GIB, total));+ }+ }+ let _ = GIB;+ None+ }++ /// The frontend's lines for the tray menu.+ #[tauri::command]+ pub(crate) fn tray_update(app: AppHandle, status: TrayStatus) -> Result<(), String> {+ apply(&app, status).map_err(|e| e.to_string())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn line(t: &str) -> TrayLine {+ TrayLine { text: t.into(), dot: None }+ }++ #[test]+ fn cloud_menu_matches_the_mock() {+ let s = TrayStatus {+ lines: vec![+ line("LU Cloud · Signed in"),+ TrayLine { text: "Pro plan · active".into(), dot: Some(TrayDot::Green) },+ line("1,240 credits left · renews Nov 14"),+ ],+ action: Some(TrayAction::Plan),+ };+ let rows = layout(&sanitize(s.clone()));+ assert_eq!(+ rows,+ vec![+ Row::Info(s.lines[0].clone()),+ Row::Info(s.lines[1].clone()),+ Row::Info(s.lines[2].clone()),+ Row::Separator,+ Row::Action(TrayAction::Plan),+ Row::Separator,+ Row::Open,+ Row::Quit,+ ]+ );+ }++ #[test]+ fn before_the_frontend_speaks_the_menu_is_open_and_quit() {+ assert_eq!(layout(&TrayStatus::default()), vec![Row::Open, Row::Quit]);+ }++ #[test]+ fn lines_without_an_action_still_get_one_separator() {+ let s = TrayStatus { lines: vec![line("Local · Ollama")], action: None };+ assert_eq!(layout(&s), vec![Row::Info(line("Local · Ollama")), Row::Separator, Row::Open, Row::Quit]);+ }++ #[test]+ fn at_most_three_lines_and_no_empty_ones() {+ let s = TrayStatus {+ lines: vec![line("a"), line(" "), line("b"), line("c"), line("d")],+ action: None,+ };+ let texts: Vec<_> = sanitize(s).lines.into_iter().map(|l| l.text).collect();+ assert_eq!(texts, ["a", "b", "c"]);+ }++ #[test]+ fn a_newline_or_tab_cannot_break_the_menu_item() {+ assert_eq!(clean_line("Qwen3\n8B\t· ready\r"), "Qwen3 8B · ready");+ }++ #[test]+ fn a_long_model_name_is_cut_with_an_ellipsis() {+ let long = "Llama-3.3-70B-Instruct-abliterated-Q4_K_M-imatrix-final.gguf · ready";+ let cut = clean_line(long);+ assert_eq!(cut.chars().count(), MAX_LINE_CHARS);+ assert!(cut.ends_with('…'));+ assert!(long.starts_with(cut.trim_end_matches('…')));+ }++ #[test]+ fn the_action_comes_from_a_fixed_list() {+ // Labels and ids live here; the page only names one of two actions.+ assert!(serde_json::from_str::<TrayStatus>(r#"{"action":"delete-everything"}"#).is_err());+ let s: TrayStatus = serde_json::from_str(r#"{"lines":[{"text":"x","dot":"green"}],"action":"models"}"#).unwrap();+ assert_eq!(s.action, Some(TrayAction::Models));+ assert_eq!(TrayAction::from_id("tray-models"), Some(TrayAction::Models));+ assert_eq!(TrayAction::from_id("open"), None);+ assert_eq!(TrayAction::Plan.label(), "Plan & Credits…");+ }++ #[test]+ fn texts_and_dots_change_in_place_but_a_new_line_count_rebuilds() {+ let a = TrayStatus { lines: vec![line("x"), line("y")], action: Some(TrayAction::Models) };+ let mut b = a.clone();+ b.lines[1] = TrayLine { text: "z".into(), dot: Some(TrayDot::Amber) };+ assert!(same_shape(&a, &b));+ b.lines.push(line("w"));+ assert!(!same_shape(&a, &b));+ let c = TrayStatus { action: Some(TrayAction::Plan), ..a.clone() };+ assert!(!same_shape(&a, &c));+ }++ #[test]+ fn the_dot_is_a_round_spot_in_a_clear_square() {+ let px = dot_rgba(TrayDot::Green, 32);+ assert_eq!(px.len(), 32 * 32 * 4);+ let alpha = |x: usize, y: usize| px[(y * 32 + x) * 4 + 3];+ assert_eq!(alpha(16, 16), 255, "the middle is solid");+ assert_eq!(alpha(0, 0), 0, "the corner is clear");+ assert_eq!(alpha(16, 2), 0, "the circle does not touch the edge");+ }++ #[test]+ fn the_tray_is_built_with_the_id_and_the_menu_from_here() {+ let lib = include_str!("lib.rs");+ assert!(lib.contains("TrayIconBuilder::with_id(tray_menu::TRAY_ID)"));+ assert!(lib.contains("tray_menu::tray_update"), "tray_update is not in generate_handler!");+ assert!(!lib.contains("\"Show\""), "the old Show item is gone");+ }+}diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsxindex 82088cee..73548758 100644--- a/src/components/layout/AppShell.tsx+++ b/src/components/layout/AppShell.tsx@@ -53,6 +53,7 @@ import type { TextChunk } from '../../types/rag'import type { Role } from '../../types/chat'import { useKeyboardShortcuts } from '../../hooks/useKeyboardShortcuts'import { useCloudAuth } from '../../hooks/useCloudAuth'+import { useTraySync } from '../../hooks/useTraySync'import { useCloudOutageWatch } from '../../hooks/useCloudOutageWatch'import { useCloudAuthStore, deriveCloudAvailable } from '../../stores/cloudAuthStore'import { useCreateStore } from '../../stores/createStore'@@ -179,6 +180,8 @@ export function AppShell() {// LU Cloud account boot: keychain session restore + /api/me probe; keeps// the cloud Create axis and the lu-cloud chat provider in sync.useCloudAuth()+ // T2: the tray menu's lines (account or engine, model, memory).+ useTraySync()useCloudOutageWatch()useNeuronFollowsPersona()diff --git a/src/hooks/__tests__/tray-sync.test.ts b/src/hooks/__tests__/tray-sync.test.tsnew file mode 100644index 00000000..01cb890e--- /dev/null+++ b/src/hooks/__tests__/tray-sync.test.ts@@ -0,0 +1,129 @@+/**+ * @vitest-environment jsdom+ *+ * T2 (3.0.9): what the tray menu is told, taken from the real stores, and+ * what a click on its action does.+ *+ * Run: npx vitest run src/hooks/__tests__/tray-sync.test.ts+ */+import { beforeEach, describe, expect, it, vi } from 'vitest'++const calls: Array<{ cmd: string; args?: Record<string, unknown> }> = []+let engineStatus: Record<string, unknown> = {}+let ollamaLoaded: Array<{ name: string }> | Error = []++vi.mock('../../api/backend', async (orig) => ({+ ...(await orig<typeof import('../../api/backend')>()),+ backendCall: vi.fn(async (cmd: string, args?: Record<string, unknown>) => {+ calls.push({ cmd, args })+ if (cmd === 'bundled_engine_status') return engineStatus+ return null+ }),+}))+vi.mock('../../api/ollama', async (orig) => ({+ ...(await orig<typeof import('../../api/ollama')>()),+ readLoadedModels: vi.fn(async () => {+ if (ollamaLoaded instanceof Error) throw ollamaLoaded+ return ollamaLoaded+ }),+}))++import { currentTrayStatus, openTrayAction, probeModelState, trayEngineName } from '../useTraySync'+import { useCloudAuthStore } from '../../stores/cloudAuthStore'+import { useModelStore } from '../../stores/modelStore'+import { useSettingsStore } from '../../stores/settingsStore'+import { useUIStore } from '../../stores/uiStore'+import type { AIModel } from '../../types/models'++const engineRow = { name: 'openai::Qwen3-8B-Q4_K_M', provider: 'openai', providerName: 'LU Engine', displayName: 'Qwen3 8B' } as unknown as AIModel+const ollamaRow = { name: 'llama3.2:3b', provider: 'ollama', providerName: 'Ollama' } as unknown as AIModel++function setMode(appMode: 'local' | 'cloud') {+ useSettingsStore.setState((s) => ({ settings: { ...s.settings, appMode } }))+}++beforeEach(() => {+ calls.length = 0+ engineStatus = {}+ ollamaLoaded = []+ setMode('local')+ useModelStore.setState({ models: [engineRow, ollamaRow], activeModel: engineRow.name })+ useCloudAuthStore.getState().setSignedOut()+})++describe('tray sync (T2)', () => {+ it('names the engine that serves the selected model', () => {+ expect(trayEngineName(engineRow.name)).toBe('LU Engine')+ expect(trayEngineName(ollamaRow.name)).toBe('Ollama')+ expect(trayEngineName('unlisted-ollama-model')).toBe('Ollama')+ })++ it('LU Engine: ready only when it holds this model and answers', async () => {+ engineStatus = { running: true, healthy: true, model_path: '/m/Qwen3-8B-Q4_K_M.gguf' }+ expect(await probeModelState(engineRow.name)).toBe('ready')+ engineStatus = { running: true, healthy: false, model_path: '/m/Qwen3-8B-Q4_K_M.gguf' }+ expect(await probeModelState(engineRow.name)).toBe('loading')+ engineStatus = { running: true, healthy: true, model_path: '/m/Other.gguf' }+ expect(await probeModelState(engineRow.name)).toBe('idle')+ engineStatus = { running: false }+ expect(await probeModelState(engineRow.name)).toBe('idle')+ })++ it('Ollama: loaded, not loaded, not answering', async () => {+ ollamaLoaded = [{ name: 'llama3.2:3b' }]+ expect(await probeModelState(ollamaRow.name)).toBe('ready')+ ollamaLoaded = []+ expect(await probeModelState(ollamaRow.name)).toBe('idle')+ ollamaLoaded = new Error('connection refused')+ expect(await probeModelState(ollamaRow.name)).toBe('engine-off')+ })++ it('local mode shows the engine and the display name, with Models as the action', () => {+ const s = currentTrayStatus()+ expect(s.action).toBe('models')+ expect(s.lines[0].text).toBe('Local · LU Engine')+ expect(s.lines[1].text).toBe('Qwen3 8B')+ })++ it('a cloud model kept from the Cloud mode is not shown as the local model', () => {+ useModelStore.setState({ activeModel: 'lu-cloud::moonshotai/Kimi-K2.6' })+ expect(currentTrayStatus().lines.map((l) => l.text)).toEqual(['Local', 'No model selected'])+ })++ it('cloud mode: "Signed in", plan, credits incl. bought ones, never the e-mail', () => {+ setMode('cloud')+ useCloudAuthStore.getState().setSignedIn(+ { id: 'u1', email: '[email protected]' },+ {+ licenseActive: true,+ tier: 'hosted-pro',+ access: true,+ quota: {+ tier: 'hosted-pro',+ period: '2026-10',+ limits: { credits: 2000 },+ costs: { image: 1, video: 10 },+ used: { credits_used: 1060 },+ remaining: { credits: 940 },+ topup: { credits: 300 },+ },+ },+ )+ const s = currentTrayStatus()+ expect(s.action).toBe('plan')+ expect(s.lines.map((l) => l.text)).toEqual(['LU Cloud · Signed in', 'Hosted Pro plan · active', '1,240 credits left'])+ expect(JSON.stringify(s)).not.toContain('@')+ })++ it('the menu action opens Models or the account in Settings, anything else nothing', () => {+ useUIStore.getState().setView('chat')+ openTrayAction('models')+ expect(useUIStore.getState().currentView).toBe('models')+ openTrayAction('plan')+ expect(useUIStore.getState().currentView).toBe('settings')+ expect(useUIStore.getState().settingsFocus).toEqual({ tab: 'general' })+ useUIStore.getState().setView('chat')+ openTrayAction('delete')+ expect(useUIStore.getState().currentView).toBe('chat')+ })+})diff --git a/src/hooks/useTraySync.ts b/src/hooks/useTraySync.tsnew file mode 100644index 00000000..abc9d7e3--- /dev/null+++ b/src/hooks/useTraySync.ts@@ -0,0 +1,175 @@+// Keeps the tray menu's grey lines current (T2, 3.0.9; lines: lib/tray-menu).+//+// Sent on every change of mode, account or selected model, and again when the+// tray icon is clicked or hovered (`lu-tray-opened`): then the engine, Ollama+// and the memory are asked fresh, and the account at most once a minute. A+// menu that is already open on a Mac takes the new texts in place.+// `lu-tray-action` is the click on "Plan & Credits…" or "Models…"; the window+// is already in front by then (tray_menu.rs).++import { useEffect } from 'react'+import { isTauri } from '../api/in-tauri'+import { backendCall } from '../api/backend'+import type { EngineStatus } from '../api/engine'+import { readLoadedModels } from '../api/ollama'+import { displayModelName, getProviderIdFromModel } from '../api/providers/model-name'+import { isMobile } from '../lib/device-kind'+import { builtinModelMatches, builtinModelNameFromPath } from '../lib/builtin-model-identity'+import { isBuiltinEngineEntry } from '../lib/lmstudio-match'+import { LU_ENGINE_NAME } from '../lib/engine-name'+import { modelDisplayLabel } from '../lib/model-label'+import {+ cloudTrayStatus,+ localTrayStatus,+ type TrayLocalInput,+ type TrayModelState,+ type TrayStatus,+} from '../lib/tray-menu'+import { useCloudAuthStore } from '../stores/cloudAuthStore'+import { useModelStore } from '../stores/modelStore'+import { useSettingsStore } from '../stores/settingsStore'+import { useUIStore } from '../stores/uiStore'+import { probeAccount } from './useCloudAuth'++const OPENED_EVENT = 'lu-tray-opened'+const ACTION_EVENT = 'lu-tray-action'+/** Hovering the icon on the way to somewhere else must not hammer anything. */+const LOCAL_REFRESH_MS = 3_000+const ACCOUNT_REFRESH_MS = 60_000++type Memory = TrayLocalInput['memory']+interface LocalProbe {+ model: string+ state: TrayModelState+}++/** What was last measured; the lines are rebuilt from it on every change. */+const probe: { local: LocalProbe | null; memory: Memory } = { local: null, memory: null }++export function trayEngineName(activeModel: string): string {+ const row = useModelStore.getState().models.find((m) => m.name === activeModel)+ if (row && isBuiltinEngineEntry(row)) return LU_ENGINE_NAME+ if (row?.providerName) return row.providerName+ return getProviderIdFromModel(activeModel) === 'ollama' ? 'Ollama' : 'Local'+}++export function currentTrayStatus(): TrayStatus {+ const { appMode } = useSettingsStore.getState().settings+ if (appMode === 'cloud') {+ const a = useCloudAuthStore.getState()+ const q = a.quota+ return cloudTrayStatus({+ signedIn: a.status === 'signed-in',+ probing: a.status === 'probing',+ tier: a.tier ?? q?.tier ?? null,+ licenseActive: a.licenseActive,+ pastDue: a.pastDue,+ credits: q ? q.remaining.credits + (q.topup?.credits ?? 0) : null,+ })+ }+ const { models, activeModel } = useModelStore.getState()+ // A cloud model kept from the Cloud mode is not a local model.+ const local = activeModel && getProviderIdFromModel(activeModel) !== 'lu-cloud' ? activeModel : null+ const measured = local && probe.local?.model === local ? probe.local.state : 'unknown'+ return localTrayStatus({+ engine: local ? trayEngineName(local) : null,+ model: local ? modelDisplayLabel(models, local) : null,+ state: measured,+ memory: probe.memory,+ })+}++/** Ask the engine that serves `model` how far it is. */+export async function probeModelState(model: string): Promise<TrayModelState> {+ const engine = trayEngineName(model)+ if (engine === LU_ENGINE_NAME) {+ const s = await backendCall<EngineStatus>('bundled_engine_status').catch(() => null)+ if (!s?.running) return 'idle'+ if (!builtinModelNameFromPath(s.model_path) || !builtinModelMatches(s.model_path, model)) return 'idle'+ return s.healthy ? 'ready' : 'loading'+ }+ if (engine === 'Ollama') {+ try {+ const loaded = await readLoadedModels()+ const want = displayModelName(model)+ return loaded.some((m) => m.name === want || m.name === `${want}:latest`) ? 'ready' : 'idle'+ } catch {+ return 'engine-off'+ }+ }+ return 'unknown'+}++let lastSent = ''+async function push(): Promise<void> {+ const status = currentTrayStatus()+ const key = JSON.stringify(status)+ if (key === lastSent) return+ lastSent = key+ await backendCall('tray_update', { status }).catch(() => {+ // No tray (Linux without AppIndicator) answers Ok; an error here is an+ // older backend. Send again next time.+ lastSent = ''+ })+}++let lastLocal = 0+let lastAccount = 0+async function refresh(): Promise<void> {+ const now = Date.now()+ const { appMode } = useSettingsStore.getState().settings+ if (appMode === 'cloud') {+ if (now - lastAccount >= ACCOUNT_REFRESH_MS && useCloudAuthStore.getState().status === 'signed-in') {+ lastAccount = now+ // probeAccount writes the store; the subscription below pushes.+ void probeAccount().catch(() => {})+ }+ return+ }+ if (now - lastLocal < LOCAL_REFRESH_MS) return+ lastLocal = now+ const model = useModelStore.getState().activeModel+ const [state, memory] = await Promise.all([+ model ? probeModelState(model) : Promise.resolve<TrayModelState>('unknown'),+ backendCall<Memory>('tray_memory').catch(() => null),+ ])+ probe.local = model ? { model, state } : null+ probe.memory = memory ?? null+ await push()+}++export function openTrayAction(action: unknown): void {+ const ui = useUIStore.getState()+ if (action === 'models') ui.setView('models')+ // The account and its plan live in Settings → General (AccountPanel).+ else if (action === 'plan') ui.openSettingsAt({ tab: 'general' })+}++export function useTraySync(): void {+ useEffect(() => {+ if (!isTauri() || isMobile()) return+ let alive = true+ const offs: Array<() => void> = []+ const sync = () => { void push() }+ offs.push(useSettingsStore.subscribe(sync))+ offs.push(useCloudAuthStore.subscribe(sync))+ offs.push(useModelStore.subscribe((s, prev) => {+ if (s.activeModel === prev.activeModel && s.models === prev.models) return+ // A new model: measure it rather than show the old one's state.+ if (s.activeModel !== prev.activeModel) lastLocal = 0+ sync()+ if (s.activeModel !== prev.activeModel) void refresh()+ }))+ void refresh().then(sync)+ void import('@tauri-apps/api/event').then(async ({ listen }) => {+ const offOpened = await listen(OPENED_EVENT, () => { void refresh() })+ const offAction = await listen(ACTION_EVENT, (e) => openTrayAction(e.payload))+ if (alive) offs.push(offOpened, offAction)+ else { offOpened(); offAction() }+ }).catch(() => {})+ return () => {+ alive = false+ offs.forEach((off) => off())+ }+ }, [])+}diff --git a/src/lib/__tests__/tray-menu.test.ts b/src/lib/__tests__/tray-menu.test.tsnew file mode 100644index 00000000..0227f07e--- /dev/null+++ b/src/lib/__tests__/tray-menu.test.ts@@ -0,0 +1,72 @@+import { describe, expect, it } from 'vitest'+import { cloudTrayStatus, localTrayStatus, planName } from '../tray-menu'++const signedIn = {+ signedIn: true,+ probing: false,+ tier: 'hosted-pro',+ licenseActive: true,+ pastDue: false,+ credits: 1240,+}++describe('tray menu lines (T2)', () => {+ it('cloud: signed in, plan, credits, then Plan & Credits — no e-mail', () => {+ expect(cloudTrayStatus(signedIn)).toEqual({+ lines: [+ { text: 'LU Cloud · Signed in' },+ { text: 'Hosted Pro plan · active', dot: 'green' },+ { text: '1,240 credits left' },+ ],+ action: 'plan',+ })+ })++ it('cloud: a failed payment is amber, no plan is grey', () => {+ expect(cloudTrayStatus({ ...signedIn, pastDue: true }).lines[1]).toEqual({ text: 'Hosted Pro plan · payment failed', dot: 'amber' })+ expect(cloudTrayStatus({ ...signedIn, licenseActive: false }).lines[1]).toEqual({ text: 'No active plan', dot: 'grey' })+ })++ it('cloud: signed out and still asking say so in one line', () => {+ expect(cloudTrayStatus({ ...signedIn, signedIn: false }).lines).toEqual([{ text: 'LU Cloud · Signed out' }])+ expect(cloudTrayStatus({ ...signedIn, probing: true }).lines).toEqual([{ text: 'LU Cloud · Connecting…' }])+ })++ it('cloud: unknown credits leave the line out, never a 0', () => {+ expect(cloudTrayStatus({ ...signedIn, credits: null }).lines).toHaveLength(2)+ expect(cloudTrayStatus({ ...signedIn, credits: -3.5 }).lines[2].text).toBe('0 credits left')+ })++ it('a tier without a known name still reads like one', () => {+ expect(planName('hosted-max')).toBe('Hosted Max')+ expect(planName('self-host')).toBe('Self Host')+ })++ it('local: engine, model with its state, memory, then Models', () => {+ expect(+ localTrayStatus({ engine: 'LU Engine', model: 'Qwen3 8B', state: 'ready', memory: { label: 'Memory', usedGb: 9.24, totalGb: 24 } }),+ ).toEqual({+ lines: [+ { text: 'Local · LU Engine' },+ { text: 'Qwen3 8B · ready', dot: 'green' },+ { text: 'Memory 9.2 of 24 GB' },+ ],+ action: 'models',+ })+ })++ it('local: the same three-line build as the cloud menu', () => {+ const local = localTrayStatus({ engine: 'Ollama', model: 'llama3', state: 'idle', memory: { label: 'GPU memory', usedGb: 1, totalGb: 12 } })+ expect(local.lines).toHaveLength(cloudTrayStatus(signedIn).lines.length)+ expect(local.lines[1]).toEqual({ text: 'llama3 · loads on first chat', dot: 'grey' })+ })++ it('local: no model, a stopped Ollama, a server LU does not ask', () => {+ expect(localTrayStatus({ engine: null, model: null, state: 'unknown', memory: null }).lines).toEqual([+ { text: 'Local' },+ { text: 'No model selected', dot: 'grey' },+ ])+ expect(localTrayStatus({ engine: 'Ollama', model: 'm', state: 'engine-off', memory: null }).lines[1]).toEqual({ text: 'm · not running', dot: 'amber' })+ expect(localTrayStatus({ engine: 'LM Studio', model: 'm', state: 'unknown', memory: null }).lines[1]).toEqual({ text: 'm' })+ })+})diff --git a/src/lib/tray-menu.ts b/src/lib/tray-menu.tsnew file mode 100644index 00000000..d3a19f08--- /dev/null+++ b/src/lib/tray-menu.ts@@ -0,0 +1,91 @@+// The grey lines of the tray menu (T2, 3.0.9). The Rust side+// (src-tauri/src/tray_menu.rs) only lays them out; what they say is decided+// here, where the account, the engine and the model are known.+//+// Both states have the same build, as David asked for after the mocks:+//+// LU Cloud · Signed in Local · LU Engine+// ● Hosted Pro plan · active ● Qwen3 8B · ready+// 1,240 credits left Memory 9.2 of 24 GB+// Plan & Credits… Models…+//+// No e-mail address in the menu (David, 31.10.), only "Signed in".++import { PLAN_NAMES } from './past-due'++export type TrayDot = 'green' | 'amber' | 'grey'+export interface TrayLine {+ text: string+ dot?: TrayDot+}+export interface TrayStatus {+ lines: TrayLine[]+ action: 'plan' | 'models' | null+}++export interface TrayCloudInput {+ signedIn: boolean+ /** Still asking the server: say nothing about the plan yet. */+ probing: boolean+ tier: string | null+ licenseActive: boolean+ pastDue: boolean+ /** Monthly allowance left plus bought credits, null when unknown. */+ credits: number | null+}++export function planName(tier: string): string {+ return PLAN_NAMES[tier] ?? tier.split('-').map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(' ')+}++export function cloudTrayStatus(c: TrayCloudInput): TrayStatus {+ if (c.probing) return { lines: [{ text: 'LU Cloud · Connecting…' }], action: 'plan' }+ if (!c.signedIn) return { lines: [{ text: 'LU Cloud · Signed out' }], action: 'plan' }+ const lines: TrayLine[] = [{ text: 'LU Cloud · Signed in' }]+ if (c.pastDue) {+ lines.push({ text: `${c.tier ? `${planName(c.tier)} plan` : 'Plan'} · payment failed`, dot: 'amber' })+ } else if (c.licenseActive && c.tier) {+ lines.push({ text: `${planName(c.tier)} plan · active`, dot: 'green' })+ } else {+ lines.push({ text: 'No active plan', dot: 'grey' })+ }+ if (c.credits !== null) {+ lines.push({ text: `${Math.max(0, Math.floor(c.credits)).toLocaleString('en-US')} credits left` })+ }+ return { lines, action: 'plan' }+}++/** How far the selected model is, as the menu says it. */+export type TrayModelState = 'ready' | 'loading' | 'idle' | 'engine-off' | 'unknown'++export interface TrayLocalInput {+ /** "LU Engine", "Ollama", "LM Studio", … null when no model is selected. */+ engine: string | null+ model: string | null+ state: TrayModelState+ memory: { label: string; usedGb: number; totalGb: number } | null+}++const STATE_WORDS: Record<TrayModelState, { word: string; dot: TrayDot } | null> = {+ ready: { word: 'ready', dot: 'green' },+ loading: { word: 'loading', dot: 'amber' },+ // Not in memory yet; the first message loads it. Normal, so not amber.+ idle: { word: 'loads on first chat', dot: 'grey' },+ 'engine-off': { word: 'not running', dot: 'amber' },+ // A server LU does not ask (LM Studio, vLLM, …): the name alone.+ unknown: null,+}++export function localTrayStatus(l: TrayLocalInput): TrayStatus {+ const lines: TrayLine[] = [{ text: l.engine ? `Local · ${l.engine}` : 'Local' }]+ if (!l.model) {+ lines.push({ text: 'No model selected', dot: 'grey' })+ } else {+ const s = STATE_WORDS[l.state]+ lines.push(s ? { text: `${l.model} · ${s.word}`, dot: s.dot } : { text: l.model })+ }+ if (l.memory && l.memory.totalGb > 0) {+ lines.push({ text: `${l.memory.label} ${l.memory.usedGb.toFixed(1)} of ${Math.round(l.memory.totalGb)} GB` })+ }+ return { lines, action: 'models' }+}