diff --git a/Cargo.lock b/Cargo.lock index 99cd7cf2e..4d3ae0f14 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -13347,7 +13347,7 @@ dependencies = [ [[package]] name = "zatex" -version = "0.3.5" +version = "0.3.7" dependencies = [ "tiny-skia", "ttf-parser", @@ -13598,7 +13598,7 @@ dependencies = [ [[package]] name = "zeron" -version = "0.3.5" +version = "0.3.7" dependencies = [ "anyhow", "clap", @@ -13623,7 +13623,7 @@ dependencies = [ [[package]] name = "zeron-audio" -version = "0.3.5" +version = "0.3.7" dependencies = [ "base64 0.22.1", "cpal 0.18.2", @@ -13635,7 +13635,7 @@ dependencies = [ [[package]] name = "zeron-cli" -version = "0.3.5" +version = "0.3.7" dependencies = [ "anyhow", "clap", @@ -13651,7 +13651,7 @@ dependencies = [ [[package]] name = "zeron-client" -version = "0.3.5" +version = "0.3.7" dependencies = [ "anyhow", "async-trait", @@ -13682,7 +13682,7 @@ dependencies = [ [[package]] name = "zeron-doc" -version = "0.3.5" +version = "0.3.7" dependencies = [ "chrono", "loro", @@ -13697,7 +13697,7 @@ dependencies = [ [[package]] name = "zeron-engine" -version = "0.3.5" +version = "0.3.7" dependencies = [ "alacritty_terminal", "anyhow", @@ -13757,7 +13757,7 @@ dependencies = [ [[package]] name = "zeron-harness" -version = "0.3.5" +version = "0.3.7" dependencies = [ "anyhow", "async-trait", @@ -13791,7 +13791,7 @@ dependencies = [ [[package]] name = "zeron-launch" -version = "0.3.5" +version = "0.3.7" dependencies = [ "libc", "tempfile", @@ -13800,14 +13800,14 @@ dependencies = [ [[package]] name = "zeron-markdown" -version = "0.3.5" +version = "0.3.7" dependencies = [ "pulldown-cmark", ] [[package]] name = "zeron-mcp" -version = "0.3.5" +version = "0.3.7" dependencies = [ "anyhow", "async-trait", @@ -13829,7 +13829,7 @@ dependencies = [ [[package]] name = "zeron-mobile" -version = "0.3.5" +version = "0.3.7" dependencies = [ "async-trait", "serde", @@ -13856,14 +13856,14 @@ dependencies = [ [[package]] name = "zeron-mobile-bindgen" -version = "0.3.5" +version = "0.3.7" dependencies = [ "uniffi", ] [[package]] name = "zeron-notify" -version = "0.3.5" +version = "0.3.7" dependencies = [ "objc", "sha2", @@ -13872,11 +13872,11 @@ dependencies = [ [[package]] name = "zeron-orb" -version = "0.3.5" +version = "0.3.7" [[package]] name = "zeron-plugin-guard" -version = "0.3.5" +version = "0.3.7" dependencies = [ "serde_json", "tempfile", @@ -13884,7 +13884,7 @@ dependencies = [ [[package]] name = "zeron-preview" -version = "0.3.5" +version = "0.3.7" dependencies = [ "anyhow", "async-trait", @@ -13914,11 +13914,11 @@ dependencies = [ [[package]] name = "zeron-preview-label" -version = "0.3.5" +version = "0.3.7" [[package]] name = "zeron-proto" -version = "0.3.5" +version = "0.3.7" dependencies = [ "chrono", "pulldown-cmark", @@ -13929,7 +13929,7 @@ dependencies = [ [[package]] name = "zeron-rpc" -version = "0.3.5" +version = "0.3.7" dependencies = [ "anyhow", "async-trait", @@ -13950,7 +13950,7 @@ dependencies = [ [[package]] name = "zeron-sync" -version = "0.3.5" +version = "0.3.7" dependencies = [ "base64 0.22.1", "block2 0.6.2", @@ -13976,7 +13976,7 @@ dependencies = [ [[package]] name = "zeron-syntax" -version = "0.3.5" +version = "0.3.7" dependencies = [ "thiserror 2.0.20", "tree-sitter", @@ -14011,14 +14011,14 @@ dependencies = [ [[package]] name = "zeron-term" -version = "0.3.5" +version = "0.3.7" dependencies = [ "alacritty_terminal", ] [[package]] name = "zeron-term-link" -version = "0.3.5" +version = "0.3.7" dependencies = [ "anyhow", "async-trait", @@ -14035,7 +14035,7 @@ dependencies = [ [[package]] name = "zeron-text" -version = "0.3.5" +version = "0.3.7" dependencies = [ "core-foundation 0.10.1", "core-graphics 0.24.0", @@ -14052,7 +14052,7 @@ dependencies = [ [[package]] name = "zeron-theme" -version = "0.3.5" +version = "0.3.7" dependencies = [ "anyhow", "clap", @@ -14067,7 +14067,7 @@ dependencies = [ [[package]] name = "zeron-ui" -version = "0.3.5" +version = "0.3.7" dependencies = [ "alacritty_terminal", "anyhow", @@ -14150,7 +14150,7 @@ dependencies = [ [[package]] name = "zeron-update" -version = "0.3.5" +version = "0.3.7" dependencies = [ "anyhow", "futures", @@ -14167,11 +14167,11 @@ dependencies = [ [[package]] name = "zeron-veil" -version = "0.3.5" +version = "0.3.7" [[package]] name = "zeron-visual" -version = "0.3.5" +version = "0.3.7" dependencies = [ "base64 0.22.1", "gltf", @@ -14183,7 +14183,7 @@ dependencies = [ [[package]] name = "zeron-visual-gpu" -version = "0.3.5" +version = "0.3.7" dependencies = [ "image", "pollster 0.4.0", @@ -14194,7 +14194,7 @@ dependencies = [ [[package]] name = "zeron-voice" -version = "0.3.5" +version = "0.3.7" dependencies = [ "anyhow", "cpal 0.17.3", @@ -14213,7 +14213,7 @@ dependencies = [ [[package]] name = "zeron-voice-media" -version = "0.3.5" +version = "0.3.7" dependencies = [ "async-trait", "semver", @@ -14228,7 +14228,7 @@ dependencies = [ [[package]] name = "zeron-voice-session" -version = "0.3.5" +version = "0.3.7" dependencies = [ "async-trait", "futures", diff --git a/Cargo.toml b/Cargo.toml index 2b3cdd9bb..7865ac29a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,7 +38,7 @@ members = [ ] [workspace.package] -version = "0.3.5" +version = "0.3.7" edition = "2024" license = "MIT" publish = false diff --git a/apps/zgx/Cargo.lock b/apps/zgx/Cargo.lock index 437ed1ee8..d096e16e9 100644 --- a/apps/zgx/Cargo.lock +++ b/apps/zgx/Cargo.lock @@ -7067,7 +7067,7 @@ dependencies = [ [[package]] name = "zatex" -version = "0.3.5" +version = "0.3.7" dependencies = [ "ttf-parser", ] @@ -7233,7 +7233,7 @@ checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" [[package]] name = "zeron-cli" -version = "0.3.5" +version = "0.3.7" dependencies = [ "anyhow", "clap", @@ -7248,7 +7248,7 @@ dependencies = [ [[package]] name = "zeron-launch" -version = "0.3.5" +version = "0.3.7" dependencies = [ "libc", "windows-sys 0.61.2", @@ -7256,7 +7256,7 @@ dependencies = [ [[package]] name = "zeron-notify" -version = "0.3.5" +version = "0.3.7" dependencies = [ "objc", "sha2", @@ -7265,18 +7265,18 @@ dependencies = [ [[package]] name = "zeron-plugin-guard" -version = "0.3.5" +version = "0.3.7" dependencies = [ "serde_json", ] [[package]] name = "zeron-preview-label" -version = "0.3.5" +version = "0.3.7" [[package]] name = "zeron-proto" -version = "0.3.5" +version = "0.3.7" dependencies = [ "chrono", "pulldown-cmark 0.12.2", @@ -7287,7 +7287,7 @@ dependencies = [ [[package]] name = "zeron-theme" -version = "0.3.5" +version = "0.3.7" dependencies = [ "anyhow", "clap", @@ -7301,7 +7301,7 @@ dependencies = [ [[package]] name = "zeron-update" -version = "0.3.5" +version = "0.3.7" dependencies = [ "anyhow", "futures", @@ -7318,7 +7318,7 @@ dependencies = [ [[package]] name = "zeron-visual" -version = "0.3.5" +version = "0.3.7" dependencies = [ "base64 0.22.1", "gltf", @@ -7330,7 +7330,7 @@ dependencies = [ [[package]] name = "zeron-visual-gpu" -version = "0.3.5" +version = "0.3.7" dependencies = [ "pollster", "tracing", @@ -7340,7 +7340,7 @@ dependencies = [ [[package]] name = "zeron-voice" -version = "0.3.5" +version = "0.3.7" dependencies = [ "anyhow", "cpal", diff --git a/apps/zgx/src/agents.rs b/apps/zgx/src/agents.rs index af62053ae..00506865c 100644 --- a/apps/zgx/src/agents.rs +++ b/apps/zgx/src/agents.rs @@ -411,6 +411,24 @@ pub fn install(host: &ScriptHost) { a.add_key(id, provider, key, name).await } }); + // An API key for Cloud's agents (Settings → Providers with Cloud + // shown): kept by the vault, authorized for the account's Cloud device + // (`device`), the key every Cloud machine uses from its next turn. + // Rejects with the engine's words, which never hold the key. + let a = agents.clone(); + host.async_action("agents.cloud_key", move |args| { + let a = a.clone(); + let provider = args.field("provider").map(text).unwrap_or_default(); + let key = args.field("key").map(text).unwrap_or_default().trim().to_string(); + let device = args.field("device").map(text).unwrap_or_default(); + async move { + crate::plugins::preview::refuse("agents.cloud_key")?; + let params = cloud_key_params(&provider, &key, &device)?; + engine::get().call("VaultPutApiKey", params).await.map_err(|error| engine::outcome(&error).to_string())?; + a.load_accounts(true).await; + Ok(Value::Nil) + } + }); // An API key's name (no secret: on whichever device shows it), rejecting // with the engine's words. let a = agents.clone(); @@ -1948,6 +1966,20 @@ fn epoch_secs(s: &str) -> Option { mod tests { use super::*; + /// A Cloud API key goes to the vault for the account's Cloud device: + /// Anthropic's or OpenAI's only, a real key, Cloud on. + #[test] + fn a_cloud_key_is_one_cloud_runs_for_its_device() { + let ok = cloud_key_params("anthropic-key", "sk-ant-123", "cloud-acct").unwrap(); + assert_eq!(ok, json!({ "provider": "anthropic-key", "key": "sk-ant-123", "authorizedDevices": ["cloud-acct"] })); + assert!(cloud_key_params("openai-key", "sk-1", "d").is_ok()); + assert!(cloud_key_params("claude", "sk", "d").is_err(), "a login isn't a key"); + assert!(cloud_key_params("anthropic-key", "", "d").is_err()); + assert!(cloud_key_params("anthropic-key", "a\nb", "d").is_err()); + assert!(cloud_key_params("anthropic-key", &"k".repeat(5000), "d").is_err()); + assert!(cloud_key_params("anthropic-key", "sk", "").is_err(), "Cloud off"); + } + /// Pi signed in to Claude, or another login put in use: Pi's models are /// looked up again. Usage moving, or another agent's, isn't Pi's change. #[test] @@ -2228,6 +2260,22 @@ pub(crate) fn shown_target() -> Option { } /// `params` addressed to the device Providers shows. +/// `VaultPutApiKey`'s params for a Cloud API key: Anthropic's or OpenAI's +/// alone, a key that's there and no longer than any key is, for the +/// account's Cloud device. Else why not. +pub(crate) fn cloud_key_params(provider: &str, key: &str, device: &str) -> Result { + if !matches!(provider, "anthropic-key" | "openai-key") { + return Err("Cloud takes Anthropic and OpenAI keys".into()); + } + if key.is_empty() || key.len() > 4096 || key.chars().any(char::is_control) { + return Err("That isn't an API key".into()); + } + if device.is_empty() { + return Err("Turn Cloud on in Settings → Cloud first".into()); + } + Ok(json!({ "provider": provider, "key": key, "authorizedDevices": [device] })) +} + pub(crate) fn addressed_to_shown(params: Json) -> Json { addressed_to(shown_target().as_deref(), params) } diff --git a/apps/zgx/src/links.rs b/apps/zgx/src/links.rs index 8d647e251..a2486dcce 100644 --- a/apps/zgx/src/links.rs +++ b/apps/zgx/src/links.rs @@ -71,6 +71,41 @@ pub fn open(url: &str) { }); } +/// Banner clicks, taken in this process. The engine posts Zeron's banners, +/// but macOS hands a click to the app its bundle names (Zeron.app's +/// interface, this process), never to the engine that posted it, so the +/// engine's own route (`open -a … zeron://notification/…`) never runs. As +/// Zeron.app's interface always has (crates/ui `notify::on_click`), the +/// click is answered here: Zeron comes forward, on the banner's chat. +pub fn take_banner_clicks() { + zeron_notify::on_click(|target| { + activate(); + clicked(&target); + }); +} + +/// A clicked banner's target (a chat, or agent updates), opened as its +/// `zeron://notification/` link is. +fn clicked(target: &str) { + open(&zeron_notify::link(target)); +} + +/// This app to the front: a banner was clicked. (Main thread: the click +/// comes through the AppKit delegate.) +#[cfg(target_os = "macos")] +fn activate() { + use objc::{class, msg_send, sel, sel_impl}; + unsafe { + let app: *mut objc::runtime::Object = msg_send![class!(NSApplication), sharedApplication]; + if !app.is_null() { + let _: () = msg_send![app, activateIgnoringOtherApps: true]; + } + } +} + +#[cfg(not(target_os = "macos"))] +fn activate() {} + fn tell(target: Target) { let seq = SEQ.with(|s| { s.set(s.get() + 1); @@ -94,6 +129,28 @@ fn tell(target: Target) { mod tests { use super::*; + fn last() -> (Option, Option) { + LAST.with(|l| { + let l = l.borrow(); + let text = |k: &str| match l.field(k) { + Some(Value::Str(s)) => Some(s.to_string()), + Some(Value::Text(s)) => Some(s.to_string()), + _ => None, + }; + (text("chat"), text("settings")) + }) + } + + /// A banner clicked in this process (macOS hands the click to the app, + /// not the engine that posted it) opens its chat as its link would. + #[test] + fn a_clicked_banner_opens_its_chat() { + clicked("chat-42"); + assert_eq!(last(), (Some("chat-42".into()), None)); + clicked(zeron_notify::AGENT_UPDATES_TARGET); + assert_eq!(last(), (None, Some("providers".into()))); + } + #[test] fn banners_and_chat_links_open_where_zeron_s_do() { assert_eq!(parse(&zeron_notify::link("chat-1")), Some((Target::Chat("chat-1".into()), None))); diff --git a/apps/zgx/src/main.rs b/apps/zgx/src/main.rs index 11a592697..e3431f7b8 100644 --- a/apps/zgx/src/main.rs +++ b/apps/zgx/src/main.rs @@ -352,6 +352,8 @@ fn main() -> Result<(), Box> { } }); } + // A clicked banner: Zeron forward on its chat (src/links.rs). + links::take_banner_clicks(); let options = match screen { Screen::Intro => intro_window(), Screen::Onboarding => onboarding_window(), diff --git a/apps/zgx/ui/ds/provider_card.luau b/apps/zgx/ui/ds/provider_card.luau index 6e3cb0f3c..959c15355 100644 --- a/apps/zgx/ui/ds/provider_card.luau +++ b/apps/zgx/ui/ds/provider_card.luau @@ -221,6 +221,9 @@ export type CardProps = { -- back, Claude's when it can't finish in the browser) or "failed". foot: (string | () -> string)?, enabled: State, + -- An agent nothing here switches or updates (Cloud's: on every Cloud + -- machine, its accounts alone managed here): no switch, no Update. + fixed: boolean?, -- The account in use, by its email. active: () -> string?, settings: boolean?, @@ -1468,7 +1471,7 @@ function M.Card(c: CardProps): Node gap = "$space.3", items = "center", ui.show(function() - return latest() ~= nil or (c.updating ~= nil and c.updating()) + return not c.fixed and (latest() ~= nil or (c.updating ~= nil and c.updating())) end, Button { locale.t("ds.provider_card.update"), tone = "secondary", @@ -1488,7 +1491,7 @@ function M.Card(c: CardProps): Node on_click = c.on_settings, } else nil, - Switch { value = c.enabled, label = locale.t("ds.provider_card.enabled", { name = provider.name }) :: any }, + if c.fixed then nil else Switch { value = c.enabled, label = locale.t("ds.provider_card.enabled", { name = provider.name }) :: any }, }, } -- Its accounts, a row each, keyed: one arriving or going is that row diff --git a/apps/zgx/ui/ds/transcript.luau b/apps/zgx/ui/ds/transcript.luau index 50071c13c..8606ca686 100644 --- a/apps/zgx/ui/ds/transcript.luau +++ b/apps/zgx/ui/ds/transcript.luau @@ -1146,6 +1146,10 @@ local function Transcript(props: Props): Node -- taken meanwhile stays where it went. local function rise(prompt: Message?) ui.after(16, function() + -- (Scrolled meanwhile: the view is the reader's, see `wheeled`.) + if glides ~= turn then + return + end local row_el = prompt and tops[prompt.id] and tops[prompt.id]:peek() local list_el = list:peek() if not row_el or not list_el or row_el.y == nil or list_el.y == nil then @@ -1158,6 +1162,9 @@ local function Transcript(props: Props): Node duration = motion.ms(GLIDE_MS), ease = "outQuad", onComplete = function() + if glides ~= turn then + return + end -- Landed: the old reply lets go of the room it held -- (above the view, so nothing seen moves), and the -- offset says where the list now rests, a real place @@ -1444,6 +1451,18 @@ local function Transcript(props: Props): Node -- (Taken somewhere of their own: a place still to come back to is -- let go.) waiting = nil + -- A send's glide under way (or its prompt still to land, a steer's): + -- the scroll is theirs, so the glide stops where it is rather than + -- pulling the view back to the end. The old reply keeps the room it + -- held until it's out of view (`rested`), so nothing shown moves. + if gliding:peek() then + glides += 1 + if glide then + glide:pause() + glide = nil + end + gliding:set(false) + end return nil end -- When focus last came to something in the list (Tab, ⇧Tab to a row's @@ -1452,6 +1471,8 @@ local function Transcript(props: Props): Node -- While the width is changing (and a moment after): the reading row -- puts the place back as its lines rewrap, the frame they do. local resizing_until = 0 + -- When the view's size last changed. + local resized_at = -math.huge local function find_reading() reading = nil local el = list:peek() @@ -1533,9 +1554,32 @@ local function Transcript(props: Props): Node local function rested() remember() find_reading() - if not at_end:peek() and ui.now() >= resizing_until then + -- Resting away from the end: let go of it once no change of size is + -- under way, or at once if a person scrolled since the last one (a + -- scroll begun just after a resize is theirs; held, the next resize, + -- however much later, would pull the view back to the end). + if not at_end:peek() and (ui.now() >= resizing_until or wheeled_at >= resized_at) then end_held = false end + -- A send's glide a scroll stopped (`wheeled`): the old reply's held + -- room goes once that reply is out of view, where it moves nothing. + local h = held:peek() + if h.id ~= "" and not gliding:peek() then + local r = rows[h.id] + local row_el = r and r.outer:peek() + local el = list:peek() + local away_from_view = not row_el + or not el + or row_el.y == nil + or row_el.height == nil + or el.y == nil + or el.height == nil + or (row_el.y :: number) + (row_el.height :: number) <= (el.y :: number) + or (row_el.y :: number) >= (el.y :: number) + (el.height :: number) + if away_from_view then + held:set { id = "", h = 0 } + end + end end local rest = ui.debounced(offset, 150, { every = true }) -- (A view just made: its place told once it has stood 150 ms.) @@ -1994,7 +2038,8 @@ local function Transcript(props: Props): Node ui.after(48, settle) end if changed then - resizing_until = ui.now() + 300 + resized_at = ui.now() + resizing_until = resized_at + 300 -- At the end: on it still, every frame of the change. if end_held and not gliding:peek() then -- (Asked of the list itself, which lands it as it lays diff --git a/apps/zgx/ui/locales/en.json b/apps/zgx/ui/locales/en.json index 960b2be33..bd46a6a85 100644 --- a/apps/zgx/ui/locales/en.json +++ b/apps/zgx/ui/locales/en.json @@ -1631,7 +1631,18 @@ }, "remove_row_description": "Chats that used it stay." }, - "couldnt_switch": "Couldn't switch accounts" + "couldnt_switch": "Couldn't switch accounts", + "cloud": "Cloud", + "cloud_keys": { + "title": "API keys", + "section_description": "Instead of signing in, Cloud can use an API key. A key saved here becomes the account its agent uses on every Cloud machine, from its next turn.", + "anthropic": "Anthropic API key", + "openai": "OpenAI API key", + "description": "For {agent} on Cloud. Kept in Zeron's vault, never on this computer.", + "placeholder": "Paste a key", + "save": "Save", + "saved": "{agent} on Cloud now uses this key" + } }, "devices": { "title": "Devices", diff --git a/apps/zgx/ui/locales/zh-Hans.json b/apps/zgx/ui/locales/zh-Hans.json index 1a6a00cc0..27d1fe97e 100644 --- a/apps/zgx/ui/locales/zh-Hans.json +++ b/apps/zgx/ui/locales/zh-Hans.json @@ -1631,7 +1631,18 @@ }, "remove_row_description": "使用过它的对话会保留。" }, - "couldnt_switch": "无法切换账户" + "couldnt_switch": "无法切换账户", + "cloud": "云端", + "cloud_keys": { + "title": "API 密钥", + "section_description": "云端也可以使用 API 密钥,而不必登录。在此保存的密钥会成为该代理在每台云端机器上使用的账户,从下一轮开始生效。", + "anthropic": "Anthropic API 密钥", + "openai": "OpenAI API 密钥", + "description": "用于云端的 {agent}。保存在 Zeron 的密钥库中,不会存放在这台电脑上。", + "placeholder": "粘贴密钥", + "save": "保存", + "saved": "云端的 {agent} 现在使用此密钥" + } }, "devices": { "title": "设备", diff --git a/apps/zgx/ui/screens/chat/shared.luau b/apps/zgx/ui/screens/chat/shared.luau index f16052d41..53a6dba09 100644 --- a/apps/zgx/ui/screens/chat/shared.luau +++ b/apps/zgx/ui/screens/chat/shared.luau @@ -13,6 +13,7 @@ local Quote = require("@ds/quote") local Annotation = require("@ds/annotation") local sessions = require("@account/sessions") local agents = require("@account/agents") +local cloud = require("@account/cloud") local locale = require("@ds/locale") local toast = require("@ds/toast") local ChatLinks = require("@app/screens/chat/chat_links") @@ -1031,9 +1032,19 @@ local here_device = ui.computed(function(): string? end) -- The accounts' key for a device: "" for this one, whose engine answers --- for itself. +-- for itself; "cloud" for any of Cloud's (a chat's machine, or the +-- account's Cloud device), whose accounts are the vault's, every Cloud +-- machine's alike, as Settings → Providers shows them (this engine answers +-- for "cloud": crates/engine cloud_accounts). A machine can't be asked: +-- its accounts aren't its own, and asking would wake it. local function account_key(device: string?): string - return if device == nil or device == here_device:get() then "" else device + if device == nil or device == here_device:get() then + return "" + end + if cloud.on_device(device) or device == cloud.device() then + return "cloud" + end + return device end -- Models of Cursor's own pool (Composer, Grok), not the third-party one. diff --git a/apps/zgx/ui/screens/settings/devices.luau b/apps/zgx/ui/screens/settings/devices.luau index 9a88ef06c..06637b28c 100644 --- a/apps/zgx/ui/screens/settings/devices.luau +++ b/apps/zgx/ui/screens/settings/devices.luau @@ -169,7 +169,9 @@ local icon_of = M.icon -- choosing one calls `choose` with its id. Built once: its options follow -- the devices as they come, go and are renamed, and the choice follows -- `shown`. -function M.picker(shown: () -> string?, choose: (id: string) -> ()): Node +-- (`extra`: more choices after the computers, each `{ value, label, icon }`: +-- Providers' Cloud, whose accounts every Cloud machine uses.) +function M.picker(shown: () -> string?, choose: (id: string) -> (), extra: (() -> { any })?): Node local function computers(): { sessions.Device } return sessions.computers(sessions.devices:get(), true) end @@ -181,9 +183,12 @@ function M.picker(shown: () -> string?, choose: (id: string) -> ()): Node end return "" end + local function extras(): { any } + return if extra then extra() else {} + end return ui.show( function(): boolean - return #computers() > 1 + return #computers() > 1 or #extras() > 0 end, ui.component(function(): Node local chosen = ui.use_state(shown() or here()) @@ -208,6 +213,9 @@ function M.picker(shown: () -> string?, choose: (id: string) -> ()): Node description = if not d.here and d.online == false then ui.t("settings.devices.offline") else nil, }) end + for _, e in extras() do + table.insert(options, e) + end return options end, on_change = choose, diff --git a/apps/zgx/ui/screens/settings/providers.luau b/apps/zgx/ui/screens/settings/providers.luau index 2876379aa..d1e13d9a3 100644 --- a/apps/zgx/ui/screens/settings/providers.luau +++ b/apps/zgx/ui/screens/settings/providers.luau @@ -23,6 +23,7 @@ local prefs = require("@app/screens/settings/prefs") local registry = require("@account/registry") local add_agent = require("@app/screens/settings/add_agent") local sign_in_terminal = require("@app/screens/settings/sign_in_terminal") +local cloud = require("@account/cloud") local M = {} @@ -108,6 +109,20 @@ local function here(): string? end return nil end +-- Cloud, as one choice after the computers (never its machines): the +-- accounts every Cloud machine uses, kept by the vault, which the engine +-- answers for (crates/engine cloud_accounts: Claude Code and Codex, their +-- logins and API keys). Offered while Cloud is on. +local CLOUD = "cloud" +local function on_cloud(): boolean + return now().target == CLOUD +end +local function cloud_choice(): { any } + if cloud.on() or on_cloud() then + return { { value = CLOUD, label = ui.t("settings.providers.cloud"):get(), icon = "cloud" } } + end + return {} +end -- The device shown: the engine's target, else this one. local function shown_device(): string? return now().target or here() @@ -115,6 +130,9 @@ end -- (In the locale shown: read where it's drawn.) local function device_name(): string local id = shown_device() + if id == CLOUD then + return ui.t("settings.providers.cloud"):get() + end for _, d in computers() do if d.id == id then return if d.here then ui.t("settings.providers.this_mac"):get() else d.name @@ -124,8 +142,11 @@ local function device_name(): string end local function choose_device(id: string) agents.target(if id == here() then nil else id) - -- (The registry as that device sees it: what it has added, its builds.) - registry.load() + -- (The registry as that device sees it: what it has added, its builds. + -- Cloud runs only Zeron's own.) + if id ~= CLOUD then + registry.load() + end end -- Which of the page's views shows: the agents, the registry ("add"), or @@ -152,7 +173,8 @@ local function kind(): string if s == "looking" or s == "unavailable" then return s end - return "found" + -- (Cloud's page is another: its accounts, its keys, nothing to add.) + return if now().target == "cloud" then "cloud" else "found" end -- Which agent's settings are open (none: ""). @@ -223,6 +245,9 @@ local function card(row: State): Node -- no accounts, and signs in its own way. (Its updates come as any -- agent's: the engine's update coordinator, the registry its feed.) local from_registry = (first :: any).registry == true + -- Cloud's (made for it: the cards are keyed by the device shown): on + -- every Cloud machine, its accounts alone managed here. + local cloud_card = on_cloud() -- The switch follows the engine; a flip goes to it, and its answer -- comes back in the row. local on = ui.use_state(first.enabled) @@ -234,7 +259,7 @@ local function card(row: State): Node if flipped ~= said then on:set(said) end - elseif flipped ~= said then + elseif flipped ~= said and not cloud_card then agents.set_enabled(id, flipped) end end) @@ -250,6 +275,7 @@ local function card(row: State): Node return (row:get() :: any).updating == true end, sign_in_only = from_registry, + fixed = cloud_card, login_note = function(): string? return (row:get() :: any).login_note end, @@ -329,7 +355,7 @@ local function card(row: State): Node end return nil end, - settings = true, + settings = not cloud_card, on_settings = function() load_subagents() open_settings:set(id) @@ -421,7 +447,13 @@ local function cards(): Node gap = "$space.4", ui.each(ui.computed(installed), function(_a: agents.Agent, _i: number, row: State): Node return card(row) - end, { key = by_id }), + end, { + -- (By the device shown too: a card is made for its device, + -- Cloud's unlike a computer's.) + key = function(a: agents.Agent): string + return `{now().target or ""}|{a.id}` + end, + }), } ) end @@ -490,6 +522,85 @@ local function more(): Node ) end +-- Cloud's API keys: Anthropic's for Claude Code, OpenAI's for Codex, kept +-- by the vault. A key saved becomes its agent's account in use, every Cloud +-- machine's from its next turn (as signing in does). +local CLOUD_KEYS = { + { provider = "anthropic-key", agent = "Claude Code", label = "settings.providers.cloud_keys.anthropic" }, + { provider = "openai-key", agent = "Codex", label = "settings.providers.cloud_keys.openai" }, +} +local function cloud_key_row(k: { provider: string, agent: string, label: string }): Node + return ui.component(function(): Node + local value = ui.use_state("") + local busy = ui.use_state(false) + local problem = ui.use_state("") + local function save() + local key = value:peek() + if busy:peek() or key == "" then + return + end + busy:set(true) + problem:set("") + host.call("agents.cloud_key", { provider = k.provider, key = key, device = cloud.device() or "" }):after(function() + busy:set(false) + value:set("") + toast.show { title = ui.t("settings.providers.cloud_keys.saved", { agent = k.agent }):get(), tone = "success" } + end, function(err: any) + busy:set(false) + problem:set(if type(err) == "table" and err.message then tostring(err.message) else tostring(err)) + end) + end + return ds.Settings.Row { + label = ui.t(k.label), + description = function(): string + local p = problem:get() + return if p ~= "" then p else ui.t("settings.providers.cloud_keys.description", { agent = k.agent }):get() + end, + control = ui.row { + gap = "$space.2", + items = "center", + ds.TextField { + value = value, + password = true, + w = 220, + size = "sm", + name = ui.t(k.label), + placeholder = ui.t("settings.providers.cloud_keys.placeholder"), + on_commit = function() + save() + end, + }, + ds.Button { + ui.t("settings.providers.cloud_keys.save"), + tone = "secondary", + size = "sm", + busy = function(): boolean + return busy:get() + end, + disabled = function(): boolean + return value:get() == "" + end, + on_click = save, + }, + }, + } + end)({}) +end +local function cloud_keys(): Node + return ds.Settings.Section { + title = ui.t("settings.providers.cloud_keys.title"), + description = ui.t("settings.providers.cloud_keys.section_description"), + ds.Settings.Group { + ui.column { + w_full = true, + cloud_key_row(CLOUD_KEYS[1]), + ds.Settings.Rule(), + cloud_key_row(CLOUD_KEYS[2]), + }, + }, + } +end + local function body(k: string): Node if k == "looking" then return ds.ProviderCard.Loading() @@ -498,6 +609,9 @@ local function body(k: string): Node return device_name() end, agents.load) end + if k == "cloud" then + return ui.column { w_full = true, gap = "$space.6", cards(), cloud_keys() } + end return ui.column { w_full = true, gap = "$space.6", cards(), more() } end @@ -767,7 +881,7 @@ local function agents_page(): Node -- Agents are per device: which one's (a choice once there's more -- than this one). -- (The same choice as Plugins': screens/settings/devices.) - trail = devices_page.picker(shown_device, choose_device), + trail = devices_page.picker(shown_device, choose_device, cloud_choice), -- (At the top right, on the title's line, as Plugins' is.) trail_top = true, ui.presence(kind, body, { w_full = true, enter = { opacity = { 0, 1 }, duration = 120 }, exit = { opacity = 0, duration = 60 }, mode = "wait" }), @@ -792,6 +906,10 @@ function M.view(): Node -- (Once a visit: a hot reload doesn't ask again.) The page opens on the -- agents; the registry is looked at too, for what it has to add. visits.once("providers", function() + -- (Whether Cloud is on, for its choice.) + if cloud.now:peek().phase == "unknown" then + cloud.load() + end agents.load() registry.load() if view:peek() ~= "agents" then diff --git a/apps/zgx/ui/settings_stub.luau b/apps/zgx/ui/settings_stub.luau index e68bd3ff8..3d0e4b6e7 100644 --- a/apps/zgx/ui/settings_stub.luau +++ b/apps/zgx/ui/settings_stub.luau @@ -432,6 +432,21 @@ end -- a switch of device shows whose. local agents = require("@account/agents") local function agents_of(target: string?): any + -- Cloud (the engine answers for it from the vault): Claude Code and + -- Codex, always installed; Codex with an account, so on. + if target == "cloud" then + local function one(id: string, name: string, mark: string, accounts: { any }): any + return { id = id, name = name, mark = mark, installed = true, can_install = false, enabled = #accounts > 0, version = nil, installing = false, login = "idle", accounts = accounts } + end + return { + state = "ready", + target = target, + list = { + one("claude-code", "Claude Code", "claude", {}), + one("codex", "Codex", "openai", { { id = "c1", email = "ada@example.com", plan = "Pro", session = 0.1, week = 0.2, active = true } }), + }, + } + end local name = if target then "Codex" else "Claude Code" local id = if target then "codex" else "claude-code" return { diff --git a/apps/zgx/ui/tests/model_accounts.test.luau b/apps/zgx/ui/tests/model_accounts.test.luau index 3ea1abea1..a79be2447 100644 --- a/apps/zgx/ui/tests/model_accounts.test.luau +++ b/apps/zgx/ui/tests/model_accounts.test.luau @@ -91,6 +91,33 @@ test("a chat on another computer reads that computer's accounts", function() expect(app:state("calls")).to_contain("switch_on:box:claude-code:b2") end) +-- A chat on a Cloud machine: its accounts are Cloud's, the vault's (as +-- Settings → Providers shows them under Cloud), never the machine's own, +-- which isn't asked (it would be woken). +test("a chat on a Cloud machine reads and switches Cloud's accounts", function() + local app = with_accounts({ + [""] = { ["claude-code"] = accounts() }, + cloud = { + ["claude-code"] = { + { id = "v1", email = "team@example.test", plan = "Max", active = true, can_switch = true, windows = { window("Week", 0.4) } }, + { id = "v2", email = "spare@example.test", plan = "Pro", active = false, can_switch = true, windows = {} }, + }, + }, + }) + app:set_state("chat_device", "cloud-f60cde46") + app:frames(10) + expect(app:state("calls")).to_contain("watch_device:cloud") + expect(string.find(app:state("calls"), "watch_device:cloud-f60cde46", 1, true)).to_be(nil) + app:click('role:button "Model"') + app:frames(30) + expect(app:tree("#model-picker-account")).to_contain("team@example.test") + app:click("#model-picker-account") + app:frames(30) + app:click('~"spare@example.test"') + app:frames(30) + expect(app:state("calls")).to_contain("switch_on:cloud:claude-code:v2") +end) + test("a computer whose accounts haven't come has neither, and is asked", function() local app = with_accounts(here(accounts())) app:set_state("chat_device", "somewhere-else") diff --git a/apps/zgx/ui/tests/providers_cloud.test.luau b/apps/zgx/ui/tests/providers_cloud.test.luau new file mode 100644 index 000000000..b6b696335 --- /dev/null +++ b/apps/zgx/ui/tests/providers_cloud.test.luau @@ -0,0 +1,77 @@ +-- Settings → Providers offers Cloud as one more choice after the computers, +-- while Cloud is on: its agents' accounts (the vault's, every Cloud machine +-- uses them), with no switch, no settings and nothing to install, and API +-- keys to save for it. Without Cloud, no such choice. On the shell in +-- ui/shell_fixture.luau, Cloud from ui/cloud_stub.luau. + +local PAGE = "#settings-page" +local NAV = "#settings-nav" + +local function shows(app: any, scope: string, text: string): boolean + return app:tree(scope):find(text, 1, true) ~= nil +end + +local function asked(app: any, entry: string): boolean + for _, c in (app:state("settings_stub_calls") :: any) or {} do + if c == entry then + return true + end + end + return false +end + +local function open(with_cloud: boolean): any + local app = mount("shell_fixture.luau") + app:resize(1200, 900) + app:frames(30) + app:command("settings_stub.sign_in") + if with_cloud then + app:command("cloud_stub.offer") + end + app:command("shell.settings") + app:frames(20) + app:click(`{NAV} >> role:tab "Providers"`) + app:frames(30) + return app +end + +test("with Cloud on, Providers offers Cloud: its agents' accounts, no switch or settings, and its API keys", function() + local app = open(true) + app:click(`{PAGE} >> role:button "Device"`) + app:frames(10) + expect(app:has('role:menuitem "Cloud"')).to_be(true) + app:click('role:menuitem "Cloud"') + app:frames(30) + expect(asked(app, "agents.target:cloud")).to_be(true) + expect(shows(app, PAGE, "Claude Code")).to_be(true) + expect(shows(app, PAGE, "Codex")).to_be(true) + expect(shows(app, PAGE, "ada@example.com")).to_be(true) + -- Nothing to switch, set or install: its accounts alone. + expect(app:has(`{PAGE} >> role:switch "Codex on"`)).to_be(false) + expect(app:has(`{PAGE} >> role:button "Codex settings"`)).to_be(false) + expect(shows(app, PAGE, "Add another agent")).to_be(false) + -- Its API keys, saved for Cloud. + expect(shows(app, PAGE, "Anthropic API key")).to_be(true) + expect(shows(app, PAGE, "OpenAI API key")).to_be(true) + app:type(`{PAGE} >> role:textbox "OpenAI API key"`, "sk-test-123") + app:frames(5) + app:click(`{PAGE} >> role:button "Save" [2]`) + app:frames(10) + expect(asked(app, "agents.cloud_key")).to_be(true) + expect(app:error()).to_be_nil() + -- Back to this computer: its agents as they were, with their switches. + app:click(`{PAGE} >> role:button "Device"`) + app:frames(10) + app:click('role:menuitem "MacBook Pro"') + app:frames(30) + expect(asked(app, "agents.target:")).to_be(true) + expect(app:has(`{PAGE} >> role:switch "Claude Code on"`)).to_be(true) + expect(shows(app, PAGE, "Anthropic API key")).to_be(false) +end) + +test("without Cloud, Providers offers no Cloud", function() + local app = open(false) + app:click(`{PAGE} >> role:button "Device"`) + app:frames(10) + expect(app:has('role:menuitem "Cloud"')).to_be(false) +end) diff --git a/apps/zgx/ui/tests/transcript_scroll_away.test.luau b/apps/zgx/ui/tests/transcript_scroll_away.test.luau new file mode 100644 index 000000000..a4dddd99a --- /dev/null +++ b/apps/zgx/ui/tests/transcript_scroll_away.test.luau @@ -0,0 +1,84 @@ +-- Scrolled away from the end, the view stays where the person took it: it +-- isn't pulled back to the end. (Nov 14: "scrolling gets stuck to the +-- bottom; scroll away and it scrolls you back down".) Two ways it was: +-- - a scroll during a send's glide (the prompt rising to the view's top, or +-- a steer's waiting to land): the glide went on to the end over it; +-- - a scroll begun within moments of the view's size changing: the end +-- stayed held, and the next resize, however much later (the sidebar, a +-- panel, the window), went back to it. +-- On chat_fixture's `long_chat` (ui/long_chat_fixture.luau). + +local function settle(app: any) + app:wait("#never-shown", { timeout_ms = 250 }) + app:frames(10) +end + +local function offset(app: any): number + return app:state("chat.transcript.offset") +end + +-- How far the view is from its end, measured by going there (which holds +-- the end again: only at the close of a test). +local function from_end(app: any): number + local at = offset(app) + app:scroll("#transcript", 1e6) + app:frames(4) + return offset(app) - at +end + +local function open(): any + local app = mount("chat_fixture.luau") + app:resize(960, 700) + app:frames(20) + app:command("long_chat_sent") + app:command("go_s7") + app:frames(30) + settle(app) + return app +end + +local function send(app: any) + app:type("role:textbox", "three and one sounds like the most optional option") + app:key("Enter") +end + +local function scroll_up(app: any) + for _ = 1, 10 do + app:wheel("#transcript", { dy = -40 }) + app:frames(1) + end +end + +test("scrolled up while a send glides, the view stays where it was taken", function() + local app = open() + send(app) + app:frames(3) + scroll_up(app) + settle(app) + settle(app) + expect(from_end(app) > 100).to_be(true) +end) + +test("scrolled up just after a resize, a later resize leaves the view where it was", function() + local app = open() + send(app) + app:frames(40) + settle(app) + for _ = 1, 60 do + app:command("long_chat_streams") + app:frames(2) + end + app:frames(10) + app:resize(940, 700) + app:frames(2) + scroll_up(app) + -- (It rests inside the resize's moment, then a while.) + settle(app) + app:wait("#never-shown", { timeout_ms = 800 }) + local at = offset(app) + app:resize(900, 700) + app:frames(10) + settle(app) + expect(math.abs(offset(app) - at) < 1).to_be(true) + expect(from_end(app) > 100).to_be(true) +end) diff --git a/crates/engine/src/desktop_notify.rs b/crates/engine/src/desktop_notify.rs index c395531a0..e27315b91 100644 --- a/crates/engine/src/desktop_notify.rs +++ b/crates/engine/src/desktop_notify.rs @@ -31,6 +31,14 @@ use zeron_proto::{Chat, ConnectivityState, HarnessUpdatePhase, HarnessUpdateStat static ENABLED: AtomicBool = AtomicBool::new(false); +/// How long a finish waits to stand before it rings. The person's own +/// message often comes with one: a steer or a queued row taken as a turn +/// ends publishes that end with Working (their message carries the turn on), +/// and a send that replaces the runtime marks the old turn's end a moment +/// before the new one starts. Neither is "finished"; a turn that follows +/// within this window takes the finish with it. +const DONE_SETTLE: chrono::Duration = chrono::Duration::seconds(2); + /// This process shows desktop banners: engines assembled from now on post /// them (and advertise [`zeron_proto::capabilities::DESKTOP_NOTIFICATIONS_V1`]). pub fn enable() { @@ -222,7 +230,12 @@ impl Prefs { /// What a banner asked for by something other than a session (a plugin's, /// through `PostNotification`) came to: shown, or why not. -pub(crate) fn asked_outcome(prefs_enabled: bool, background_only: bool, focused: bool, desktop: bool) -> &'static str { +pub(crate) fn asked_outcome( + prefs_enabled: bool, + background_only: bool, + focused: bool, + desktop: bool, +) -> &'static str { if !desktop { "unavailable" } else if !prefs_enabled { @@ -237,7 +250,13 @@ pub(crate) fn asked_outcome(prefs_enabled: bool, background_only: bool, focused: /// A banner asked for (a plugin's): shown as the engine's own are, under /// the same Settings (`notificationsEnabled`, "only when in the /// background"), clicking it opening `target` (a session). What it came to. -pub(crate) fn post_asked(data_dir: &Path, focus: &ViewportFocus, title: &str, body: &str, target: Option<&str>) -> &'static str { +pub(crate) fn post_asked( + data_dir: &Path, + focus: &ViewportFocus, + title: &str, + body: &str, + target: Option<&str>, +) -> &'static str { let prefs = Prefs::read(data_dir); let outcome = asked_outcome(prefs.enabled, prefs.background_only, focus.any(), enabled()); if outcome == "posted" { @@ -261,7 +280,9 @@ pub(crate) fn post_for( std::sync::LazyLock::new(Default::default); let body: String = body.chars().take(500).collect(); let paced = { - let mut pace = PACE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut pace = PACE + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); !asked_in_time(pace.entry(source.to_owned()).or_default(), Instant::now()) }; if paced { @@ -273,11 +294,19 @@ pub(crate) fn post_for( /// Whether one more banner from a source may show, given when its last /// ones did: at most [`ASKED_PER_MINUTE`] a minute, [`ASKED_APART`] apart. -pub(crate) fn asked_in_time(history: &mut std::collections::VecDeque, now: Instant) -> bool { - while history.front().is_some_and(|at| now.duration_since(*at) >= Duration::from_secs(60)) { +pub(crate) fn asked_in_time( + history: &mut std::collections::VecDeque, + now: Instant, +) -> bool { + while history + .front() + .is_some_and(|at| now.duration_since(*at) >= Duration::from_secs(60)) + { history.pop_front(); } - let apart = history.back().is_none_or(|at| now.duration_since(*at) >= ASKED_APART); + let apart = history + .back() + .is_none_or(|at| now.duration_since(*at) >= ASKED_APART); if apart && history.len() < ASKED_PER_MINUTE { history.push_back(now); return true; @@ -316,6 +345,9 @@ struct Notifier { focus: ViewportFocus, post: Post, baselines: HashMap, + /// Finishes waiting to stand ([`DONE_SETTLE`]): chat → its title and + /// when it rings. + settling: HashMap)>, connectivity: ConnectivityNotificationState, updates_seen: HashSet, } @@ -328,6 +360,7 @@ impl Notifier { focus, post, baselines: HashMap::new(), + settling: HashMap::new(), connectivity: ConnectivityNotificationState::default(), updates_seen: HashSet::new(), } @@ -356,15 +389,56 @@ impl Notifier { if !chat.is_some_and(Chat::is_top_level) { continue; } + // A turn going on (or asking, or failing) takes a waiting + // finish with it. + if status.indicator != Indicator::None { + self.settling.remove(&session.chat_id); + } if let Some(prev) = prev && let Some(ping) = status.ping_since(&prev, false) { let title = chat .and_then(|chat| chat.title.clone()) .unwrap_or_else(|| "New session".into()); - due.push((title, ping, session.chat_id.clone())); + match ping { + // Published with the next turn already running: the + // person's message carried it on, nothing finished. + Ping::Done if status.indicator == Indicator::Working => {} + Ping::Done => { + self.settling + .insert(session.chat_id.clone(), (title, now + DONE_SETTLE)); + } + _ => due.push((title, ping, session.chat_id.clone())), + } } } + self.post_due(due); + } + + /// When the next waiting finish rings. + fn next_settled(&self) -> Option> { + self.settling.values().map(|(_, at)| *at).min() + } + + /// Ring the finishes that have stood for [`DONE_SETTLE`]. + fn flush(&mut self, now: chrono::DateTime) { + let stood: Vec = self + .settling + .iter() + .filter(|(_, (_, at))| *at <= now) + .map(|(chat, _)| chat.clone()) + .collect(); + let due = stood + .into_iter() + .filter_map(|chat| { + let (title, _) = self.settling.remove(&chat)?; + Some((title, Ping::Done, chat)) + }) + .collect(); + self.post_due(due); + } + + fn post_due(&mut self, due: Vec<(String, Ping, String)>) { if due.is_empty() || self.allowed().is_none() { return; } @@ -464,6 +538,7 @@ pub(crate) fn spawn(core: &crate::EngineCore, data_dir: PathBuf) -> tokio::task: let mut updates_due: Option = Some(tokio::time::Instant::now() + UPDATE_DEBOUNCE); loop { + let settles_at = notifier.next_settled(); tokio::select! { changed = sessions.changed() => { if changed.is_err() { break; } @@ -485,6 +560,17 @@ pub(crate) fn spawn(core: &crate::EngineCore, data_dir: PathBuf) -> tokio::task: updates.borrow_and_update(); updates_due.get_or_insert(tokio::time::Instant::now() + UPDATE_DEBOUNCE); } + _ = async { + match settles_at { + Some(at) => { + let wait = (at - chrono::Utc::now()).to_std().unwrap_or_default(); + tokio::time::sleep(wait).await; + } + None => std::future::pending().await, + } + } => { + notifier.flush(chrono::Utc::now()); + } _ = async { match updates_due { Some(at) => tokio::time::sleep_until(at).await, @@ -505,21 +591,38 @@ mod tests { #[test] fn a_plugin_s_banner_keeps_to_the_settings_and_its_pace() { assert_eq!(asked_outcome(true, false, true, true), "posted"); - assert_eq!(asked_outcome(true, true, true, true), "held", "only when in the background, and a window is in front"); + assert_eq!( + asked_outcome(true, true, true, true), + "held", + "only when in the background, and a window is in front" + ); assert_eq!(asked_outcome(true, true, false, true), "posted"); assert_eq!(asked_outcome(false, false, false, true), "off"); - assert_eq!(asked_outcome(true, false, false, false), "unavailable", "a server never shows banners"); + assert_eq!( + asked_outcome(true, false, false, false), + "unavailable", + "a server never shows banners" + ); let mut history = std::collections::VecDeque::new(); let t0 = Instant::now(); assert!(asked_in_time(&mut history, t0)); - assert!(!asked_in_time(&mut history, t0 + Duration::from_secs(1)), "too soon after the last"); + assert!( + !asked_in_time(&mut history, t0 + Duration::from_secs(1)), + "too soon after the last" + ); let mut at = t0; for _ in 1..ASKED_PER_MINUTE { at += ASKED_APART; assert!(asked_in_time(&mut history, at)); } - assert!(!asked_in_time(&mut history, at + ASKED_APART), "a minute's worth"); - assert!(asked_in_time(&mut history, t0 + Duration::from_secs(61)), "a minute on, one more"); + assert!( + !asked_in_time(&mut history, at + ASKED_APART), + "a minute's worth" + ); + assert!( + asked_in_time(&mut history, t0 + Duration::from_secs(61)), + "a minute on, one more" + ); } use super::*; @@ -782,6 +885,8 @@ mod tests { &chats, now, ); + // (Once it has settled: a finish waits a moment for a turn to follow.) + notifier.flush(now + DONE_SETTLE); assert_eq!( *posted.lock().unwrap(), vec![( @@ -793,6 +898,7 @@ mod tests { // A focused window holds it back (background-only is the default). focus.set("window", true); notifier.sessions(&[session("a", Some("t3"), now)], &chats, now); + notifier.flush(now + DONE_SETTLE); assert_eq!(posted.lock().unwrap().len(), 1); // Banners off: nothing, focused or not. focus.set("window", false); @@ -802,9 +908,68 @@ mod tests { ) .unwrap(); notifier.sessions(&[session("a", Some("t4"), now)], &chats, now); + notifier.flush(now + DONE_SETTLE); assert_eq!(posted.lock().unwrap().len(), 1); } + fn working(chat_id: &str, turn: Option<&str>, now: chrono::DateTime) -> Session { + let mut row = session(chat_id, turn, now); + row.status = zeron_proto::SessionStatus::Working; + row.started_at = Some(now); + row + } + + /// Your own message never rings "finished". These are the rows + /// crates/engine/src/sessions.rs publishes at such a send. + #[test] + fn a_send_steer_or_queued_send_never_rings_finished() { + let dir = tempfile::tempdir().unwrap(); + let (mut notifier, posted, _) = notifier(dir.path()); + let chats = [chat("a", "Fix the build", None)]; + let t0 = chrono::Utc::now(); + let at = |ms: i64| t0 + chrono::Duration::milliseconds(ms); + notifier.sessions(&[session("a", Some("t1"), at(0))], &chats, at(0)); + + // A plain send to an idle chat: Working, the marker as it was. + notifier.sessions(&[working("a", Some("t1"), at(10))], &chats, at(10)); + notifier.flush(at(10_000)); + // A steer (or a queued row taken) as the turn ends: the end is + // published with Working, the person's message carrying it on. + notifier.sessions(&[working("a", Some("t2"), at(20))], &chats, at(20)); + notifier.flush(at(10_000)); + // A send that replaces the runtime: the held end lands Idle, then + // the new turn starts a moment later. + notifier.sessions(&[session("a", Some("t3"), at(30))], &chats, at(30)); + notifier.sessions(&[working("a", Some("t3"), at(200))], &chats, at(200)); + notifier.flush(at(10_000)); + assert!( + posted.lock().unwrap().is_empty(), + "rang on a send: {:?}", + posted.lock().unwrap() + ); + + // The turn your message started finishing: that rings, once. + notifier.sessions(&[session("a", Some("t4"), at(20_000))], &chats, at(20_000)); + notifier.flush(at(30_000)); + notifier.flush(at(40_000)); + assert_eq!(posted.lock().unwrap().len(), 1); + } + + /// A question or a failure doesn't wait: it rings at once. + #[test] + fn a_question_or_failure_rings_at_once() { + let dir = tempfile::tempdir().unwrap(); + let (mut notifier, posted, _) = notifier(dir.path()); + let chats = [chat("a", "Fix the build", None)]; + let now = chrono::Utc::now(); + notifier.sessions(&[working("a", Some("t1"), now)], &chats, now); + let mut asking = working("a", Some("t1"), now); + asking.status = zeron_proto::SessionStatus::AwaitingInput; + notifier.sessions(&[asking], &chats, now); + assert_eq!(posted.lock().unwrap().len(), 1); + assert_eq!(posted.lock().unwrap()[0].1, "Waiting on your input"); + } + #[test] fn agent_updates_banner_once_per_release() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/update/src/lib.rs b/crates/update/src/lib.rs index d698dbe58..067653bbd 100644 --- a/crates/update/src/lib.rs +++ b/crates/update/src/lib.rs @@ -1248,10 +1248,11 @@ fn on_cloud() -> bool { on_cloud_platform(std::env::var("ZERON_DEVICE_PLATFORM").ok().as_deref()) } -/// Release files a Cloud machine never runs: the desktop app's background -/// engine (78 MB). A Cloud machine runs `zeron headless`, which links the -/// engine, and its disk is copied back in on every wake. -pub const CLOUD_UNUSED_FILES: &[&str] = &["zeron-engine"]; +/// Release files a Cloud machine never runs: none. (`zeron-engine` was here +/// until 2026-11-15, when `zeron headless` linked the engine. Since 0.3.0 the +/// release's `zeron` is the zgx app, whose `zeron headless` runs the +/// `zeron-engine` beside it: a machine without it never came online.) +pub const CLOUD_UNUSED_FILES: &[&str] = &[]; /// Remove [`CLOUD_UNUSED_FILES`] from the version folder `dir`. pub fn strip_cloud_unused(dir: &Path) { @@ -3692,9 +3693,11 @@ mod tests { assert_eq!(folders(&app_root), ["0.2.10", "0.2.11", "0.2.12", "current"]); } + /// `zeron headless` runs the `zeron-engine` beside it: a Cloud machine + /// keeps it in every version (it once left it out, and never came online). #[cfg(unix)] #[test] - fn a_cloud_machine_keeps_no_desktop_engine() { + fn a_cloud_machine_keeps_the_engine_its_headless_runs() { let tmp = tempfile::tempdir().unwrap(); let app_root = tmp.path().join("app"); versions_installed(&app_root, &["0.2.10", "0.2.11"]); @@ -3708,7 +3711,7 @@ mod tests { strip_unused_from_versions(&app_root); for ver in ["0.2.10", "0.2.11"] { - assert!(!app_root.join(ver).join("zeron-engine").exists(), "{ver}"); + assert!(app_root.join(ver).join("zeron-engine").exists(), "{ver}"); assert!(app_root.join(ver).join("zeron").exists(), "{ver}"); } assert!(app_root.join("notes").join("zeron-engine").exists()); @@ -4169,11 +4172,11 @@ mod tests { assert!(staged.join("zeron").is_file()); } - /// The release carries the desktop's background engine; a Cloud machine - /// stages the release without it, anywhere else keeps it. + /// The release carries `zeron-engine`, which `zeron headless` runs: a + /// Cloud machine stages it as anywhere else does. #[cfg(unix)] #[tokio::test] - async fn a_cloud_machine_stages_a_release_without_the_desktop_engine() { + async fn a_cloud_machine_stages_a_release_with_its_engine() { let tmp = tempfile::tempdir().unwrap(); let pkg = tmp.path().join("pkg"); std::fs::create_dir_all(pkg.join("zeron-pkg")).unwrap(); @@ -4190,7 +4193,7 @@ mod tests { .into(), ..Manifest::default() }; - for (cloud, kept) in [(true, false), (false, true)] { + for (cloud, kept) in [(true, true), (false, true)] { let app_root = tmp.path().join(format!("app-{cloud}")); std::fs::create_dir_all(&app_root).unwrap(); let (base, server) = serve_forever(bytes.clone()).await; diff --git a/crates/update/tests/update_transaction.rs b/crates/update/tests/update_transaction.rs index 3a50d6bb3..882ab5210 100644 --- a/crates/update/tests/update_transaction.rs +++ b/crates/update/tests/update_transaction.rs @@ -489,7 +489,7 @@ mod versioned { let mut rig = Rig::new("ok"); rig.platform = platform; rig.install_old(&["0.8.0", "0.9.0"]); - // The desktop's background engine, as the release ships it. + // The engine `zeron headless` runs, as the release ships it. for version in ["1.0.0", "2.0.0"] { std::fs::write(rig.app.join(version).join("zeron-engine"), "desktop").unwrap(); } @@ -497,12 +497,9 @@ mod versioned { rig.run_until_settled(); rig.assert_updated(&id); rig.app_settles_to(expected); - // A Cloud machine never runs it, and copies it back in on every wake. - assert_eq!( - rig.app.join("2.0.0/zeron-engine").exists(), - platform.is_none(), - "platform {platform:?}" - ); + // Kept everywhere, Cloud too: `zeron headless` runs it (a Cloud + // machine once left it out, and never came online). + assert!(rig.app.join("2.0.0/zeron-engine").exists(), "platform {platform:?}"); } } diff --git a/docs/design/cloud-device.md b/docs/design/cloud-device.md index df22d29af..994867f73 100644 --- a/docs/design/cloud-device.md +++ b/docs/design/cloud-device.md @@ -431,12 +431,12 @@ machine (`ZERON_DEVICE_PLATFORM=cloud`) keeps none of them: going back there is downloads anyway. Other Linux installs keep the newest older one, to go back to by hand. Never `current`, the running executable's folder, or a newer version (an update being staged). -A Cloud machine doesn't keep the release's `zeron-engine` either: it's the desktop app's background -engine (78 MB), and the unit runs `zeron headless`, which links the engine. The installer and the -updater leave it out, and the tidy and the pre-sleep cleanup remove it from versions installed before. -Measured on staging (send to first output, n=8 each), a machine on one version went from a median of -17.5 s to 14.2 s once neither it nor Codex's downloads came back with each wake; its wake downloaded -225 MB, 205 of them the engine it runs. +A Cloud machine keeps the release's `zeron-engine` (78 MB). From 2026-11-07 to 2026-11-15 the +installer, the updater and the tidy left it out, when the unit's `zeron headless` linked the engine; +since 0.3.0 the release's `zeron` is the zgx app, whose `zeron headless` runs that `zeron-engine`, so +a machine without it exited at once and never enrolled. The installer keeps it now, and a repair +(`~/.zeron/repair-engine`, the unit's `ExecStartPre=-`, set up by the installer and every wake) puts +it back before each start if an older updater left it out (edge/src/cloud/install-script.ts). A longer wake reads as updating: the engine says so (`POST /runner/wake-stage`), `CloudSession.stage` is `updating` while it lasts (a stage nobody clears stops showing after 10 minutes), the desktop's diff --git a/edge/src/cloud/install-script.ts b/edge/src/cloud/install-script.ts index eed6fe562..b6c96c15d 100644 --- a/edge/src/cloud/install-script.ts +++ b/edge/src/cloud/install-script.ts @@ -48,6 +48,60 @@ ExecStart=/bin/systemctl start --no-block ${CLOUD_UNIT_NAME} WantedBy=multi-user.target `; +/** + * Puts back the release's `zeron-engine` beside the `zeron` the unit runs, when + * it's missing. Since 0.3.0 the release's `zeron` is the zgx app, whose + * `zeron headless` hands off to that engine: without it the unit exits at + * once, restarts every second and never enrolls. Machines lost it to the + * installer, the engine's own updater and the pre-sleep tidy, which all left + * it out on Cloud (0.3.5's still do), so the unit runs this before every start + * (`ExecStartPre=-`: it never fails a start). Downloads only while it's + * missing, the version `current` names, from the edge's own releases. + */ +export const REPAIR_ENGINE_SCRIPT = `#!/bin/sh +# Zeron Cloud: put back a missing zeron-engine (edge/src/cloud/install-script.ts). +home="\${ZERON_CLOUD_HOME:-$HOME}" +cur="$home/.zeron/app/current" +[ -x "$cur/zeron" ] || exit 0 +[ -f "$cur/zeron-engine" ] && exit 0 +dest="$(readlink -f "$cur")" || exit 0 +ver="$(basename "$dest")" +case "$ver" in + "" | *[!A-Za-z0-9._+-]*) exit 0 ;; +esac +case "$(uname -m)" in + x86_64 | amd64) arch=x86_64 ;; + aarch64 | arm64) arch=aarch64 ;; + *) exit 0 ;; +esac +[ -n "\${ZERON_EDGE_URL:-}" ] || exit 0 +tmp="$(mktemp -d "$home/.zeron/.repair.XXXXXX")" || exit 0 +trap 'rm -rf "$tmp"' EXIT +curl -fsSL --retry 3 --connect-timeout 15 --speed-limit 1048576 --speed-time 15 \\ + -o "$tmp/zeron.tar.gz" "$ZERON_EDGE_URL/releases/zeron-$ver-linux-$arch.tar.gz" || exit 0 +tar -xzf "$tmp/zeron.tar.gz" -C "$tmp" "zeron-$ver-linux-$arch/zeron-engine" || exit 0 +chmod 755 "$tmp/zeron-$ver-linux-$arch/zeron-engine" +mv -f "$tmp/zeron-$ver-linux-$arch/zeron-engine" "$dest/zeron-engine" +echo "zeron cloud: put back zeron-engine for $ver" +`; + +/** + * Writes the repair script (`REPAIR_ENGINE_SCRIPT`) to `~/.zeron/repair-engine` + * and a drop-in running it before the engine's unit starts, each only when it + * differs, reloading systemd only then. Run by the installer and by every + * wake's first command, so machines set up before it get it as they wake. + * Best effort: a failure here never stops what follows. + * `ZERON_CLOUD_HOME` / `ZERON_CLOUD_UNIT_DIR` exist for the unit tier. + */ +export const ENSURE_REPAIR = + `{ h="\${ZERON_CLOUD_HOME:-$HOME}"; r="$h/.zeron/repair-engine"; ` + + `dd="\${ZERON_CLOUD_UNIT_DIR:-/etc/systemd/system}/${CLOUD_UNIT_NAME}.d"; ` + + `t="$(mktemp)" && printf %s '${btoa(REPAIR_ENGINE_SCRIPT)}' | base64 -d >"$t" && ` + + `{ cmp -s "$t" "$r" || install -m 0700 "$t" "$r"; } && ` + + `printf '[Service]\\nExecStartPre=-%s\\n' "$r" >"$t" && ` + + `{ cmp -s "$t" "$dd/repair-engine.conf" || { sudo mkdir -p "$dd" && sudo install -m 0644 "$t" "$dd/repair-engine.conf" && sudo systemctl daemon-reload; }; }; ` + + `rm -f "$t"; } >/dev/null 2>&1 || true`; + export const CLOUD_INSTALL_SCRIPT = `#!/bin/sh # Zeron Cloud engine installer (edge/src/cloud/install-script.ts). # POSIX sh, idempotent, provider-neutral. @@ -85,7 +139,9 @@ esac restart=0 dest="$app/$ver" -if [ -x "$dest/zeron" ]; then +# (Whole, its zeron-engine too: \`zeron headless\` runs it, and installs +# made before 2026-11-15 left it out.) +if [ -x "$dest/zeron" ] && [ -f "$dest/zeron-engine" ]; then echo "zeron $ver already installed" else tmp="$(mktemp -d "$data/.download.XXXXXX")" @@ -99,10 +155,8 @@ else tar -xzf "$tmp/zeron.tar.gz" -C "$tmp/unpacked" --strip-components=1 # Probe before switching: a binary that cannot start must not replace one that can. "$tmp/unpacked/zeron" --version >/dev/null - # The desktop app's background engine (78 MB): never run here (the unit runs - # \`zeron headless\`, which links the engine), and every byte on this disk is - # copied back in on every wake. The engine's updater leaves it out too. - rm -f "$tmp/unpacked/zeron-engine" + # (zeron-engine stays: \`zeron headless\` runs it. Without it the unit + # exits at once and the machine never enrolls.) rm -rf "$dest" mv "$tmp/unpacked" "$dest" fi @@ -172,6 +226,8 @@ else rm -f "$boot_new" fi +# A zeron-engine an update leaves out is put back before each start. +${ENSURE_REPAIR} sudo systemctl daemon-reload sudo systemctl enable ${CLOUD_UNIT_NAME} ${CLOUD_BOOT_UNIT_NAME} >/dev/null sudo systemctl start ${CLOUD_BOOT_UNIT_NAME} @@ -253,6 +309,9 @@ export const RESTART_ENGINE_COMMAND = `sudo systemctl restart ${CLOUD_UNIT_NAME} * systemd hasn't read yet gets one reload. `--no-block` answers at once (the * engine's first token says it's up). Idempotent: a no-op when it's running. */ export const START_ENGINE_COMMAND = + // (First, the repair of a missing zeron-engine before each start, for + // machines set up before it: a no-op once it's there.) + `${ENSURE_REPAIR}; ` + `sudo systemctl start --no-block ${CLOUD_UNIT_NAME} || ` + `{ sudo systemctl daemon-reload; sudo systemctl start --no-block ${CLOUD_UNIT_NAME}; }`; diff --git a/edge/test/unit/install-script.test.ts b/edge/test/unit/install-script.test.ts index b96da8ce3..a4b8420ec 100644 --- a/edge/test/unit/install-script.test.ts +++ b/edge/test/unit/install-script.test.ts @@ -13,6 +13,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { CLOUD_BOOT_UNIT, CLOUD_INSTALL_SCRIPT, + REPAIR_ENGINE_SCRIPT, START_ENGINE_COMMAND, STOP_ENGINE_COMMAND, installCommand, @@ -110,8 +111,15 @@ describe("cloud install script", { timeout: 60_000 }, () => { const data = join(home, ".zeron"); expect(readlinkSync(join(data, "app", "current"))).toBe(join(data, "app", "1.2.3")); expect(existsSync(join(data, "app", "1.2.3", "zeron"))).toBe(true); - // Never run on Cloud, and copied back in on every wake if kept. - expect(existsSync(join(data, "app", "1.2.3", "zeron-engine"))).toBe(false); + // Kept: `zeron headless` runs it (without it the unit exits at once and + // the machine never enrolls). + expect(existsSync(join(data, "app", "1.2.3", "zeron-engine"))).toBe(true); + // And put back before each start, should an update leave it out. + expect(statSync(join(data, "repair-engine")).mode & 0o777).toBe(0o700); + expect(readFileSync(join(data, "repair-engine"), "utf8")).toBe(REPAIR_ENGINE_SCRIPT); + expect(readFileSync(join(units, "zeron-cloud.service.d", "repair-engine.conf"), "utf8")).toBe( + `[Service]\nExecStartPre=-${join(data, "repair-engine")}\n` + ); const envFile = join(data, "env"); expect(statSync(envFile).mode & 0o777).toBe(0o600); expect(readFileSync(envFile, "utf8")).toBe( @@ -159,6 +167,45 @@ describe("cloud install script", { timeout: 60_000 }, () => { expect(calls()).toContain("systemctl restart zeron-cloud.service"); }); + it("downloads again a version installed without its zeron-engine", () => { + const { home, run, calls, clearCalls } = setup(); + run("org.user.cloud-1.codeA"); + const engine = join(home, ".zeron", "app", "1.2.3", "zeron-engine"); + rmSync(engine); + clearCalls(); + run("org.user.cloud-1.codeA"); + expect(existsSync(engine)).toBe(true); + expect(calls().filter((c) => c.includes(".tar.gz"))).toHaveLength(1); + }); + + it("puts back a zeron-engine an update left out, and does nothing once it's there", () => { + const { home, run, calls, clearCalls } = setup(); + run("org.user.cloud-1.codeA"); + const data = join(home, ".zeron"); + const engine = join(data, "app", "1.2.3", "zeron-engine"); + const repair = () => + execFileSync("sh", [join(data, "repair-engine")], { + env: { PATH: `${join(root, "bin")}:/usr/bin:/bin`, ZERON_CLOUD_HOME: home, ZERON_EDGE_URL: "https://edge.test" }, + encoding: "utf8" + }); + rmSync(engine); + clearCalls(); + expect(repair()).toContain("put back zeron-engine for 1.2.3"); + expect(existsSync(engine)).toBe(true); + expect(statSync(engine).mode & 0o111).not.toBe(0); + expect(calls().filter((c) => c.includes("/releases/zeron-1.2.3-linux-x86_64.tar.gz"))).toHaveLength(1); + // There: no download. + clearCalls(); + repair(); + expect(calls().filter((c) => c.startsWith("curl"))).toHaveLength(0); + // A download that fails leaves the start to go on (it never fails it). + rmSync(engine); + writeFileSync(join(root, "bin", "curl"), "#!/bin/sh\nexit 22\n"); + chmodSync(join(root, "bin", "curl"), 0o755); + expect(() => repair()).not.toThrow(); + expect(existsSync(engine)).toBe(false); + }); + it("doesn't wait for the network to start the engine, and starts it on boot without being asked", () => { const { units, run } = setup(); run("org.user.cloud-1.codeA"); @@ -237,9 +284,19 @@ describe("cloud install script", { timeout: 60_000 }, () => { }); it("starts the engine without waiting on it, and reloads once for a unit systemd hasn't read", () => { - const { calls, clearCalls } = setup(); + const { home, units, calls, clearCalls } = setup(); + mkdirSync(join(home, ".zeron"), { recursive: true }); const start = () => - execFileSync("sh", ["-c", START_ENGINE_COMMAND], { env: { PATH: `${join(root, "bin")}:/usr/bin:/bin` }, encoding: "utf8" }); + execFileSync("sh", ["-c", START_ENGINE_COMMAND], { + env: { PATH: `${join(root, "bin")}:/usr/bin:/bin`, ZERON_CLOUD_HOME: home, ZERON_CLOUD_UNIT_DIR: units }, + encoding: "utf8" + }); + // A machine set up before the repair: its first wake writes it, once. + clearCalls(); + start(); + expect(calls()).toEqual(["systemctl daemon-reload", "systemctl start --no-block zeron-cloud.service"]); + expect(readFileSync(join(home, ".zeron", "repair-engine"), "utf8")).toBe(REPAIR_ENGINE_SCRIPT); + expect(readFileSync(join(units, "zeron-cloud.service.d", "repair-engine.conf"), "utf8")).toContain("ExecStartPre=-"); clearCalls(); start(); expect(calls()).toEqual(["systemctl start --no-block zeron-cloud.service"]);