Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(desktop): add the desktop pet window, shortcut, and Show in pet (#2384)
Max8cd7f750fb3c
diff --git a/desktop/Cargo.lock b/desktop/Cargo.lockindex 772e21614..b48dfe0b6 100644--- a/desktop/Cargo.lock+++ b/desktop/Cargo.lock@@ -255,6 +255,7 @@ dependencies = ["tauri-plugin-autostart","tauri-plugin-deep-link","tauri-plugin-dialog",+ "tauri-plugin-global-shortcut","tauri-plugin-notification","tauri-plugin-opener","tauri-plugin-single-instance",@@ -1365,6 +1366,16 @@ dependencies = ["version_check",]+[[package]]+name = "gethostname"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"+dependencies = [+ "rustix",+ "windows-link 0.2.1",+]+[[package]]name = "getrandom"version = "0.2.17"@@ -1488,6 +1499,24 @@ version = "0.3.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"+[[package]]+name = "global-hotkey"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8c386b0a4a70cb2d39fffd74480f985b6f0bfbcb934b6a6b6b7e630e448f242e"+dependencies = [+ "crossbeam-channel",+ "keyboard-types",+ "objc2",+ "objc2-app-kit",+ "once_cell",+ "serde",+ "thiserror 2.0.19",+ "windows-sys 0.59.0",+ "x11rb",+ "xkeysym",+]+[[package]]name = "gobject-sys"version = "0.18.0"@@ -2865,7 +2894,7 @@ dependencies = ["once_cell","socket2","tracing",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -3974,6 +4003,21 @@ dependencies = ["url",]+[[package]]+name = "tauri-plugin-global-shortcut"+version = "2.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4dd9f4c5136c09cd962da0c86dc4accd4666db2ea591cf16e6597435843bd2b"+dependencies = [+ "global-hotkey",+ "log",+ "serde",+ "serde_json",+ "tauri",+ "tauri-plugin",+ "thiserror 2.0.19",+]+[[package]]name = "tauri-plugin-notification"version = "2.4.0"@@ -5501,6 +5545,23 @@ dependencies = ["pkg-config",]+[[package]]+name = "x11rb"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"+dependencies = [+ "gethostname",+ "rustix",+ "x11rb-protocol",+]++[[package]]+name = "x11rb-protocol"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"+[[package]]name = "xattr"version = "1.6.1"@@ -5511,6 +5572,12 @@ dependencies = ["rustix",]+[[package]]+name = "xkeysym"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"+[[package]]name = "yoke"version = "0.8.3"diff --git a/desktop/README.md b/desktop/README.mdindex a4bfcf4e2..1aefcbee5 100644--- a/desktop/README.md+++ b/desktop/README.md@@ -414,6 +414,45 @@ is also why the Workbench's own `navigator.setAppBadge` call, which only browserand PWAs implement, is not relied on here. Windows has no badge count in Tauri;a taskbar overlay icon is follow-up work.+## Desktop pet++The pet is a small always-on-top window that shows one session: its latest+exchange, live activity, and a composer. It is off by default.++- **Tray.** "Show Pet" turns it on and off. "Pet Shortcut" picks the summon+ shortcut from three presets: `Control+Alt+Space` (the default),+ `Control+Shift+Space` and `Alt+Shift+Space`. A preset the OS refuses (often+ because another app holds it) is shown in that submenu instead of failing+ silently. On macOS the default can collide with "Select next source in Input+ menu"; pick another preset if it does.+- **Summoning.** The shortcut registers only while the pet is on, and only its+ press wakes the pet, with the composer focused. The tray switch and the+ Workbench's "Show in pet" bring it forward without focusing input. Closing+ the window only hides it.+- **Lifecycle.** The window exists exactly when the pet is on and the shell+ has handed the Workbench to a ready Runtime. It loads `/pet` from that+ Runtime's origin and is destroyed when the Runtime stops, is lost, or+ changes origin. It may navigate only to `/pet` on that origin and never+ opens a second window.+- **`pet.json`** sits next to `notifications.json` in the app's local data+ directory: `{ "version": 1, "enabled", "shortcut", "anchor": { "x", "y",+ "monitor" }, "binding" }`, every field but `version` optional. `anchor` is+ where the user last dragged the pet, in points (on Windows and Linux, at the+ primary display's scale), and is clamped back onto a connected display on+ the next start. `binding` is the shown session id. A file the shell cannot read, or with another `version`, keeps the pet+ off for that run and is never overwritten by a drag or a binding; turning+ the pet on from the tray replaces it.++The page reaches the shell through five commands, declared in `build.rs`:+`pet_ready`, `pet_set_expanded`, `pet_bind`, `pet_unbind` and `pet_open`.+`capabilities/pet.json` grants them, plus `start_dragging`, to the `pet`+window for literal-loopback pages only; each command also checks that its+caller is the pet window on its own `/pet` page. `capabilities/main-pet-bind.json`+grants only `pet_bind` to the Workbench, for "Show in pet", which the shell+offers through the top-level `__AVIBE_DESKTOP_PET__` marker. The shell talks+back with two DOM events, `avibe:pet-summon` and `avibe:pet-bound`, so the+pet has no event permission. `ui/src/pet/petBridge.ts` is the page contract.+## MicrophoneWorkbench voice input records through `getUserMedia` inside the WebView. Ondiff --git a/desktop/runtime-host/src/lib.rs b/desktop/runtime-host/src/lib.rsindex 983e417ad..cdff95ce3 100644--- a/desktop/runtime-host/src/lib.rs+++ b/desktop/runtime-host/src/lib.rs@@ -29,6 +29,7 @@ pub mod launcher;pub mod login_path;pub mod notifications;pub mod origin;+pub mod pet;pub mod private_runtime;pub mod status;pub mod window_frame;diff --git a/desktop/runtime-host/src/pet.rs b/desktop/runtime-host/src/pet.rsnew file mode 100644index 000000000..80369a835--- /dev/null+++ b/desktop/runtime-host/src/pet.rs@@ -0,0 +1,1031 @@+//! The desktop pet's decisions that need no window: its durable preferences+//! (`pet.json`), the session binding and its revision, summon delivery around+//! page readiness, and where the window goes when the panel opens.+//!+//! The shell (`src-tauri/src/pet.rs`) owns the window and calls in here. See+//! `docs/plans/2026-10-01-desktop-pet.md`.++use std::path::{Path, PathBuf};++use serde::{Deserialize, Serialize};++use crate::deep_link::parse_deep_link;++/// The only `pet.json` shape this build reads or writes.+pub const PREFERENCES_VERSION: u64 = 1;++/// Whether the pet is on when the user never chose. Off while the pet has no+/// voice; the voice build turns it on, and an explicit choice always wins.+pub const DEFAULT_ENABLED: bool = false;++/// `⌃⌥Space` on macOS, `Ctrl+Alt+Space` on Windows.+pub const DEFAULT_SHORTCUT: &str = "Control+Alt+Space";++/// The shortcuts the tray offers. `pet.json` may name any other accelerator.+pub const SHORTCUT_PRESETS: [&str; 3] = [DEFAULT_SHORTCUT, "Control+Shift+Space", "Alt+Shift+Space"];++/// Why the pet was summoned. Only the hotkey asks to listen; every display or+/// navigation path shows.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum PetIntent {+ Listen,+ Show,+}++/// The pet image's top-left corner in logical screen coordinates, and the+/// display it was on. The window frame is derived from it.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct PetAnchor {+ pub x: f64,+ pub y: f64,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub monitor: Option<String>,+}++/// Everything durable about the pet. `enabled` is written only by the tray+/// switch, so saving an anchor or a binding never freezes the build default.+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+pub struct PetPreferences {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub enabled: Option<bool>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub shortcut: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub anchor: Option<PetAnchor>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub binding: Option<String>,+}++#[derive(Serialize)]+struct PreferencesFile<'a> {+ version: u64,+ #[serde(flatten)]+ preferences: &'a PetPreferences,+}++#[derive(Debug, PartialEq)]+pub enum PreferencesLoad {+ /// No file: the build defaults apply.+ Absent,+ Loaded(PetPreferences),+ /// Present but unreadable, malformed, or another version's shape.+ Unusable,+}++pub fn load_preferences(path: &Path) -> PreferencesLoad {+ let bytes = match std::fs::read(path) {+ Ok(bytes) => bytes,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return PreferencesLoad::Absent,+ Err(_) => return PreferencesLoad::Unusable,+ };+ let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes) else {+ return PreferencesLoad::Unusable;+ };+ if value.get("version").and_then(serde_json::Value::as_u64) != Some(PREFERENCES_VERSION) {+ return PreferencesLoad::Unusable;+ }+ match serde_json::from_value::<PetPreferences>(value) {+ Ok(mut preferences) => {+ // A binding is only ever a session id; anything else names nothing.+ preferences.binding = preferences.binding.filter(|binding| valid_session_id(binding));+ PreferencesLoad::Loaded(preferences)+ }+ Err(_) => PreferencesLoad::Unusable,+ }+}++fn write_preferences(path: &Path, preferences: &PetPreferences) -> std::io::Result<()> {+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent)?;+ }+ let bytes = serde_json::to_vec_pretty(&PreferencesFile {+ version: PREFERENCES_VERSION,+ preferences,+ })?;+ let temporary = path.with_extension("tmp");+ let result = std::fs::write(&temporary, bytes).and_then(|()| std::fs::rename(&temporary, path));+ if result.is_err() {+ let _ = std::fs::remove_file(&temporary);+ }+ result+}++/// A session id the pet may be bound to: exactly what a session deep link accepts.+pub fn valid_session_id(session_id: &str) -> bool {+ parse_deep_link(&format!("avibe://session/{session_id}")).is_some()+}++/// The binding as the shell reports it. `revision` rises by one on every+/// change, so the page can order reports that cross.+#[derive(Clone, Debug, PartialEq, Eq, Serialize)]+pub struct PetBinding {+ pub binding: Option<String>,+ pub revision: u64,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]+pub struct PendingSummon {+ pub intent: PetIntent,+}++/// The answer to `pet_ready()`.+#[derive(Clone, Debug, PartialEq, Eq, Serialize)]+pub struct PetReady {+ #[serde(flatten)]+ pub binding: PetBinding,+ pub summon_pending: Option<PendingSummon>,+}++/// The pet's preferences and in-run state, one per shell.+pub struct PetStore {+ path: PathBuf,+ preferences: PetPreferences,+ /// False after a present file could not be used. The pet stays off and the+ /// file is left as it is, so a newer build's state and an opt-out both+ /// survive, until the tray switch writes a fresh version-1 file.+ trusted: bool,+ revision: u64,+ page_ready: bool,+ pending_summon: Option<PetIntent>,+}++impl PetStore {+ pub fn load(path: PathBuf) -> Self {+ let (preferences, trusted) = match load_preferences(&path) {+ PreferencesLoad::Absent => (PetPreferences::default(), true),+ PreferencesLoad::Loaded(preferences) => (preferences, true),+ PreferencesLoad::Unusable => {+ eprintln!(+ "The desktop pet is off for this run: its preferences file could not be read. \+ Turning the pet on from the tray replaces it."+ );+ (PetPreferences::default(), false)+ }+ };+ Self {+ path,+ preferences,+ trusted,+ revision: 0,+ page_ready: false,+ pending_summon: None,+ }+ }++ pub fn enabled(&self) -> bool {+ self.trusted && self.preferences.enabled.unwrap_or(DEFAULT_ENABLED)+ }++ /// The tray switch: the one writer of `enabled`, and the recovery for an+ /// unusable file. A failed write changes nothing.+ pub fn set_enabled(&mut self, enabled: bool) -> std::io::Result<()> {+ let next = PetPreferences {+ enabled: Some(enabled),+ ..self.preferences.clone()+ };+ write_preferences(&self.path, &next)?;+ self.preferences = next;+ self.trusted = true;+ Ok(())+ }++ pub fn shortcut(&self) -> &str {+ self.preferences.shortcut.as_deref().unwrap_or(DEFAULT_SHORTCUT)+ }++ pub fn set_shortcut(&mut self, shortcut: &str) {+ if self.shortcut() == shortcut {+ return;+ }+ self.preferences.shortcut = Some(shortcut.to_owned());+ self.persist();+ }++ pub fn anchor(&self) -> Option<&PetAnchor> {+ self.preferences.anchor.as_ref()+ }++ pub fn set_anchor(&mut self, anchor: PetAnchor) {+ if self.preferences.anchor.as_ref() == Some(&anchor) {+ return;+ }+ self.preferences.anchor = Some(anchor);+ self.persist();+ }++ pub fn binding(&self) -> PetBinding {+ PetBinding {+ binding: self.preferences.binding.clone(),+ revision: self.revision,+ }+ }++ /// Binds `session_id`. The caller has checked it with [`valid_session_id`].+ pub fn bind(&mut self, session_id: &str) -> PetBinding {+ if self.preferences.binding.as_deref() != Some(session_id) {+ self.preferences.binding = Some(session_id.to_owned());+ self.revision += 1;+ self.persist();+ }+ self.binding()+ }++ /// Clears the binding only if it is still `session_id`, so a late result+ /// about an old session can never clear a newer one.+ pub fn unbind(&mut self, session_id: &str) -> PetBinding {+ if self.preferences.binding.as_deref() == Some(session_id) {+ self.preferences.binding = None;+ self.revision += 1;+ self.persist();+ }+ self.binding()+ }++ /// A new document is loading in the pet window: summons wait for its+ /// `pet_ready()`. A summon already waiting is kept for it.+ pub fn page_loading(&mut self) {+ self.page_ready = false;+ }++ /// The window is gone; nothing is waiting for it.+ pub fn window_gone(&mut self) {+ self.page_ready = false;+ self.pending_summon = None;+ }++ pub fn page_is_ready(&self) -> bool {+ self.page_ready+ }++ /// The page has its listeners installed. Returns the binding and consumes+ /// any summon that arrived before.+ pub fn page_ready(&mut self) -> PetReady {+ self.page_ready = true;+ PetReady {+ binding: self.binding(),+ summon_pending: self.pending_summon.take().map(|intent| PendingSummon { intent }),+ }+ }++ /// Returns the intent to deliver now, or keeps it for `pet_ready()`. A+ /// later summon replaces a waiting one.+ pub fn summon(&mut self, intent: PetIntent) -> Option<PetIntent> {+ if self.page_ready {+ return Some(intent);+ }+ self.pending_summon = Some(intent);+ None+ }++ /// A summon while no window can exist yet, because the Workbench has no+ /// Runtime. It waits for the next page as `show`: the pet comes up with+ /// its composer focused once a Runtime is ready, but a key pressed during+ /// startup never opens the microphone long after.+ pub fn summon_before_window(&mut self) {+ self.page_ready = false;+ self.pending_summon = Some(PetIntent::Show);+ }++ fn persist(&self) {+ if !self.trusted {+ return;+ }+ if write_preferences(&self.path, &self.preferences).is_err() {+ eprintln!("The desktop pet preferences could not be saved; this run keeps them in memory.");+ }+ }+}++/// A rectangle in logical screen coordinates.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct LogicalRect {+ pub x: f64,+ pub y: f64,+ pub width: f64,+ pub height: f64,+}++impl LogicalRect {+ fn right(&self) -> f64 {+ self.x + self.width+ }++ fn bottom(&self) -> f64 {+ self.y + self.height+ }++ fn contains(&self, other: &LogicalRect) -> bool {+ other.x >= self.x && other.y >= self.y && other.right() <= self.right() && other.bottom() <= self.bottom()+ }++ fn overlap(&self, other: &LogicalRect) -> f64 {+ let width = self.right().min(other.right()) - self.x.max(other.x);+ let height = self.bottom().min(other.bottom()) - self.y.max(other.y);+ if width > 0.0 && height > 0.0 {+ width * height+ } else {+ 0.0+ }+ }+}++/// A display's work area and the name the shell knows it by, in the space the+/// anchor is stored in. `unit` is how long one of the display's own points is+/// in that space: the pet is `PET_SIZE` points on whichever display shows it,+/// so its extent there is `PET_SIZE * unit`.+#[derive(Clone, Debug, PartialEq)]+pub struct WorkArea {+ pub name: Option<String>,+ pub area: LogicalRect,+ pub unit: f64,+}++impl WorkArea {+ fn pet_extent(&self) -> f64 {+ PET_SIZE * self.unit+ }++ fn pet_at(&self, anchor: (f64, f64)) -> LogicalRect {+ LogicalRect {+ x: anchor.0,+ y: anchor.1,+ width: self.pet_extent(),+ height: self.pet_extent(),+ }+ }+}++// These match the `/pet` route's layout: an 88 px avatar inside `p-2`, a+// 320 px panel, and `gap-2` between them (`ui/src/pet/`).+pub const PET_SIZE: f64 = 88.0;+const PADDING: f64 = 8.0;+const GAP: f64 = 8.0;+const PANEL_WIDTH: f64 = 320.0;+const EXPANDED_HEIGHT: f64 = 480.0;+/// Distance from the work area's corner for a pet with no saved place.+const DEFAULT_MARGIN: f64 = 24.0;++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]+#[serde(rename_all = "lowercase")]+pub enum PanelSide {+ Left,+ Right,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]+#[serde(rename_all = "lowercase")]+pub enum PanelEdge {+ Top,+ Bottom,+}++/// Where the panel sits relative to the pet, shared by the native frame and+/// the page. `edge: bottom` aligns the panel's bottom with the pet's, so the+/// panel grows upward.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]+pub struct PetLayout {+ pub panel_side: PanelSide,+ pub panel_edge: PanelEdge,+}++impl Default for PetLayout {+ fn default() -> Self {+ Self {+ panel_side: PanelSide::Left,+ panel_edge: PanelEdge::Bottom,+ }+ }+}++pub fn window_size(expanded: bool) -> (f64, f64) {+ if expanded {+ (PADDING + PANEL_WIDTH + GAP + PET_SIZE + PADDING, EXPANDED_HEIGHT)+ } else {+ (PET_SIZE + 2.0 * PADDING, PET_SIZE + 2.0 * PADDING)+ }+}++/// Where the pet image sits inside the window.+pub fn pet_offset(expanded: bool, layout: PetLayout) -> (f64, f64) {+ if !expanded {+ return (PADDING, PADDING);+ }+ let (width, height) = window_size(true);+ let x = match layout.panel_side {+ PanelSide::Left => width - PADDING - PET_SIZE,+ PanelSide::Right => PADDING,+ };+ let y = match layout.panel_edge {+ PanelEdge::Bottom => height - PADDING - PET_SIZE,+ PanelEdge::Top => PADDING,+ };+ (x, y)+}++pub fn window_origin(anchor: (f64, f64), expanded: bool, layout: PetLayout) -> (f64, f64) {+ let (dx, dy) = pet_offset(expanded, layout);+ (anchor.0 - dx, anchor.1 - dy)+}++pub fn anchor_from_window(origin: (f64, f64), expanded: bool, layout: PetLayout) -> (f64, f64) {+ let (dx, dy) = pet_offset(expanded, layout);+ (origin.0 + dx, origin.1 + dy)+}++/// Moves a point between two views of one physical desktop, each that desktop+/// divided by a scale. The pet window's own scale changes as it crosses+/// displays, so a saved anchor uses one fixed scale that the next restore+/// shares; scale 1 is the physical desktop itself.+pub fn rescale(point: (f64, f64), from_scale: f64, to_scale: f64) -> (f64, f64) {+ let factor = from_scale / to_scale;+ (point.0 * factor, point.1 * factor)+}++/// Opens the panel toward the room it has: left and above by default, flipped+/// near the left or top edge, and toward the larger room when neither fits.+pub fn choose_layout(anchor: (f64, f64), work_area: LogicalRect) -> PetLayout {+ let (width, height) = window_size(true);+ let fits = |start: f64, end: f64, low: f64, high: f64| (start - low, high - end);+ let left = PetLayout {+ panel_side: PanelSide::Left,+ panel_edge: PanelEdge::Bottom,+ };+ let right = PetLayout {+ panel_side: PanelSide::Right,+ panel_edge: PanelEdge::Top,+ };+ let left_x = window_origin(anchor, true, left).0;+ let right_x = window_origin(anchor, true, right).0;+ let (room_left, _) = fits(left_x, left_x + width, work_area.x, work_area.right());+ let (_, room_right) = fits(right_x, right_x + width, work_area.x, work_area.right());+ let panel_side = if room_left >= 0.0 || room_left >= room_right {+ PanelSide::Left+ } else {+ PanelSide::Right+ };+ let above_y = window_origin(anchor, true, left).1;+ let below_y = window_origin(anchor, true, right).1;+ let (room_above, _) = fits(above_y, above_y + height, work_area.y, work_area.bottom());+ let (_, room_below) = fits(below_y, below_y + height, work_area.y, work_area.bottom());+ let panel_edge = if room_above >= 0.0 || room_above >= room_below {+ PanelEdge::Bottom+ } else {+ PanelEdge::Top+ };+ PetLayout { panel_side, panel_edge }+}++/// The place for a pet that has none: the work area's bottom-right corner.+pub fn default_anchor(work_area: &WorkArea) -> PetAnchor {+ let inset = (PET_SIZE + DEFAULT_MARGIN) * work_area.unit;+ PetAnchor {+ x: work_area.area.right() - inset,+ y: work_area.area.bottom() - inset,+ monitor: work_area.name.clone(),+ }+}++/// The display the pet's centre is on, else the first one (the primary).+pub fn area_for(areas: &[WorkArea], anchor: (f64, f64)) -> Option<&WorkArea> {+ areas+ .iter()+ .find(|area| {+ let half = area.pet_extent() / 2.0;+ let center = (anchor.0 + half, anchor.1 + half);+ center.0 >= area.area.x+ && center.0 < area.area.right()+ && center.1 >= area.area.y+ && center.1 < area.area.bottom()+ })+ .or_else(|| areas.first())+}++/// Where a collapsed pet window starts so the pet sits on `anchor`, on a+/// display whose points are `unit` long in the anchor's space.+pub fn restored_window_origin(anchor: (f64, f64), unit: f64) -> (f64, f64) {+ let (dx, dy) = pet_offset(false, PetLayout::default());+ (anchor.0 - dx * unit, anchor.1 - dy * unit)+}++/// Keeps a restored pet whole on a connected display. A pet already inside a+/// work area stays exactly where it was. Otherwise it moves into the area it+/// overlaps most; with no overlap, into its own display if that is still+/// connected, else the first area (the primary display).+pub fn clamp_anchor(anchor: &PetAnchor, work_areas: &[WorkArea]) -> PetAnchor {+ let at = (anchor.x, anchor.y);+ let usable: Vec<&WorkArea> = work_areas+ .iter()+ .filter(|area| area.area.width >= area.pet_extent() && area.area.height >= area.pet_extent())+ .collect();+ if let Some(home) = usable.iter().find(|area| area.area.contains(&area.pet_at(at))) {+ return PetAnchor {+ monitor: home.name.clone().or_else(|| anchor.monitor.clone()),+ ..anchor.clone()+ };+ }+ let overlapping = usable+ .iter()+ .map(|area| (area.area.overlap(&area.pet_at(at)), *area))+ .filter(|(overlap, _)| *overlap > 0.0)+ .max_by(|a, b| a.0.total_cmp(&b.0))+ .map(|(_, area)| area);+ let named = || {+ usable+ .iter()+ .find(|area| area.name.is_some() && area.name == anchor.monitor)+ .copied()+ };+ let Some(target) = overlapping.or_else(named).or_else(|| usable.first().copied()) else {+ return anchor.clone();+ };+ PetAnchor {+ x: anchor.x.clamp(target.area.x, target.area.right() - target.pet_extent()),+ y: anchor+ .y+ .clamp(target.area.y, target.area.bottom() - target.pet_extent()),+ monitor: target.name.clone(),+ }+}++/// How the platform writes `accelerator` in its menus: `⌃⌥Space` on macOS,+/// `Ctrl+Alt+Space` elsewhere.+pub fn shortcut_label(accelerator: &str, macos: bool) -> String {+ let parts: Vec<String> = accelerator+ .split('+')+ .map(|part| {+ let lowered = part.trim().to_ascii_lowercase();+ let (mac, other) = match lowered.as_str() {+ "control" | "ctrl" => ("⌃", "Ctrl"),+ "alt" | "option" => ("⌥", "Alt"),+ "shift" => ("⇧", "Shift"),+ "super" | "command" | "cmd" | "meta" => ("⌘", "Win"),+ "cmdorctrl" | "commandorcontrol" | "cmdorcontrol" | "commandorctrl" => ("⌘", "Ctrl"),+ _ => {+ let key = part.trim();+ let key = key+ .strip_prefix("Key")+ .or_else(|| key.strip_prefix("Digit"))+ .unwrap_or(key);+ return key.to_owned();+ }+ };+ (if macos { mac } else { other }).to_owned()+ })+ .collect();+ parts.join(if macos { "" } else { "+" })+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::sync::atomic::{AtomicU64, Ordering};++ struct TestDirectory(PathBuf);++ impl TestDirectory {+ fn new() -> Self {+ static NEXT: AtomicU64 = AtomicU64::new(0);+ let directory = std::env::temp_dir().join(format!(+ "avibe-pet-preferences-{}-{}",+ std::process::id(),+ NEXT.fetch_add(1, Ordering::SeqCst)+ ));+ std::fs::create_dir(&directory).unwrap();+ Self(directory)+ }++ fn file(&self) -> PathBuf {+ self.0.join("pet.json")+ }+ }++ impl Drop for TestDirectory {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.0);+ }+ }++ fn area(name: &str, x: f64, y: f64, width: f64, height: f64) -> WorkArea {+ WorkArea {+ name: Some(name.to_owned()),+ area: LogicalRect { x, y, width, height },+ unit: 1.0,+ }+ }++ #[test]+ fn an_absent_file_or_absent_enabled_follows_the_build_default() {+ let directory = TestDirectory::new();+ assert_eq!(load_preferences(&directory.file()), PreferencesLoad::Absent);+ assert_eq!(PetStore::load(directory.file()).enabled(), DEFAULT_ENABLED);+ assert!(!directory.file().exists(), "loading never writes");++ std::fs::write(directory.file(), r#"{"version":1,"binding":"s1"}"#).unwrap();+ let store = PetStore::load(directory.file());+ assert_eq!(store.enabled(), DEFAULT_ENABLED);+ assert_eq!(store.binding().binding.as_deref(), Some("s1"));+ }++ #[test]+ fn an_explicit_choice_survives_the_default_and_other_writes() {+ let directory = TestDirectory::new();+ std::fs::write(directory.file(), r#"{"version":1,"enabled":false}"#).unwrap();+ let mut store = PetStore::load(directory.file());+ assert!(!store.enabled());+ store.bind("s1");+ store.set_anchor(PetAnchor {+ x: 10.0,+ y: 20.0,+ monitor: None,+ });+ assert_eq!(+ load_preferences(&directory.file()),+ PreferencesLoad::Loaded(PetPreferences {+ enabled: Some(false),+ shortcut: None,+ anchor: Some(PetAnchor {+ x: 10.0,+ y: 20.0,+ monitor: None+ }),+ binding: Some("s1".into()),+ })+ );++ // A user who never touched the switch carries no `enabled`, so the+ // build default decides for them.+ let fresh = TestDirectory::new();+ let mut store = PetStore::load(fresh.file());+ store.bind("s2");+ let written = std::fs::read_to_string(fresh.file()).unwrap();+ assert!(!written.contains("enabled"), "{written}");+ assert!(written.contains("\"version\": 1"), "{written}");+ }++ #[test]+ fn an_unreadable_or_unknown_version_file_fails_closed_and_is_left_untouched() {+ for content in [+ "not json",+ r#"{"version":2,"enabled":true}"#,+ r#"{"enabled":true}"#,+ r#"{"version":1,"enabled":"yes"}"#,+ ] {+ let directory = TestDirectory::new();+ std::fs::write(directory.file(), content).unwrap();+ let mut store = PetStore::load(directory.file());+ assert!(!store.enabled(), "{content}");+ store.bind("s1");+ store.set_shortcut("Alt+Shift+Space");+ store.set_anchor(PetAnchor {+ x: 1.0,+ y: 2.0,+ monitor: None,+ });+ assert_eq!(std::fs::read_to_string(directory.file()).unwrap(), content);+ // This run still uses what the user chose.+ assert_eq!(store.binding().binding.as_deref(), Some("s1"));+ assert_eq!(store.shortcut(), "Alt+Shift+Space");++ // The tray switch is the recovery: a fresh version-1 file.+ store.set_enabled(true).unwrap();+ assert!(store.enabled());+ let PreferencesLoad::Loaded(written) = load_preferences(&directory.file()) else {+ panic!("the switch writes a readable file");+ };+ assert_eq!(written.enabled, Some(true));+ assert_eq!(written.binding.as_deref(), Some("s1"));+ }+ }++ #[test]+ fn a_failed_switch_write_changes_nothing() {+ let directory = TestDirectory::new();+ let mut store = PetStore::load(directory.file());+ std::fs::create_dir(directory.file()).unwrap();+ assert!(store.set_enabled(true).is_err());+ assert_eq!(store.enabled(), DEFAULT_ENABLED);+ assert!(!directory.file().with_extension("tmp").exists());+ }++ #[test]+ fn an_invalid_saved_binding_is_dropped() {+ let directory = TestDirectory::new();+ std::fs::write(directory.file(), r#"{"version":1,"binding":"../etc"}"#).unwrap();+ assert_eq!(PetStore::load(directory.file()).binding().binding, None);+ assert!(valid_session_id("abc_123-x.y"));+ for invalid in ["", "..", "a/b", "a?b", &"x".repeat(129)] {+ assert!(!valid_session_id(invalid), "{invalid}");+ }+ }++ #[test]+ fn every_binding_change_raises_the_revision_by_one_and_unbind_compares() {+ let directory = TestDirectory::new();+ let mut store = PetStore::load(directory.file());+ assert_eq!(+ store.binding(),+ PetBinding {+ binding: None,+ revision: 0+ }+ );+ assert_eq!(store.bind("a").revision, 1);+ assert_eq!(store.bind("a").revision, 1, "binding the same session is not a change");+ assert_eq!(+ store.bind("b"),+ PetBinding {+ binding: Some("b".into()),+ revision: 2+ }+ );+ assert_eq!(+ store.unbind("a"),+ PetBinding {+ binding: Some("b".into()),+ revision: 2+ },+ "a late clear about an old session keeps the newer binding"+ );+ assert_eq!(+ store.unbind("b"),+ PetBinding {+ binding: None,+ revision: 3+ }+ );+ assert_eq!(store.page_ready().binding.revision, 3);+ // The binding is the shell's, not the Runtime origin's: it survives a restart.+ store.bind("c");+ let restarted = PetStore::load(directory.file());+ assert_eq!(restarted.binding().binding.as_deref(), Some("c"));+ }++ #[test]+ fn a_summon_before_the_page_is_ready_waits_and_keeps_its_intent() {+ let directory = TestDirectory::new();+ let mut store = PetStore::load(directory.file());+ store.page_loading();+ assert_eq!(store.summon(PetIntent::Show), None);+ assert_eq!(+ store.summon(PetIntent::Listen),+ None,+ "a later summon replaces a waiting one"+ );+ // A reload while it waits keeps it for the next document.+ store.page_loading();+ let ready = store.page_ready();+ assert_eq!(+ ready.summon_pending,+ Some(PendingSummon {+ intent: PetIntent::Listen+ })+ );+ assert_eq!(store.page_ready().summon_pending, None, "delivered once");+ assert_eq!(+ store.summon(PetIntent::Show),+ Some(PetIntent::Show),+ "a ready page gets it at once"+ );+ assert_eq!(store.page_ready().summon_pending, None);++ store.page_loading();+ store.summon(PetIntent::Show);+ store.window_gone();+ assert_eq!(+ store.page_ready().summon_pending,+ None,+ "a destroyed window takes nothing with it"+ );+ }++ #[test]+ fn pet_ready_serializes_to_the_page_contract() {+ let ready = PetReady {+ binding: PetBinding {+ binding: Some("s".into()),+ revision: 4,+ },+ summon_pending: Some(PendingSummon {+ intent: PetIntent::Listen,+ }),+ };+ assert_eq!(+ serde_json::to_value(ready).unwrap(),+ serde_json::json!({"binding": "s", "revision": 4, "summon_pending": {"intent": "listen"}})+ );+ assert_eq!(+ serde_json::to_value(PetLayout::default()).unwrap(),+ serde_json::json!({"panel_side": "left", "panel_edge": "bottom"})+ );+ }++ #[test]+ fn the_anchor_is_the_pet_image_whichever_way_the_panel_opened() {+ let anchor = (1000.0, 700.0);+ for expanded in [false, true] {+ for panel_side in [PanelSide::Left, PanelSide::Right] {+ for panel_edge in [PanelEdge::Top, PanelEdge::Bottom] {+ let layout = PetLayout { panel_side, panel_edge };+ let origin = window_origin(anchor, expanded, layout);+ assert_eq!(anchor_from_window(origin, expanded, layout), anchor);+ let (width, height) = window_size(expanded);+ let (dx, dy) = pet_offset(expanded, layout);+ assert!(dx >= 0.0 && dx + PET_SIZE <= width && dy >= 0.0 && dy + PET_SIZE <= height);+ }+ }+ }+ // The panel opening to the left moves the window's origin, never the pet.+ let left = window_origin(anchor, true, PetLayout::default());+ assert!(left.0 < anchor.0 - 300.0);+ }++ #[test]+ fn the_panel_flips_toward_the_room_near_each_screen_edge() {+ let screen = LogicalRect {+ x: 0.0,+ y: 25.0,+ width: 1440.0,+ height: 875.0,+ };+ let cases = [+ ((1300.0, 780.0), PanelSide::Left, PanelEdge::Bottom),+ ((20.0, 780.0), PanelSide::Right, PanelEdge::Bottom),+ ((1300.0, 40.0), PanelSide::Left, PanelEdge::Top),+ ((20.0, 40.0), PanelSide::Right, PanelEdge::Top),+ ((700.0, 450.0), PanelSide::Left, PanelEdge::Bottom),+ ];+ for (anchor, side, edge) in cases {+ let layout = choose_layout(anchor, screen);+ assert_eq!((layout.panel_side, layout.panel_edge), (side, edge), "{anchor:?}");+ let origin = window_origin(anchor, true, layout);+ let (width, height) = window_size(true);+ assert!(origin.0 >= screen.x && origin.0 + width <= screen.right(), "{anchor:?}");+ assert!(+ origin.1 >= screen.y && origin.1 + height <= screen.bottom(),+ "{anchor:?}"+ );+ }+ // A screen too small for the panel either way opens toward the larger room.+ let tiny = LogicalRect {+ x: 0.0,+ y: 0.0,+ width: 400.0,+ height: 400.0,+ };+ assert_eq!(choose_layout((300.0, 300.0), tiny).panel_side, PanelSide::Left);+ assert_eq!(choose_layout((10.0, 10.0), tiny).panel_side, PanelSide::Right);+ }++ #[test]+ fn a_restore_keeps_a_visible_pet_and_clamps_one_whose_display_is_gone() {+ let areas = [+ area("Built-in", 0.0, 25.0, 1440.0, 875.0),+ area("External", 1440.0, 0.0, 1920.0, 1055.0),+ ];+ let on_external = PetAnchor {+ x: 3000.0,+ y: 900.0,+ monitor: Some("External".into()),+ };+ assert_eq!(clamp_anchor(&on_external, &areas), on_external);++ // The external display is unplugged: the pet lands whole on the built-in one.+ let clamped = clamp_anchor(&on_external, &areas[..1]);+ assert_eq!((clamped.x, clamped.y), (1440.0 - PET_SIZE, 900.0 - PET_SIZE));+ assert_eq!(clamped.monitor.as_deref(), Some("Built-in"));++ // Half off an edge: pulled in on the display it overlaps.+ let straddling = PetAnchor {+ x: -40.0,+ y: 400.0,+ monitor: None,+ };+ let pulled = clamp_anchor(&straddling, &areas);+ assert_eq!((pulled.x, pulled.y), (0.0, 400.0));++ // With no overlap, its own display wins over the primary one.+ let lost = PetAnchor {+ x: 9000.0,+ y: 9000.0,+ monitor: Some("External".into()),+ };+ let home = clamp_anchor(&lost, &areas);+ assert_eq!(home.monitor.as_deref(), Some("External"));+ assert_eq!((home.x, home.y), (1440.0 + 1920.0 - PET_SIZE, 1055.0 - PET_SIZE));++ assert_eq!(clamp_anchor(&lost, &[]), lost, "no display information moves nothing");++ let corner = default_anchor(&areas[0]);+ assert_eq!(clamp_anchor(&corner, &areas), corner);+ }++ #[test]+ fn a_summon_before_any_runtime_waits_for_the_first_page_as_show() {+ let directory = TestDirectory::new();+ let mut store = PetStore::load(directory.file());+ // The hotkey during Runtime startup: no window can exist yet.+ store.summon_before_window();+ // The Runtime becomes ready and the window's page loads.+ store.page_loading();+ assert_eq!(+ store.page_ready().summon_pending,+ Some(PendingSummon {+ intent: PetIntent::Show+ })+ );+ // Delivered once.+ store.page_loading();+ assert_eq!(store.page_ready().summon_pending, None);+ // A Runtime that goes away before any window takes the wait with it.+ store.summon_before_window();+ store.window_gone();+ assert_eq!(store.page_ready().summon_pending, None);+ }++ #[test]+ fn shortcuts_are_labelled_the_way_each_platform_writes_them() {+ assert_eq!(shortcut_label(DEFAULT_SHORTCUT, true), "⌃⌥Space");+ assert_eq!(shortcut_label(DEFAULT_SHORTCUT, false), "Ctrl+Alt+Space");+ assert_eq!(shortcut_label("Alt+Shift+Space", true), "⌥⇧Space");+ assert_eq!(shortcut_label("Super+Shift+KeyP", false), "Win+Shift+P");+ assert_eq!(SHORTCUT_PRESETS[0], DEFAULT_SHORTCUT);+ }++ #[test]+ fn a_drag_on_a_scaled_secondary_display_restores_to_the_same_physical_spot() {+ // One physical desktop: a 125% primary and a 150% display to its right.+ // The pet sits at physical (3000, 200) on the second one.+ let (primary, window) = (1.25, 1.5);+ let in_window_points = rescale((3000.0, 200.0), 1.0, window);+ let saved = rescale(in_window_points, window, primary);+ let areas = [+ area("primary", 0.0, 0.0, 2560.0 / primary, 1440.0 / primary),+ WorkArea {+ unit: window / primary,+ ..area("side", 2560.0 / primary, 0.0, 3840.0 / primary, 2160.0 / primary)+ },+ ];+ let restored = clamp_anchor(+ &PetAnchor {+ x: saved.0,+ y: saved.1,+ monitor: Some("side".to_owned()),+ },+ &areas,+ );+ let physical = rescale((restored.x, restored.y), primary, 1.0);+ assert!((physical.0 - 3000.0).abs() < 1e-9 && (physical.1 - 200.0).abs() < 1e-9);+ assert_eq!(restored.monitor.as_deref(), Some("side"));+ assert_eq!(+ area_for(&areas, saved).and_then(|area| area.name.as_deref()),+ Some("side")+ );+ // The window starts the pet's 8-point padding, at the side display's+ // scale, above and left of it.+ let window_at = rescale(restored_window_origin(saved, window / primary), primary, 1.0);+ assert!((window_at.0 - (3000.0 - 12.0)).abs() < 1e-9 && (window_at.1 - (200.0 - 12.0)).abs() < 1e-9);+ }++ #[test]+ fn a_pet_clamped_onto_a_denser_display_stays_whole_in_its_own_points() {+ // A 100% primary and a 150% display to its right, in primary points.+ // There the 88-point pet is 132 units wide.+ let side = WorkArea {+ unit: 1.5,+ ..area("side", 1920.0, 0.0, 2560.0, 1440.0)+ };+ let areas = [area("primary", 0.0, 0.0, 1920.0, 1080.0), side.clone()];+ let edge = (side.area.right() - 132.0, side.area.bottom() - 132.0);+ // Overlapping the right edge: pulled in by its scaled extent, not 88.+ let past_edge = PetAnchor {+ x: side.area.right() - 100.0,+ y: 300.0,+ monitor: Some("side".to_owned()),+ };+ let pulled = clamp_anchor(&past_edge, &areas);+ assert_eq!((pulled.x, pulled.y), (edge.0, 300.0));+ // Inside by 88 but not by 132 is not whole.+ let almost = PetAnchor {+ x: side.area.right() - 100.0,+ y: side.area.bottom() - 100.0,+ monitor: Some("side".to_owned()),+ };+ assert_eq!(clamp_anchor(&almost, &areas).x, edge.0);+ // The display is gone from its saved place: it lands whole inside.+ let lost = PetAnchor {+ x: 9000.0,+ y: 9000.0,+ monitor: Some("side".to_owned()),+ };+ let home = clamp_anchor(&lost, &areas);+ assert_eq!((home.x, home.y), edge);+ // A pet with no place keeps the margin in the display's own points.+ let corner = default_anchor(&side);+ assert_eq!(+ (corner.x, corner.y),+ (side.area.right() - 168.0, side.area.bottom() - 168.0)+ );+ assert_eq!(clamp_anchor(&corner, &areas), corner);+ }+}diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.tomlindex f7709b46c..12e1f0fe3 100644--- a/desktop/src-tauri/Cargo.toml+++ b/desktop/src-tauri/Cargo.toml@@ -27,10 +27,12 @@ serde.workspace = trueserde_json.workspace = truesys-locale.workspace = truetar = "0.4"-tauri = { version = "2", features = ["tray-icon"] }+tauri = { version = "2", features = ["tray-icon", "macos-private-api"] }tauri-plugin-autostart = "2"tauri-plugin-deep-link = "2"tauri-plugin-dialog = "2"+# The desktop pet's summon shortcut, registered from Rust only.+tauri-plugin-global-shortcut = "~2.3" # 2.4 requires tauri 2.12tauri-plugin-notification = "2"tauri-plugin-opener = "2"tauri-plugin-single-instance = "2"@@ -41,7 +43,7 @@ url.workspace = true[dev-dependencies]async-trait.workspace = true-tauri = { version = "2", features = ["tray-icon", "test"] }+tauri = { version = "2", features = ["tray-icon", "macos-private-api", "test"] }[target.'cfg(windows)'.dev-dependencies]# Reads a native menu item's text, where muda keeps its accelerator.diff --git a/desktop/src-tauri/build.rs b/desktop/src-tauri/build.rsindex 3863ed223..739791e24 100644--- a/desktop/src-tauri/build.rs+++ b/desktop/src-tauri/build.rs@@ -2,11 +2,21 @@ fn main() {println!("cargo:rerun-if-env-changed=AVIBE_DESKTOP_UPDATER_PUBLIC_KEY");// Application commands are ungated by default in Tauri v2: any page loaded in// any window could invoke them. Declaring them here makes `tauri-build`- // generate per-command permissions, so `capabilities/bootstrap.json`- // becomes the only thing that can hand them out — and it hands them only to- // the shell's own local page.- let manifest =- tauri_build::AppManifest::new().commands(&["bootstrap_status", "bootstrap_retry", "open_install_docs"]);+ // generate per-command permissions, so the capability files become the only+ // thing that can hand them out: `bootstrap.json` gives the bootstrap+ // commands only to the shell's own local page, `pet.json` gives the pet+ // commands only to the pet window, and `main-pet-bind.json` gives the+ // Workbench `pet_bind` alone.+ let manifest = tauri_build::AppManifest::new().commands(&[+ "bootstrap_status",+ "bootstrap_retry",+ "open_install_docs",+ "pet_ready",+ "pet_set_expanded",+ "pet_bind",+ "pet_unbind",+ "pet_open",+ ]);let mut attributes = tauri_build::Attributes::new().app_manifest(manifest);// tauri-build embeds its Windows application manifest, which binds Common// Controls v6, into the app binary only. A test binary that builds a Tauridiff --git a/desktop/src-tauri/capabilities/main-pet-bind.json b/desktop/src-tauri/capabilities/main-pet-bind.jsonnew file mode 100644index 000000000..3fe204e0f--- /dev/null+++ b/desktop/src-tauri/capabilities/main-pet-bind.json@@ -0,0 +1,11 @@+{+ "$schema": "../gen/schemas/desktop-schema.json",+ "identifier": "main-pet-bind",+ "description": "The Workbench's \"Show in pet\" action: bind the desktop pet to a session and bring it forward. Granted to the main window for the loopback Runtime origin only, never to the bundled bootstrap page. It is the only pet command the main window gets.",+ "local": false,+ "windows": ["main"],+ "remote": {+ "urls": ["http://127.0.0.1:*/*", "http://[\\:\\:1]:*/*"]+ },+ "permissions": ["allow-pet-bind"]+}diff --git a/desktop/src-tauri/capabilities/pet.json b/desktop/src-tauri/capabilities/pet.jsonnew file mode 100644index 000000000..04c84003c--- /dev/null+++ b/desktop/src-tauri/capabilities/pet.json@@ -0,0 +1,18 @@+{+ "$schema": "../gen/schemas/desktop-schema.json",+ "identifier": "pet",+ "description": "The desktop pet window's whole native surface: report readiness, resize between the pet and its panel, bind or clear its one session, open an avibe:// link in the main window, and drag itself. Only the pet window gets it, and only for the loopback Runtime origin it loads; it never sees the bundled bootstrap page, so it has no bootstrap command and no event permission (the shell reaches the page through dispatched DOM events).",+ "local": false,+ "windows": ["pet"],+ "remote": {+ "urls": ["http://127.0.0.1:*/*", "http://[\\:\\:1]:*/*"]+ },+ "permissions": [+ "allow-pet-ready",+ "allow-pet-set-expanded",+ "allow-pet-bind",+ "allow-pet-unbind",+ "allow-pet-open",+ "core:window:allow-start-dragging"+ ]+}diff --git a/desktop/src-tauri/permissions/autogenerated/pet_bind.toml b/desktop/src-tauri/permissions/autogenerated/pet_bind.tomlnew file mode 100644index 000000000..aa28f688c--- /dev/null+++ b/desktop/src-tauri/permissions/autogenerated/pet_bind.toml@@ -0,0 +1,11 @@+# Automatically generated - DO NOT EDIT!++[[permission]]+identifier = "allow-pet-bind"+description = "Enables the pet_bind command without any pre-configured scope."+commands.allow = ["pet_bind"]++[[permission]]+identifier = "deny-pet-bind"+description = "Denies the pet_bind command without any pre-configured scope."+commands.deny = ["pet_bind"]diff --git a/desktop/src-tauri/permissions/autogenerated/pet_open.toml b/desktop/src-tauri/permissions/autogenerated/pet_open.tomlnew file mode 100644index 000000000..76e94734c--- /dev/null+++ b/desktop/src-tauri/permissions/autogenerated/pet_open.toml@@ -0,0 +1,11 @@+# Automatically generated - DO NOT EDIT!++[[permission]]+identifier = "allow-pet-open"+description = "Enables the pet_open command without any pre-configured scope."+commands.allow = ["pet_open"]++[[permission]]+identifier = "deny-pet-open"+description = "Denies the pet_open command without any pre-configured scope."+commands.deny = ["pet_open"]diff --git a/desktop/src-tauri/permissions/autogenerated/pet_ready.toml b/desktop/src-tauri/permissions/autogenerated/pet_ready.tomlnew file mode 100644index 000000000..d6e9d741b--- /dev/null+++ b/desktop/src-tauri/permissions/autogenerated/pet_ready.toml@@ -0,0 +1,11 @@+# Automatically generated - DO NOT EDIT!++[[permission]]+identifier = "allow-pet-ready"+description = "Enables the pet_ready command without any pre-configured scope."+commands.allow = ["pet_ready"]++[[permission]]+identifier = "deny-pet-ready"+description = "Denies the pet_ready command without any pre-configured scope."+commands.deny = ["pet_ready"]diff --git a/desktop/src-tauri/permissions/autogenerated/pet_set_expanded.toml b/desktop/src-tauri/permissions/autogenerated/pet_set_expanded.tomlnew file mode 100644index 000000000..bb20a56a0--- /dev/null+++ b/desktop/src-tauri/permissions/autogenerated/pet_set_expanded.toml@@ -0,0 +1,11 @@+# Automatically generated - DO NOT EDIT!++[[permission]]+identifier = "allow-pet-set-expanded"+description = "Enables the pet_set_expanded command without any pre-configured scope."+commands.allow = ["pet_set_expanded"]++[[permission]]+identifier = "deny-pet-set-expanded"+description = "Denies the pet_set_expanded command without any pre-configured scope."+commands.deny = ["pet_set_expanded"]diff --git a/desktop/src-tauri/permissions/autogenerated/pet_unbind.toml b/desktop/src-tauri/permissions/autogenerated/pet_unbind.tomlnew file mode 100644index 000000000..9b820e84f--- /dev/null+++ b/desktop/src-tauri/permissions/autogenerated/pet_unbind.toml@@ -0,0 +1,11 @@+# Automatically generated - DO NOT EDIT!++[[permission]]+identifier = "allow-pet-unbind"+description = "Enables the pet_unbind command without any pre-configured scope."+commands.allow = ["pet_unbind"]++[[permission]]+identifier = "deny-pet-unbind"+description = "Denies the pet_unbind command without any pre-configured scope."+commands.deny = ["pet_unbind"]diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rsindex b906dd76d..5739ff1d2 100644--- a/desktop/src-tauri/src/lib.rs+++ b/desktop/src-tauri/src/lib.rs@@ -21,6 +21,7 @@ use std::time::Duration;mod native_frame;mod notifications;+mod pet;mod update_install;mod updater;@@ -108,6 +109,7 @@ struct DesktopBootstrapCatalog {tray: NativeTrayCatalog,updater: updater::Catalog,notifications: notifications::NativeNotificationCatalog,+ pet: pet::NativePetCatalog,#[cfg(feature = "bundled-runtime")]uninstall: NativeUninstallCatalog,}@@ -331,6 +333,7 @@ fn install_native_tray(app: &AppHandle) -> tauri::Result<()> {app.state::<notifications::Notifications>().enabled(),None::<&str>,)?;+ let (pet_toggle, pet_shortcut) = pet::tray_items(app)?;let updater = app.state::<updater::Updater>();let tray = Menu::with_items(app,@@ -343,6 +346,8 @@ fn install_native_tray(app: &AppHandle) -> tauri::Result<()> {&updater.channel_menu,&login,¬ifications,+ &pet_toggle,+ &pet_shortcut,&PredefinedMenuItem::separator(app)?,&quit,],@@ -706,6 +711,9 @@ fn stop_runtime(app: AppHandle, quit: bool) {CliOutcome::Failed { .. } | CliOutcome::Unrunnable => (BootstrapNoticeCode::RuntimeStopFailed, true),};let _ = return_to_bootstrap(&app);+ // Whether or not the window could leave the Workbench, the shell no+ // longer vouches for the Runtime it showed.+ let _ = set_active_origin(&app, None);let mut status = BootstrapStatus::rejected(code, true);if let Some(previous) = previous_status {status.origin = previous.origin;@@ -884,12 +892,17 @@ fn is_runtime_rebind_target(url: &Url) -> bool {&& url.fragment().is_none()}+/// Records the Runtime the Workbench shows, or that it shows none. This is the+/// only writer, so the pet, which follows it, is reconciled here.fn set_active_origin(app: &AppHandle, origin: Option<LoopbackOrigin>) -> bool {- app.state::<Shell>()+ let recorded = app+ .state::<Shell>().active_origin.lock().map(|mut active| *active = origin)- .is_ok()+ .is_ok();+ pet::reconcile(app);+ recorded}/// The current bootstrap status, or `null` before the first one is published.@@ -1228,6 +1241,7 @@ fn ensure_main_window(app: &AppHandle) -> Option<WebviewWindow> {let builder = WebviewWindowBuilder::from_config(app, &config).ok()?.initialization_script(DESKTOP_SHELL_MARKER)+ .initialization_script(pet::DESKTOP_PET_MARKER).initialization_script(format!("if (window.self === window.top) Object.defineProperty(window, '__AVIBE_DESKTOP_VERSION__', {{ value: {} }});",serde_json::to_string(&app.package_info().version.to_string()).expect("version JSON")@@ -1736,6 +1750,16 @@ pub fn run() {.plugin(tauri_plugin_dialog::init()).plugin(tauri_plugin_autostart::Builder::new().build()).plugin(tauri_plugin_notification::init())+ // The pet's summon shortcut. Only a press wakes it; the release is ignored.+ .plugin(+ tauri_plugin_global_shortcut::Builder::new()+ .with_handler(|app, _shortcut, event| {+ if event.state() == tauri_plugin_global_shortcut::ShortcutState::Pressed {+ pet::wake(app, avibe_runtime_host::pet::PetIntent::Listen);+ }+ })+ .build(),+ ).on_menu_event(|app, event| {if let Some(quit) = runtime_lifecycle_request(event.id().as_ref()) {request_runtime_lifecycle(app.clone(), quit);@@ -1753,6 +1777,8 @@ pub fn run() {let _ = menus.notifications.set_checked(notifications.enabled());}}+ pet::MENU_ID => pet::toggle(app),+ id if id.starts_with(pet::SHORTCUT_MENU_PREFIX) => pet::choose_shortcut(app, id),_ => {}}#[cfg(feature = "bundled-runtime")]@@ -1763,6 +1789,9 @@ pub fn run() {.plugin(PluginBuilder::<_, ()>::new("shell-run-events").on_page_load(|webview, payload| {+ if webview.label() == pet::PET_WINDOW && payload.event() == tauri::webview::PageLoadEvent::Started {+ pet::page_loading(webview.app_handle());+ }if webview.label() == MAIN_WINDOW && payload.event() == tauri::webview::PageLoadEvent::Finished {// The native frame is independent of the Runtime UI version;// older adopted Workbench pages must not restore a title bar.@@ -1776,6 +1805,9 @@ pub fn run() {}}).on_navigation(|webview, url| {+ if webview.label() == pet::PET_WINDOW {+ return pet::navigation_allowed(webview.app_handle(), url);+ }if webview.label() == MAIN_WINDOW && url.as_str() == updater::OPEN_URL {updater::check(webview.app_handle().clone(), true);return false;@@ -1806,6 +1838,20 @@ pub fn run() {let _ = window.hide();}}+ if label == pet::PET_WINDOW {+ api.prevent_close();+ pet::hide(app);+ }+ }+ if let RunEvent::WindowEvent {+ label,+ event: WindowEvent::Moved(_),+ ..+ } = event+ {+ if label == pet::PET_WINDOW {+ pet::window_moved(app);+ }}if let RunEvent::ExitRequested { api, .. } = event {if let Some(shell) = app.try_state::<Shell>() {@@ -1815,13 +1861,17 @@ pub fn run() {}}}+ // The pet is a visible window too, so whether any window is+ // visible says nothing about the Workbench: a Dock click+ // restores `main` whenever `main` itself is not on screen.#[cfg(target_os = "macos")]- if let RunEvent::Reopen {- has_visible_windows: false,- ..- } = event- {- focus_or_restore_main_window(app);+ if let RunEvent::Reopen { .. } = event {+ let main_visible = app+ .get_webview_window(MAIN_WINDOW)+ .is_some_and(|window| window.is_visible().unwrap_or(false));+ if !main_visible {+ focus_or_restore_main_window(app);+ }}}).build(),@@ -1829,7 +1879,12 @@ pub fn run() {.invoke_handler(tauri::generate_handler![bootstrap_status,bootstrap_retry,- open_install_docs+ open_install_docs,+ pet::pet_ready,+ pet::pet_set_expanded,+ pet::pet_bind,+ pet::pet_unbind,+ pet::pet_open]).setup(|app| {let window = ensure_main_window(app.handle()).ok_or_else(|| {@@ -1864,6 +1919,7 @@ pub fn run() {app.manage(notifications::Notifications::new(app.path().app_local_data_dir()?.join("notifications.json"),));+ app.manage(pet::Pet::new(app.path().app_local_data_dir()?.join("pet.json")));#[cfg(target_os = "macos")]macos_terminate::install(app.handle());if let Ok(mut links) = app.state::<Mutex<DeepLinks>>().lock() {@@ -1875,6 +1931,7 @@ pub fn run() {}updater::init(app.handle())?;install_native_tray(app.handle())?;+ pet::apply_shortcut(app.handle());updater::check(app.handle().clone(), false);let _ = spawn_bootstrap(app.handle().clone(), BootstrapTrigger::Launch);Ok(())diff --git a/desktop/src-tauri/src/pet.rs b/desktop/src-tauri/src/pet.rsnew file mode 100644index 000000000..298e3b106--- /dev/null+++ b/desktop/src-tauri/src/pet.rs@@ -0,0 +1,800 @@+//! The desktop pet's native window: when it exists, where it sits, how it is+//! woken, and the narrow command surface its `/pet` page and the Workbench's+//! "Show in pet" use. The decisions that need no window live in+//! `avibe_runtime_host::pet`; see `docs/plans/2026-10-01-desktop-pet.md`.+//!+//! Lifecycle in one sentence: the window exists exactly when the pet is+//! enabled and the Workbench shows a Runtime, at that Runtime's origin, and+//! [`reconcile_now`] is the only code that creates or destroys it. The Shell's+//! `active_origin` is the one record of that Runtime; the pet keeps no copy+//! and is reconciled whenever that record is written.++use std::path::PathBuf;+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};+use std::sync::{Arc, Mutex, MutexGuard};+use std::time::Duration;++use avibe_runtime_host::deep_link::parse_deep_link;+use avibe_runtime_host::pet::{+ anchor_from_window, area_for, choose_layout, clamp_anchor, default_anchor, rescale, restored_window_origin,+ shortcut_label, valid_session_id, window_origin, window_size, LogicalRect, PetAnchor, PetBinding, PetIntent,+ PetLayout, PetReady, PetStore, WorkArea, SHORTCUT_PRESETS,+};+use avibe_runtime_host::LoopbackOrigin;+use serde::{Deserialize, Serialize};+use tauri::menu::{CheckMenuItem, MenuItem, Submenu};+use tauri::{+ AppHandle, LogicalPosition, LogicalSize, Manager, Monitor, PhysicalPosition, WebviewUrl, WebviewWindow,+ WebviewWindowBuilder,+};+use tauri_plugin_global_shortcut::GlobalShortcutExt;+use url::Url;++use crate::{native_catalog_for_locales, Shell, DESKTOP_SHELL_MARKER, MAIN_WINDOW};++pub const PET_WINDOW: &str = "pet";+pub const MENU_ID: &str = "show-pet";+pub const SHORTCUT_MENU_PREFIX: &str = "pet-shortcut:";+const PET_PATH: &str = "/pet";+const SUMMON_EVENT: &str = "avibe:pet-summon";+const BOUND_EVENT: &str = "avibe:pet-bound";+/// A drag settles before its anchor is saved, as the main window's frame does.+const MOVE_SETTLE: Duration = Duration::from_millis(400);++/// Tells the Workbench, before its scripts run, that this shell can show a+/// session in the pet. An older shell has no `pet_bind`, so the page offers+/// "Show in pet" only when this is present.+pub const DESKTOP_PET_MARKER: &str =+ "if (window.self === window.top) Object.defineProperty(window, '__AVIBE_DESKTOP_PET__', { value: true });";++#[derive(Clone, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativePetCatalog {+ toggle: String,+ shortcut_menu: String,+ shortcut_unavailable: String,+}++fn native_pet_catalog() -> NativePetCatalog {+ native_catalog_for_locales(sys_locale::get_locales()).pet+}++#[derive(Clone, Copy)]+struct Frame {+ expanded: bool,+ layout: PetLayout,+}++pub struct Pet {+ store: Mutex<PetStore>,+ /// The origin the current pet window was built for. The pet may load only+ /// this origin.+ window_origin: Mutex<Option<LoopbackOrigin>>,+ frame: Mutex<Frame>,+ /// The accelerator the OS refused, shown in the tray until a registration succeeds.+ shortcut_error: Mutex<Option<String>>,+ move_generation: Arc<AtomicU64>,+}++impl Pet {+ pub fn new(path: PathBuf) -> Self {+ Self {+ store: Mutex::new(PetStore::load(path)),+ window_origin: Mutex::new(None),+ frame: Mutex::new(Frame {+ expanded: false,+ layout: PetLayout::default(),+ }),+ shortcut_error: Mutex::new(None),+ move_generation: Arc::new(AtomicU64::new(0)),+ }+ }++ fn store(&self) -> MutexGuard<'_, PetStore> {+ self.store.lock().unwrap_or_else(|poisoned| poisoned.into_inner())+ }++ pub fn enabled(&self) -> bool {+ self.store().enabled()+ }+}++fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {+ mutex.lock().unwrap_or_else(|poisoned| poisoned.into_inner())+}++pub struct PetMenus {+ toggle: CheckMenuItem<tauri::Wry>,+ shortcut: Submenu<tauri::Wry>,+ presets: Vec<CheckMenuItem<tauri::Wry>>,+ unavailable: MenuItem<tauri::Wry>,+ unavailable_present: AtomicBool,+}++/// The tray's pet switch and shortcut presets, placed next to Notifications.+pub fn tray_items(app: &AppHandle) -> tauri::Result<(CheckMenuItem<tauri::Wry>, Submenu<tauri::Wry>)> {+ let catalog = native_pet_catalog();+ let enabled = app.state::<Pet>().enabled();+ let toggle = CheckMenuItem::with_id(app, MENU_ID, &catalog.toggle, true, enabled, None::<&str>)?;+ let macos = cfg!(target_os = "macos");+ let presets = SHORTCUT_PRESETS+ .iter()+ .map(|preset| {+ CheckMenuItem::with_id(+ app,+ format!("{SHORTCUT_MENU_PREFIX}{preset}"),+ shortcut_label(preset, macos),+ true,+ false,+ None::<&str>,+ )+ })+ .collect::<tauri::Result<Vec<_>>>()?;+ let shortcut = Submenu::with_id(app, "pet-shortcut", &catalog.shortcut_menu, true)?;+ for preset in &presets {+ shortcut.append(preset)?;+ }+ let unavailable = MenuItem::with_id(app, "pet-shortcut-unavailable", "", false, None::<&str>)?;+ app.manage(PetMenus {+ toggle: toggle.clone(),+ shortcut: shortcut.clone(),+ presets,+ unavailable,+ unavailable_present: AtomicBool::new(false),+ });+ Ok((toggle, shortcut))+}++fn refresh_menu(app: &AppHandle) {+ let Some(menus) = app.try_state::<PetMenus>() else {+ return;+ };+ let pet = app.state::<Pet>();+ let (enabled, shortcut) = {+ let store = pet.store();+ (store.enabled(), store.shortcut().to_owned())+ };+ let error = lock(&pet.shortcut_error).clone();+ let update = || -> tauri::Result<()> {+ menus.toggle.set_checked(enabled)?;+ for (item, preset) in menus.presets.iter().zip(SHORTCUT_PRESETS) {+ item.set_checked(preset == shortcut)?;+ }+ if let Some(refused) = &error {+ let label = native_pet_catalog()+ .shortcut_unavailable+ .replace("{{shortcut}}", &shortcut_label(refused, cfg!(target_os = "macos")));+ menus.unavailable.set_text(label)?;+ }+ if error.is_some() != menus.unavailable_present.load(Ordering::SeqCst) {+ if error.is_some() {+ menus.shortcut.append(&menus.unavailable)?;+ } else {+ menus.shortcut.remove(&menus.unavailable)?;+ }+ menus.unavailable_present.store(error.is_some(), Ordering::SeqCst);+ }+ Ok(())+ };+ if update().is_err() {+ eprintln!("failed to refresh the desktop pet menu");+ }+}++/// Registers the summon shortcut while the pet is on, and nothing while it is+/// off. A shortcut the OS refuses is shown in the tray, never swallowed.+pub fn apply_shortcut(app: &AppHandle) {+ let pet = app.state::<Pet>();+ let (enabled, shortcut) = {+ let store = pet.store();+ (store.enabled(), store.shortcut().to_owned())+ };+ let shortcuts = app.global_shortcut();+ let _ = shortcuts.unregister_all();+ let error = if enabled {+ match shortcuts.register(shortcut.as_str()) {+ Ok(()) => None,+ Err(error) => {+ eprintln!("The desktop pet shortcut could not be registered: {error}");+ Some(shortcut)+ }+ }+ } else {+ None+ };+ *lock(&pet.shortcut_error) = error;+ refresh_menu(app);+}++/// The tray switch.+pub fn toggle(app: &AppHandle) {+ let pet = app.state::<Pet>();+ let enabled = !pet.enabled();+ if pet.store().set_enabled(enabled).is_err() {+ eprintln!("The desktop pet preference could not be saved.");+ }+ apply_shortcut(app);+ if pet.enabled() {+ wake(app, PetIntent::Show);+ } else {+ reconcile(app);+ }+}++/// A shortcut preset from the tray.+pub fn choose_shortcut(app: &AppHandle, id: &str) {+ let Some(preset) = preset_for_menu(id) else {+ return;+ };+ app.state::<Pet>().store().set_shortcut(preset);+ apply_shortcut(app);+}++/// Presets only: the tray never registers an accelerator it did not offer.+fn preset_for_menu(id: &str) -> Option<&'static str> {+ let choice = id.strip_prefix(SHORTCUT_MENU_PREFIX)?;+ SHORTCUT_PRESETS.iter().copied().find(|preset| *preset == choice)+}++/// Brings the window in line with the switch and the Runtime the Workbench+/// shows. The Shell calls this whenever it records or clears that Runtime.+pub fn reconcile(app: &AppHandle) {+ let handle = app.clone();+ let _ = app.run_on_main_thread(move || {+ reconcile_now(&handle);+ });+}++/// What the window must become: `destroy` the existing one, then `build` one+/// for an origin.+#[derive(Debug, PartialEq, Eq)]+struct WindowChange {+ destroy: bool,+ build: Option<LoopbackOrigin>,+}++/// The window shows `/pet` from the Workbench's Runtime while the pet is on,+/// and does not exist otherwise. `existing` is `None` without a window, else+/// the origin that window was built for.+fn window_change(+ enabled: bool,+ workbench: Option<&LoopbackOrigin>,+ existing: Option<Option<&LoopbackOrigin>>,+) -> WindowChange {+ let desired = workbench.filter(|_| enabled);+ match existing {+ Some(built_for) if desired.is_some() && built_for == desired => WindowChange {+ destroy: false,+ build: None,+ },+ _ => WindowChange {+ destroy: existing.is_some(),+ build: desired.cloned(),+ },+ }+}++/// The only creator and destroyer of `pet`; see [`window_change`].+fn reconcile_now(app: &AppHandle) -> Option<WebviewWindow> {+ let (pet, shell) = (app.try_state::<Pet>()?, app.try_state::<Shell>()?);+ let workbench = lock(&shell.active_origin).clone();+ let built_for = lock(&pet.window_origin).clone();+ let window = app.get_webview_window(PET_WINDOW);+ let change = window_change(+ pet.enabled(),+ workbench.as_ref(),+ window.as_ref().map(|_| built_for.as_ref()),+ );+ match window {+ Some(window) if !change.destroy => return Some(window),+ Some(window) => {+ let _ = window.destroy();+ *lock(&pet.window_origin) = None;+ pet.store().window_gone();+ }+ None => {}+ }+ let origin = change.build?;+ // The navigation hook also judges the window's first load, so the origin+ // it may load is recorded before the webview starts loading it.+ *lock(&pet.window_origin) = Some(origin.clone());+ let window = build_window(app, &origin);+ if window.is_none() {+ *lock(&pet.window_origin) = None;+ }+ window+}++fn build_window(app: &AppHandle, origin: &LoopbackOrigin) -> Option<WebviewWindow> {+ let pet = app.state::<Pet>();+ let mut url = origin.navigation_url();+ url.set_path(PET_PATH);+ let scale = anchor_scale(app, None);+ let areas = work_areas(app, scale);+ let saved = pet.store().anchor().cloned();+ let anchor = match (saved, areas.first()) {+ (Some(saved), _) => clamp_anchor(&saved, &areas),+ (None, Some(primary)) => default_anchor(primary),+ (None, None) => PetAnchor {+ x: 0.0,+ y: 0.0,+ monitor: None,+ },+ };+ let layout = PetLayout::default();+ *lock(&pet.frame) = Frame {+ expanded: false,+ layout,+ };+ let (width, height) = window_size(false);+ let at = (anchor.x, anchor.y);+ let unit = area_for(&areas, at).map_or(1.0, |area| area.unit);+ let (x, y) = restored_window_origin(at, unit);+ pet.store().page_loading();+ let builder = WebviewWindowBuilder::new(app, PET_WINDOW, WebviewUrl::External(url))+ .initialization_script(DESKTOP_SHELL_MARKER)+ .on_new_window(|_, _| tauri::webview::NewWindowResponse::Deny)+ .title("Avibe")+ .inner_size(width, height)+ .position(x, y)+ .transparent(true)+ .decorations(false)+ .shadow(false)+ .resizable(false)+ .maximizable(false)+ .minimizable(false)+ .always_on_top(true)+ .visible_on_all_workspaces(true)+ .skip_taskbar(true)+ .focused(false);+ #[cfg(target_os = "macos")]+ let builder = builder.accept_first_mouse(true);+ match builder.build() {+ Ok(window) => {+ // Off macOS the builder's points use a scale this code does not+ // choose, so the window is put on the saved physical spot.+ if !cfg!(target_os = "macos") {+ let (x, y) = rescale((x, y), scale, 1.0);+ let _ = window.set_position(PhysicalPosition::new(x.round() as i32, y.round() as i32));+ }+ Some(window)+ }+ Err(error) => {+ eprintln!("The desktop pet window could not be created: {error}");+ pet.store().window_gone();+ None+ }+ }+}++/// Every way to summon the pet. The hotkey listens; everything else shows.+pub fn wake(app: &AppHandle, intent: PetIntent) {+ let handle = app.clone();+ let _ = app.run_on_main_thread(move || {+ let pet = handle.state::<Pet>();+ if !pet.enabled() {+ return;+ }+ let Some(window) = reconcile_now(&handle) else {+ // The Workbench has no Runtime yet; the summon waits for the+ // window that Runtime will bring.+ pet.store().summon_before_window();+ return;+ };+ let _ = window.show();+ let _ = window.set_focus();+ let deliver = pet.store().summon(intent);+ if let Some(intent) = deliver {+ dispatch(&window, SUMMON_EVENT, &serde_json::json!({ "intent": intent }));+ }+ });+}++fn dispatch(window: &WebviewWindow, event: &str, detail: &serde_json::Value) {+ let script = format!(+ "window.dispatchEvent(new CustomEvent({}, {{ detail: {} }}));",+ serde_json::to_string(event).expect("event name JSON"),+ detail+ );+ let _ = window.eval(script);+}++fn announce_binding(app: &AppHandle, binding: &PetBinding) {+ let ready = app.state::<Pet>().store().page_is_ready();+ if let Some(window) = app.get_webview_window(PET_WINDOW).filter(|_| ready) {+ dispatch(+ &window,+ BOUND_EVENT,+ &serde_json::json!({ "session_id": binding.binding, "revision": binding.revision }),+ );+ }+}++/// The pet may only show its own route on the Runtime it was built for, so+/// it can never become a second Workbench.+pub fn navigation_allowed(app: &AppHandle, url: &Url) -> bool {+ app.try_state::<Pet>()+ .is_some_and(|pet| is_pet_page(lock(&pet.window_origin).as_ref(), url))+}++fn is_pet_page(origin: Option<&LoopbackOrigin>, url: &Url) -> bool {+ origin.is_some_and(|origin| origin.matches_url_origin(url)) && url.path() == PET_PATH+}++/// The pet window's own document is starting over: summons wait for it.+pub fn page_loading(app: &AppHandle) {+ if let Some(pet) = app.try_state::<Pet>() {+ pet.store().page_loading();+ }+}++/// An OS close request only hides the pet; the tray switch turns it off.+pub fn hide(app: &AppHandle) {+ if let Some(window) = app.get_webview_window(PET_WINDOW) {+ let _ = window.hide();+ }+}++/// Saves where the user dragged the pet once the drag settles.+pub fn window_moved(app: &AppHandle) {+ let Some(pet) = app.try_state::<Pet>() else {+ return;+ };+ let generation = pet.move_generation.clone();+ let observed = generation.fetch_add(1, Ordering::SeqCst) + 1;+ let app = app.clone();+ tauri::async_runtime::spawn(async move {+ tokio::time::sleep(MOVE_SETTLE).await;+ let handle = app.clone();+ let _ = app.run_on_main_thread(move || {+ if generation.load(Ordering::SeqCst) != observed {+ return;+ }+ let Some(window) = handle.get_webview_window(PET_WINDOW) else {+ return;+ };+ let (Some(anchor), Ok(window_scale)) = (current_anchor(&handle, &window), window.scale_factor()) else {+ return;+ };+ let scale = anchor_scale(&handle, Some(window_scale));+ let anchor = rescale(anchor, window_scale, scale);+ let areas = work_areas(&handle, scale);+ let monitor = area_for(&areas, anchor).and_then(|area| area.name.clone());+ handle.state::<Pet>().store().set_anchor(PetAnchor {+ x: anchor.0.round(),+ y: anchor.1.round(),+ monitor,+ });+ });+ });+}++fn current_anchor(app: &AppHandle, window: &WebviewWindow) -> Option<(f64, f64)> {+ let scale = window.scale_factor().ok()?;+ let position = window.outer_position().ok()?.to_logical::<f64>(scale);+ let frame = *lock(&app.state::<Pet>().frame);+ Some(anchor_from_window(+ (position.x, position.y),+ frame.expanded,+ frame.layout,+ ))+}++/// The scale `pet.json`'s anchor is stored in. macOS places every window in+/// one space of points, which the window's own scale reaches. Windows and Linux+/// place windows on one physical desktop, and the pet window's scale changes+/// as it crosses displays, so the anchor uses the primary display's scale both+/// when it is saved and when it is restored.+fn anchor_scale(app: &AppHandle, window_scale: Option<f64>) -> f64 {+ let primary = || {+ app.primary_monitor()+ .ok()+ .flatten()+ .map_or(1.0, |monitor| monitor.scale_factor())+ };+ match window_scale {+ Some(scale) if cfg!(target_os = "macos") => scale,+ _ => primary(),+ }+}++/// Each display's work area in points, the primary display first. Off macOS,+/// `scale` turns the one physical desktop into points.+fn work_areas(app: &AppHandle, scale: f64) -> Vec<WorkArea> {+ let primary = app+ .primary_monitor()+ .ok()+ .flatten()+ .and_then(|monitor| monitor.name().cloned());+ let mut areas: Vec<WorkArea> = app+ .available_monitors()+ .unwrap_or_default()+ .iter()+ .map(|monitor| logical_work_area(monitor, scale))+ .collect();+ areas.sort_by_key(|area| area.name != primary);+ areas+}++fn logical_work_area(monitor: &Monitor, scale: f64) -> WorkArea {+ // macOS reports each display in its own pixels and shares one space of+ // points; off macOS a display's points are its own scale over `scale`.+ let (scale, unit) = if cfg!(target_os = "macos") {+ (monitor.scale_factor(), 1.0)+ } else {+ (scale, monitor.scale_factor() / scale)+ };+ let area = monitor.work_area();+ WorkArea {+ name: monitor.name().cloned(),+ area: LogicalRect {+ x: f64::from(area.position.x) / scale,+ y: f64::from(area.position.y) / scale,+ width: f64::from(area.size.width) / scale,+ height: f64::from(area.size.height) / scale,+ },+ unit,+ }+}++const UNAVAILABLE: &str = "This command is only available to the Avibe desktop pet.";++/// The second layer behind the `pet` capability: the caller is the pet window+/// showing its own route on the Runtime it was built for.+fn ensure_pet_page(window: &WebviewWindow) -> Result<(), String> {+ let pet = window.state::<Pet>();+ let url = window.url().map_err(|_| UNAVAILABLE.to_owned())?;+ if is_pet_caller(window.label(), lock(&pet.window_origin).as_ref(), &url) {+ Ok(())+ } else {+ Err(UNAVAILABLE.to_owned())+ }+}++fn is_pet_caller(label: &str, built_for: Option<&LoopbackOrigin>, url: &Url) -> bool {+ label == PET_WINDOW && is_pet_page(built_for, url)+}++/// The Workbench in `main`, on the Runtime the shell navigated it to.+fn is_workbench(window: &WebviewWindow) -> bool {+ let Some(shell) = window.try_state::<Shell>() else {+ return false;+ };+ let active = lock(&shell.active_origin).clone();+ window+ .url()+ .is_ok_and(|url| is_workbench_caller(window.label(), active.as_ref(), &url))+}++fn is_workbench_caller(label: &str, active: Option<&LoopbackOrigin>, url: &Url) -> bool {+ label == MAIN_WINDOW && active.is_some_and(|origin| origin.matches_url_origin(url))+}++/// Called once the `/pet` page has its listeners installed.+#[tauri::command]+pub fn pet_ready(window: WebviewWindow) -> Result<PetReady, String> {+ ensure_pet_page(&window)?;+ let pet = window.state::<Pet>();+ // A new document starts collapsed, so the frame does too.+ let expanded = lock(&pet.frame).expanded;+ if expanded {+ let _ = set_expanded(&window, false);+ }+ let ready = pet.store().page_ready();+ // A summon that waited for this page brings the window forward now; the+ // window was built without focus.+ if ready.summon_pending.is_some() {+ let _ = window.show();+ let _ = window.set_focus();+ }+ Ok(ready)+}++/// Grows the window to fit the panel, or shrinks it to the pet, keeping the+/// pet where it is. The answer is the one placement the page renders from.+#[tauri::command]+pub fn pet_set_expanded(window: WebviewWindow, expanded: bool) -> Result<PetLayout, String> {+ ensure_pet_page(&window)?;+ set_expanded(&window, expanded)+}++fn set_expanded(window: &WebviewWindow, expanded: bool) -> Result<PetLayout, String> {+ let app = window.app_handle();+ let anchor = current_anchor(app, window).ok_or_else(|| "The pet window has no position.".to_owned())?;+ let pet = app.state::<Pet>();+ let previous = *lock(&pet.frame);+ let layout = if expanded {+ let areas = work_areas(app, window.scale_factor().unwrap_or(1.0));+ match area_for(&areas, anchor) {+ Some(area) => choose_layout(anchor, area.area),+ None => PetLayout::default(),+ }+ } else {+ previous.layout+ };+ *lock(&pet.frame) = Frame { expanded, layout };+ let (width, height) = window_size(expanded);+ let (x, y) = window_origin(anchor, expanded, layout);+ window+ .set_size(LogicalSize::new(width, height))+ .and_then(|()| window.set_position(LogicalPosition::new(x, y)))+ .map_err(|_| "The pet window could not be resized.".to_owned())?;+ Ok(layout)+}++#[derive(Serialize)]+pub struct BindResult {+ #[serde(flatten)]+ binding: PetBinding,+ /// Whether the pet will show the session now. False while the pet is off.+ shown: bool,+}++/// Binds the pet to a session: the pet's switcher, and the Workbench's+/// "Show in pet", which also brings the pet forward.+#[tauri::command]+pub fn pet_bind(window: WebviewWindow, session_id: String) -> Result<BindResult, String> {+ let from_workbench = is_workbench(&window);+ if !from_workbench {+ ensure_pet_page(&window)?;+ }+ if !valid_session_id(&session_id) {+ return Err("Not a session id.".to_owned());+ }+ let app = window.app_handle().clone();+ let pet = app.state::<Pet>();+ let binding = pet.store().bind(&session_id);+ announce_binding(&app, &binding);+ let shown = pet.enabled();+ if from_workbench && shown {+ // Off the command's own thread: creating a window inside an IPC+ // callback deadlocks on Windows.+ let wake_app = app.clone();+ tauri::async_runtime::spawn(async move { wake(&wake_app, PetIntent::Show) });+ }+ Ok(BindResult { binding, shown })+}++/// Clears the binding only if it is still `session_id`.+#[tauri::command]+pub fn pet_unbind(window: WebviewWindow, session_id: String) -> Result<PetBinding, String> {+ ensure_pet_page(&window)?;+ let app = window.app_handle();+ let pet = app.state::<Pet>();+ let before = pet.store().binding().revision;+ let binding = pet.store().unbind(&session_id);+ if binding.revision != before {+ announce_binding(app, &binding);+ }+ Ok(binding)+}++/// Opens a deep link in `main`, exactly as a clicked `avibe://` link would.+#[tauri::command]+pub fn pet_open(window: WebviewWindow, link: String) -> Result<(), String> {+ ensure_pet_page(&window)?;+ if parse_deep_link(&link).is_none() {+ return Err("Not an Avibe link.".to_owned());+ }+ let app = window.app_handle().clone();+ tauri::async_runtime::spawn(async move {+ let handle = app.clone();+ let _ = app.run_on_main_thread(move || crate::receive_native_deep_link(&handle, [link]));+ });+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_pet_navigates_only_to_its_own_route_on_its_own_runtime() {+ let origin = LoopbackOrigin::parse("http://127.0.0.1:5123").unwrap();+ let allowed = |raw: &str| is_pet_page(Some(&origin), &Url::parse(raw).unwrap());+ assert!(allowed("http://127.0.0.1:5123/pet"));+ assert!(allowed("http://127.0.0.1:5123/pet?x=1"));+ assert!(!allowed("http://127.0.0.1:5123/"));+ assert!(!allowed("http://127.0.0.1:5123/chat/abc"));+ assert!(!allowed("http://127.0.0.1:5124/pet"));+ assert!(!allowed("http://localhost:5123/pet"));+ assert!(!is_pet_page(None, &Url::parse("http://127.0.0.1:5123/pet").unwrap()));+ }++ #[test]+ fn the_pet_catalog_is_complete_in_every_locale() {+ for locale in ["en-US", "zh-CN"] {+ let catalog = native_catalog_for_locales([locale.to_owned()]).pet;+ assert!(!catalog.toggle.is_empty());+ assert!(!catalog.shortcut_menu.is_empty());+ assert!(catalog.shortcut_unavailable.contains("{{shortcut}}"));+ }+ }++ fn origin(raw: &str) -> LoopbackOrigin {+ LoopbackOrigin::parse(raw).unwrap()+ }++ #[test]+ fn the_window_follows_the_switch_and_the_runtime_the_workbench_shows() {+ let (a, b) = (origin("http://127.0.0.1:5123"), origin("http://127.0.0.1:6174"));+ let change = |destroy, build: Option<&LoopbackOrigin>| WindowChange {+ destroy,+ build: build.cloned(),+ };+ // The Workbench reaches a Runtime: the pet appears there.+ assert_eq!(window_change(true, Some(&a), None), change(false, Some(&a)));+ assert_eq!(window_change(true, Some(&a), Some(Some(&a))), change(false, None));+ // The Runtime moves: the old window goes and one is built for the new origin.+ assert_eq!(window_change(true, Some(&b), Some(Some(&a))), change(true, Some(&b)));+ // The Workbench no longer shows a Runtime (stopped, lost, or `main`+ // recreated): the pet goes with it.+ assert_eq!(window_change(true, None, Some(Some(&a))), change(true, None));+ assert_eq!(window_change(true, None, None), change(false, None));+ // The switch is off: no window, whatever the Workbench shows.+ assert_eq!(window_change(false, Some(&a), Some(Some(&a))), change(true, None));+ assert_eq!(window_change(false, Some(&a), None), change(false, None));+ }++ #[test]+ fn pet_commands_answer_only_the_pet_page_and_the_workbench() {+ let (a, b) = (origin("http://127.0.0.1:5123"), origin("http://127.0.0.1:6174"));+ let url = |raw: &str| Url::parse(raw).unwrap();+ assert!(is_pet_caller(PET_WINDOW, Some(&a), &url("http://127.0.0.1:5123/pet")));+ assert!(!is_pet_caller(MAIN_WINDOW, Some(&a), &url("http://127.0.0.1:5123/pet")));+ assert!(!is_pet_caller(+ PET_WINDOW,+ Some(&a),+ &url("http://127.0.0.1:5123/chat/abc")+ ));+ assert!(!is_pet_caller(PET_WINDOW, Some(&b), &url("http://127.0.0.1:5123/pet")));+ assert!(!is_pet_caller(PET_WINDOW, None, &url("http://127.0.0.1:5123/pet")));++ assert!(is_workbench_caller(+ MAIN_WINDOW,+ Some(&a),+ &url("http://127.0.0.1:5123/chat/abc")+ ));+ assert!(!is_workbench_caller(+ PET_WINDOW,+ Some(&a),+ &url("http://127.0.0.1:5123/pet")+ ));+ assert!(!is_workbench_caller(+ MAIN_WINDOW,+ Some(&b),+ &url("http://127.0.0.1:5123/")+ ));+ assert!(!is_workbench_caller(MAIN_WINDOW, None, &url("http://127.0.0.1:5123/")));+ assert!(!is_workbench_caller(MAIN_WINDOW, Some(&a), &url("tauri://localhost/")));+ }++ #[test]+ fn the_tray_registers_only_the_presets_it_offers() {+ for preset in SHORTCUT_PRESETS {+ assert_eq!(+ preset_for_menu(&format!("{SHORTCUT_MENU_PREFIX}{preset}")),+ Some(preset)+ );+ }+ assert_eq!(preset_for_menu(&format!("{SHORTCUT_MENU_PREFIX}Super+KeyQ")), None);+ assert_eq!(preset_for_menu(SHORTCUT_PRESETS[0]), None);+ assert_eq!(preset_for_menu(MENU_ID), None);+ }++ #[test]+ fn the_page_listens_for_the_events_and_marker_the_shell_sends() {+ let ui = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../ui/src");+ let read = |path: &str| std::fs::read_to_string(ui.join(path)).unwrap();+ let bridge = read("pet/petBridge.ts");+ for event in [SUMMON_EVENT, BOUND_EVENT] {+ assert!(+ bridge.contains(&format!("'{event}'")),+ "the pet page must listen for {event}"+ );+ }+ assert!(DESKTOP_PET_MARKER.starts_with("if (window.self === window.top)"));+ assert!(DESKTOP_PET_MARKER.contains("'__AVIBE_DESKTOP_PET__'"));+ assert!(read("lib/desktopShell.ts").contains("window.__AVIBE_DESKTOP_PET__ === true"));+ }+}diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.jsonindex 8634c0504..c85a978f7 100644--- a/desktop/src-tauri/tauri.conf.json+++ b/desktop/src-tauri/tauri.conf.json@@ -27,10 +27,13 @@"hiddenTitle": true}],+ "macOSPrivateApi": true,"security": {"capabilities": ["bootstrap",- "window-drag"+ "window-drag",+ "pet",+ "main-pet-bind"],"csp": "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; connect-src 'self' ipc: http://ipc.localhost"}diff --git a/desktop/src-tauri/tests/shell_boundaries.rs b/desktop/src-tauri/tests/shell_boundaries.rsindex 5a9b8597d..28184b586 100644--- a/desktop/src-tauri/tests/shell_boundaries.rs+++ b/desktop/src-tauri/tests/shell_boundaries.rs@@ -100,10 +100,10 @@ fn the_bootstrap_capability_grants_only_the_three_shell_commands() {}#[test]-fn the_shell_enables_only_bootstrap_and_window_drag() {+fn the_shell_enables_only_its_four_capabilities() {assert_eq!(config()["app"]["security"]["capabilities"],- serde_json::json!(["bootstrap", "window-drag"])+ serde_json::json!(["bootstrap", "window-drag", "pet", "main-pet-bind"]));}@@ -396,15 +396,32 @@ fn every_shell_command_is_declared_so_its_permission_exists() {// undeclared command has no `allow-*` permission and so no capability can// scope it.let build_rs = shipping_source("build.rs");- let lib_rs = shipping_source("src/lib.rs");-- let declared: Vec<&str> = ["bootstrap_status", "bootstrap_retry", "open_install_docs"]+ let commands = [+ "bootstrap_status",+ "bootstrap_retry",+ "open_install_docs",+ "pet_ready",+ "pet_set_expanded",+ "pet_bind",+ "pet_unbind",+ "pet_open",+ ];+ let declared: Vec<&str> = commands.into_iter()- .filter(|command| build_rs.contains(command))+ .filter(|command| build_rs.contains(&format!("\"{command}\""))).collect();- assert_eq!(declared, ["bootstrap_status", "bootstrap_retry", "open_install_docs"]);+ assert_eq!(declared, commands);- let defined = lib_rs.matches("#[tauri::command]").count();+ let defined: usize = std::fs::read_dir(crate_dir().join("src"))+ .unwrap()+ .map(|entry| entry.unwrap().path())+ .filter(|path| path.extension().is_some_and(|extension| extension == "rs"))+ .map(|path| {+ shipping_text(&read_to_string(&path))+ .matches("#[tauri::command]")+ .count()+ })+ .sum();assert_eq!(defined,declared.len(),@@ -1016,3 +1033,68 @@ fn workbench_window_permissions_are_narrow_and_match_literal_loopback_origins()assert!(!patterns.iter().any(|pattern| pattern.test(&url)), "{url}");}}++fn loopback_patterns(grant: &Value) -> Vec<tauri::utils::acl::RemoteUrlPattern> {+ grant["remote"]["urls"]+ .as_array()+ .unwrap()+ .iter()+ .map(|pattern| pattern.as_str().unwrap().parse().unwrap())+ .collect()+}++#[test]+fn the_pet_and_the_workbench_get_only_their_pet_commands_on_loopback_pages() {+ let pet = read_json(crate_dir().join("capabilities/pet.json"));+ assert_eq!(pet["windows"], serde_json::json!(["pet"]));+ assert_eq!(pet["local"], false, "the pet never loads the bundled bootstrap page");+ assert_eq!(+ pet["permissions"],+ serde_json::json!([+ "allow-pet-ready",+ "allow-pet-set-expanded",+ "allow-pet-bind",+ "allow-pet-unbind",+ "allow-pet-open",+ "core:window:allow-start-dragging"+ ])+ );+ let workbench = read_json(crate_dir().join("capabilities/main-pet-bind.json"));+ assert_eq!(workbench["windows"], serde_json::json!([MAIN_WINDOW]));+ assert_eq!(workbench["local"], false);+ assert_eq!(workbench["permissions"], serde_json::json!(["allow-pet-bind"]));+ // No other capability reaches a pet command, and the pet gets no+ // bootstrap command and no event channel.+ for name in ["bootstrap", "window-drag"] {+ let grant = read_to_string(&crate_dir().join(format!("capabilities/{name}.json")));+ assert!(!grant.contains("allow-pet-"), "{name} must not grant pet commands");+ }+ let pet_grant = pet["permissions"].to_string();+ assert!(!pet_grant.contains("bootstrap") && !pet_grant.contains("core:event"));+ // The summon shortcut is the shell's alone: no page may register one.+ for grant in std::fs::read_dir(crate_dir().join("capabilities")).unwrap() {+ let grant = read_to_string(&grant.unwrap().path());+ assert!(!grant.contains("global-shortcut"), "no page may register a shortcut");+ }+ assert_eq!(+ config()["app"]["macOSPrivateApi"],+ true,+ "a transparent pet needs it on macOS"+ );+ for grant in [&pet, &workbench] {+ let patterns = loopback_patterns(grant);+ for allowed in ["http://127.0.0.1:5123/pet", "http://[::1]:6174/chat/abc"] {+ let url = url::Url::parse(allowed).unwrap();+ assert!(patterns.iter().any(|pattern| pattern.test(&url)), "{url}");+ }+ for rejected in [+ "https://example.com/pet",+ "http://127.0.0.1.example.com/pet",+ "http://192.168.1.2:5123/pet",+ "http://localhost:5123/pet",+ ] {+ let url = url::Url::parse(rejected).unwrap();+ assert!(!patterns.iter().any(|pattern| pattern.test(&url)), "{url}");+ }+ }+}diff --git a/docs/plans/2026-10-01-desktop-pet.md b/docs/plans/2026-10-01-desktop-pet.mdindex 2e2075a63..097c3fa31 100644--- a/docs/plans/2026-10-01-desktop-pet.md+++ b/docs/plans/2026-10-01-desktop-pet.md@@ -761,6 +761,54 @@ The code and its tests are the contract; this section records why.instance editor who is a project viewer therefore sees state but no composeror quick replies; POST remains rejected by project-role middleware.+- **The shell's window has one owner, and the pet keeps no copy of the+ Runtime.** `reconcile_now` alone creates and destroys `pet`: the window+ exists exactly when the pet is on and the Workbench shows a Runtime, at that+ Runtime's origin. The Shell's `active_origin` is the one record of that+ Runtime, and `set_active_origin`, its only writer, reconciles the pet, so+ every path that hands the Workbench a Runtime or takes it away (handoff,+ return to bootstrap, explicit stop, `main` recreated) moves the pet with+ it. The first review rounds found two call sites that forgot to tell an+ earlier pet-side copy; removing the copy closes that class rather than the+ instances. Every wake runs on the main thread and checks the switch first. `pet_bind` and `pet_open` move their+ window work off the IPC callback, because creating a window inside one+ deadlocks on Windows.+- **Commands check their caller twice.** The `pet` capability (and+ `main-pet-bind` for the Workbench) only grants literal-loopback pages, and+ each command checks again that its caller is the pet window on its own+ `/pet` page, or, for `pet_bind`, the `main` window on the active Runtime.+ The Workbench learns "Show in pet" exists from a top-level+ `__AVIBE_DESKTOP_PET__` marker, so an older shell never offers it.+- **A summon before any Runtime waits as `show`.** The shortcut is live from+ launch and the tray can turn the pet on during bootstrap, before a window+ can exist. Such a summon is kept for the first page and delivered as+ `show` with the window focused, so the pet answers once the Runtime is+ ready, but a key pressed during a startup that can take a while never+ opens the microphone long after. A Runtime that goes away first drops it.+- **The shortcut plugin is pinned to 2.3.** `tauri-plugin-global-shortcut`+ 2.4 requires Tauri 2.12; `~2.3` keeps the locked Tauri 2.11 and adds only+ the hotkey crates to the lock file. Lift the pin with the Tauri upgrade.+- **Placement has one coordinate space per platform.** macOS places every+ window in one space of points. Windows and Linux place windows on one+ physical desktop, and the pet window's scale changes as it crosses+ displays, so the saved anchor is that desktop divided by the primary+ display's scale, both when saving and restoring, and the restored window is+ positioned in physical pixels. In that space each display carries a `unit`,+ the length of one of its own points: the pet's extent, its default margin,+ its centre and the window's padding are all scaled by the unit of the+ display they are measured on, so a pet clamped onto a denser display stays+ whole. (Review found positions normalized but the extent not; every+ quantity measured in the stored space now goes through the unit.) The anchor saved after a drag settles+ (400 ms) is the pet's own top-left corner, rounded, with the display's name;+ it is clamped back onto a connected display when the window is built.+- **`⌃⌥Space` can collide with macOS input-source switching.** It is the+ default "Select next source in Input menu" shortcut, which many users with+ a second input method keep. The default stays as specified; a refused+ registration shows in the tray, and the presets are the way out.+- **Scenario.** `AUTH-SETUP-128` stays partial: its packaged two-window+ journey is a manual check on the built shell. "Show in pet" has no scenario+ catalog of its own; the session-actions tests cover it.+## Follow-ups- Bind to the main-agent session when the session type lands, and remove the@@ -775,14 +823,15 @@ The code and its tests are the contract; this section records why.## Todo- [x] Update G8 and G10 in `desktop-product-gaps.md` to point here.-- [ ] Pet window, lifecycle invariants, capability file, and IPC.-- [ ] Global shortcut, tray toggle and presets, `pet.json`.-- [x] `/pet` route and session binding ("Show in pet" ships with the shell PR).+- [x] Pet window, lifecycle invariants, capability file, and IPC.+- [x] Global shortcut, tray toggle and presets, `pet.json`.+- [x] `/pet` route, session binding, and "Show in pet".- [x] `derivePetState` with Vitest coverage.- [x] Panel: latest exchange, activity strip, needs input, text send.- [x] Input-freshness table for the pet route (`usePetSession`, `FencedSource`).- [ ] Shared dictation hook; cross-window voice claim; pet listening flow.- [x] Vibey pose assets, CSS motion, i18n strings.- [ ] Panel frames in `design.pen`.-- [ ] Rust boundary tests; manual checks on macOS and Windows.-- [ ] User docs: `desktop/README.md` pet section.+- [x] Rust boundary tests.+- [ ] Manual checks on macOS and Windows.+- [x] User docs: `desktop/README.md` pet section.diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yamlindex d7d91363c..208252f63 100644--- a/tests/scenarios/auth_setup/catalog.yaml+++ b/tests/scenarios/auth_setup/catalog.yaml@@ -501,7 +501,7 @@ scenarios:visibility change, so finishing the wizard in the main window clears itwithout a restart. The route tests drive the real setup gate, summon storeand config read against controlled responses; the packaged two-window- journey lands with the desktop shell PR that creates the pet window.+ journey through the desktop shell's pet window is a manual check.owning_layer: L4 integrated acceptance (packaged desktop shell against a live instance)partial_evidence:covers: the server half at the real boundary — the `/pet` shell document, authentication refusal of the config read, a signed-in pet read that reports setup pending with the fields the setup rule reads, completion from a second client through CSRF, and the pet's per-call re-read seeing it; the browser rules are the supporting tests below, against controlled responsesdiff --git a/ui/src/components/workbench/sessionActions.tsx b/ui/src/components/workbench/sessionActions.tsxindex bb92c7140..8218ad4c2 100644--- a/ui/src/components/workbench/sessionActions.tsx+++ b/ui/src/components/workbench/sessionActions.tsx@@ -14,7 +14,7 @@ import { SESSION_ROW_ACTION_BUTTON_CLASS } from './sessionRowLayout';// header. The actions themselves (labels, writes, pending state) come from// useSessionActions.tsx; surfaces opt into only the capabilities they can render.-export type SessionActionId = 'pin' | 'reference' | 'fork' | 'rename' | 'hide' | 'archive';+export type SessionActionId = 'pin' | 'reference' | 'fork' | 'pet' | 'rename' | 'hide' | 'archive';/** Menu grouping — rendered with a hairline divider between groups. */export type SessionActionGroup = 'organize' | 'continue' | 'lifecycle';diff --git a/ui/src/components/workbench/useSessionActions.test.tsx b/ui/src/components/workbench/useSessionActions.test.tsxindex 1ea8d8cb2..bc17e4fed 100644--- a/ui/src/components/workbench/useSessionActions.test.tsx+++ b/ui/src/components/workbench/useSessionActions.test.tsx@@ -18,6 +18,8 @@ const mocks = vi.hoisted(() => ({setSessionVisibility: vi.fn(),showToast: vi.fn(),authorizeRouteAction: vi.fn<() => UnsavedChangesActionAuthorization | null>(),+ canShowInDesktopPet: vi.fn(() => false),+ showInPet: vi.fn<(sessionId: string) => Promise<{ shown: boolean }>>(),}));vi.mock('../../context/ApiContext', () => ({@@ -35,6 +37,8 @@ vi.mock('../../context/WorkbenchProjectsContext', () => ({vi.mock('../../context/useUnsavedChangesActionGuard', () => ({useUnsavedChangesActionGuard: () => mocks.authorizeRouteAction,}));+vi.mock('../../lib/desktopShell', () => ({ canShowInDesktopPet: mocks.canShowInDesktopPet }));+vi.mock('../../pet/petBridge', () => ({ petBridge: { showInPet: mocks.showInPet } }));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));const session = (over: Partial<WorkbenchSession> = {}): WorkbenchSession =>@@ -106,6 +110,8 @@ beforeEach(() => {mocks.setSessionPinned.mockResolvedValue(undefined);mocks.archiveSession.mockResolvedValue(undefined);mocks.authorizeRouteAction.mockImplementation(grantedAuthorization);+ mocks.canShowInDesktopPet.mockReturnValue(false);+ mocks.showInPet.mockResolvedValue({ shown: true });});describe('surface-specific actions', () => {@@ -268,3 +274,38 @@ describe('a metadata-only session', () => {expect(h.archiveDialog).toBeNull();});});++// "Show in pet": the Workbench hands one session to the pet.+describe('show in pet', () => {+ it('is offered only by a desktop shell that has a pet', () => {+ expect(mount(options()).actions.map((action) => action.id)).not.toContain('pet');++ mocks.canShowInDesktopPet.mockReturnValue(true);+ const ids = mount(options()).actions.map((action) => action.id);+ expect(ids).toEqual(['pin', 'rename', 'fork', 'pet', 'hide', 'archive']);+ // Read-only sessions still offer nothing.+ expect(mount(options({ session: session({ status: 'archived' }) })).actions).toEqual([]);+ });++ it('binds the session and stays quiet when the pet shows it', async () => {+ mocks.canShowInDesktopPet.mockReturnValue(true);+ select(mount(options()), 'pet');++ expect(mocks.showInPet).toHaveBeenCalledWith('ses_standalone');+ await flush();+ expect(mocks.showToast).not.toHaveBeenCalled();+ });++ it('says how to turn the pet on when it is off, and reports a failure', async () => {+ mocks.canShowInDesktopPet.mockReturnValue(true);+ mocks.showInPet.mockResolvedValueOnce({ shown: false });+ select(mount(options()), 'pet');+ await flush();+ expect(mocks.showToast).toHaveBeenCalledWith('pet.showInPetOff', 'warning');++ mocks.showInPet.mockRejectedValueOnce(new Error('denied'));+ select(mount(options()), 'pet');+ await flush();+ expect(mocks.showToast).toHaveBeenLastCalledWith('pet.showInPetFailed', 'error');+ });+});diff --git a/ui/src/components/workbench/useSessionActions.tsx b/ui/src/components/workbench/useSessionActions.tsxindex 6e613e6d7..47f8a8ee3 100644--- a/ui/src/components/workbench/useSessionActions.tsx+++ b/ui/src/components/workbench/useSessionActions.tsx@@ -1,7 +1,7 @@import type * as React from 'react';import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { Archive, EyeOff, GitFork, Hash, Pencil, Pin, PinOff } from 'lucide-react';+import { Archive, EyeOff, GitFork, Hash, PawPrint, Pencil, Pin, PinOff } from 'lucide-react';import { useApi } from '../../context/ApiContext';import type { WorkbenchSession } from '../../context/ApiContext';@@ -9,7 +9,9 @@ import { useComposerInsertTarget } from '../../context/ComposerBridgeContext';import { useWorkbenchProjectsActions } from '../../context/WorkbenchProjectsContext';import { useToast } from '../../context/ToastContext';import { useUnsavedChangesActionGuard } from '../../context/useUnsavedChangesActionGuard';+import { canShowInDesktopPet } from '../../lib/desktopShell';import { hideSessionToBackground } from '../../lib/sessionVisibilityActions';+import { petBridge } from '../../pet/petBridge';import { archiveRequestIsLive, isSessionReadOnly } from './sessionArchived';import { ArchiveSessionDialog } from './ArchiveSessionDialog';import type { SessionActionDescriptor } from './sessionActions';@@ -171,6 +173,16 @@ export const useSessionActions = ({});}, [target, api.setSessionVisibility, showToast, t]);+ const showInPet = useCallback(() => {+ if (!target) return;+ petBridge.showInPet(target.id).then(+ ({ shown }) => {+ if (!shown) showToast(t('pet.showInPetOff'), 'warning');+ },+ () => showToast(t('pet.showInPetFailed'), 'error'),+ );+ }, [target, showToast, t]);+const actions = useMemo<SessionActionDescriptor[]>(() => {if (!target) return [];const canFork = Boolean(target.native_session_id);@@ -222,6 +234,17 @@ export const useSessionActions = ({onSelect: () => void fork(),});}+ // Only a desktop shell with a pet can take the session; a browser tab or+ // an older shell never sees the row.+ if (canShowInDesktopPet()) {+ rows.push({+ id: 'pet',+ group: 'continue',+ icon: PawPrint,+ label: t('workbench.sessionShowInPet'),+ onSelect: showInPet,+ });+ }rows.push({id: 'hide',group: 'continue',@@ -250,6 +273,7 @@ export const useSessionActions = ({togglePinned,onRenameStart,fork,+ showInPet,hide,requestArchive,archiveHint,diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 27a0db89c..b78c3a40e 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -65,6 +65,11 @@"body": "Background work was canceled."}},+ "pet": {+ "toggle": "Show Pet",+ "shortcutMenu": "Pet Shortcut",+ "shortcutUnavailable": "{{shortcut}} is unavailable — another app may be using it"+ },"uninstall": {"menuLabel": "Uninstall Avibe…","confirmTitle": "Uninstall Avibe",@@ -2919,6 +2924,7 @@"sessionReference": "Reference this session","sessionFork": "Fork session","sessionForkUnavailable": "This session has no native agent session to fork yet.",+ "sessionShowInPet": "Show in pet","sessionHideToBackground": "Hide to background","sessionHiddenToast": "Hidden to background · Find it in Agents → Runs","sessionArchive": "Archive session",@@ -5465,6 +5471,8 @@"unreadBadge_one": "{{count}} unread reply","unreadBadge_other": "{{count}} unread replies","setupPending": "Finish setting up in Avibe to talk to your agent here.",+ "showInPetOff": "The session is set for the pet. Turn on Show Pet in the Avibe tray menu to see it.",+ "showInPetFailed": "The pet could not show this session.","openAvibe": "Open Avibe","toggle": "Show or hide the pet panel","panel": "Pet panel",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 20334cb6d..5c74fb6c7 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -65,6 +65,11 @@"body": "后台工作已取消。"}},+ "pet": {+ "toggle": "显示桌宠",+ "shortcutMenu": "桌宠快捷键",+ "shortcutUnavailable": "{{shortcut}} 不可用,可能已被其他应用占用"+ },"uninstall": {"menuLabel": "卸载 Avibe…","confirmTitle": "卸载 Avibe",@@ -2919,6 +2924,7 @@"sessionReference": "引用该会话","sessionFork": "复刻会话","sessionForkUnavailable": "此会话还没有可复刻的原生 Agent 会话。",+ "sessionShowInPet": "在桌宠中显示","sessionHideToBackground": "隐藏到后台","sessionHiddenToast": "已隐藏到后台 · 可在 Agents→Runs 找回","sessionArchive": "归档会话",@@ -5465,6 +5471,8 @@"unreadBadge_one": "{{count}} 条未读回复","unreadBadge_other": "{{count}} 条未读回复","setupPending": "先在 Avibe 里完成设置,就可以在这里和 agent 对话了。",+ "showInPetOff": "桌宠已切换到这个会话。在 Avibe 托盘菜单中打开“显示桌宠”即可看到。",+ "showInPetFailed": "桌宠无法显示这个会话。","openAvibe": "打开 Avibe","toggle": "展开或收起宠物面板","panel": "宠物面板",diff --git a/ui/src/lib/desktopShell.ts b/ui/src/lib/desktopShell.tsindex ebc3dcc37..26d91a285 100644--- a/ui/src/lib/desktopShell.ts+++ b/ui/src/lib/desktopShell.ts@@ -5,6 +5,8 @@ declare global {readonly __AVIBE_DESKTOP_VERSION__?: string;/** The macOS shell grants Tauri window dragging to this page. */readonly __AVIBE_DESKTOP_DRAG__?: true;+ /** The shell has a desktop pet this page can bind a session to (`pet_bind`). */+ readonly __AVIBE_DESKTOP_PET__?: true;}}@@ -34,3 +36,12 @@ export function desktopDragRegion(): '' | undefined {// whose HTML predates the optional metadata tag.return isDesktopShell() && window.__AVIBE_DESKTOP_DRAG__ === true ? '' : undefined;}++/**+ * True when this Workbench runs in a desktop shell that can show a session in+ * its pet. An older shell has no pet, so the page offers "Show in pet" only on+ * this marker, never on the shell marker alone.+ */+export function canShowInDesktopPet(): boolean {+ return isDesktopShell() && window.__AVIBE_DESKTOP_PET__ === true;+}diff --git a/ui/src/pet/petBridge.ts b/ui/src/pet/petBridge.tsindex ed7b9a9f6..58a96472b 100644--- a/ui/src/pet/petBridge.ts+++ b/ui/src/pet/petBridge.ts@@ -13,6 +13,11 @@ import { openLinkInNewContext } from '@/lib/pwaNavigation';* pet_open({ link }) any link the deep-link parser accepts* plugin:window|start_dragging the `start-dragging` permission*+ * Workbench → shell, granted only to the `main` window ("Show in pet"):+ * pet_bind({ sessionId }) -> PetBinding & { shown: boolean }+ * also brings the pet forward; `shown`+ * is false while the pet is turned off+ ** Shell → page, DOM events dispatched on `window` by a shell-evaluated script* (the same channel as the Settings… menu, so no event permission is needed):* avibe:pet-summon detail { intent } only after pet_ready(); earlier summons@@ -139,6 +144,19 @@ export const petBridge = {return parseBinding(await invoke('pet_unbind', { sessionId }));},+ /**+ * The Workbench's "Show in pet": binds the pet to `sessionId` and brings it+ * forward. `shown` is false while the pet is turned off; the binding is kept+ * for when it is turned on.+ */+ showInPet: async (sessionId: string): Promise<{ shown: boolean }> => {+ const invoke = shellInvoke();+ if (!invoke) throw new Error('the desktop pet is only available in the Avibe desktop app');+ const result = (await invoke('pet_bind', { sessionId })) as { shown?: unknown } | null;+ parseBinding(result);+ return { shown: result?.shown === true };+ },+/** Moves the native window with the pointer (`start-dragging`). */startDragging: (): void => {void shellInvoke()?.('plugin:window|start_dragging');