Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

feat(desktop): add anchored mini cards and voice-first input (#2508)

Max95e13ce4a5b6
diff --git a/desktop/runtime-host/src/pet.rs b/desktop/runtime-host/src/pet.rs
index 80369a835..4afbf36d2 100644
--- a/desktop/runtime-host/src/pet.rs
+++ b/desktop/runtime-host/src/pet.rs
@@ -30,6 +30,7 @@ pub const SHORTCUT_PRESETS: [&str; 3] = [DEFAULT_SHORTCUT, "Control+Shift+Space"
#[serde(rename_all = "lowercase")]
pub enum PetIntent {
Listen,
+ Release,
Show,
}
@@ -55,6 +56,8 @@ pub struct PetPreferences {
pub anchor: Option<PetAnchor>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub binding: Option<String>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub dismissed_ids: Vec<String>,
}
#[derive(Serialize)]
@@ -135,6 +138,8 @@ pub struct PetReady {
#[serde(flatten)]
pub binding: PetBinding,
pub summon_pending: Option<PendingSummon>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub dismissed_ids: Vec<String>,
}
/// The pet's preferences and in-run state, one per shell.
@@ -225,6 +230,7 @@ impl PetStore {
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.preferences.dismissed_ids.clear();
self.revision += 1;
self.persist();
}
@@ -236,12 +242,29 @@ impl PetStore {
pub fn unbind(&mut self, session_id: &str) -> PetBinding {
if self.preferences.binding.as_deref() == Some(session_id) {
self.preferences.binding = None;
+ self.preferences.dismissed_ids.clear();
self.revision += 1;
self.persist();
}
self.binding()
}
+ pub fn set_dismissed_ids(&mut self, session_id: &str, ids: Vec<String>) -> std::io::Result<()> {
+ if self.preferences.binding.as_deref() != Some(session_id) {
+ return Ok(());
+ }
+ if self.preferences.dismissed_ids == ids {
+ return Ok(());
+ }
+ let next = PetPreferences {
+ dismissed_ids: ids,
+ ..self.preferences.clone()
+ };
+ write_preferences(&self.path, &next)?;
+ self.preferences = next;
+ Ok(())
+ }
+
/// 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) {
@@ -265,6 +288,7 @@ impl PetStore {
PetReady {
binding: self.binding(),
summon_pending: self.pending_summon.take().map(|intent| PendingSummon { intent }),
+ dismissed_ids: self.preferences.dismissed_ids.clone(),
}
}
@@ -279,12 +303,15 @@ impl PetStore {
}
/// 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) {
+ /// Runtime. A hotkey becomes a released hold, opening text when ready;
+ /// a show action still opens the stack. Startup never starts a stale mic.
+ pub fn summon_before_window(&mut self, intent: PetIntent) {
self.page_ready = false;
- self.pending_summon = Some(PetIntent::Show);
+ self.pending_summon = Some(if intent == PetIntent::Listen {
+ PetIntent::Release
+ } else {
+ PetIntent::Show
+ });
}
fn persist(&self) {
@@ -348,21 +375,21 @@ impl WorkArea {
fn pet_at(&self, anchor: (f64, f64)) -> LogicalRect {
LogicalRect {
- x: anchor.0,
- y: anchor.1,
- width: self.pet_extent(),
- height: self.pet_extent(),
+ x: restored_window_origin(anchor, self.unit).0,
+ y: restored_window_origin(anchor, self.unit).1,
+ width: WINDOW_WIDTH * self.unit,
+ height: WINDOW_HEIGHT * self.unit,
}
}
}
-// 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;
+// Shared with pet-mini.css: image top-left (172.5, 449), dock at y=552.
+pub const PET_SIZE: f64 = 115.0;
+pub const WINDOW_WIDTH: f64 = 460.0;
+pub const WINDOW_HEIGHT: f64 = 600.0;
+const PET_BOTTOM: f64 = 36.0;
+// pet-mini.css: the dock starts 103px below the image top and is 40px high.
+const PET_AND_DOCK_HEIGHT: f64 = 143.0;
/// Distance from the work area's corner for a pet with no saved place.
const DEFAULT_MARGIN: f64 = 24.0;
@@ -398,29 +425,13 @@ impl Default for PetLayout {
}
}
-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)
- }
+pub fn window_size(_expanded: bool) -> (f64, f64) {
+ (WINDOW_WIDTH, WINDOW_HEIGHT)
}
-/// 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)
+/// The image stays at the same position in every interaction state.
+pub fn pet_offset(_expanded: bool, _layout: PetLayout) -> (f64, f64) {
+ ((WINDOW_WIDTH - PET_SIZE) / 2.0, WINDOW_HEIGHT - PET_BOTTOM - PET_SIZE)
}
pub fn window_origin(anchor: (f64, f64), expanded: bool, layout: PetLayout) -> (f64, f64) {
@@ -442,46 +453,16 @@ pub fn rescale(point: (f64, f64), from_scale: f64, to_scale: f64) -> (f64, f64)
(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 mini has one bottom-anchored column; it never flips or moves on expand.
+pub fn choose_layout(_anchor: (f64, f64), _work_area: LogicalRect) -> PetLayout {
+ PetLayout::default()
}
-/// 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;
+ let (dx, dy) = pet_offset(false, PetLayout::default());
PetAnchor {
- x: work_area.area.right() - inset,
- y: work_area.area.bottom() - inset,
+ x: work_area.area.right() - (WINDOW_WIDTH + DEFAULT_MARGIN) * work_area.unit + dx * work_area.unit,
+ y: work_area.area.bottom() - (WINDOW_HEIGHT + DEFAULT_MARGIN) * work_area.unit + dy * work_area.unit,
monitor: work_area.name.clone(),
}
}
@@ -511,43 +492,77 @@ pub fn restored_window_origin(anchor: (f64, f64), unit: f64) -> (f64, f64) {
/// 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).
+/// connected, else the first area (the primary display). Use the fixed window
+/// on a display that fits it, otherwise preserve access to the image and dock.
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))) {
+ let image = |area: &WorkArea| LogicalRect {
+ x: anchor.x,
+ y: anchor.y,
+ width: PET_SIZE * area.unit,
+ height: PET_SIZE * area.unit,
+ };
+ let footprint = |area: &WorkArea| {
+ if area.area.width >= WINDOW_WIDTH * area.unit && area.area.height >= WINDOW_HEIGHT * area.unit {
+ area.pet_at(at)
+ } else {
+ LogicalRect {
+ height: PET_AND_DOCK_HEIGHT * area.unit,
+ ..image(area)
+ }
+ }
+ };
+ if let Some(home) = work_areas.iter().find(|area| area.area.contains(&footprint(area))) {
return PetAnchor {
monitor: home.name.clone().or_else(|| anchor.monitor.clone()),
..anchor.clone()
};
}
- let overlapping = usable
+ let overlapping = work_areas
.iter()
- .map(|area| (area.area.overlap(&area.pet_at(at)), *area))
+ .map(|area| (area.area.overlap(&image(area)), area))
.filter(|(overlap, _)| *overlap > 0.0)
.max_by(|a, b| a.0.total_cmp(&b.0))
.map(|(_, area)| area);
let named = || {
- usable
+ work_areas
.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 {
+ let Some(target) = overlapping.or_else(named).or_else(|| work_areas.first()) else {
return anchor.clone();
};
+ let bounds = footprint(target);
+ let left = target.area.x + anchor.x - bounds.x;
+ let top = target.area.y + anchor.y - bounds.y;
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()),
+ x: anchor
+ .x
+ .clamp(left, (left + target.area.width - bounds.width).max(left)),
+ y: anchor.y.clamp(top, (top + target.area.height - bounds.height).max(top)),
monitor: target.name.clone(),
}
}
+/// Window-local logical coordinates; shadows deliberately do not enlarge these.
+#[derive(Clone, Copy, Debug, Deserialize)]
+pub struct HitRect {
+ pub x: f64,
+ pub y: f64,
+ pub width: f64,
+ pub height: f64,
+}
+impl HitRect {
+ pub fn valid(&self) -> bool {
+ [self.x, self.y, self.width, self.height].iter().all(|v| v.is_finite())
+ && self.width >= 0.0
+ && self.height >= 0.0
+ }
+ pub fn contains(&self, x: f64, y: f64) -> bool {
+ x >= self.x && x <= self.x + self.width && y >= self.y && y <= self.y + self.height
+ }
+}
+
/// How the platform writes `accelerator` in its menus: `⌃⌥Space` on macOS,
/// `Ctrl+Alt+Space` elsewhere.
pub fn shortcut_label(accelerator: &str, macos: bool) -> String {
@@ -614,6 +629,66 @@ mod tests {
}
}
+ #[test]
+ fn dismissed_cards_survive_restart_and_stay_scoped_to_the_binding() {
+ let directory = TestDirectory::new();
+ // Released files without the optional field retain their binding.
+ std::fs::write(directory.file(), r#"{"version":1,"enabled":true,"binding":"s1"}"#).unwrap();
+ let mut store = PetStore::load(directory.file());
+ assert!(store.page_ready().dismissed_ids.is_empty());
+ store
+ .set_dismissed_ids("s1", vec!["watch:w1".into(), "task:t1".into()])
+ .unwrap();
+ let mut restored = PetStore::load(directory.file());
+ assert_eq!(restored.page_ready().dismissed_ids, vec!["watch:w1", "task:t1"]);
+ restored.bind("s2");
+ restored.set_dismissed_ids("s1", vec!["stale".into()]).unwrap();
+ let mut next = PetStore::load(directory.file());
+ assert_eq!(next.binding().binding.as_deref(), Some("s2"));
+ assert!(next.page_ready().dismissed_ids.is_empty());
+ }
+
+ #[test]
+ fn hit_regions_accept_only_finite_nonnegative_extents() {
+ let rect = HitRect {
+ x: 10.0,
+ y: 20.0,
+ width: 30.0,
+ height: 40.0,
+ };
+ assert!(rect.valid());
+ assert!(rect.contains(10.0, 20.0));
+ assert!(!rect.contains(9.9, 20.0));
+ assert!(!rect.contains(40.1, 20.0));
+ for invalid in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
+ assert!(!HitRect { x: invalid, ..rect }.valid());
+ assert!(!HitRect { y: invalid, ..rect }.valid());
+ assert!(!HitRect { width: invalid, ..rect }.valid());
+ assert!(!HitRect {
+ height: invalid,
+ ..rect
+ }
+ .valid());
+ }
+ assert!(!HitRect { width: -1.0, ..rect }.valid());
+ assert!(!HitRect { height: -1.0, ..rect }.valid());
+ }
+
+ #[test]
+ fn releasing_a_shortcut_during_page_load_never_replays_a_held_microphone() {
+ let directory = TestDirectory::new();
+ let mut store = PetStore::load(directory.file());
+ assert_eq!(store.summon(PetIntent::Listen), None);
+ assert_eq!(store.summon(PetIntent::Release), None);
+ assert_eq!(
+ store.page_ready().summon_pending,
+ Some(PendingSummon {
+ intent: PetIntent::Release
+ })
+ );
+ assert_eq!(store.page_ready().summon_pending, None);
+ }
+
#[test]
fn an_absent_file_or_absent_enabled_follows_the_build_default() {
let directory = TestDirectory::new();
@@ -650,6 +725,7 @@ mod tests {
monitor: None
}),
binding: Some("s1".into()),
+ dismissed_ids: Vec::new(),
})
);
@@ -809,6 +885,7 @@ mod tests {
summon_pending: Some(PendingSummon {
intent: PetIntent::Listen,
}),
+ dismissed_ids: Vec::new(),
};
assert_eq!(
serde_json::to_value(ready).unwrap(),
@@ -835,46 +912,39 @@ mod tests {
}
}
}
- // 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);
+ // Expansion changes no geometry in the fixed mini window.
+ assert_eq!(
+ window_origin(anchor, false, PetLayout::default()),
+ window_origin(anchor, true, PetLayout::default())
+ );
}
#[test]
- fn the_panel_flips_toward_the_room_near_each_screen_edge() {
+ fn the_fixed_window_stays_whole_and_layout_never_flips() {
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 {
+ for anchor in [(1300.0, 780.0), (20.0, 40.0), (700.0, 450.0)] {
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:?}"
- );
+ assert_eq!(layout, PetLayout::default());
}
- // 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,
+ let area = WorkArea {
+ name: Some("primary".into()),
+ area: screen,
+ unit: 1.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);
+ let anchor = default_anchor(&area);
+ let origin = window_origin((anchor.x, anchor.y), false, PetLayout::default());
+ assert_eq!(
+ origin,
+ (
+ screen.right() - WINDOW_WIDTH - DEFAULT_MARGIN,
+ screen.bottom() - WINDOW_HEIGHT - DEFAULT_MARGIN
+ )
+ );
}
#[test]
@@ -892,7 +962,7 @@ mod tests {
// 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.x, clamped.y), (1152.5, 749.0));
assert_eq!(clamped.monitor.as_deref(), Some("Built-in"));
// Half off an edge: pulled in on the display it overlaps.
@@ -902,7 +972,7 @@ mod tests {
monitor: None,
};
let pulled = clamp_anchor(&straddling, &areas);
- assert_eq!((pulled.x, pulled.y), (0.0, 400.0));
+ assert_eq!((pulled.x, pulled.y), (172.5, 474.0));
// With no overlap, its own display wins over the primary one.
let lost = PetAnchor {
@@ -912,7 +982,7 @@ mod tests {
};
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!((home.x, home.y), (3072.5, 904.0));
assert_eq!(clamp_anchor(&lost, &[]), lost, "no display information moves nothing");
@@ -921,24 +991,91 @@ mod tests {
}
#[test]
- fn a_summon_before_any_runtime_waits_for_the_first_page_as_show() {
+ fn short_display_fallback_selects_by_image_overlap_then_saved_display_then_primary() {
+ let areas = [
+ area("primary", 0.0, 0.0, 800.0, 550.0),
+ area("side", 800.0, 0.0, 800.0, 550.0),
+ ];
+ for (x, saved, expected) in [
+ (750.0, "primary", "side"), // Image overlaps side most; transparent frame overlaps primary most.
+ (9000.0, "side", "side"),
+ (9000.0, "detached", "primary"),
+ ] {
+ let restored = clamp_anchor(
+ &PetAnchor {
+ x,
+ y: 500.0,
+ monitor: Some(saved.into()),
+ },
+ &areas,
+ );
+ assert_eq!(restored.monitor.as_deref(), Some(expected));
+ let target = areas
+ .iter()
+ .find(|area| area.name.as_deref() == Some(expected))
+ .unwrap();
+ assert!(target.area.contains(&LogicalRect {
+ x: restored.x,
+ y: restored.y,
+ width: PET_SIZE,
+ height: PET_AND_DOCK_HEIGHT,
+ }));
+ assert_eq!(restored.y, 407.0, "the dock, not only the image, must fit");
+ }
+ }
+
+ #[test]
+ fn a_small_laptop_keeps_its_pet_when_a_full_frame_external_display_is_connected() {
+ let areas = [
+ area("short", 0.0, 0.0, 800.0, 550.0),
+ area("full", 800.0, -100.0, 1000.0, 900.0),
+ ];
+ let on_laptop = PetAnchor {
+ x: 100.0,
+ y: 100.0,
+ monitor: Some("short".into()),
+ };
+ assert_eq!(clamp_anchor(&on_laptop, &areas), on_laptop);
+ let low_laptop = clamp_anchor(&PetAnchor { y: 500.0, ..on_laptop }, &areas);
+ assert_eq!(low_laptop.monitor.as_deref(), Some("short"));
+ assert_eq!((low_laptop.x, low_laptop.y), (100.0, 407.0));
+ assert!(areas[0].area.contains(&LogicalRect {
+ x: low_laptop.x,
+ y: low_laptop.y,
+ width: PET_SIZE,
+ height: PET_AND_DOCK_HEIGHT,
+ }));
+ let external = clamp_anchor(
+ &PetAnchor {
+ x: 900.0,
+ y: 0.0,
+ monitor: Some("full".into()),
+ },
+ &areas,
+ );
+ assert_eq!(external.monitor.as_deref(), Some("full"));
+ assert!(areas[1].area.contains(&areas[1].pet_at((external.x, external.y))));
+ }
+
+ #[test]
+ fn a_hotkey_before_any_runtime_opens_text_without_replaying_capture() {
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();
+ store.summon_before_window(PetIntent::Listen);
// 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
+ intent: PetIntent::Release
})
);
// 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.summon_before_window(PetIntent::Listen);
store.window_gone();
assert_eq!(store.page_ready().summon_pending, None);
}
@@ -957,8 +1094,7 @@ mod tests {
// 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 saved = rescale((3000.0, 200.0), 1.0, primary);
let areas = [
area("primary", 0.0, 0.0, 2560.0 / primary, 1440.0 / primary),
WorkArea {
@@ -975,7 +1111,7 @@ mod tests {
&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!((physical.0 - 3000.0).abs() < 1e-9 && (physical.1 - 673.5).abs() < 1e-9);
assert_eq!(restored.monitor.as_deref(), Some("side"));
assert_eq!(
area_for(&areas, saved).and_then(|area| area.name.as_deref()),
@@ -983,29 +1119,42 @@ mod tests {
);
// 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);
+ let window_at = rescale(
+ restored_window_origin((restored.x, restored.y), window / primary),
+ primary,
+ 1.0,
+ );
+ assert!((window_at.0 - (3000.0 - 258.75)).abs() < 1e-9 && window_at.1.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.
+ // The full fixed window is 690 by 900 units on the dense display.
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 edge = (
+ side.area.right() - (WINDOW_WIDTH - pet_offset(false, PetLayout::default()).0) * side.unit,
+ side.area.bottom() - (WINDOW_HEIGHT - pet_offset(false, PetLayout::default()).1) * side.unit,
+ );
+ // Overlapping the right edge: pulled in by the fixed window extent.
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.
+ assert_eq!(
+ (pulled.x, pulled.y),
+ (
+ edge.0,
+ side.area.y + pet_offset(false, PetLayout::default()).1 * side.unit
+ )
+ );
+ // Inside by the image size but not by the full window is not whole.
let almost = PetAnchor {
x: side.area.right() - 100.0,
y: side.area.bottom() - 100.0,
@@ -1022,9 +1171,13 @@ mod tests {
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);
+ let (dx, dy) = pet_offset(false, PetLayout::default());
assert_eq!(
(corner.x, corner.y),
- (side.area.right() - 168.0, side.area.bottom() - 168.0)
+ (
+ side.area.right() - (WINDOW_WIDTH + DEFAULT_MARGIN - dx) * side.unit,
+ side.area.bottom() - (WINDOW_HEIGHT + DEFAULT_MARGIN - dy) * side.unit,
+ )
);
assert_eq!(clamp_anchor(&corner, &areas), corner);
}
diff --git a/desktop/src-tauri/build.rs b/desktop/src-tauri/build.rs
index 739791e24..5ff50ddaf 100644
--- a/desktop/src-tauri/build.rs
+++ b/desktop/src-tauri/build.rs
@@ -13,6 +13,8 @@ fn main() {
"open_install_docs",
"pet_ready",
"pet_set_expanded",
+ "pet_hit_regions",
+ "pet_set_dismissed",
"pet_bind",
"pet_unbind",
"pet_open",
diff --git a/desktop/src-tauri/capabilities/pet.json b/desktop/src-tauri/capabilities/pet.json
index 04c84003c..50b59cc15 100644
--- a/desktop/src-tauri/capabilities/pet.json
+++ b/desktop/src-tauri/capabilities/pet.json
@@ -1,7 +1,7 @@
{
"$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).",
+ "description": "The desktop pet window's whole native surface: report readiness, record panel state and hit regions, persist dismissed cards, 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": {
@@ -10,6 +10,8 @@
"permissions": [
"allow-pet-ready",
"allow-pet-set-expanded",
+ "allow-pet-hit-regions",
+ "allow-pet-set-dismissed",
"allow-pet-bind",
"allow-pet-unbind",
"allow-pet-open",
diff --git a/desktop/src-tauri/permissions/autogenerated/pet_hit_regions.toml b/desktop/src-tauri/permissions/autogenerated/pet_hit_regions.toml
new file mode 100644
index 000000000..bf5b556bd
--- /dev/null
+++ b/desktop/src-tauri/permissions/autogenerated/pet_hit_regions.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-pet-hit-regions"
+description = "Enables the pet_hit_regions command without any pre-configured scope."
+commands.allow = ["pet_hit_regions"]
+
+[[permission]]
+identifier = "deny-pet-hit-regions"
+description = "Denies the pet_hit_regions command without any pre-configured scope."
+commands.deny = ["pet_hit_regions"]
diff --git a/desktop/src-tauri/permissions/autogenerated/pet_set_dismissed.toml b/desktop/src-tauri/permissions/autogenerated/pet_set_dismissed.toml
new file mode 100644
index 000000000..d63732bcc
--- /dev/null
+++ b/desktop/src-tauri/permissions/autogenerated/pet_set_dismissed.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-pet-set-dismissed"
+description = "Enables the pet_set_dismissed command without any pre-configured scope."
+commands.allow = ["pet_set_dismissed"]
+
+[[permission]]
+identifier = "deny-pet-set-dismissed"
+description = "Denies the pet_set_dismissed command without any pre-configured scope."
+commands.deny = ["pet_set_dismissed"]
diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs
index 5e33f5a3e..91ec84fc1 100644
--- a/desktop/src-tauri/src/lib.rs
+++ b/desktop/src-tauri/src/lib.rs
@@ -1979,6 +1979,8 @@ pub fn run() {
.with_handler(|app, _shortcut, event| {
if event.state() == tauri_plugin_global_shortcut::ShortcutState::Pressed {
pet::wake(app, avibe_runtime_host::pet::PetIntent::Listen);
+ } else {
+ pet::wake(app, avibe_runtime_host::pet::PetIntent::Release);
}
})
.build(),
@@ -2109,6 +2111,8 @@ pub fn run() {
open_install_docs,
pet::pet_ready,
pet::pet_set_expanded,
+ pet::pet_hit_regions,
+ pet::pet_set_dismissed,
pet::pet_bind,
pet::pet_unbind,
pet::pet_open
diff --git a/desktop/src-tauri/src/pet.rs b/desktop/src-tauri/src/pet.rs
index 298e3b106..01d762f96 100644
--- a/desktop/src-tauri/src/pet.rs
+++ b/desktop/src-tauri/src/pet.rs
@@ -16,17 +16,14 @@ 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,
+ anchor_from_window, area_for, clamp_anchor, default_anchor, rescale, restored_window_origin, shortcut_label,
+ valid_session_id, window_size, HitRect, 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::{AppHandle, Manager, Monitor, PhysicalPosition, WebviewUrl, WebviewWindow, WebviewWindowBuilder};
use tauri_plugin_global_shortcut::GlobalShortcutExt;
use url::Url;
@@ -74,6 +71,9 @@ pub struct Pet {
/// The accelerator the OS refused, shown in the tray until a registration succeeds.
shortcut_error: Mutex<Option<String>>,
move_generation: Arc<AtomicU64>,
+ hit_regions: Mutex<Vec<HitRect>>,
+ poll_generation: AtomicU64,
+ poll_wake: Arc<tokio::sync::Notify>,
}
impl Pet {
@@ -87,6 +87,9 @@ impl Pet {
}),
shortcut_error: Mutex::new(None),
move_generation: Arc::new(AtomicU64::new(0)),
+ hit_regions: Mutex::new(Vec::new()),
+ poll_generation: AtomicU64::new(0),
+ poll_wake: Arc::new(tokio::sync::Notify::new()),
}
}
@@ -97,6 +100,16 @@ impl Pet {
pub fn enabled(&self) -> bool {
self.store().enabled()
}
+
+ fn page_loading(&self) {
+ self.store().page_loading();
+ lock(&self.hit_regions).clear();
+ }
+
+ fn window_gone(&self) {
+ self.store().window_gone();
+ lock(&self.hit_regions).clear();
+ }
}
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
@@ -288,9 +301,11 @@ fn reconcile_now(app: &AppHandle) -> Option<WebviewWindow> {
match window {
Some(window) if !change.destroy => return Some(window),
Some(window) => {
+ pet.poll_generation.fetch_add(1, Ordering::SeqCst);
+ pet.poll_wake.notify_one();
let _ = window.destroy();
*lock(&pet.window_origin) = None;
- pet.store().window_gone();
+ pet.window_gone();
}
None => {}
}
@@ -312,15 +327,7 @@ fn build_window(app: &AppHandle, origin: &LoopbackOrigin) -> Option<WebviewWindo
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 anchor = initial_anchor(saved.as_ref(), &areas);
let layout = PetLayout::default();
*lock(&pet.frame) = Frame {
expanded: false,
@@ -330,7 +337,7 @@ fn build_window(app: &AppHandle, origin: &LoopbackOrigin) -> Option<WebviewWindo
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();
+ pet.page_loading();
let builder = WebviewWindowBuilder::new(app, PET_WINDOW, WebviewUrl::External(url))
.initialization_script(DESKTOP_SHELL_MARKER)
.on_new_window(|_, _| tauri::webview::NewWindowResponse::Deny)
@@ -357,16 +364,31 @@ fn build_window(app: &AppHandle, origin: &LoopbackOrigin) -> Option<WebviewWindo
let (x, y) = rescale((x, y), scale, 1.0);
let _ = window.set_position(PhysicalPosition::new(x.round() as i32, y.round() as i32));
}
+ let _ = window.set_ignore_cursor_events(true);
+ start_cursor_poll(app);
Some(window)
}
Err(error) => {
eprintln!("The desktop pet window could not be created: {error}");
- pet.store().window_gone();
+ pet.window_gone();
None
}
}
}
+/// Both restored and first-use positions must remain reachable on short displays.
+fn initial_anchor(saved: Option<&PetAnchor>, areas: &[WorkArea]) -> PetAnchor {
+ match (saved, areas.first()) {
+ (Some(saved), _) => clamp_anchor(saved, areas),
+ (None, Some(primary)) => clamp_anchor(&default_anchor(primary), areas),
+ (None, None) => PetAnchor {
+ x: 0.0,
+ y: 0.0,
+ monitor: None,
+ },
+ }
+}
+
/// Every way to summon the pet. The hotkey listens; everything else shows.
pub fn wake(app: &AppHandle, intent: PetIntent) {
let handle = app.clone();
@@ -378,11 +400,16 @@ pub fn wake(app: &AppHandle, intent: PetIntent) {
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();
+ if intent != PetIntent::Release {
+ pet.store().summon_before_window(intent);
+ }
return;
};
- let _ = window.show();
- let _ = window.set_focus();
+ if intent != PetIntent::Release {
+ let _ = window.show();
+ pet.poll_wake.notify_one();
+ let _ = window.set_focus();
+ }
let deliver = pet.store().summon(intent);
if let Some(intent) = deliver {
dispatch(&window, SUMMON_EVENT, &serde_json::json!({ "intent": intent }));
@@ -424,7 +451,7 @@ fn is_pet_page(origin: Option<&LoopbackOrigin>, url: &Url) -> bool {
/// 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();
+ pet.page_loading();
}
}
@@ -585,13 +612,13 @@ pub fn pet_ready(window: WebviewWindow) -> Result<PetReady, String> {
// window was built without focus.
if ready.summon_pending.is_some() {
let _ = window.show();
+ pet.poll_wake.notify_one();
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.
+/// Records the page state without moving or resizing the fixed mini window.
#[tauri::command]
pub fn pet_set_expanded(window: WebviewWindow, expanded: bool) -> Result<PetLayout, String> {
ensure_pet_page(&window)?;
@@ -599,29 +626,93 @@ pub fn pet_set_expanded(window: WebviewWindow, expanded: bool) -> Result<PetLayo
}
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
- };
+ let pet = window.state::<Pet>();
+ let layout = PetLayout::default();
*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)
}
+#[tauri::command]
+pub fn pet_hit_regions(window: WebviewWindow, rects: Vec<HitRect>) -> Result<(), String> {
+ ensure_pet_page(&window)?;
+ if rects.len() > 4096 || rects.iter().any(|rect| !rect.valid()) {
+ return Err("Invalid pet hit regions.".to_owned());
+ }
+ *lock(&window.state::<Pet>().hit_regions) = rects;
+ Ok(())
+}
+
+#[tauri::command]
+pub fn pet_set_dismissed(window: WebviewWindow, session_id: String, ids: Vec<String>) -> Result<(), String> {
+ ensure_pet_page(&window)?;
+ window
+ .state::<Pet>()
+ .store()
+ .set_dismissed_ids(&session_id, ids)
+ .map_err(|_| "The dismissed pet cards could not be saved.".to_owned())
+}
+
+/// One poller per native window. All window calls and cursor-event toggles
+/// happen on the main thread; a hidden window waits for an explicit wake.
+fn start_cursor_poll(app: &AppHandle) {
+ let pet = app.state::<Pet>();
+ let generation = pet.poll_generation.fetch_add(1, Ordering::SeqCst) + 1;
+ let wake = pet.poll_wake.clone();
+ let app = app.clone();
+ tauri::async_runtime::spawn(async move {
+ let mut ignoring = true;
+ loop {
+ let handle = app.clone();
+ let (send, receive) = tokio::sync::oneshot::channel();
+ if app
+ .run_on_main_thread(move || {
+ let pet = handle.state::<Pet>();
+ if pet.poll_generation.load(Ordering::SeqCst) != generation {
+ return;
+ }
+ let Some(window) = handle.get_webview_window(PET_WINDOW) else {
+ return;
+ };
+ if !window.is_visible().unwrap_or(false) {
+ let _ = send.send((None, ignoring));
+ return;
+ }
+ let (Ok(cursor), Ok(origin), Ok(scale), Ok(size)) = (
+ handle.cursor_position(),
+ window.outer_position(),
+ window.scale_factor(),
+ window.inner_size(),
+ ) else {
+ let _ = send.send((Some(100), ignoring));
+ return;
+ };
+ let x = (cursor.x - origin.x as f64) / scale;
+ let y = (cursor.y - origin.y as f64) / scale;
+ let in_window =
+ x >= 0.0 && y >= 0.0 && x < size.width as f64 / scale && y < size.height as f64 / scale;
+ let next = !lock(&pet.hit_regions).iter().any(|rect| rect.contains(x, y));
+ if next != ignoring && window.set_ignore_cursor_events(next).is_ok() {
+ ignoring = next;
+ }
+ let _ = send.send((Some(if in_window { 16 } else { 100 }), ignoring));
+ })
+ .is_err()
+ {
+ break;
+ }
+ let Ok((delay, applied)) = receive.await else {
+ break;
+ };
+ ignoring = applied;
+ if let Some(delay) = delay {
+ tokio::time::sleep(Duration::from_millis(delay)).await;
+ } else {
+ wake.notified().await;
+ }
+ }
+ });
+}
+
#[derive(Serialize)]
pub struct BindResult {
#[serde(flatten)]
@@ -688,6 +779,150 @@ pub fn pet_open(window: WebviewWindow, link: String) -> Result<(), String> {
mod tests {
use super::*;
+ #[test]
+ fn window_build_placement_keeps_the_image_and_dock_reachable_on_small_displays() {
+ let area = |name: &str, x, y, width, height, unit| WorkArea {
+ name: Some(name.into()),
+ area: LogicalRect { x, y, width, height },
+ unit,
+ };
+ let detached = PetAnchor {
+ x: 9000.0,
+ y: 9000.0,
+ monitor: Some("detached".into()),
+ };
+ let primary_125 = area("primary", 0.0, 0.0, 1366.0 / 1.25, 718.0 / 1.25, 1.0);
+ let side_150 = area("side", -1200.0, -180.0, 1200.0, 660.0, 1.5 / 1.25);
+ let cases = [
+ (
+ "detached display",
+ Some(detached.clone()),
+ vec![area("primary", 0.0, 0.0, 800.0, 550.0, 1.0)],
+ 1.0,
+ "primary",
+ ),
+ (
+ "125% primary",
+ Some(detached.clone()),
+ vec![primary_125.clone()],
+ 1.25,
+ "primary",
+ ),
+ (
+ "small laptop with full-size external connected",
+ Some(PetAnchor {
+ x: 100.0,
+ y: 500.0,
+ monitor: Some("primary".into()),
+ }),
+ vec![
+ primary_125.clone(),
+ area("external", 1366.0 / 1.25, 0.0, 1920.0, 1080.0, 1.2),
+ ],
+ 1.25,
+ "primary",
+ ),
+ (
+ "mixed DPI with negative origin",
+ Some(PetAnchor {
+ monitor: Some("side".into()),
+ ..detached.clone()
+ }),
+ vec![primary_125, side_150],
+ 1.25,
+ "side",
+ ),
+ (
+ "negative primary",
+ Some(detached),
+ vec![area("primary", -800.0, -550.0, 800.0, 550.0, 1.0)],
+ 1.0,
+ "primary",
+ ),
+ (
+ "first use on narrow display",
+ None,
+ vec![area("primary", 0.0, 0.0, 200.0, 500.0, 1.0)],
+ 1.0,
+ "primary",
+ ),
+ ];
+ for (case, saved, areas, primary_scale, expected_display) in cases {
+ // This is build_window's actual anchor selection and coordinate
+ // conversion, including the target monitor's own logical scale.
+ let anchor = initial_anchor(saved.as_ref(), &areas);
+ let target = area_for(&areas, (anchor.x, anchor.y)).unwrap();
+ assert_eq!(target.name.as_deref(), Some(expected_display), "{case}");
+ let origin = restored_window_origin((anchor.x, anchor.y), target.unit);
+ let (dx, dy) = avibe_runtime_host::pet::pet_offset(false, PetLayout::default());
+ let image = (origin.0 + dx * target.unit, origin.1 + dy * target.unit);
+ let physical_image = rescale(image, primary_scale, 1.0);
+ let physical_unit = target.unit * primary_scale;
+ let physical_area = LogicalRect {
+ x: target.area.x * primary_scale,
+ y: target.area.y * primary_scale,
+ width: target.area.width * primary_scale,
+ height: target.area.height * primary_scale,
+ };
+ // CSS: 115px image; dock top 103px, height 40px, centred and
+ // narrower than the image. Both rects must fit in physical pixels.
+ assert!(physical_image.0 >= physical_area.x - 1e-9, "{case}");
+ assert!(physical_image.1 >= physical_area.y - 1e-9, "{case}");
+ assert!(
+ physical_image.0 + 115.0 * physical_unit <= physical_area.x + physical_area.width + 1e-9,
+ "{case}"
+ );
+ assert!(
+ physical_image.1 + 143.0 * physical_unit <= physical_area.y + physical_area.height + 1e-9,
+ "{case}"
+ );
+ assert_eq!(window_size(false), (460.0, 600.0));
+ assert_eq!(window_size(true), (460.0, 600.0));
+ }
+ assert_eq!(
+ initial_anchor(None, &[]),
+ PetAnchor {
+ x: 0.0,
+ y: 0.0,
+ monitor: None
+ }
+ );
+ }
+
+ #[test]
+ fn document_and_window_lifetimes_release_input_regions_and_fence_summons() {
+ let directory = tempfile::tempdir().unwrap();
+ let pet = Pet::new(directory.path().join("pet.json"));
+ let seed = || {
+ pet.store().page_ready();
+ lock(&pet.hit_regions).push(HitRect {
+ x: 10.0,
+ y: 20.0,
+ width: 100.0,
+ height: 50.0,
+ });
+ };
+ seed();
+ pet.page_loading();
+ assert!(lock(&pet.hit_regions).is_empty());
+ assert!(!pet.store().page_is_ready());
+ assert_eq!(pet.store().summon(PetIntent::Show), None);
+ // A reload/build keeps a queued summon until the replacement is ready.
+ pet.page_loading();
+ assert_eq!(pet.store().page_ready().summon_pending.unwrap().intent, PetIntent::Show);
+
+ seed();
+ pet.store().page_loading();
+ assert_eq!(pet.store().summon(PetIntent::Listen), None);
+ pet.window_gone();
+ assert!(lock(&pet.hit_regions).is_empty());
+ assert!(!pet.store().page_is_ready());
+ assert!(pet.store().page_ready().summon_pending.is_none());
+ // A fresh document may register its own regions after the old ones go.
+ seed();
+ assert!(lock(&pet.hit_regions)[0].contains(50.0, 40.0));
+ }
+
#[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();
diff --git a/desktop/src-tauri/tests/shell_boundaries.rs b/desktop/src-tauri/tests/shell_boundaries.rs
index 980276e6f..977d13c8e 100644
--- a/desktop/src-tauri/tests/shell_boundaries.rs
+++ b/desktop/src-tauri/tests/shell_boundaries.rs
@@ -402,6 +402,8 @@ fn every_shell_command_is_declared_so_its_permission_exists() {
"open_install_docs",
"pet_ready",
"pet_set_expanded",
+ "pet_hit_regions",
+ "pet_set_dismissed",
"pet_bind",
"pet_unbind",
"pet_open",
@@ -1091,6 +1093,8 @@ fn the_pet_and_the_workbench_get_only_their_pet_commands_on_loopback_pages() {
serde_json::json!([
"allow-pet-ready",
"allow-pet-set-expanded",
+ "allow-pet-hit-regions",
+ "allow-pet-set-dismissed",
"allow-pet-bind",
"allow-pet-unbind",
"allow-pet-open",
diff --git a/docs/plans/2026-10-01-desktop-pet.md b/docs/plans/2026-10-01-desktop-pet.md
index 81345fda0..3a876a5ad 100644
--- a/docs/plans/2026-10-01-desktop-pet.md
+++ b/docs/plans/2026-10-01-desktop-pet.md
@@ -1,5 +1,8 @@
# Desktop Pet
+The mini layout and interactions are superseded by [Desktop mini v2](2026-10-12-desktop-mini-main-agent.md). Binding, authorization, send ownership, and lifecycle rules below still apply.
+
+
Status: in progress (2026-10-04). Delivery is split into three PRs; see
"Implementation notes".
diff --git a/docs/plans/2026-10-12-desktop-mini-delivery.md b/docs/plans/2026-10-12-desktop-mini-delivery.md
new file mode 100644
index 000000000..0e24ec6f7
--- /dev/null
+++ b/docs/plans/2026-10-12-desktop-mini-delivery.md
@@ -0,0 +1,303 @@
+# Desktop mini v2 delivery contract and evidence
+
+The behavior contract is [the verbatim owner specification](2026-10-12-desktop-mini-main-agent.md).
+This implementation builds on the existing binding, authorization, send-ownership,
+quick-reply, and pet lifecycle paths. Backend APIs are outside this change.
+
+## Change contract
+
+- Vibey's image box stays at `(172.5, 449, 115, 115)` in a fixed `460 × 600`
+ logical-pixel window. The column grows upward; expanded content scrolls inside
+ a fixed 292px viewport. Inner detail and card exits never resize the window.
+- Main history is read through `api.getMainSession()`, currently adapting the
+ existing pet binding. The switcher remains available in the main-card detail.
+- Main detail retains Markdown, quick replies, vault actions, queue and uncertain
+ send notices. Mark-read additionally waits for the result to intersect the
+ fixed scroll viewport. One document-level send owner survives component changes.
+ The unread badge remains until the inbox confirms the read. Without a main
+ exchange, the picker remains reachable, including when sub-task cards exist.
+- `usePetSession` owns one surface epoch: binding plus authorization generation.
+ A change clears retained cards, stop/dismiss phases and timers, ordering and
+ the switcher before paint. Late surface callbacks cannot write into another
+ epoch. Authorization changes preserve the user's draft and composing state;
+ binding changes retain their existing reset behavior.
+- Background activities supply sub-task cards. Running items lead when collapsed;
+ expanded order is stable and new items enter below main. Watch/task pause calls
+ use their native IDs, require a second press within 3s, and wait for the response.
+ Success lingers for 2.5s before the two-beat exit. Agent runs have no stop control.
+ Durable `enabled` watches and `scheduled` tasks can be paused while waiting;
+ only `running`/`processing` executions affect the running dot, order and busy pose.
+- Dismissal writes the optional `dismissed_ids` field in `pet.json`. Old files load;
+ a binding change clears the IDs. Only an authoritative turn read removes stale IDs.
+- The page reports clipped logical hit rectangles. The native poller runs at 16ms
+ inside the window, 100ms outside, and sleeps while hidden. Both new commands
+ enforce the existing pet-only origin/caller check and capability boundary.
+ Unmounting the page clears the rectangles, so authorization rechecks leave
+ the empty native window fully click-through.
+- If the selected work area cannot fit the fixed frame, placement instead contains
+ the 115px image and its dock (143px combined height). The transparent frame
+ may overflow; the expanded list can be clipped at the top. Selection keeps
+ image-overlap, saved-display, primary priority across all connected displays.
+ The footprint is decided per target, so a small laptop keeps its pet when a
+ large external display is connected. Both saved and first-use anchors take
+ the same path; full-frame fitting on the target and no-display behavior stay
+ intact. This is the owner-approved §9.1 fallback after breaker diagnosis.
+- Hotkey press and release are distinct. A released hotkey during page/runtime
+ startup opens text rather than starting a microphone later. Hold threshold is
+ 320ms; leaving before the threshold cancels it. Dragging retains the existing path.
+- Voice ownership remains a separate commit. Composer receives only the readiness
+ wait; its dictation implementation is not refactored. Pet uses the existing
+ `ShowPageVoiceDictation` wrapper and thus the same capture/transcription pipeline.
+
+## Voice gate: deliberately off by default
+
+No production shell currently installs `__AVIBE_PET_VOICE_ENABLED__`. Pet voice
+therefore stays off on every platform, even when Web Locks and ASR are available.
+Hotkey/hold open text, and both microphone controls are hidden. Missing Web Locks
+also denies pet voice regardless of this marker. This follows the owner's
+explicit requirement to withhold default enablement until captured-speech handoff
+has been demonstrated across the desktop webviews.
+
+In the isolated macOS desktop build, `main` and `pet` both exposed Web Locks and
+reported the same `avibe.voice-capture` owner/client ID. A pet claim changed that
+owner and finished the main Composer's pending dictation. **The main capture had
+not produced a transcript**, so this does not prove captured speech survives a
+real cross-webview handoff. Background scripted audio startup was suspended, and
+the native driver refused the main mic's background AX action. No foreground
+activation was requested to bypass that refusal. The release gate remains off;
+no shell arbiter was added.
+
+Independent-module unit tests share one fake lock manager and prove local
+ownership/release semantics, newest-claim ordering, remote-steal finalization,
+and preservation of buffered PCM through `finish()`. They do not substitute for
+the missing desktop captured-speech evidence.
+
+## Visual evidence
+
+The task shell was built as a separate **Avibe Mini.app**, identifier
+`bot.avibe.desktop.mini`, and pointed through `AVIBE_DESKTOP_ORIGIN` at a test-only
+loopback server. Its real native `main` and `pet` webviews loaded a production
+bundle of the branch's real Composer/PetPage components. Session, authorization,
+ASR responses and microphone samples were test fixtures. No production runtime,
+user session, physical microphone, or external transcription service was used.
+The installed `/Applications/Avibe.app` was not replaced, and the local `vibe`
+service was not restarted.
+
+The reference was rendered from the untouched prototype source copied into an
+isolated temporary directory. Both views were compared at 460 × 600 logical px,
+with Vibey aligned. The prototype retains its surrounding page copy, mock tool
+phrases and run stop controls; production uses the specified status fallback,
+existing theme mint/background roles, and hides run stop. Its fixture also has
+one fewer sub-task, so the collapsed layer height differs by one 9px step.
+
+![Prototype and native desktop comparison](desktop-mini-v2-evidence/reference-comparison.png)
+
+![Native desktop states](desktop-mini-v2-evidence/states.png)
+
+Individual captures:
+
+- [Collapsed](desktop-mini-v2-evidence/desktop-collapsed.png)
+- [Expanded](desktop-mini-v2-evidence/desktop-expanded.png)
+- [Scrolled](desktop-mini-v2-evidence/desktop-scrolled.png)
+- [Main detail open](desktop-mini-v2-evidence/desktop-main-detail.png)
+- [Input bubble open](desktop-mini-v2-evidence/desktop-bubble-open.png)
+- [Listening UI](desktop-mini-v2-evidence/desktop-dictating.png)
+- [Pause confirmation](desktop-mini-v2-evidence/desktop-stop-confirm.png)
+- [Mid-dismiss](desktop-mini-v2-evidence/desktop-mid-dismiss.png)
+
+The listening screenshot uses the QA-only voice marker and synthetic audio; it
+is UI evidence, not permission to enable production voice. For a reproducible
+static mid-dismiss image, the actual CSS animations were paused at 100ms using
+Web Animations, and the test harness delayed row removal. Ordinary-timing tests
+separately assert the 500ms removal and 2.5s stop linger. The remaining captures
+wait for the requested DOM state and its transition before native window capture.
+[Measured geometry](desktop-mini-v2-evidence/geometry.json) records unchanged
+Vibey bounds and window dimensions across the seven steady states.
+
+The owner corrected spec §3.3 during review: collapsed layers now match the
+front card's measured height instead of a fixed 52px. The refreshed native
+collapsed capture measures a 90px front card, five 90px layers, a 135px stack,
+and 45px between the front and final layer's bottom edges. The reference was
+recopied from the corrected prototype source. The owner's subsequent §3.2 decision
+removes the desktop backing fill, retaining all padding and geometry. The gaps
+show the desktop and are absent from the native hit-region reports. The prototype
+keeps its page-coloured plate solely to cover the surrounding web-page text.
+
+## Validation
+
+- Focused pet, voice ownership, dictation-wrapper and bridge suites: 156 tests.
+ The parity sweep also ran all 15 existing session-action hook tests,
+ including “Show in pet”, and 13 session-action component tests:
+ 184 passing UI tests in total.
+ The five retained-card regressions were also run against isolated copies of
+ the pre-fix `be8701709` surface: all five fail because the revoked title
+ remains visible. They pass with the epoch repair. The temporary copies were
+ removed without changing the worktree's production files.
+- `npm run test:pet-mini`: 14 real-browser layout/lifecycle checks across Chromium and
+ WebKit. They cover both front-card heights and 1/3/5 layers, exact stack/peek
+ geometry, long-title containment, unchanged avatar bounds on expansion, and
+ transparent gaps excluded from the actual hit-region reporter's output.
+ Unmounting during motion releases all hit regions without later reinstalling
+ them; remounting reports the new surface's regions.
+- UI production build.
+- Desktop workspace Rust tests: 370 passed, including shell capability boundaries,
+ fixed-window anchoring, optional persistence and cold-start shortcut release.
+ Small-display cases consume the shell's actual initial-anchor function and
+ window-origin/DPI conversion, checking the image and dock in physical pixels;
+ they do not claim an OS display reconfiguration on this Mac.
+- Desktop workspace formatting and clippy for all targets/features, warnings denied.
+- Separate macOS app bundle build and native screenshots above.
+
+The PR's exact-head Codex review, unresolved-thread inventory and CI are separate
+delivery gates. Windows/Linux native visual and voice handoff evidence is not
+claimed by these macOS captures. Production voice stays off pending its gate.
+
+## Test preservation
+
+All 66 pre-v2 `PetPage` cases from base `5018b6ffc` remain. Twenty keep their
+original titles and bodies; 46 adapt entry points, selectors or names to the
+main-card/detail and input-slot model. Five of those have renamed titles:
+four replace native-resize terminology with panel activation, and one follows
+v2 §8 by including the main session's own running sub-tasks in Vibey's busy pose.
+No binding, authorization, send, unread, setup or event-order invariant was
+removed. The PR body lists every adapted original test and its reason.
+
+The default bound-session fixtures now contain one user message so a main card
+exists to open; separate empty-session cases cover switching with and without
+background work. A failed-first-session-read case verifies that the status event
+performs a second read, restores the validated chat capability and permits a
+send; it no longer uses the removed v1 session-title header as a proxy.
+
+The suite has 92 cases after additions. In particular, the quick-reply tests
+exercise both orders of `message.updated` and the POST response, preserve the
+single-message lock while pending, and verify an older update cannot reclaim a
+newer result's options. A separate uncertain quick-reply case blocks both typed
+input and newer quick-reply groups until admission uncertainty is resolved.
+
+## v1 capability parity sweep
+
+Checked against base `5018b6ffc` before the post-breaker push. Every requested
+capability remains; the deliberate v1 removals are the resizable side-panel
+geometry and automatic panel expansion, replaced by the spec's fixed stack.
+The following separates automated consuming evidence from native event-wiring
+inspection; it does not claim new manual OS-input tests.
+
+| Capability | v2 status and evidence |
+| --- | --- |
+| Summon before ready; setup pending | Preserved. Runtime-host tests cover queued summons and release during startup; PetPage tests cover pre-ready binding/revision races and setup recovery on summon/focus. |
+| “Show in pet” under the main-session mock | Preserved. `useSessionActions` still calls `petBridge.showInPet`; its three existing tests cover availability, binding, off-state and failure messages. `api.getMainSession()` reads the same shell binding. |
+| Tray toggle; shortcut-refused message | Preserved. Native `toggle` persists the explicit preference, registers/unregisters shortcuts and reconciles the window. Registration failure still populates the localized tray message. Store and native catalog tests pass; OS shortcut contention was verified by source parity, not a fresh registration probe. |
+| Drag and anchor save | Preserved. The avatar's drag threshold calls `startDragging`; native `Moved` debounces for 400ms and saves the image anchor in the stable coordinate space. Persistence and mixed-DPI placement tests cover the storage/restore path; the new build-boundary tests cover too-small work areas. |
+| Closing only hides the pet | Preserved. `CloseRequested` still prevents closure and calls `pet::hide`, retaining the page and binding. This native event wiring is unchanged from v1. |
+| Dock reopen while the pet is visible | Preserved. The macOS `Reopen` branch checks main-window visibility, independently of the pet, then restores main. Existing shell-boundary coverage and unchanged event wiring were checked. |
+| Destroy on Runtime stop, loss or origin change | Preserved. The sole active-origin setter calls `pet::reconcile`; `window_change` destroys/rebuilds as required. Its consuming tests cover loss, replacement and disabling. Destruction also invalidates the poller and clears hit regions. |
+| Navigation guard | Preserved. The pet admits only `/pet` at the exact Runtime origin; new windows are denied. Native tests exercise the origin/path predicate. |
+| Caller checks on every pet command | Preserved. `pet_ready`, `pet_set_expanded`, `pet_hit_regions`, `pet_set_dismissed`, `pet_unbind` and `pet_open` check the pet caller. `pet_bind` admits either the validated main caller or the pet. Caller tests and the complete command/capability inventory in `shell_boundaries` pass. |
+| Mark-read rules | Preserved and narrowed to the visible main detail. Active-window, complete-unread-tail and rendered-result checks remain; viewport intersection adds the v2 scroll gate. PetPage tests cover hidden/switcher/unfocused states, retry, duplicate avoidance, old binding, trimmed tails, and “More in Avibe” when the unread tail is incomplete. |
+
+## Review inventory
+
+The first findings-bearing head, `6b969e9d2`, received three Codex findings:
+
+| Root-cause class | Resolution and consuming evidence |
+| --- | --- |
+| Durable activity status mapping | Separate pause eligibility from execution; watch/task interaction fixtures use the producer's `enabled`/`scheduled` statuses. |
+| Unread affordance preservation | Restore the existing ready-state badge and test that the inbox owns its removal. |
+| Binding control reachability | Keep the picker accessible before the first exchange, with and without sub-task cards; test selecting another session in both states. |
+
+The second findings-bearing head, `fe0736241`, received one finding:
+
+| Root-cause class | Resolution and consuming evidence |
+| --- | --- |
+| Native hit-region lifecycle cleanup | Clear shell rectangles when PetPage unmounts and when the shell loads a document or loses a window. Chromium/WebKit tests remove the page during motion, assert the empty surface stays click-through beyond the motion window, and verify new regions on remount. A shell lifecycle test consumes the same loading/destruction methods and checks input release and pending-summon ownership. |
+
+The whole lifecycle class was checked in this repair:
+
+- Authorization loading removes only PetPage: its effect cleanup clears regions
+ and cancels its animation/observer work.
+- Hide/show retains the document and its regions. A hidden native window cannot
+ intercept desktop input; the poller sleeps while hidden and wakes on summon.
+ Summon changes the rendered panel through the existing DOM reporter.
+- Runtime loss or replacement destroys the window and invalidates its poller
+ generation. The shell now clears the old rectangles at this boundary as well.
+- Window creation now clears regions before building, without waiting for the
+ first page-load callback. Navigation/reload uses the same loading method.
+ Queued summons survive loading but are discarded when the window is gone.
+
+The third findings-bearing head, `b4b835cad`, received one finding:
+
+| Root-cause class | Resolution and consuming evidence |
+| --- | --- |
+| Fixed-frame work-area fallback / anchor recoverability | Select the display by image overlap, saved display, then primary; contain the full frame if that target fits it, or the image and dock otherwise. The shell's actual `initial_anchor`/window-origin conversion is tested for a detached display, a 125% primary, mixed DPI, negative origins, and first use on a narrow display. Selection priority and per-target footprint choice are also tested, including a small laptop coexisting with a full-size external display. |
+
+Three distinct findings-bearing heads carried five findings in five classes.
+Counts use the review envelope's commit, not the inline comment's reanchored
+commit. The post-rewrite breaker tripped and the lane stopped before edits or
+pushes. Parent session `sesexk2xpr89k` independently verified the entire GitHub
+inventory, inspected the placement implementation and consuming tests, and
+recorded its diagnosis and resumption authorization on 2026-10-12 at 17:52
+UTC+08:00. The model stays; no architecture rewrite is needed. The classes are
+v1 affordances omitted by the rewrite, plus lifecycle/placement boundaries
+introduced by the fixed frame. The amended authoritative spec §9.1 records the
+small-display fallback. The breaker remains armed: a repeated root class on the
+next head stops the lane again before further edits or pushes.
+
+The parent spot-check of `be8701709` identified a sibling before the next bot
+verdict: globally filtering to full-frame-fitting displays moved a pet from a
+small laptop to its large external screen. At 18:03 UTC+08:00 the parent amended
+spec §9.1 to choose from all displays first and decide the footprint per target,
+and explicitly authorized the correction. The tests now keep the laptop pet on
+the laptop while still clamping the full frame on its external display. This
+correction was prepared locally while review was pending; it must not be pushed
+until that exact-head review is terminal.
+
+The fourth findings-bearing head, `be8701709`, received one finding:
+
+| Root-cause class | Resolution and consuming evidence |
+| --- | --- |
+| Authorized surface state outliving its binding/authorization context | One epoch from `usePetSession` invalidates retained cards and every late presentation writer. PetPage tests cover watch/task pause success and failure, dismiss with an already-queued removal callback, binding A→B→A, typed and quick-reply sends, remount uncertainty, a queued native pick, voice preview/finalization, animation hit reports, and result intersection/read completion. |
+
+The inventory is now four findings-bearing heads and six findings in six narrow
+classes. Native hit-region lifetime and authorized UI retention share the wider
+family of surface state outliving its context. The lane stopped again. Parent
+`sesexk2xpr89k` independently fetched the review envelopes, read the affected
+code and authorized this family-wide repair at 18:12 UTC+08:00 on 2026-10-12,
+together with the per-display correction. **Any finding on the next head stops
+the lane for another full inventory and parent diagnosis before edits or push.**
+Before this push, the parent independently inspected the epoch owner, callback
+fences and per-display diff, ran nine selected consuming cases successfully,
+and confirmed the repair could proceed (parent Run `936fd3cc76bd`).
+
+### Epoch ownership and callback audit
+
+The existing authorization event owner in `usePetSession` synchronously advances
+the generation before React commits its reset. No second surface authorization
+listener was added. The epoch also checks the current binding and mount lifetime.
+The only production `currentBinding()` read in pet code is this central check;
+the previous call-site comparisons have been replaced.
+
+| Writer | Boundary |
+| --- | --- |
+| Typed send / quick reply | Capture the epoch before admission; ignore late rows, optimistic titles and draft clearing after invalidation. |
+| Dismiss / stop | Clear retained cards, phase refs, leaving IDs, ordering and timers before paint. Guard confirmation expiry, pause success/failure, stopped linger and queued removal by their captured epoch. |
+| Voice | Abort on epoch cleanup; fence status reads, capture startup, preview and final text. User-typed draft survives. Production voice remains off. |
+| Switcher | Close on epoch reset. Gate the UI pick with the full epoch and any queued, unsent native bind with its authorization generation. |
+| Hit regions | Dispose the old reporter, clear regions and fence queued animation callbacks before the new reporter takes ownership. Setup-only reporting is fenced by its mount lifetime because it has no session. |
+| Mark-read | Tag result intersections with the epoch. Ignore old observer/read completions; a new epoch requires a new visible-result observation. |
+| Focus / hold / sleep / post-send grace | Timers check the captured epoch before changing surface state. |
+
+Intentional document-owned exceptions preserve existing invariants:
+
+- The send ledger always releases its own in-flight slot, and records uncertain
+ admission for the original session even after a recheck or remount. Discarding
+ those writes would leave a stuck lock or permit duplicate messages. These
+ records contain no retained task/watch title.
+- A bind IPC already sent changes the native shell's authoritative binding.
+ Its reply still enters the monotonic revision ledger; the UI reads authorized
+ session data afresh. A queued pick that has not reached native is dropped on
+ authorization invalidation. Using the full binding predicate on that queue
+ would reject the pick's own intentional optimistic binding change.
+- Panel acknowledgments stay serialized by the existing document-level panel
+ owner. Persisted dismissal IDs likewise record already-completed user actions;
+ they do not carry authorized presentation data. Surface callbacks that create
+ those actions are epoch-fenced.
diff --git a/docs/plans/2026-10-12-desktop-mini-main-agent.md b/docs/plans/2026-10-12-desktop-mini-main-agent.md
new file mode 100644
index 000000000..a3e77700c
--- /dev/null
+++ b/docs/plans/2026-10-12-desktop-mini-main-agent.md
@@ -0,0 +1,557 @@
+# Desktop mini (main agent) — interaction and implementation spec
+
+Status: ready for implementation, v2 (2026-10-12). Supersedes v1 of this file.
+
+- **Reference prototype:** Show Page "会话卡片" tab,
+ <https://max-app.avibe.bot/show/sesexk2xpr89k/>. The source is
+ `src/pages/index.tsx` and `src/styles.css` in the Show Page workspace
+ `/Users/max/.avibe/show/sesexk2xpr89k/`. Every size, colour, duration and
+ curve below was read from that source.
+- **Precedence:** where this spec and the prototype disagree, this spec wins.
+ §12 lists the prototype-only parts.
+- **Owner decisions:** every behaviour here was decided with the owner in the
+ design session. Do not "simplify" a detail away. If a detail cannot be built
+ as written, stop and ask.
+- **Existing design:** `docs/plans/2026-10-01-desktop-pet.md` (#2384, #2401,
+ #2408) stays the base for binding, IPC, the shortcut, `pet.json`, poses and
+ mark-read. This spec changes the layout and interaction on top of it.
+
+## 1. What changes, in one walk-through
+
+1. Vibey (歪比) sits at the bottom of the mini. Above it is a **collapsed
+ stack**. The front card is the **main agent card**: the user's last message
+ to the main agent, and below it what the agent is doing ("Thinking").
+ Thin layers under it show that more cards exist.
+2. The user clicks Vibey or the stack. The stack **expands upward** into a
+ fixed-height, scrollable list. Under the main agent card are the main
+ agent's **sub-task cards**: delegated runs, watches and scheduled tasks.
+ Vibey does not move.
+3. The user **presses and holds Vibey** and speaks. The cards fade aside. A
+ one-line **marquee** above Vibey's head shows the live transcript. The
+ user releases.
+4. The marquee becomes an **input bubble** in the same place, prefilled. The
+ user edits and presses Enter. The main agent card now shows that message,
+ and its subtitle follows the turn: Thinking → Ran command → "已回复:…".
+ If the agent hands work off, a new sub-task card appears below.
+5. A sub-task card has a **stop** button. The first press asks "停止?", the
+ second stops it. A card's **×** removes it from the stack.
+
+The mini talks **only to the main agent**. To change a sub-task, the user tells
+the main agent; there is no Follow up on cards.
+
+## 2. Terms
+
+| Term | Meaning |
+|---|---|
+| Main agent | The user's built-in `main` session (§10). |
+| Main agent card | The pinned first card; it represents the main agent's current or last turn. |
+| Sub-task card | One in-flight item of the main agent: a delegated run, a watch or a scheduled task. |
+| Collapsed stack | The front card plus one layer per remaining card. |
+| Expanded list | Every card at full size, in a fixed-height scroll box. |
+| Speech slot | The single place between the cards and Vibey's head that holds the marquee or the input bubble. |
+| Dock | The small two-button pill under Vibey's feet. |
+
+## 3. Layout
+
+### 3.1 Column and anchoring
+
+- **Vibey is anchored.** Nothing in this spec moves Vibey on screen:
+ expanding, collapsing, the speech slot, dismissing or stopping a card.
+- Above Vibey is one **column**: the card stack, then the speech slot. Its
+ bottom sits on the top edge of Vibey's image box and overlaps it by 4px
+ (the art has its own transparent margin). The column is centred on Vibey.
+- The column grows **upward**. It is a floating layer above everything else
+ in the window.
+- **Column width:** `min(440px, 94vw)`. Every card, the marquee and the input
+ bubble are **the same width**: the column minus 18px on each side.
+ - Expanded: 6px panel padding plus 12px scroll padding.
+ - Collapsed: 18px stack padding.
+- A card's width never depends on its content or on the number of cards.
+- **Long text never widens anything.** Every flex/grid item on the path from
+ the list to a text node needs `min-width: 0`, and grid rows need
+ `grid-template-columns: minmax(0, 1fr)`. (A grid column sized by a long
+ nowrap title was the bug we hit.)
+
+### 3.2 Expanded box
+
+- **No backing panel on the desktop (owner decision, 2026-10-12).** The
+ expanded list sits in a transparent wrapper with 6px padding (kept so the
+ widths in §3.1 hold). Cards float directly over the desktop, separated by
+ their own border and shadow. The gaps between cards show the wallpaper and
+ pass clicks through (§9.2). The prototype keeps a page-coloured plate only
+ to hide the web page's own text behind it (§12).
+- **Scroll box:** **fixed height** of about 3.5 cards (prototype **292px**),
+ horizontal padding 12px. The half card at the bottom signals "more".
+ - Hidden scrollbar: `scrollbar-width: none`, plus `::-webkit-scrollbar
+ { display: none }`.
+- **List padding:** top 10px, so the first card's × is never clipped; bottom
+ 0.
+- **Row spacing:** 8px after each card, and **16px after the main agent
+ card**, so it reads as its own group. Spacing is row bottom padding, never a
+ flex `gap` (§7.4).
+- **Bottom alignment:** cards are bottom-aligned (next to Vibey). Put the list
+ in a column flex box and give it `margin-top: auto`; never use
+ `justify-content: flex-end`, which makes overflow unreachable.
+- **Scroll edge fades:** §7.5.
+
+### 3.3 Collapsed stack
+
+- **Front card:** the **first** card (the main agent card when it exists),
+ showing its title and subtitle only: no ×, no stop button.
+- **Layers:** **one per remaining card**, behind the front card (6 cards →
+ front card + 5 layers). For layer `i` (0-based, nearest first):
+ - **the same height as the front card**, offset `(i + 1) × 9px` below it,
+ so its bottom edge peeks out `(i + 1) × 9px` under the front card's
+ bottom whatever the front card's height. Do not use a fixed layer height:
+ a fixed 52px is hidden entirely behind a taller front card (the main card
+ with its eyebrow);
+ - horizontal inset `18 + 6 + 3i` px from each column edge;
+ - radius 24px, background `#1a1a1e`, border `white / 8%`;
+ - **the same opacity as the front card** (no per-depth fade);
+ - nearer layers stack above farther ones.
+- The stack's height is the front card plus `layers × 9px`.
+- The whole stack is one button: a click expands it.
+
+## 4. Cards
+
+### 4.1 Common anatomy
+
+| Part | Spec |
+|---|---|
+| Container | Radius 28px; padding 20px × 14px; background `#2a2a2e`; border 1px `white / 8%`; shadow `0 18px 50px rgba(0,0,0,.45)`. |
+| Title | 15px, semibold, tight tracking, white, one line, ellipsis. The full text is the tooltip. |
+| Subtitle | 13px, `white / 45%`, 2px below the title, one line, ellipsis, with the full text as the tooltip. While running it has a 6px pulsing dot (`emerald-400`) before the text. |
+| × (dismiss) | Expanded list only, never on the main agent card. 20px circle at the top-left corner, offset −6px/−6px. Background `#3a3a3e`, glyph 11px `white / 70%`; on hover `#4a4a50` with a white glyph. Sits above the card content. |
+| Stop | Expanded list only, running sub-tasks only (§6). A 32px circle with background `white / 10%` and a filled rounded-square SVG icon at `white / 80%`. Its right gap and top gap to the card edge are both 16px. |
+
+- There is **no reply/return button** and **no Follow up** (owner decisions).
+- **Icons are SVG**, never Unicode glyphs. iOS renders `↩` as a blue emoji.
+
+### 4.2 Main agent card
+
+- **Position:** always the first card, collapsed or expanded. It cannot be
+ dismissed and has no stop button in this version.
+- **Eyebrow:** "MAIN AGENT" above the title, 2px gap.
+ - 10px, semibold, uppercase, tracking 0.14em.
+ - Light green at 80%: map to the theme's mint token; the prototype used
+ `emerald-300`.
+ - It names the card type, not the speaker.
+- **Title:** the user's last message to the main agent. No avatar or icon:
+ these are the user's own words, so nothing may suggest Vibey said them.
+- **Subtitle:**
+ - while the turn runs, the current step ("Thinking", "Reading file", "Ran
+ command", "Delegating", …) with the running dot;
+ - after the turn, the start of the reply, "已回复:…", with no dot.
+- **Distinct but quiet:**
+ - background `#34343b`, one step lighter than sub-task cards;
+ - border light green at 45% (the same mint token);
+ - 16px of row spacing after it.
+- **Click to open the conversation detail.** Clicking the main agent card in
+ the expanded list opens an inline detail region inside the card. This keeps
+ everything today's pet panel does, so nothing regresses (decided in review):
+ - the latest exchange: the last user message and the unread results (or the
+ last result), rendered with the existing Markdown renderer. Mark-read
+ follows the existing rule: what is rendered and seen is marked read; when
+ unread rows reach past the loaded tail, show "More in Avibe";
+ - quick replies for the latest result, clickable, using the existing
+ `QuickReplies` path (they never change Vibey's pose, #2408);
+ - pending vault requests, one "需要授权,在 Avibe 中打开" button each;
+ - the uncertain-send notice and the queued notice from the existing panel;
+ - an "在 Avibe 中打开" link.
+
+ The detail opens and closes with the `grid-template-rows 0fr ↔ 1fr`
+ technique: 280ms settle for the rows, opacity 200ms ease. It grows inside
+ the fixed scroll box: the box and Vibey do not move. It closes when the
+ stack collapses, and clicking the card again also closes it.
+- **Before the first send,** the card shows the main session's last exchange.
+ If there is none, it is absent.
+- **Pose:** Vibey takes the running pose while this card's turn runs.
+
+### 4.3 Sub-task cards
+
+- **Source:** the main session's turn state, `background_activities`. It
+ already unions delegated runs (`item_kind: agent_run`), watches (`watch`)
+ and scheduled tasks (`task`); this was verified live.
+- **Title:** the item's `label`, falling back to `description`.
+- **Subtitle:** "{kind} · {status}". Map the kind and raw status to readable,
+ localized text: 委派运行 / 监控 / 定时任务; Running, 排队中, 等待中…
+ Never show raw values such as `enabled`.
+- **Running** means `status` is `running` or `processing`; it shows the
+ running dot and the stop button.
+- **Order:** the main agent card first, then running sub-tasks, then the rest.
+ A sub-task the current turn just created goes directly below the main agent
+ card. Live data must not reshuffle rows under the pointer while the list is
+ expanded; apply reorders on collapse.
+
+### 4.4 Empty
+
+- With no main agent card and no sub-tasks, show nothing above Vibey. If the
+ main session has history, there is always a main agent card.
+
+## 5. Input: voice first, no always-on text box
+
+### 5.1 Vibey and the dock
+
+- **Click Vibey:** toggle the stack between collapsed and expanded.
+- **Press and hold Vibey (≥ 320ms):** start dictation; release to stop.
+ - A press shorter than 320ms is a click.
+ - Leaving Vibey before the hold fires cancels the hold.
+ - Suppress the context menu.
+- **The summon hotkey** has the same effect as a hold: press starts
+ dictation, release stops it. The global-shortcut handler handles only
+ `Pressed` today; add `Released`.
+- **While listening:**
+ - Vibey takes the `listening` pose (`vibey-focus`);
+ - a soft rose glow breathes around it: a radial gradient
+ `rgba(251,113,133,.28) → 0`, about 1.2× Vibey's size, scale .92 ↔ 1.12
+ with opacity .7 ↔ 1 over 1.6s ease-in-out;
+ - the card stack fades out and moves 8px down (opacity 220ms ease,
+ transform 260ms settle) and ignores the pointer. It comes back when
+ dictation ends.
+- **Dock:** a pill under Vibey's feet that overlaps the image by 12px.
+ - Background `#2a2a2e`, padding 4px, shadow `0 8px 24px rgba(0,0,0,.45)`.
+ - Two 32px buttons with a 4px gap and a 1px × 16px `white / 10%` hairline
+ between them:
+ - **mic** starts or stops dictation; it turns solid rose with a stop
+ square while dictating;
+ - **keyboard** opens or closes the input bubble; it is filled white while
+ the bubble is open.
+ - Hidden by default. It fades and rises in (opacity 180ms ease, transform
+ 220ms settle, from `translateY(-6px) scale(.92)`) on hover over Vibey or
+ the dock, or on keyboard focus.
+ - It stays visible while dictating or typing, and is always visible on
+ devices without hover (`@media (hover: none)`).
+
+### 5.2 Speech slot
+
+- **One slot** sits at the bottom of the column, between the cards and
+ Vibey. By priority it holds the marquee while dictating, otherwise the
+ input bubble when it is open, otherwise nothing.
+- **No margin of its own.** The last card's row spacing plus the panel's 6px
+ padding separate it from the cards (about 14px).
+- **Motion:**
+ - opening grows the slot's height (`grid-template-rows 0fr → 1fr`, 300ms
+ settle), so the stack above slides up with it;
+ - the content fades and rises (opacity 180ms; `translateY(8px)
+ scale(.97)` → rest over 300ms settle; 60ms delay on open);
+ - closing reverses both;
+ - the slot clips while it moves, then unclips once open so shadows show;
+ - a closed slot stays mounted but `inert`.
+
+### 5.3 Marquee (live transcript)
+
+- **Look:** one line, the same width as a card.
+ - Pill: background `#2a2a2e`, padding 8px vertical, 12px left, 16px right,
+ shadow `0 12px 32px rgba(0,0,0,.45)`.
+ - A 10px pulsing rose dot on the left, then 13px white text.
+- **Text:** the realtime preview from the existing pipeline
+ (`VoiceRealtimeSession` preview text + stash).
+ - The newest words always stay visible: translate the line left by
+ `max(0, scrollWidth − clientWidth)` with a 300ms ease-out transition.
+ - A 28px mask fades the left edge once the text overflows.
+ - Before any text: "正在听…", muted.
+- **Ending dictation** (mic again, release, or end of speech) turns the slot
+ into the input bubble, prefilled with the final text (appended after a space
+ if a draft exists) and focused. **It is not sent.**
+- **Esc** cancels dictation and discards the transcript.
+- The marquee is `aria-live="polite"`.
+
+### 5.4 Input bubble
+
+- **Opens** after dictation, prefilled; or from the keyboard button, empty.
+ Either way it gets focus.
+- **Look:** the same width as a card, radius 22px, background `#2a2a2e`,
+ border `white / 10%`, padding 6px (14px left), shadow as the marquee.
+- **Textarea:** one line by default, auto-grows to 4 lines (96px), 13px,
+ placeholder "和 main agent 说…".
+- **Buttons, right side:**
+ - a 32px mic (`white / 10%`) that dictates more and appends;
+ - a 32px send button: white with a black up-arrow SVG; `white / 10%` and
+ disabled when empty.
+- **Keys:**
+ - Enter sends; Shift+Enter is a newline; Enter during IME composition does
+ not send;
+ - Esc closes the bubble and discards the draft. Esc while dictating cancels
+ dictation first. Esc with nothing open collapses the stack.
+- **Sending:**
+ - goes to the main agent only, with the existing composer rules: one
+ message in flight, the uncertain-send lock, server-side queueing;
+ - closes the bubble;
+ - the main agent card takes over as the feedback: its title becomes the
+ message, its subtitle starts at "Thinking", and Vibey takes the running
+ pose until the real turn state takes over.
+
+## 6. Stop a sub-task
+
+Stop is the emergency brake: direct and deterministic.
+
+- **Where:** expanded list, running sub-task cards only.
+- **Two presses, no dialog.**
+ - First press: the circle becomes a rose pill (`rose-500`, height 32px,
+ 12px horizontal padding, 12px semibold white text) that reads "停止?"
+ for runs or "暂停?" for watches and tasks. It pops in over 180ms
+ (`scale .85 → 1`, settle).
+ - A second press within **3s** confirms. After 3s the pill reverts.
+- **By kind:**
+ - watch → `setHarnessWatchEnabled(id, false)` (exists);
+ - task → `setHarnessTaskEnabled(id, false)` (exists);
+ - agent run → **no HTTP cancel exists yet** (only the CLI `vibe runs
+ cancel`). Hide the stop button on agent runs until the backend adds the
+ endpoint (§11).
+- **Pending:** the subtitle reads "正在停止…" / "正在暂停…" and the dot goes
+ off. The button shows a 14px spinner and is disabled. Wait for the server's
+ answer, not the click.
+- **Done:** the subtitle reads "已停止" / "已暂停" in `white / 60%` with a grey
+ dot (`white / 40%`), and the button disappears. The card lingers **2.5s**,
+ then leaves with the dismiss motion (§7.3).
+- **Failed:** restore the card, show "没停下来,稍后再试" in the subtitle, and
+ keep the stop button.
+- **The main agent is told** through the existing run/harness events; the
+ user does not have to tell it.
+
+## 7. Motion
+
+The primary curve is **settle**: `cubic-bezier(0.32, 0.72, 0, 1)`.
+
+### 7.1 Expand / collapse
+
+- The column animates its **height** between the collapsed and expanded
+ heights: 360ms, settle, with `overflow: hidden` while it moves.
+- The incoming content fades and rises from `opacity 0, translateY(8px),
+ scale(.98)`: 360ms, settle.
+- Because the column is bottom-anchored, it grows and shrinks upward.
+- **Only the collapsed ↔ expanded switch drives the outer height.** Changes
+ inside the list (the main card detail, a dismissed card, a stopped card)
+ move content inside the fixed box. Never let an outer height transition
+ chase an inner one: two animations on different curves read as a jump.
+
+### 7.2 Main agent card detail
+
+- `grid-template-rows 0fr ↔ 1fr` over 280ms settle, with opacity over 200ms
+ ease (§4.2).
+
+### 7.3 Dismiss (×), and the end of a stop
+
+Two beats, so the exit reads before the reflow:
+
+1. **Exit, 0–200ms.** The card falls back and fades:
+ - `opacity 1 → 0`, `translateZ(0 → −120px)`, `translateY(0 → −4px)`,
+ `scale(1 → .88)`, `blur(0 → 2px)`;
+ - 200ms, `cubic-bezier(0.4, 0, 1, 1)`, fill forwards;
+ - the row has a 900px perspective.
+2. **Close the gap, 140–480ms.** The row collapses with
+ `grid-template-rows 1fr → 0fr` over 340ms settle, **with a 140ms delay**.
+ The cards below slide up.
+3. Remove the card from the data at about 500ms.
+
+- The leaving row ignores the pointer.
+- A second click on the same × is a no-op.
+- A dismissed card does **not** come back on a refresh (§9.3).
+
+### 7.4 No reflow jumps
+
+- Spacing lives inside the collapsing row. A list `gap` does not animate: it
+ stays during the collapse and vanishes on removal, which makes an ~8px jump
+ at the end.
+
+### 7.5 Scroll edge fades
+
+- Mask the scroll box: `linear-gradient(to bottom, transparent 0, #000
+ {top}px, #000 calc(100% − {bottom}px), transparent 100%)`.
+ - `top = min(32, scrollTop)`: no fade at the top until the user scrolls.
+ - `bottom = min(32, scrollHeight − clientHeight − scrollTop)`: no fade once
+ the end is reached.
+- Recompute on scroll, and whenever the box or its content resizes
+ (ResizeObserver on both).
+
+### 7.6 Poses
+
+- Keep `ui/src/pet/pet.css`, including:
+ - the 320ms squash on a pose change;
+ - breathing on working poses;
+ - the 30s breathing settle on resting poses, which keeps idle cost near
+ zero.
+- Vibey on the mini stage is **115px** (the owner tuned it on the prototype:
+ 2×, then −10%). Verify the size on a real desktop with the owner.
+
+### 7.7 Reduced motion
+
+With `prefers-reduced-motion: reduce`, every transition and animation in this
+spec is off. States switch instantly, a dismissed card disappears at once, and
+the marquee text still updates.
+
+## 8. Busy rule (pose)
+
+Vibey shows the running pose when **any** agent is working in a conversation
+the user can see: the main session, built-in role sessions, or ordinary user
+sessions.
+
+- This keeps #2401: an `active` foreground session in the running-agents
+ snapshot.
+- It **adds the main session's own running sub-tasks**: running items in its
+ turn state's `background_activities`. They run in background sessions, which
+ #2401 excludes.
+- The main session's own needs-input, blocked and ready states still win over
+ busy (existing priority).
+
+## 9. Shell (Tauri) work
+
+### 9.1 Window
+
+- **One fixed window size** in every state, large enough for the expanded
+ column plus the speech slot, Vibey and the dock: about **460 × 600**
+ logical px.
+ - Collapsing does not resize the window; click-through (§9.2) makes the
+ empty area harmless.
+ - This replaces the collapsed 88 × 88 / expanded side-panel geometry
+ (`window_size`, `PetLayout`).
+- **Placement:** Vibey is anchored at the bottom centre of the window.
+ - The stored anchor is Vibey's position.
+ - The window is clamped into the work area, so Vibey cannot sit higher
+ than the window's height above it.
+ - Dragging Vibey drags the window (existing `startDragging`).
+- **When the frame does not fit (decision 2026-10-12, from the #2508
+ breaker).** On a work area shorter or narrower than the frame (for
+ example 1366×768 at 125% minus the taskbar), full-frame clamping is
+ impossible.
+ - **Priority:** Vibey and its dock must always be fully inside a connected
+ work area and reachable. The transparent rest of the frame may extend
+ past the work area.
+ - **How, decided per display:** choose the target from all connected
+ displays: the one Vibey overlaps most, else its saved display if it is
+ connected, else the primary. Then clamp with the whole frame if *that
+ display* fits it, otherwise with Vibey's rect plus the dock. A pet the
+ user parked on a small laptop screen stays there, even when a large
+ external display is connected. With no display at all, keep today's
+ behaviour.
+ - **Expanded list on a short display:** its top may fall off-screen. This
+ is accepted in v1; do not shrink or flip the column.
+
+### 9.2 Click-through (verified in a spike)
+
+- Only the cards, the speech slot, the dock and Vibey take the mouse.
+ Everything else passes clicks to whatever is below.
+- **One mechanism on every platform:**
+ - The page reports its hit rects (window-local logical px) to the shell
+ whenever layout changes: ResizeObserver, plus after state changes.
+ - The shell polls the cursor (`AppHandle::cursor_position`), converts it to
+ window-local logical px, and toggles `set_ignore_cursor_events(!inside)`
+ on the main thread, only when the value changes.
+- **Why not native:** on macOS, fully transparent pixels pass clicks through,
+ but semi-transparent pixels (card shadows) catch them; this was verified.
+ Windows and Linux have no native pass-through.
+- **Cost:**
+ - poll every 16ms only while the cursor is inside the window bounds;
+ - back off to about 100ms when the cursor is outside them;
+ - stop while the window is hidden.
+- **Spike source:** `spec/spike-passthrough/` in the Show Page workspace.
+- The new IPC command, for example `pet_hit_regions(rects)`, is granted to
+ the pet page only, like the other pet commands, and must recheck its
+ caller.
+
+## 10. Main agent session (dependency; owned by another lane)
+
+- **Model:**
+ - sessions get a built-in type (`main`, `memory`, `ops`, …);
+ - each user has their **own** `main`;
+ - `main` is a writable session with **normal visibility** (the pet's
+ validity rule accepts it);
+ - it is **built in at install** (upgrades must create it too);
+ - it **cannot be archived or deleted**;
+ - its **id is stable** across context rotation.
+- **Lookup API — not built yet; mock it.** Proposed contract:
+
+ ```
+ GET /api/sessions/main
+ 200 { "session": WorkbenchSession, "capabilities": { "can_chat": bool } }
+ ```
+
+ - The pet reads the main session only through one client function,
+ `api.getMainSession()`.
+ - Until the endpoint exists, the function returns the session the pet is
+ bound to today (the user-picked binding from `pet_ready()`), in the same
+ shape. Under this mock, keep a way to pick the session (for example in
+ the main card's detail header).
+ - When the endpoint lands: call it on start, on reconnect and after
+ authorization changes. Then remove the switcher, "在桌宠中显示" and the
+ binding writes. Older `pet.json` files that contain `binding` must still
+ load; ignore the field (persisted-shape rule).
+
+## 11. Backend gaps (not in this delivery; degrade gracefully)
+
+1. **No "current step" text.**
+ - Neither the main card subtitle nor sub-task progress has a server field;
+ activity rows are raw (`🔧 Bash {…}`).
+ - Until the server emits a localized step phrase, show "Thinking" while
+ the main turn runs. Show the mapped status for sub-tasks.
+ - **Do not guess from tool names in the client.**
+2. **No HTTP cancel for agent runs.** Hide stop on agent runs until it exists
+ (§6).
+3. **Dismiss persistence.** There is no server state for dismissed cards.
+ Keep the dismissed ids in `pet.json`, so a dismissed card stays gone across
+ restarts. Forget an id once its item disappears from the turn state. This
+ adds an optional field, so older files keep loading.
+
+## 12. Prototype-only (do not copy)
+
+- The mock cards that pad the list to six.
+- The simulated dictation script and its timing (one or two characters every
+ 100ms).
+- The simulated turn steps and the spawned sub-task.
+- The simulated stop and its 900ms pending time.
+- The 3s polling of turn state; production uses the existing events plus the
+ reconcile cadence in `usePetSession`.
+- Hard-coded Chinese strings. Production copy goes through `ui/src/i18n`
+ (en + zh).
+- The page header, the "还差什么" section, and the extra chevron under Vibey
+ in earlier versions.
+- The page-coloured plate behind the expanded list (it only hides the web
+ page's text; the desktop has none, §3.2).
+
+## 13. Acceptance checklist
+
+- [ ] Vibey never moves for any interaction in this spec.
+- [ ] Collapsed: the front card is the first card (main when present); there
+ is one layer per other card, with 9px steps, a `18+6+3i` inset and the
+ same opacity as the front card.
+- [ ] Clicking Vibey or the stack expands upward (360ms settle, height plus
+ content fade); clicking Vibey again collapses.
+- [ ] Expanded: fixed 3.5-card box; cards bottom-aligned; overflow scrolls;
+ scrollbar hidden; 10px top padding.
+- [ ] No backing plate behind the expanded list; gaps show the desktop and
+ pass clicks through.
+- [ ] Edge fades: none at the top until the user scrolls, up to 32px, none at
+ the end; recomputed on resize.
+- [ ] Cards, marquee and bubble share one width. A long title truncates and
+ never widens a card.
+- [ ] Main card: "MAIN AGENT" eyebrow; mint border; `#34343b` background;
+ 16px after it; no ×; no stop; no avatar.
+- [ ] Clicking the main card opens and closes the detail inside the fixed
+ box (280ms). The detail has the latest exchange, mark-read, More in
+ Avibe, quick replies, vault buttons, uncertain and queued notices.
+- [ ] Sub-tasks come from the main session's `background_activities`, with
+ readable localized status and running first.
+- [ ] Pressing and holding Vibey for 320ms, or the hotkey, starts dictation;
+ release stops it. The listening pose and rose glow show, and the cards
+ fade aside.
+- [ ] The marquee shows the realtime preview with the newest words visible,
+ a 300ms slide and a 28px left fade.
+- [ ] Dictation ends in a prefilled, focused, unsent input bubble. The
+ keyboard button opens an empty one.
+- [ ] The slot opens and closes with height and content motion (300ms); the
+ cards slide with it.
+- [ ] Enter sends to main (IME-safe). The main card becomes the message and
+ starts at "Thinking". Esc behaviour follows §5.4.
+- [ ] The dock appears on hover or focus, stays while talking or typing, and
+ is always shown without hover.
+- [ ] Stop: two presses (3s window), then pending, done (2.5s linger, exit
+ motion) or failed (restore). Watches and tasks pause; runs are hidden
+ until a cancel API exists.
+- [ ] Dismiss: 200ms exit, then a 340ms gap close after a 140ms delay; no end
+ jump; the card stays gone after a refresh and a restart.
+- [ ] Busy rule follows §8.
+- [ ] Window: fixed size; Vibey anchored at the bottom; clicks pass through
+ everywhere except the reported regions on macOS and Windows (shadows
+ included); polling backs off and stops when hidden.
+- [ ] Reduced motion turns everything above into instant switches.
+- [ ] Icons are SVG. All copy is localized in en and zh.
diff --git a/docs/plans/desktop-mini-v2-evidence/desktop-bubble-open.png b/docs/plans/desktop-mini-v2-evidence/desktop-bubble-open.png
new file mode 100644
index 000000000..d32d43ef5
Binary files /dev/null and b/docs/plans/desktop-mini-v2-evidence/desktop-bubble-open.png differ
diff --git a/docs/plans/desktop-mini-v2-evidence/desktop-collapsed.png b/docs/plans/desktop-mini-v2-evidence/desktop-collapsed.png
new file mode 100644
index 000000000..d03e83996
Binary files /dev/null and b/docs/plans/desktop-mini-v2-evidence/desktop-collapsed.png differ
diff --git a/docs/plans/desktop-mini-v2-evidence/desktop-dictating.png b/docs/plans/desktop-mini-v2-evidence/desktop-dictating.png
new file mode 100644
index 000000000..f52b420ba
Binary files /dev/null and b/docs/plans/desktop-mini-v2-evidence/desktop-dictating.png differ
diff --git a/docs/plans/desktop-mini-v2-evidence/desktop-expanded.png b/docs/plans/desktop-mini-v2-evidence/desktop-expanded.png
new file mode 100644
index 000000000..115cf127a
Binary files /dev/null and b/docs/plans/desktop-mini-v2-evidence/desktop-expanded.png differ
diff --git a/docs/plans/desktop-mini-v2-evidence/desktop-main-detail.png b/docs/plans/desktop-mini-v2-evidence/desktop-main-detail.png
new file mode 100644
index 000000000..9a348e34b
Binary files /dev/null and b/docs/plans/desktop-mini-v2-evidence/desktop-main-detail.png differ
diff --git a/docs/plans/desktop-mini-v2-evidence/desktop-mid-dismiss.png b/docs/plans/desktop-mini-v2-evidence/desktop-mid-dismiss.png
new file mode 100644
index 000000000..083154711
Binary files /dev/null and b/docs/plans/desktop-mini-v2-evidence/desktop-mid-dismiss.png differ
diff --git a/docs/plans/desktop-mini-v2-evidence/desktop-scrolled.png b/docs/plans/desktop-mini-v2-evidence/desktop-scrolled.png
new file mode 100644
index 000000000..f695df68f
Binary files /dev/null and b/docs/plans/desktop-mini-v2-evidence/desktop-scrolled.png differ
diff --git a/docs/plans/desktop-mini-v2-evidence/desktop-stop-confirm.png b/docs/plans/desktop-mini-v2-evidence/desktop-stop-confirm.png
new file mode 100644
index 000000000..2fc4fe359
Binary files /dev/null and b/docs/plans/desktop-mini-v2-evidence/desktop-stop-confirm.png differ
diff --git a/docs/plans/desktop-mini-v2-evidence/geometry.json b/docs/plans/desktop-mini-v2-evidence/geometry.json
new file mode 100644
index 000000000..fba197bba
--- /dev/null
+++ b/docs/plans/desktop-mini-v2-evidence/geometry.json
@@ -0,0 +1,256 @@
+{
+ "desktop-collapsed": {
+ "pose": "running",
+ "expanded": false,
+ "detail": false,
+ "slot": false,
+ "avatar": {
+ "x": 172.5,
+ "y": 449,
+ "width": 115,
+ "height": 115,
+ "top": 449,
+ "right": 287.5,
+ "bottom": 564,
+ "left": 172.5
+ },
+ "size": [
+ 460,
+ 600
+ ],
+ "stack": {
+ "x": 13.75,
+ "y": 320.125,
+ "width": 432.390625,
+ "height": 135,
+ "top": 320.125,
+ "right": 446.140625,
+ "bottom": 455.125,
+ "left": 13.75
+ },
+ "front": {
+ "x": 31.75,
+ "y": 320.125,
+ "width": 396.390625,
+ "height": 90,
+ "top": 320.125,
+ "right": 428.140625,
+ "bottom": 410.125,
+ "left": 31.75
+ },
+ "layers": [
+ {
+ "x": 37.75,
+ "y": 329.125,
+ "width": 384.390625,
+ "height": 90,
+ "top": 329.125,
+ "right": 422.140625,
+ "bottom": 419.125,
+ "left": 37.75
+ },
+ {
+ "x": 40.75,
+ "y": 338.125,
+ "width": 378.390625,
+ "height": 90,
+ "top": 338.125,
+ "right": 419.140625,
+ "bottom": 428.125,
+ "left": 40.75
+ },
+ {
+ "x": 43.75,
+ "y": 347.125,
+ "width": 372.390625,
+ "height": 90,
+ "top": 347.125,
+ "right": 416.140625,
+ "bottom": 437.125,
+ "left": 43.75
+ },
+ {
+ "x": 46.75,
+ "y": 356.125,
+ "width": 366.390625,
+ "height": 90,
+ "top": 356.125,
+ "right": 413.140625,
+ "bottom": 446.125,
+ "left": 46.75
+ },
+ {
+ "x": 49.75,
+ "y": 365.125,
+ "width": 360.390625,
+ "height": 90,
+ "top": 365.125,
+ "right": 410.140625,
+ "bottom": 455.125,
+ "left": 49.75
+ }
+ ],
+ "panelBackground": null
+ },
+ "desktop-expanded": {
+ "pose": "running",
+ "expanded": true,
+ "detail": false,
+ "slot": false,
+ "avatar": {
+ "x": 172.5,
+ "y": 449,
+ "width": 115,
+ "height": 115,
+ "top": 449,
+ "right": 287.5,
+ "bottom": 564,
+ "left": 172.5
+ },
+ "size": [
+ 460,
+ 600
+ ],
+ "scroll": 0,
+ "layers": [],
+ "panelBackground": "rgba(0, 0, 0, 0)"
+ },
+ "desktop-scrolled": {
+ "pose": "running",
+ "expanded": true,
+ "detail": false,
+ "slot": false,
+ "avatar": {
+ "x": 172.5,
+ "y": 449,
+ "width": 115,
+ "height": 115,
+ "top": 449,
+ "right": 287.5,
+ "bottom": 564,
+ "left": 172.5
+ },
+ "size": [
+ 460,
+ 600
+ ],
+ "scroll": 120,
+ "layers": [],
+ "panelBackground": "rgba(0, 0, 0, 0)"
+ },
+ "desktop-main-detail": {
+ "pose": "running",
+ "expanded": true,
+ "detail": true,
+ "slot": false,
+ "avatar": {
+ "x": 172.5,
+ "y": 449,
+ "width": 115,
+ "height": 115,
+ "top": 449,
+ "right": 287.5,
+ "bottom": 564,
+ "left": 172.5
+ },
+ "size": [
+ 460,
+ 600
+ ],
+ "scroll": 0,
+ "layers": [],
+ "panelBackground": "rgba(0, 0, 0, 0)"
+ },
+ "desktop-bubble-open": {
+ "pose": "running",
+ "expanded": true,
+ "detail": false,
+ "slot": true,
+ "avatar": {
+ "x": 172.5,
+ "y": 449,
+ "width": 115,
+ "height": 115,
+ "top": 449,
+ "right": 287.5,
+ "bottom": 564,
+ "left": 172.5
+ },
+ "size": [
+ 460,
+ 600
+ ],
+ "scroll": 0,
+ "layers": [],
+ "panelBackground": "rgba(0, 0, 0, 0)"
+ },
+ "desktop-stop-confirm": {
+ "pose": "running",
+ "expanded": true,
+ "detail": false,
+ "slot": false,
+ "avatar": {
+ "x": 172.5,
+ "y": 449,
+ "width": 115,
+ "height": 115,
+ "top": 449,
+ "right": 287.5,
+ "bottom": 564,
+ "left": 172.5
+ },
+ "size": [
+ 460,
+ 600
+ ],
+ "scroll": 75,
+ "layers": [],
+ "panelBackground": "rgba(0, 0, 0, 0)"
+ },
+ "desktop-mid-dismiss": {
+ "pose": "running",
+ "expanded": true,
+ "detail": false,
+ "slot": false,
+ "avatar": {
+ "x": 172.5,
+ "y": 449,
+ "width": 115,
+ "height": 115,
+ "top": 449,
+ "right": 287.5,
+ "bottom": 564,
+ "left": 172.5
+ },
+ "size": [
+ 460,
+ 600
+ ],
+ "scroll": 75,
+ "layers": [],
+ "panelBackground": "rgba(0, 0, 0, 0)"
+ },
+ "desktop-dictating": {
+ "pose": "listening",
+ "expanded": true,
+ "detail": false,
+ "slot": true,
+ "avatar": {
+ "x": 172.5,
+ "y": 449,
+ "width": 115,
+ "height": 115,
+ "top": 449,
+ "right": 287.5,
+ "bottom": 564,
+ "left": 172.5
+ },
+ "size": [
+ 460,
+ 600
+ ],
+ "scroll": 75,
+ "layers": [],
+ "panelBackground": "rgba(0, 0, 0, 0)"
+ }
+}
diff --git a/docs/plans/desktop-mini-v2-evidence/reference-comparison.png b/docs/plans/desktop-mini-v2-evidence/reference-comparison.png
new file mode 100644
index 000000000..26c9ca4e5
Binary files /dev/null and b/docs/plans/desktop-mini-v2-evidence/reference-comparison.png differ
diff --git a/docs/plans/desktop-mini-v2-evidence/states.png b/docs/plans/desktop-mini-v2-evidence/states.png
new file mode 100644
index 000000000..5373fc5bf
Binary files /dev/null and b/docs/plans/desktop-mini-v2-evidence/states.png differ
diff --git a/ui/e2e/pet-mini/fixture.html b/ui/e2e/pet-mini/fixture.html
new file mode 100644
index 000000000..cd848ab7b
--- /dev/null
+++ b/ui/e2e/pet-mini/fixture.html
@@ -0,0 +1,11 @@
+<!doctype html>
+<html>
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width" />
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="./fixture.tsx"></script>
+ </body>
+</html>
diff --git a/ui/e2e/pet-mini/fixture.tsx b/ui/e2e/pet-mini/fixture.tsx
new file mode 100644
index 000000000..6ac882a3d
--- /dev/null
+++ b/ui/e2e/pet-mini/fixture.tsx
@@ -0,0 +1,84 @@
+import { createRoot } from 'react-dom/client';
+import { PetPage } from '../../src/pet/PetPage';
+import { PetWindow } from '../../src/pet/PetWindow';
+import { petBridge } from '../../src/pet/petBridge';
+import { ApiProvider } from '../../src/context/ApiContext';
+import { InstanceAuthorizationProvider } from '../../src/context/InstanceAuthorizationProvider';
+import { WorkbenchInboxProvider } from '../../src/context/WorkbenchInboxProvider';
+import { ToastProvider } from '../../src/context/ToastProvider';
+import { OWNER_INSTANCE_CAPABILITIES } from '../../src/lib/sessionInfo';
+import i18n from '../../src/i18n';
+import '../../src/index.css';
+
+await i18n.changeLanguage('en');
+declare global {
+ interface Window {
+ petLayoutHitRegions: Parameters<typeof petBridge.setHitRegions>[0];
+ setPetLayoutVisible: (visible: boolean) => void;
+ }
+}
+window.petLayoutHitRegions = [];
+petBridge.setHitRegions = async (rects) => { window.petLayoutHitRegions = rects; };
+const params = new URLSearchParams(location.search);
+const hasMain = params.get('main') !== 'false';
+const layers = Number(params.get('layers') ?? 3);
+const title = 'A long unbroken title '.repeat(40);
+const session = {
+ id: 'pet-layout', scope_id: 'fixture', title, agent_backend: 'codex',
+ status: 'active', visibility: 'foreground', agent_status: 'idle', metadata: {},
+};
+const messages = hasMain ? [{
+ id: 'user', session_id: session.id, scope_id: session.scope_id,
+ author: 'user', type: 'user', text: title, metadata: {}, content: {},
+ created_at: '2026-10-12T00:00:00Z', updated_at: '2026-10-12T00:00:00Z',
+}] : [];
+const activities = Array.from({ length: layers + (hasMain ? 0 : 1) }, (_, i) => ({
+ id: `watch:fixture-${i}`, item_kind: 'watch', status: 'enabled', label: title,
+ description: title, backend: 'codex', runtime_key: `fixture-${i}`,
+ session_id: session.id, kind: 'watch', started_at: '2026-10-12T00:00:00Z',
+}));
+localStorage.setItem('avibe.pet.devBinding', JSON.stringify({ binding: session.id, revision: 1 }));
+
+// Every API read is fixture-owned. Unexpected calls fail rather than reaching a
+// user's runtime; the Vite proxy also points at an unused local port.
+window.fetch = async (input) => {
+ const path = new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url, location.origin).pathname;
+ const payloads: Record<string, unknown> = {
+ '/api/config': { mode: 'self_host', setup_state: { needs_setup: false } },
+ '/api/session': { remote: false, instance_kind: 'personal', capabilities: OWNER_INSTANCE_CAPABILITIES },
+ '/api/sessions/pet-layout': session,
+ '/api/sessions/pet-layout/messages': { messages, next_after_id: null, next_before_id: null },
+ '/api/sessions/pet-layout/turn-state': {
+ foreground: 'idle', in_flight: false, native_turn_started: false, pending_input_count: 0,
+ background_activities: activities, pending_activity_output_count: 0, connection: 'connected',
+ },
+ '/api/vault/requests': { ok: true, requests: [] },
+ '/api/asr/status': { available: false },
+ '/api/running-agents': { ok: true, agents: [], counts: { total: 0, active: 0, idle: 0, orphan: 0, by_backend: {} } },
+ '/api/sessions': { sessions: [session], next_before_id: null },
+ '/api/inbox': { ok: true, sessions: [], unread_by_session: {}, total_unread: 0, next_before_id: null },
+ };
+ if (!(path in payloads)) throw new Error(`Unexpected pet fixture request: ${path}`);
+ return new Response(JSON.stringify(payloads[path]), { headers: { 'Content-Type': 'application/json' } });
+};
+// A disconnected event stream is sufficient for this fixed layout fixture.
+class FixtureEvents {
+ static OPEN = 1;
+ readyState = 1;
+ addEventListener() {}
+ removeEventListener() {}
+ close() {}
+}
+window.EventSource = FixtureEvents as unknown as typeof EventSource;
+
+const root = createRoot(document.getElementById('root')!);
+window.setPetLayoutVisible = (visible) => root.render(
+ <ToastProvider>
+ <ApiProvider>
+ <InstanceAuthorizationProvider session={{ remote: false, instance_kind: 'personal', capabilities: OWNER_INSTANCE_CAPABILITIES }}>
+ <WorkbenchInboxProvider><PetWindow>{visible ? <PetPage /> : null}</PetWindow></WorkbenchInboxProvider>
+ </InstanceAuthorizationProvider>
+ </ApiProvider>
+ </ToastProvider>,
+);
+window.setPetLayoutVisible(true);
diff --git a/ui/e2e/pet-mini/layout.spec.ts b/ui/e2e/pet-mini/layout.spec.ts
new file mode 100644
index 000000000..979bf09ae
--- /dev/null
+++ b/ui/e2e/pet-mini/layout.spec.ts
@@ -0,0 +1,81 @@
+import { expect, test } from '@playwright/test';
+
+test('an unmounted surface releases desktop input and a remount reports fresh regions', async ({ page }) => {
+ await page.goto('/e2e/pet-mini/fixture.html');
+ await expect(page.locator('.pet-mini-collapsed')).toBeVisible();
+ await expect.poll(() => page.evaluate(() => window.petLayoutHitRegions.length)).toBeGreaterThan(0);
+ // Unmount during the reporter's motion window, as an authorization recheck
+ // does. Queued animation/observer work must not reinstall invisible regions.
+ await page.locator('.pet-mini-collapsed').click();
+ await page.evaluate(() => window.setPetLayoutVisible(false));
+ await expect(page.locator('.pet-mini-avatar-button')).toHaveCount(0);
+ await expect.poll(() => page.evaluate(() => window.petLayoutHitRegions)).toEqual([]);
+ await page.evaluate(() => new Promise<void>((resolve, reject) => {
+ const until = performance.now() + 600;
+ const check = () => {
+ if (window.petLayoutHitRegions.length) reject(new Error('Unmounted pet reclaimed desktop input'));
+ else if (performance.now() >= until) resolve();
+ else requestAnimationFrame(check);
+ };
+ requestAnimationFrame(check);
+ }));
+ await page.evaluate(() => window.setPetLayoutVisible(true));
+ await expect(page.locator('.pet-mini-avatar-button')).toBeVisible();
+ await expect.poll(() => page.evaluate(() => {
+ const avatar = document.querySelector('.pet-mini-avatar-button')!.getBoundingClientRect();
+ const x = avatar.left + avatar.width / 2, y = avatar.top + avatar.height / 2;
+ return window.petLayoutHitRegions.some((rect) =>
+ x >= rect.x && x < rect.x + rect.width && y >= rect.y && y < rect.y + rect.height);
+ })).toBe(true);
+});
+
+for (const main of [true, false]) {
+ for (const layers of [1, 3, 5]) {
+ test(`collapsed layers follow the front height (main=${main}, layers=${layers})`, async ({ page }) => {
+ const errors: string[] = [];
+ page.on('pageerror', (error) => errors.push(error.message));
+ await page.goto(`/e2e/pet-mini/fixture.html?main=${main}&layers=${layers}`);
+ await expect(page.locator('.pet-mini-layer')).toHaveCount(layers);
+ // Wait for the real CSS entrance before measuring its transformed bounds.
+ await page.locator('.pet-mini-swap').evaluate(async (node) => {
+ await Promise.all(node.getAnimations().map((animation) => animation.finished));
+ });
+ const bounds = await page.locator('.pet-mini-collapsed').evaluate((stack) => {
+ const front = stack.querySelector('.pet-mini-front')!.getBoundingClientRect();
+ const backs = Array.from(stack.querySelectorAll('.pet-mini-layer'), (layer) => layer.getBoundingClientRect().toJSON());
+ return { stack: stack.getBoundingClientRect().toJSON(), front: front.toJSON(), backs };
+ });
+ expect(bounds.stack.height).toBeCloseTo(bounds.front.height + layers * 9, 1);
+ expect(bounds.backs.at(-1)!.bottom - bounds.front.bottom).toBeCloseTo(layers * 9, 1);
+ for (const [index, layer] of bounds.backs.entries()) {
+ expect(layer.height).toBeCloseTo(bounds.front.height, 1);
+ expect(layer.bottom - bounds.front.bottom).toBeCloseTo((index + 1) * 9, 1);
+ }
+ const avatar = await page.locator('.pet-mini-avatar-button').boundingBox();
+ await page.locator('.pet-mini-collapsed').click();
+ await expect(page.locator('.pet-mini-scroll')).toBeVisible();
+ await page.locator('.pet-mini-swap').evaluate(async (node) => {
+ await Promise.all(node.getAnimations().map((animation) => animation.finished));
+ });
+ expect(await page.locator('.pet-mini-panel').evaluate((node) => getComputedStyle(node).backgroundColor)).toBe('rgba(0, 0, 0, 0)');
+ // Consume the actual reporter's output at its transport boundary. The
+ // native poller must receive the card's rectangle but no inter-card gap.
+ await expect.poll(() => page.evaluate(() => {
+ const [first, second] = Array.from(document.querySelectorAll('.pet-mini-card'), (node) => node.getBoundingClientRect());
+ const covers = (x: number, y: number) => window.petLayoutHitRegions.some((rect) => x >= rect.x && x < rect.x + rect.width && y >= rect.y && y < rect.y + rect.height);
+ const x = (first.left + first.right) / 2;
+ return { card: covers(x, (first.top + first.bottom) / 2), gap: covers(x, (first.bottom + second.top) / 2) };
+ })).toEqual({ card: true, gap: false });
+ if (main) await page.locator('.pet-mini-card[role=button]').click();
+ // A long nowrap title and long detail must remain inside the fixed list.
+ const widths = await page.locator('.pet-mini-scroll').evaluate((scroll) => ({
+ client: scroll.clientWidth, content: scroll.scrollWidth,
+ cards: Array.from(scroll.querySelectorAll('.pet-mini-card'), (card) => card.getBoundingClientRect().width),
+ }));
+ expect(widths.content).toBe(widths.client);
+ expect(widths.cards.every((width) => width <= widths.client)).toBe(true);
+ expect(await page.locator('.pet-mini-avatar-button').boundingBox()).toEqual(avatar);
+ expect(errors).toEqual([]);
+ });
+ }
+}
diff --git a/ui/package.json b/ui/package.json
index e32a349e8..c0248acb9 100644
--- a/ui/package.json
+++ b/ui/package.json
@@ -34,6 +34,7 @@
"test:workbench-general": "tsc -p e2e/workbench-general/tsconfig.json --noEmit && playwright test --config playwright.workbench-general.config.ts",
"test:workbench-general-build": "tsc -p e2e/workbench-general/tsconfig.json --noEmit && playwright test --config playwright.workbench-general-build.config.ts",
"test:voice-shortcut": "tsc -p e2e/voice-shortcut/tsconfig.json --noEmit && playwright test --config playwright.voice-shortcut.config.ts",
+ "test:pet-mini": "playwright test --config playwright.pet-mini.config.ts",
"validate:catalog": "node scripts/validate-scenario-catalog.mjs",
"validate:theme": "node scripts/validate-theme.mjs"
},
diff --git a/ui/playwright.pet-mini.config.ts b/ui/playwright.pet-mini.config.ts
new file mode 100644
index 000000000..26141131f
--- /dev/null
+++ b/ui/playwright.pet-mini.config.ts
@@ -0,0 +1,21 @@
+import { defineConfig } from '@playwright/test';
+
+export default defineConfig({
+ testDir: './e2e/pet-mini',
+ outputDir: './e2e/.artifacts/pet-mini',
+ workers: 1,
+ retries: 0,
+ use: {
+ baseURL: 'http://127.0.0.1:5229',
+ viewport: { width: 460, height: 600 },
+ },
+ webServer: {
+ command: 'npm run dev -- --host 127.0.0.1 --port 5229 --strictPort',
+ env: { VIBE_UI_BACKEND: 'http://127.0.0.1:9' },
+ url: 'http://127.0.0.1:5229/e2e/pet-mini/fixture.html',
+ },
+ projects: [
+ { name: 'chromium', use: { browserName: 'chromium' } },
+ { name: 'webkit', use: { browserName: 'webkit' } },
+ ],
+});
diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsx
index 7ae855a73..8b59211fe 100644
--- a/ui/src/components/workbench/Composer.tsx
+++ b/ui/src/components/workbench/Composer.tsx
@@ -1098,6 +1098,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
});
voiceCaptureClaimRef.current = captureClaim;
try {
+ await captureClaim.ready;
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
if (!captureClaim.isCurrent() || unmountedRef.current || disabledRef.current) {
stream.getTracks().forEach((track) => track.stop());
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 600841850..d2a9ab864 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -723,6 +723,9 @@ export type ApiContextType = {
createSession: (payload: WorkbenchSessionCreate) => Promise<WorkbenchSession>;
forkSession: (sessionId: string) => Promise<WorkbenchSession>;
getSession: (sessionId: string, params?: { cache?: boolean; handleError?: boolean }) => Promise<WorkbenchSession>;
+ /** Main-agent lookup seam. The endpoint is not shipped yet; the pet client
+ * currently resolves the session bound to its native window here. */
+ getMainSession: () => Promise<WorkbenchSessionReadResult>;
getSessionResult: (sessionId: string) => Promise<WorkbenchSessionReadResult>;
getSessionBootstrap: (sessionId: string) => Promise<WorkbenchSessionBootstrap>;
updateSession: (sessionId: string, payload: Partial<WorkbenchSessionUpdate>) => Promise<WorkbenchSession>;
@@ -3729,6 +3732,20 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
: await getCachedJson(`/api/sessions/${encodeURIComponent(sessionId)}`, undefined, { handleError: params?.handleError });
return sessionRowFromPayload(payload);
},
+ getMainSession: async () => {
+ const binding = (window as unknown as { __AVIBE_PET_BINDING__?: unknown }).__AVIBE_PET_BINDING__;
+ if (typeof binding !== 'string' || !binding) return { status: 404, session: null };
+ const res = await apiFetch(`/api/sessions/${encodeURIComponent(binding)}`);
+ const payload = await res.json().catch(() => null);
+ if (!(res.ok && payload && typeof payload.id === 'string')) {
+ return { status: res.status, session: null };
+ }
+ return {
+ status: res.status,
+ session: sessionRowFromPayload(payload),
+ capabilities: sessionCanChatFromPayload(payload),
+ };
+ },
getSessionResult: async (sessionId) => {
const res = await apiFetch(`/api/sessions/${encodeURIComponent(sessionId)}`);
const payload = await res.json().catch(() => null);
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index fc90e8933..f584831c7 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -5580,12 +5580,59 @@
"chooseSession": "Choose a session",
"switchSession": "Switch session",
"openInAvibe": "Open in Avibe",
- "inputPlaceholder": "Message the agent…",
+ "inputPlaceholder": "Message the main agent…",
"send": "Send",
"queued": "Queued — it will run after the current turn.",
"moreInAvibe": "More replies in Avibe",
"empty": "No messages yet. Say something to get started.",
"vaultRequest": "Approval needed — open in Avibe",
- "noSessions": "No active sessions yet. Start one in Avibe."
+ "noSessions": "No active sessions yet. Start one in Avibe.",
+ "mainAgent": "Main agent",
+ "mainAgentTitle": "Main agent",
+ "thinking": "Thinking",
+ "waiting": "Waiting",
+ "repliedPrefix": "Replied:",
+ "untitledTask": "Untitled task",
+ "dismiss": "Dismiss task",
+ "voiceContinue": "Continue voice input",
+ "voice": {
+ "cloudRequired": "Voice input needs Avibe Cloud. You can type a message instead.",
+ "listening": "Listening…",
+ "open": "Voice input",
+ "stop": "Stop voice input"
+ },
+ "keyboard": {
+ "open": "Type a message",
+ "close": "Close input"
+ },
+ "stack": {
+ "expand": "Expand session cards"
+ },
+ "activityKind": {
+ "watch": "Monitor",
+ "task": "Scheduled task",
+ "agent_run": "Delegated run",
+ "backend_activity": "Background activity"
+ },
+ "activityStatus": {
+ "running": "Running",
+ "queued": "Queued",
+ "waiting": "Waiting",
+ "stopped": "Stopped",
+ "completed": "Completed",
+ "failed": "Failed",
+ "unknown": "In progress"
+ },
+ "stop": {
+ "stop": "Stop",
+ "pause": "Pause",
+ "confirmStop": "Stop?",
+ "confirmPause": "Pause?",
+ "stopping": "Stopping…",
+ "pausing": "Pausing…",
+ "stopped": "Stopped",
+ "paused": "Paused",
+ "failed": "Could not stop; try again later"
+ }
}
}
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 540fb053c..1e427b3de 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -5580,12 +5580,59 @@
"chooseSession": "选择一个会话",
"switchSession": "切换会话",
"openInAvibe": "在 Avibe 中打开",
- "inputPlaceholder": "给 agent 发消息…",
+ "inputPlaceholder": "和 main agent 说…",
"send": "发送",
"queued": "已排队,当前这轮结束后执行。",
"moreInAvibe": "更多回复请在 Avibe 中查看",
"empty": "还没有消息,说点什么开始吧。",
"vaultRequest": "需要授权,在 Avibe 中打开",
- "noSessions": "还没有进行中的会话,先在 Avibe 里新建一个。"
+ "noSessions": "还没有进行中的会话,先在 Avibe 里新建一个。",
+ "mainAgent": "MAIN AGENT",
+ "mainAgentTitle": "主 agent",
+ "thinking": "思考中",
+ "waiting": "等待中",
+ "repliedPrefix": "已回复:",
+ "untitledTask": "未命名任务",
+ "dismiss": "移除任务",
+ "voiceContinue": "继续语音输入",
+ "voice": {
+ "cloudRequired": "语音输入需要 Avibe Cloud,暂时可以打字发送。",
+ "listening": "正在听…",
+ "open": "语音输入",
+ "stop": "停止语音输入"
+ },
+ "keyboard": {
+ "open": "输入消息",
+ "close": "关闭输入"
+ },
+ "stack": {
+ "expand": "展开会话卡片"
+ },
+ "activityKind": {
+ "watch": "监控",
+ "task": "定时任务",
+ "agent_run": "委派运行",
+ "backend_activity": "后台活动"
+ },
+ "activityStatus": {
+ "running": "运行中",
+ "queued": "排队中",
+ "waiting": "等待中",
+ "stopped": "已停止",
+ "completed": "已完成",
+ "failed": "失败",
+ "unknown": "处理中"
+ },
+ "stop": {
+ "stop": "停止",
+ "pause": "暂停",
+ "confirmStop": "停止?",
+ "confirmPause": "暂停?",
+ "stopping": "正在停止…",
+ "pausing": "正在暂停…",
+ "stopped": "已停止",
+ "paused": "已暂停",
+ "failed": "没停下来,稍后再试"
+ }
}
}
diff --git a/ui/src/lib/showPageVoiceDictation.ts b/ui/src/lib/showPageVoiceDictation.ts
index eaf080753..f4179dca0 100644
--- a/ui/src/lib/showPageVoiceDictation.ts
+++ b/ui/src/lib/showPageVoiceDictation.ts
@@ -127,6 +127,7 @@ export class ShowPageVoiceDictation {
});
this.captureClaim = captureClaim;
try {
+ await captureClaim.ready;
const stream = await this.dependencies.getUserMedia();
if (this.abortController.signal.aborted || !captureClaim.isCurrent()) {
stream.getTracks().forEach((track) => track.stop());
diff --git a/ui/src/lib/voiceRecording.test.ts b/ui/src/lib/voiceRecording.test.ts
index e11cd2351..141d731a3 100644
--- a/ui/src/lib/voiceRecording.test.ts
+++ b/ui/src/lib/voiceRecording.test.ts
@@ -12,6 +12,8 @@ import {
VoiceRecordingPipeline,
} from './voiceRecording';
+const initialNavigatorLocks = Object.getOwnPropertyDescriptor(navigator, 'locks');
+
type CaptureHandlers = {
onSamples: (samples: Int16Array) => void;
onStopped: () => void;
@@ -109,6 +111,8 @@ const wavSamples = async (blob: Blob): Promise<number[]> => {
};
afterEach(() => {
+ Reflect.deleteProperty(navigator, 'locks');
+ if (initialNavigatorLocks) Object.defineProperty(navigator, 'locks', initialNavigatorLocks);
vi.useRealTimers();
vi.restoreAllMocks();
vi.unstubAllGlobals();
@@ -650,6 +654,72 @@ describe('deleteMapValueIfCurrent', () => {
});
describe('voice capture ownership', () => {
+ // One lock manager shared by independently loaded JS realms. Callbacks are
+ // asynchronous, as in Web Locks; stealing rejects the previous request.
+ const installLocks = () => {
+ let current: { reject: (error: unknown) => void } | null = null;
+ const locks = {
+ request: vi.fn((_name: string, options: { steal?: boolean }, callback: () => Promise<void>) =>
+ new Promise<void>((resolve, reject) => {
+ queueMicrotask(() => {
+ if (options.steal) current?.reject(new DOMException('lock stolen', 'AbortError'));
+ const owner = { reject };
+ current = owner;
+ void callback().then(() => {
+ if (current === owner) current = null;
+ resolve();
+ }, reject);
+ });
+ })),
+ };
+ Object.defineProperty(navigator, 'locks', { configurable: true, value: locks });
+ return locks;
+ };
+
+ const anotherRealm = async () => {
+ vi.resetModules();
+ return import('./voiceRecording');
+ };
+
+ it('preserves captured samples when another realm steals the lock', async () => {
+ installLocks();
+ const main = await anotherRealm();
+ const pet = await anotherRealm();
+ const recording = setup();
+ await recording.pipeline.start();
+ recording.capture().emit(123, 456);
+ const finish = vi.fn(() => recording.pipeline.finish());
+ const oldOwner = main.claimVoiceCapture(finish);
+ await oldOwner.ready;
+ const newOwner = pet.claimVoiceCapture(vi.fn());
+ await newOwner.ready;
+ await vi.waitFor(() => expect(finish).toHaveBeenCalledOnce());
+ expect(oldOwner.isCurrent()).toBe(false);
+ expect(newOwner.isCurrent()).toBe(true);
+ recording.capture().settle();
+ expect(recording.onSegment).toHaveBeenCalledOnce();
+ expect(await wavSamples(recording.onSegment.mock.calls[0][0])).toEqual([123, 456]);
+ oldOwner.release();
+ expect(newOwner.isCurrent()).toBe(true);
+ newOwner.release();
+ });
+
+ it('orders simultaneous independent-realm claims with the newest owning capture', async () => {
+ installLocks();
+ const main = await anotherRealm();
+ const pet = await anotherRealm();
+ const finishMain = vi.fn();
+ const first = main.claimVoiceCapture(finishMain);
+ const last = pet.claimVoiceCapture(vi.fn());
+ await Promise.allSettled([first.ready, last.ready]);
+ await vi.waitFor(() => expect(finishMain).toHaveBeenCalledOnce());
+ expect(first.isCurrent()).toBe(false);
+ expect(last.isCurrent()).toBe(true);
+ first.release();
+ expect(last.isCurrent()).toBe(true);
+ last.release();
+ });
+
it('finishes the previous surface and ignores its stale release', () => {
const finishChat = vi.fn();
const finishShowPage = vi.fn();
@@ -668,6 +738,55 @@ describe('voice capture ownership', () => {
expect(finishShowPage).not.toHaveBeenCalled();
next.release();
});
+
+ it('keeps local replacement semantics when Web Locks is unavailable', () => {
+ const previousDescriptor = Object.getOwnPropertyDescriptor(navigator, 'locks');
+ Reflect.deleteProperty(navigator, 'locks');
+ const previousFinish = vi.fn();
+ const nextFinish = vi.fn();
+ const previous = claimVoiceCapture(previousFinish);
+ const next = claimVoiceCapture(nextFinish);
+
+ expect(previous.isCurrent()).toBe(false);
+ expect(next.isCurrent()).toBe(true);
+ expect(previousFinish).toHaveBeenCalledOnce();
+ previous.release();
+ expect(next.isCurrent()).toBe(true);
+
+ next.release();
+ expect(next.isCurrent()).toBe(false);
+ if (previousDescriptor) Object.defineProperty(navigator, 'locks', previousDescriptor);
+ });
+
+ it('finishes an old owner through the Web Lock steal path without double finishing', async () => {
+ installLocks();
+ const previousFinish = vi.fn();
+ const nextFinish = vi.fn();
+ const previous = claimVoiceCapture(previousFinish);
+ await previous.ready;
+ const next = claimVoiceCapture(nextFinish);
+
+ await expect(next.ready).resolves.toBeUndefined();
+ await Promise.resolve();
+ expect(previousFinish).toHaveBeenCalledOnce();
+ expect(next.isCurrent()).toBe(true);
+ next.release();
+ });
+
+ it('makes the newest simultaneous claim the owner', async () => {
+ installLocks();
+ const firstFinish = vi.fn();
+ const secondFinish = vi.fn();
+ const first = claimVoiceCapture(firstFinish);
+ const second = claimVoiceCapture(secondFinish);
+
+ await expect(second.ready).resolves.toBeUndefined();
+ await Promise.resolve();
+ expect(first.isCurrent()).toBe(false);
+ expect(second.isCurrent()).toBe(true);
+ expect(firstFinish).toHaveBeenCalledOnce();
+ second.release();
+ });
});
describe('isVoiceControlDisabled', () => {
diff --git a/ui/src/lib/voiceRecording.ts b/ui/src/lib/voiceRecording.ts
index c9ec3ccce..653142955 100644
--- a/ui/src/lib/voiceRecording.ts
+++ b/ui/src/lib/voiceRecording.ts
@@ -325,6 +325,12 @@ export const deleteMapValueIfCurrent = <Key, Value>(
export type VoiceCaptureClaim = {
isCurrent(): boolean;
release(): void;
+ /**
+ * Resolves once the cross-window capture lock is held. Existing callers can
+ * start immediately in a browser without Web Locks; desktop callers await
+ * this before opening the microphone.
+ */
+ ready: Promise<void>;
};
type ActiveVoiceCapture = {
@@ -333,6 +339,7 @@ type ActiveVoiceCapture = {
};
let activeVoiceCapture: ActiveVoiceCapture | null = null;
+const VOICE_CAPTURE_LOCK = 'avibe.voice-capture';
/**
* Give the newest explicit voice action sole ownership of the browser mic.
@@ -341,21 +348,68 @@ let activeVoiceCapture: ActiveVoiceCapture | null = null;
*/
export const claimVoiceCapture = (finish: () => void): VoiceCaptureClaim => {
const token = Symbol('voice-capture');
+ let finished = false;
+ const finishOnce = () => {
+ if (finished) return;
+ finished = true;
+ try {
+ finish();
+ } catch {
+ // Ownership has already moved; a stale recorder cannot block the new one.
+ }
+ };
const previous = activeVoiceCapture;
- activeVoiceCapture = { token, finish };
- try {
- previous?.finish();
- } catch {
- // Ownership has already moved; a stale recorder cannot block the new one.
- }
+ activeVoiceCapture = { token, finish: finishOnce };
+ previous?.finish();
let released = false;
+ let revoked = false;
+ let releaseLock: (() => void) | null = null;
+ let resolveReady!: () => void;
+ let rejectReady!: (error: unknown) => void;
+ const ready = new Promise<void>((resolve, reject) => {
+ resolveReady = resolve;
+ rejectReady = reject;
+ });
+ // A claim can be replaced before its caller reaches the microphone step.
+ // The caller still observes the rejection when it awaits ready.
+ void ready.catch(() => undefined);
+ const locks = typeof navigator !== 'undefined' ? navigator.locks : undefined;
+ if (!locks) {
+ resolveReady();
+ } else {
+ const lockHold = new Promise<void>((resolve) => {
+ releaseLock = resolve;
+ });
+ void locks.request(
+ VOICE_CAPTURE_LOCK,
+ { steal: true },
+ async () => {
+ if (released || activeVoiceCapture?.token !== token) {
+ rejectReady(new DOMException('Voice capture replaced', 'AbortError'));
+ return;
+ }
+ resolveReady();
+ await lockHold;
+ },
+ ).catch((error: unknown) => {
+ // A newer claim steals this lock. The old surface finishes through its
+ // existing replacement path, preserving the captured speech.
+ if (!released && error instanceof DOMException && error.name === 'AbortError') {
+ revoked = true;
+ finishOnce();
+ }
+ rejectReady(error);
+ });
+ }
return {
- isCurrent: () => !released && activeVoiceCapture?.token === token,
+ isCurrent: () => !released && !revoked && activeVoiceCapture?.token === token,
release: () => {
if (released) return;
released = true;
if (activeVoiceCapture?.token === token) activeVoiceCapture = null;
+ releaseLock?.();
},
+ ready,
};
};
diff --git a/ui/src/pet/PetPage.test.tsx b/ui/src/pet/PetPage.test.tsx
index 72e8e0cd5..9a2ebc514 100644
--- a/ui/src/pet/PetPage.test.tsx
+++ b/ui/src/pet/PetPage.test.tsx
@@ -1,6 +1,6 @@
/* @vitest-environment jsdom */
-import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react';
+import { fireEvent, act, cleanup, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -117,6 +117,9 @@ const markRead = vi.fn(async (): Promise<boolean> => {
});
const api = {
+ setHarnessWatchEnabled: vi.fn(async () => ({ ok: true })),
+ setHarnessTaskEnabled: vi.fn(async () => ({ ok: true })),
+ getMainSession: vi.fn(() => api.getSessionResult((window as unknown as { __AVIBE_PET_BINDING__: string }).__AVIBE_PET_BINDING__)),
getConfig: vi.fn(async () => (setupDone
? { mode: 'self_host', setup_state: { needs_setup: false } }
: { mode: 'self_host', setup_state: { needs_setup: true } })),
@@ -194,9 +197,17 @@ const bound = (sessionId: string | null) => act(() => {
const shellBound = (sessionId: string | null, revision: number) => act(() => {
window.dispatchEvent(new CustomEvent(PET_BOUND_EVENT, { detail: { session_id: sessionId, revision } }));
});
-const summon = (intent: 'listen' | 'show') => act(() => {
+const summon = (intent: 'listen' | 'show' | 'release') => act(() => {
window.dispatchEvent(new CustomEvent(PET_SUMMON_EVENT, { detail: { intent } }));
});
+// v2 puts the exchange behind the main card. Tests of the exchange explicitly
+// open it; raw summon remains available for collapsed/detail visibility tests.
+const showDetail = async () => {
+ summon('show');
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 15)));
+ const main = document.querySelector('.pet-mini-card[role="button"]');
+ if (main && !document.querySelector('.pet-mini-detail.is-open')) fireEvent.click(main);
+};
const pose = () => document.querySelector('.pet-avatar')?.getAttribute('data-pose');
// The shell store lives for one document, so each test loads a fresh module
@@ -213,7 +224,7 @@ beforeEach(async () => {
runningAgents = { ok: true, agents: [], counts: { total: 0, active: 0, idle: 0, orphan: 0, by_backend: {} } };
api.getRunningAgents.mockClear();
sessionReads = {};
- tails = {};
+ tails = Object.fromEntries(['S', 'A', 'B', 'C'].map((id) => [id, [message(`u-${id}`, id, { author: 'user', type: 'user', text: `Session ${id}` })]]));
switcherSessions = [];
unreadBySession = {};
markRead.mockClear();
@@ -244,7 +255,7 @@ describe('PetPage setup', () => {
render(<PetPage />);
await screen.findByText('pet.setupPending');
setupDone = true;
- summon('show');
+ await showDetail();
await waitFor(() => expect(screen.queryByText('pet.setupPending')).toBeNull());
expect(api.getConfig).toHaveBeenLastCalledWith({ cache: false });
});
@@ -269,10 +280,11 @@ describe('PetPage binding', () => {
render(<PetPage />);
await waitFor(() => expect(api.getSessionResult).toHaveBeenCalledWith('A'));
await bound('B');
+ summon('listen');
await waitFor(() => expect(api.getSessionResult).toHaveBeenCalledWith('B'));
await act(async () => lateA.resolve({ status: 404, session: null }));
- summon('show');
- expect(await screen.findByText('Session B')).toBeTruthy();
+ await showDetail();
+ expect(await screen.findAllByText('Session B')).toBeTruthy();
expect(devBinding().binding).toBe('B');
});
@@ -309,7 +321,7 @@ describe('PetPage state', () => {
tails.S = [message('u', 'S', { author: 'user', type: 'user' }), asking];
devBind('S');
render(<PetPage />);
- summon('show');
+ await showDetail();
expect(await screen.findByText('Yes')).toBeTruthy();
expect(pose()).toBe('idle');
});
@@ -352,7 +364,7 @@ describe('PetPage state', () => {
devBind('S');
render(<PetPage />);
await waitFor(() => expect(pose()).toBe('ready'));
- summon('show');
+ await showDetail();
await screen.findByText('reply r3');
await waitFor(() => expect(markRead).toHaveBeenCalledWith('S', 'r3'));
});
@@ -365,7 +377,7 @@ describe('PetPage state', () => {
unreadBySession = { S: 5 };
devBind('S');
render(<PetPage />);
- summon('show');
+ await showDetail();
expect(await screen.findByText('pet.moreInAvibe')).toBeTruthy();
expect(markRead).not.toHaveBeenCalled();
});
@@ -458,7 +470,7 @@ describe('PetPage review fixes', () => {
unreadBySession = { S: 1 };
devBind('S');
render(<PetPage />);
- summon('show');
+ await showDetail();
await screen.findByText('reply r1');
await waitFor(() => expect(markRead).toHaveBeenCalled());
await act(async () => new Promise((resolve) => setTimeout(resolve, 50)));
@@ -475,6 +487,7 @@ describe('PetPage review fixes', () => {
const input = await screen.findByLabelText('pet.inputPlaceholder');
await userEvent.type(input, 'hello{Enter}');
await bound('B');
+ summon('listen');
await screen.findByText('B only');
await act(async () => pending.resolve(message('a-sent', 'A', { author: 'user', type: 'user', text: 'sent to A' })));
// B neither shows A's row nor enters A's post-send Running grace.
@@ -507,12 +520,12 @@ describe('PetPage review fixes, round 2', () => {
switcherSessions = [session('S'), session('T')];
devBind('S');
render(<PetPage />);
- summon('show');
+ await showDetail();
await screen.findByText('reply r1');
await waitFor(() => expect(markRead).toHaveBeenCalledTimes(1));
// A newer reply arrives while the user is looking at the switcher.
await userEvent.click(screen.getByLabelText('pet.switchSession'));
- await screen.findByText('Session T');
+ await screen.findAllByText('Session T');
await emit((h) => h.onMessageNew?.(message('r2', 'S', { read_at: null })));
await act(async () => new Promise((resolve) => setTimeout(resolve, 50)));
expect(markRead).toHaveBeenCalledTimes(1);
@@ -526,12 +539,12 @@ describe('PetPage review fixes, round 2', () => {
});
devBind('S');
render(<PetPage />);
- summon('show');
+ await showDetail();
await waitFor(() => expect(markRead).toHaveBeenCalledTimes(1));
act(() => {
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
});
- summon('show');
+ await showDetail();
await waitFor(() => expect(markRead).toHaveBeenCalledTimes(2));
expect(markRead).toHaveBeenLastCalledWith('S', 'r1');
});
@@ -571,7 +584,7 @@ describe('PetPage review fixes, round 3', () => {
try {
devBind('S');
render(<PetPage />);
- summon('show');
+ await showDetail();
await screen.findByText('reply r1');
await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));
expect(markRead).not.toHaveBeenCalled();
@@ -597,8 +610,8 @@ describe('PetPage review fixes, round 3', () => {
// The shell moved to B (revision 2) after answering pet_ready at revision 1.
await shellBound('B', 2);
await act(async () => ready.resolve({ binding: 'A', revision: 1, summon_pending: null }));
- summon('show');
- expect(await screen.findByText('Session B')).toBeTruthy();
+ await showDetail();
+ expect(await screen.findAllByText('Session B')).toBeTruthy();
});
});
@@ -612,7 +625,7 @@ describe('PetPage independent sweep', () => {
try {
devBind('S');
render(<PetPage />);
- summon('show');
+ await showDetail();
await waitFor(() => expect(markRead).toHaveBeenCalledTimes(1));
// The panel stays open; the window is hidden and shown again.
visibility = 'hidden';
@@ -632,8 +645,8 @@ describe('PetPage independent sweep', () => {
it('lands a bound summon on the session even if the switcher was left open', async () => {
switcherSessions = [session('S')];
render(<PetPage />);
- summon('show');
- expect(await screen.findByText('Session S')).toBeTruthy();
+ await showDetail();
+ expect(await screen.findAllByText('Session S')).toBeTruthy();
act(() => {
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
});
@@ -651,6 +664,7 @@ describe('PetPage independent sweep', () => {
const input = await screen.findByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement;
await userEvent.type(input, 'deploy{Enter}');
await bound('B');
+ summon('listen');
await act(async () => pending.resolve(message('a-sent', 'A', { author: 'user', type: 'user' })));
expect((screen.getByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement).value).toBe('');
});
@@ -668,7 +682,7 @@ describe('PetPage independent sweep', () => {
}
h.onMessageNew?.(message('r2', 'S', { read_at: null, text: 'reply r2' }));
});
- summon('show');
+ await showDetail();
expect(await screen.findByText('pet.moreInAvibe')).toBeTruthy();
expect(markRead).not.toHaveBeenCalled();
});
@@ -685,8 +699,8 @@ describe('PetPage review fixes, round 4', () => {
Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });
switcherSessions = [session('A'), session('B')];
render(<PetPage />);
- summon('show');
- expect(await screen.findByText('Session A')).toBeTruthy();
+ await showDetail();
+ expect(await screen.findAllByText('Session A')).toBeTruthy();
await userEvent.click(screen.getByLabelText('pet.switchSession'));
await userEvent.click(await screen.findByText('Session B'));
await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_bind', { sessionId: 'B' }));
@@ -709,9 +723,9 @@ describe('PetPage review fixes, round 5', () => {
render(<PetPage />);
await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_unbind', { sessionId: 'A' }));
await act(async () => new Promise((resolve) => setTimeout(resolve, 50)));
- summon('show');
+ await showDetail();
// The invalid session is never offered as usable: the switcher shows.
- expect(await screen.findByText('Session B')).toBeTruthy();
+ expect(await screen.findAllByText('Session B')).toBeTruthy();
expect(api.getSessionResult.mock.calls.filter(([id]) => id === 'A')).toHaveLength(1);
expect(invoke.mock.calls.filter(([command]) => command === 'pet_unbind')).toHaveLength(1);
});
@@ -725,7 +739,7 @@ describe('PetPage review fixes, round 6', () => {
render(<PetPage />);
summon('listen');
await screen.findByLabelText('pet.panel');
- expect(screen.queryByLabelText('pet.inputPlaceholder')).toBeNull();
+ expect(screen.queryByRole('textbox', { name: 'pet.inputPlaceholder' })).toBeNull();
expect(api.sendSessionMessage).not.toHaveBeenCalled();
await act(async () => validation.resolve({
status: 200,
@@ -744,7 +758,8 @@ describe('PetPage review fixes, round 6', () => {
const input = await screen.findByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement;
await userEvent.type(input, 'meant for A');
await bound('B');
- await screen.findByText('Session B');
+ summon('listen');
+ await screen.findAllByText('Session B');
expect((screen.getByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement).value).toBe('');
});
@@ -783,15 +798,15 @@ describe('PetPage review fixes, round 7', () => {
await screen.findByLabelText('pet.toggle');
// The live summon is newer than the pending one pet_ready still carries.
await shellBound('S', 1);
- summon('show');
- await screen.findByText('Session S');
+ await showDetail();
+ expect(screen.getByLabelText('pet.toggle').getAttribute('aria-expanded')).toBe('true');
act(() => {
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
});
await act(async () => ready.resolve({ binding: 'S', revision: 1, summon_pending: { intent: 'listen' } }));
await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));
// The stale pending summon did not reopen the panel.
- expect(screen.queryByLabelText('pet.inputPlaceholder')).toBeNull();
+ expect(screen.queryByRole('textbox', { name: 'pet.inputPlaceholder' })).toBeNull();
});
});
@@ -806,7 +821,7 @@ describe('PetPage review fixes, round 8', () => {
});
devBind('S');
render(<PetPage />);
- summon('show');
+ await showDetail();
await waitFor(() => expect(markRead).toHaveBeenCalledWith('S', 'r1'));
await waitFor(() => expect(api.listSessionMessages.mock.calls.length).toBeGreaterThan(1));
await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));
@@ -825,6 +840,7 @@ describe('PetPage review fixes, round 8', () => {
render(<PetPage />);
summon('listen');
const input = await screen.findByLabelText('pet.inputPlaceholder');
+ await showDetail();
await userEvent.click(await screen.findByText('Yes'));
await userEvent.type(input, 'also this{Enter}');
expect(api.sendSessionMessage).toHaveBeenCalledTimes(1);
@@ -840,7 +856,8 @@ describe('PetPage review fixes, round 8', () => {
const input = await screen.findByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement;
await userEvent.type(input, 'continue{Enter}');
await bound('B');
- await screen.findByText('Session B');
+ summon('listen');
+ await screen.findAllByText('Session B');
const inputB = screen.getByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement;
await userEvent.type(inputB, 'continue');
await act(async () => pending.resolve(message('a-sent', 'A', { author: 'user', type: 'user' })));
@@ -849,7 +866,7 @@ describe('PetPage review fixes, round 8', () => {
});
describe('PetPage review fixes, round 9', () => {
- it('shows a background-work count on the collapsed pet without changing its pose', async () => {
+ it('counts own running sub-tasks in the collapsed busy pose', async () => {
api.getTurnState.mockImplementation(async () => ({
...idleTurn,
background_activities: [
@@ -862,7 +879,7 @@ describe('PetPage review fixes, round 9', () => {
render(<PetPage />);
expect(await screen.findByLabelText('chat.activities.running')).toBeTruthy();
expect(screen.getByLabelText('chat.activities.running').textContent).toBe('2');
- expect(pose()).toBe('idle');
+ expect(pose()).toBe('running');
} finally {
api.getTurnState.mockImplementation(async () => idleTurn);
}
@@ -876,7 +893,7 @@ describe('PetPage review fixes, round 10', () => {
windowFocused = false;
devBind('S');
render(<PetPage />);
- summon('show');
+ await showDetail();
await screen.findByText('unseen');
await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));
expect(markRead).not.toHaveBeenCalled();
@@ -898,10 +915,11 @@ describe('PetPage review fixes, round 10', () => {
Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });
switcherSessions = [session('A'), session('B'), session('C')];
render(<PetPage />);
- summon('show');
- await screen.findByText('Session A');
+ await showDetail();
+ await screen.findAllByText('Session A');
await userEvent.click(screen.getByLabelText('pet.switchSession'));
await userEvent.click(await screen.findByText('Session B'));
+ await showDetail();
await userEvent.click(await screen.findByLabelText('pet.switchSession'));
await userEvent.click(await screen.findByText('Session C'));
await act(async () => binds.B.reject(new Error('disk full')));
@@ -911,7 +929,7 @@ describe('PetPage review fixes, round 10', () => {
});
describe('PetPage review fixes, round 12', () => {
- it('keeps the panel matching the native frame when a resize fails', async () => {
+ it('keeps the panel matching the acknowledged shell state when activation fails', async () => {
const invoke = vi.fn((command: string) => {
if (command === 'pet_ready') return Promise.resolve({ binding: 'S', revision: 1, summon_pending: null });
if (command === 'pet_set_expanded') return Promise.reject(new Error('no monitor'));
@@ -936,7 +954,7 @@ describe('PetPage review fixes, round 13', () => {
summon('listen');
await screen.findByLabelText('pet.panel');
await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));
- expect(screen.queryByLabelText('pet.inputPlaceholder')).toBeNull();
+ expect(screen.queryByRole('textbox', { name: 'pet.inputPlaceholder' })).toBeNull();
expect(screen.queryByText('Yes')).toBeNull();
});
@@ -952,8 +970,8 @@ describe('PetPage review fixes, round 13', () => {
render(<PetPage />);
summon('listen');
await screen.findByLabelText('pet.panel');
- await screen.findByText('Session S');
- expect(screen.queryByLabelText('pet.inputPlaceholder')).toBeNull();
+ await waitFor(() => expect(api.getSessionResult).toHaveBeenCalledWith('S'));
+ expect(screen.queryByRole('textbox', { name: 'pet.inputPlaceholder' })).toBeNull();
expect(screen.queryByText('Yes')).toBeNull();
await userEvent.keyboard('should not send{Enter}');
expect(api.sendSessionMessage).not.toHaveBeenCalled();
@@ -976,7 +994,7 @@ describe('PetPage review fixes, round 13', () => {
tails.S = [message('r1', 'S', { text: 'private reply' })];
devBind('S');
render(<PetPage />);
- summon('show');
+ await showDetail();
await screen.findByText('private reply');
sessionReads.S = async () => ({ status: 403, session: null });
await emit((h) => h.onAuthorizationChanged?.({}));
@@ -998,10 +1016,11 @@ describe('PetPage async closure', () => {
Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });
switcherSessions = [session('A'), session('B'), session('C')];
render(<PetPage />);
- summon('show');
- await screen.findByText('Session A');
+ await showDetail();
+ await screen.findAllByText('Session A');
await userEvent.click(screen.getByLabelText('pet.switchSession'));
await userEvent.click(await screen.findByText('Session B'));
+ await showDetail();
await userEvent.click(await screen.findByLabelText('pet.switchSession'));
await userEvent.click(await screen.findByText('Session C'));
// C waits for B's answer, so the shell sees the picks in the user's order.
@@ -1013,14 +1032,14 @@ describe('PetPage async closure', () => {
await shellBound('B', 2);
await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));
expect(api.getSessionResult).toHaveBeenLastCalledWith('C');
- expect(await screen.findByText('Session C')).toBeTruthy();
+ expect(await screen.findAllByText('Session C')).toBeTruthy();
});
// Read freshness: what was read under the old authorization goes at once.
it('drops switcher rows at once when authorization changes, then re-reads', async () => {
switcherSessions = [session('X', { title: 'Revoked project' })];
render(<PetPage />);
- summon('show');
+ await showDetail();
await screen.findByText('Revoked project');
const reread = deferred<{ sessions: WorkbenchSession[]; next_before_id: null }>();
api.listSessions.mockImplementationOnce(() => reread.promise);
@@ -1037,7 +1056,7 @@ describe('PetPage async closure', () => {
unreadBySession = { S: 3 };
devBind('S');
render(<PetPage />);
- summon('show');
+ await showDetail();
await screen.findByLabelText('pet.panel');
await emit((h) => h.onMessageNew?.(message('live', 'S', { read_at: null })));
await screen.findByText('reply live');
@@ -1072,7 +1091,8 @@ describe('PetPage async closure', () => {
const notice = screen.getByRole('status');
await userEvent.click(within(notice).getByRole('button', { name: 'pet.openInAvibe' }));
expect(screen.queryByText('newSession.sendUncertain')).toBeNull();
- await userEvent.type(input, '{Enter}');
+ summon('listen');
+ await userEvent.type(await screen.findByRole('textbox', { name: 'pet.inputPlaceholder' }), '{Enter}');
expect(api.sendSessionMessage).toHaveBeenCalledTimes(2);
});
@@ -1087,7 +1107,8 @@ describe('PetPage async closure', () => {
await userEvent.type(input, 'again{Enter}');
await waitFor(() => expect(api.sendSessionMessage).toHaveBeenCalledTimes(1));
expect(screen.queryByText('newSession.sendUncertain')).toBeNull();
- await userEvent.type(input, '{Enter}');
+ summon('listen');
+ await userEvent.type(await screen.findByRole('textbox', { name: 'pet.inputPlaceholder' }), '{Enter}');
expect(api.sendSessionMessage).toHaveBeenCalledTimes(2);
});
@@ -1103,7 +1124,7 @@ describe('PetPage async closure', () => {
act(() => {
window.dispatchEvent(new Event('focus'));
});
- summon('show');
+ await showDetail();
await act(async () => new Promise((resolve) => setTimeout(resolve, 10)));
await act(async () => seesDone.resolve({ mode: 'self_host', setup_state: { needs_setup: false } }));
await waitFor(() => expect(screen.queryByText('pet.setupPending')).toBeNull());
@@ -1151,6 +1172,7 @@ describe('PetPage live convergence', () => {
expect(await screen.findByText('newSession.sendUncertain')).toBeTruthy();
await bound('B');
+ summon('listen');
await waitFor(() => expect(api.getSessionResult).toHaveBeenCalledWith('B'));
const inputB = await screen.findByLabelText('pet.inputPlaceholder') as HTMLTextAreaElement;
await settle();
@@ -1161,7 +1183,8 @@ describe('PetPage live convergence', () => {
await bound('A');
await settle();
expect(screen.getByText('newSession.sendUncertain')).toBeTruthy();
- await userEvent.type(screen.getByLabelText('pet.inputPlaceholder'), 'again{Enter}');
+ expect(screen.queryByRole('textbox', { name: 'pet.inputPlaceholder' })).toBeNull();
+ await userEvent.keyboard('again{Enter}');
expect(api.sendSessionMessage).toHaveBeenCalledTimes(2);
});
@@ -1181,19 +1204,19 @@ describe('PetPage live convergence', () => {
Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });
tails.S = [message('u', 'S', { author: 'user', type: 'user' })];
render(<PetPage />);
- summon('show');
+ await showDetail();
await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_set_expanded', { expanded: true }));
await act(async () => first.resolve({ panel_side: 'left', panel_edge: 'bottom' }));
await screen.findByLabelText('pet.panel');
- summon('show');
+ await showDetail();
await waitFor(() => expect(invoke.mock.calls.filter(([c]) => c === 'pet_set_expanded')).toHaveLength(2));
await act(async () => second.reject(new Error('already expanded')));
await settle();
expect(screen.getByLabelText('pet.panel')).toBeTruthy();
});
- it('shows the panel and marks replies read only once the shell has grown the frame', async () => {
+ it('shows the panel and marks replies read only once the shell acknowledges activation', async () => {
tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('r', 'S', { read_at: null })];
unreadBySession = { S: 1 };
const grow = deferred<unknown>();
@@ -1205,13 +1228,13 @@ describe('PetPage live convergence', () => {
Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });
Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });
render(<PetPage />);
- summon('show');
+ await showDetail();
await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_set_expanded', { expanded: true }));
await settle();
expect(screen.queryByLabelText('pet.panel')).toBeNull();
expect(markRead).not.toHaveBeenCalled();
- await act(async () => grow.reject(new Error('resize failed')));
+ await act(async () => grow.reject(new Error('panel activation failed')));
await settle();
expect(screen.queryByLabelText('pet.panel')).toBeNull();
expect(markRead).not.toHaveBeenCalled();
@@ -1220,23 +1243,28 @@ describe('PetPage live convergence', () => {
it('reads the session on a status event when no read has supplied it yet', async () => {
sessionReads.S = vi.fn()
.mockResolvedValueOnce({ status: 500, session: null })
- .mockResolvedValue({ status: 200, session: session('S') });
+ .mockResolvedValue({ status: 200, session: session('S'), capabilities: { can_chat: true } });
devBind('S');
render(<PetPage />);
- summon('show');
+ await showDetail();
await screen.findByLabelText('pet.panel');
await settle();
- expect(screen.queryByText('Session S')).toBeNull();
+ expect(sessionReads.S).toHaveBeenCalledTimes(1);
+ expect(screen.getByLabelText('pet.keyboard.open').hasAttribute('disabled')).toBe(true);
await emit((h) => h.onSessionStatus?.({ session_id: 'S', agent_status: 'idle' }));
- expect(await screen.findByText('Session S')).toBeTruthy();
+ await waitFor(() => expect(sessionReads.S).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(screen.getByLabelText('pet.keyboard.open').hasAttribute('disabled')).toBe(false));
+ summon('listen');
+ await userEvent.type(await screen.findByRole('textbox'), 'recovered{Enter}');
+ expect(api.sendSessionMessage).toHaveBeenCalledExactlyOnceWith('S', { text: 'recovered' });
});
it('reads the tail on a live row when no tail read has landed yet', async () => {
api.listSessionMessages.mockRejectedValueOnce(new Error('network'));
devBind('S');
render(<PetPage />);
- summon('show');
+ await showDetail();
await screen.findByLabelText('pet.panel');
await settle();
const reads = api.listSessionMessages.mock.calls.filter(([id]) => id === 'S').length;
@@ -1249,7 +1277,7 @@ describe('PetPage live convergence', () => {
it('re-reads the tail when the session is marked read in another window', async () => {
devBind('S');
render(<PetPage />);
- summon('show');
+ await showDetail();
await screen.findByLabelText('pet.panel');
await settle();
const reads = api.listSessionMessages.mock.calls.filter(([id]) => id === 'S').length;
@@ -1269,7 +1297,7 @@ describe('PetPage review fixes, round 14', () => {
}));
devBind('S');
render(<PetPage />);
- summon('show');
+ await showDetail();
expect(await screen.findByText('pet.moreInAvibe')).toBeTruthy();
expect(markRead).not.toHaveBeenCalled();
});
@@ -1304,12 +1332,12 @@ describe('PetPage review fixes, round 14', () => {
render(<PetPage />);
summon('listen');
expect(await screen.findByText('newSession.sendUncertain')).toBeTruthy();
- const again = await screen.findByLabelText('pet.inputPlaceholder');
- await userEvent.type(again, 'again{Enter}');
+ expect(screen.queryByRole('textbox', { name: 'pet.inputPlaceholder' })).toBeNull();
+ await userEvent.keyboard('again{Enter}');
expect(api.sendSessionMessage).toHaveBeenCalledTimes(1);
});
- it('sends overlapping native resizes in the order they were asked', async () => {
+ it('sends overlapping panel-state commands in the order they were asked', async () => {
const first = deferred<unknown>();
const second = deferred<unknown>();
const order: boolean[] = [];
@@ -1325,7 +1353,7 @@ describe('PetPage review fixes, round 14', () => {
Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });
tails.S = [message('u', 'S', { author: 'user', type: 'user' })];
render(<PetPage />);
- summon('show');
+ await showDetail();
await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_set_expanded', { expanded: true }));
expect(order).toEqual([true]);
// Collapse while expand is still in flight: Esc is not listening yet
@@ -1338,7 +1366,7 @@ describe('PetPage review fixes, round 14', () => {
await act(async () => second.resolve({ panel_side: 'left', panel_edge: 'bottom' }));
});
- it('focuses the input only after the native panel has grown and the composer is on screen', async () => {
+ it('focuses the input after panel activation and the composer is on screen', async () => {
const grow = deferred<unknown>();
const invoke = vi.fn((command: string) => {
if (command === 'pet_ready') return Promise.resolve({ binding: 'S', revision: 1, summon_pending: null });
@@ -1351,7 +1379,7 @@ describe('PetPage review fixes, round 14', () => {
render(<PetPage />);
summon('listen');
await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_set_expanded', { expanded: true }));
- expect(screen.queryByLabelText('pet.inputPlaceholder')).toBeNull();
+ expect(screen.queryByRole('textbox', { name: 'pet.inputPlaceholder' })).toBeNull();
await act(async () => grow.resolve({ panel_side: 'left', panel_edge: 'bottom' }));
const input = await screen.findByLabelText('pet.inputPlaceholder');
@@ -1359,3 +1387,510 @@ describe('PetPage review fixes, round 14', () => {
});
});
+
+
+describe('desktop mini v2 interaction contract', () => {
+ // Match derive_session_harness_activities(): definitions carry durable
+ // enabled/scheduled states, while delegated executions carry running.
+ const activity = (id: string, item_kind: 'watch' | 'task' | 'agent_run', status = { watch: 'enabled', task: 'scheduled', agent_run: 'running' }[item_kind]) => ({
+ id, item_kind, status, label: id, description: id, backend: 'codex',
+ runtime_key: id, session_id: 'S', kind: item_kind, started_at: '', updated_at: '',
+ });
+ const turn = (items: ReturnType<typeof activity>[]) => {
+ api.getTurnState.mockResolvedValue({ ...idleTurn, background_activities: items } as never);
+ };
+ beforeEach(() => {
+ api.setHarnessWatchEnabled.mockReset().mockResolvedValue({ ok: true });
+ api.setHarnessTaskEnabled.mockReset().mockResolvedValue({ ok: true });
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ api.getTurnState.mockResolvedValue(idleTurn);
+ });
+
+ it.each([
+ ['watch', 'success'], ['watch', 'failure'], ['task', 'success'], ['task', 'failure'],
+ ] as const)('drops a retained %s on authorization change and fences late pause %s', async (kind, outcome) => {
+ const id = `${kind}:private`;
+ turn([activity(id, kind)]);
+ const pending = deferred<{ ok: boolean }>();
+ const pause = kind === 'watch' ? api.setHarnessWatchEnabled : api.setHarnessTaskEnabled;
+ pause.mockImplementationOnce(() => pending.promise);
+ devBind('S'); render(<PetPage />); await showDetail();
+ const stop = await screen.findByLabelText('pet.stop.confirmPause');
+ vi.useFakeTimers();
+ fireEvent.click(stop); fireEvent.click(stop);
+ expect(screen.getByText('pet.stop.pausing')).toBeTruthy();
+ turn([]);
+ await emit((h) => h.onAuthorizationChanged?.({}));
+ expect(screen.queryByText(id)).toBeNull();
+ expect(screen.queryByText('pet.stop.pausing')).toBeNull();
+ // An authorized new version with the same id must not inherit old phases.
+ turn([{ ...activity(id, kind), label: 'Allowed replacement' }]);
+ await emit((h) => h.onDefinitionsUpdated?.({}));
+ expect(screen.getByText('Allowed replacement')).toBeTruthy();
+ const freshStop = screen.getByLabelText('pet.stop.confirmPause');
+ expect(freshStop.hasAttribute('disabled')).toBe(false);
+ fireEvent.click(freshStop);
+ expect(freshStop.classList.contains('is-confirm')).toBe(true);
+ await act(async () => {
+ if (outcome === 'success') pending.resolve({ ok: true });
+ else pending.reject(new Error('old pause failed'));
+ });
+ expect(freshStop.classList.contains('is-confirm')).toBe(true);
+ expect(screen.queryByText('pet.stop.paused')).toBeNull();
+ expect(screen.queryByText('pet.stop.failed')).toBeNull();
+ await act(async () => vi.advanceTimersByTime(4000));
+ expect(screen.getByText('Allowed replacement')).toBeTruthy();
+ expect(document.querySelector('.is-leaving')).toBeNull();
+ expect(pause).toHaveBeenCalledTimes(1);
+ });
+
+ it('drops an exiting card on authorization change and ignores its already-queued removal', async () => {
+ const id = 'watch:private';
+ turn([activity(id, 'watch')]);
+ devBind('S'); render(<PetPage />); await showDetail();
+ vi.useFakeTimers();
+ const timeouts = vi.spyOn(window, 'setTimeout');
+ fireEvent.click(screen.getByLabelText('pet.dismiss'));
+ const remove = timeouts.mock.calls.find(([, delay]) => delay === 500)?.[0];
+ timeouts.mockRestore();
+ expect(typeof remove).toBe('function');
+ expect(document.querySelector('.is-leaving')).toBeTruthy();
+ turn([]);
+ await emit((h) => h.onAuthorizationChanged?.({}));
+ expect(screen.queryByText(id)).toBeNull();
+ expect(document.querySelector('.is-leaving')).toBeNull();
+ turn([{ ...activity(id, 'watch'), label: 'New authorized card' }]);
+ await emit((h) => h.onDefinitionsUpdated?.({}));
+ await act(async () => { (remove as () => void)(); });
+ await act(async () => vi.advanceTimersByTime(500));
+ expect(screen.getByText('New authorized card')).toBeTruthy();
+ const { petShell } = await import('./petShell');
+ expect(petShell.dismissed()).not.toContain(id);
+ });
+
+ it('fences a pause after switching away and back to the same binding', async () => {
+ const id = 'watch:private';
+ turn([activity(id, 'watch')]);
+ const pending = deferred<{ ok: boolean }>();
+ api.setHarnessWatchEnabled.mockImplementationOnce(() => pending.promise);
+ devBind('S'); render(<PetPage />); await showDetail();
+ const stop = await screen.findByLabelText('pet.stop.confirmPause');
+ fireEvent.click(stop); fireEvent.click(stop);
+ turn([]);
+ await bound('B');
+ expect(screen.queryByText(id)).toBeNull();
+ turn([{ ...activity(id, 'watch'), label: 'Fresh S card' }]);
+ await bound('S');
+ await showDetail();
+ expect(await screen.findByText('Fresh S card')).toBeTruthy();
+ await act(async () => pending.resolve({ ok: true }));
+ expect(screen.queryByText('pet.stop.paused')).toBeNull();
+ expect(screen.getByLabelText('pet.stop.confirmPause').hasAttribute('disabled')).toBe(false);
+ });
+
+ it.each(['success', 'uncertain'])('preserves user text while fencing a late send %s after authorization changes', async (outcome) => {
+ const pending = deferred<WorkbenchMessage>();
+ api.sendSessionMessage.mockImplementationOnce(() => pending.promise);
+ devBind('S'); render(<PetPage />); summon('listen');
+ const input = await screen.findByRole('textbox');
+ await userEvent.type(input, 'my own words{Enter}');
+ await emit((h) => h.onAuthorizationChanged?.({}));
+ expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe('my own words');
+ await userEvent.keyboard('{Enter}');
+ expect(api.sendSessionMessage).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ if (outcome === 'success') pending.resolve(message('late-private', 'S', { text: 'Old authorized response' }));
+ else pending.reject(new Error('unknown admission'));
+ });
+ const { petComposer } = await import('./petComposer');
+ expect(petComposer.isSending()).toBe(false);
+ expect(petComposer.isUncertain('S')).toBe(outcome === 'uncertain');
+ expect(screen.queryByText('Old authorized response')).toBeNull();
+ // The async completion cannot clear the user's draft or open old detail.
+ if (outcome === 'success') expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe('my own words');
+ else expect(document.querySelector('.pet-mini-title')?.textContent).toBe('my own words');
+ expect(document.querySelector('.pet-mini-detail.is-open')).toBeNull();
+ });
+
+ it('keeps the document send ledger locked when an old page fails after remount', async () => {
+ const pending = deferred<WorkbenchMessage>();
+ api.sendSessionMessage.mockImplementationOnce(() => pending.promise);
+ devBind('S');
+ const first = render(<PetPage />);
+ summon('listen');
+ await userEvent.type(await screen.findByRole('textbox'), 'preserve this{Enter}');
+ first.unmount();
+ render(<PetPage />); summon('listen');
+ const input = await screen.findByRole('textbox');
+ expect((input as HTMLTextAreaElement).value).toBe('preserve this');
+ await userEvent.keyboard('{Enter}');
+ expect(api.sendSessionMessage).toHaveBeenCalledTimes(1);
+ await act(async () => pending.reject(new Error('unknown outcome')));
+ const { petComposer } = await import('./petComposer');
+ expect(petComposer.isUncertain('S')).toBe(true);
+ expect(petComposer.isSending()).toBe(false);
+ expect(screen.queryByRole('textbox')).toBeNull();
+ expect(document.querySelector('.pet-mini-title')?.textContent).toBe('preserve this');
+ await userEvent.keyboard('{Enter}');
+ expect(api.sendSessionMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('discards an unauthorized queued pick while mirroring the already-sent native binding', async () => {
+ const pending = deferred<unknown>();
+ const invoke = vi.fn((command: string) => {
+ if (command === 'pet_ready') return Promise.resolve({ binding: 'S', revision: 1, summon_pending: null });
+ if (command === 'pet_bind') return pending.promise;
+ return Promise.resolve(null);
+ });
+ Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });
+ Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });
+ switcherSessions = [session('A'), session('B')];
+ render(<PetPage />); await showDetail();
+ await userEvent.click(screen.getByLabelText('pet.switchSession'));
+ await userEvent.click(await screen.findByRole('button', { name: 'Session A' }));
+ await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_bind', { sessionId: 'A' }));
+ await showDetail();
+ await userEvent.click(screen.getByLabelText('pet.switchSession'));
+ await userEvent.click(await screen.findByRole('button', { name: 'Session B' }));
+ await emit((h) => h.onAuthorizationChanged?.({}));
+ await act(async () => pending.resolve({ binding: 'A', revision: 2 }));
+ expect(invoke.mock.calls.filter(([command]) => command === 'pet_bind')).toEqual([['pet_bind', { sessionId: 'A' }]]);
+ const { petShell } = await import('./petShell');
+ expect(petShell.currentBinding()).toBe('A');
+ expect(await screen.findAllByText('Session A')).toHaveLength(2);
+ expect(screen.queryByText('Session B')).toBeNull();
+ });
+
+ it('discards voice preview and final text from the previous authorization epoch', async () => {
+ const done = deferred<string>();
+ let preview!: (text: string) => void;
+ const abort = vi.fn();
+ vi.doMock('@/lib/showPageVoiceDictation', () => ({
+ ShowPageVoiceDictation: class {
+ done = done.promise;
+ constructor(options: { onPreview: (text: string) => void }) { preview = options.onPreview; }
+ start = async () => {};
+ finish = () => {};
+ abort = abort;
+ },
+ }));
+ const locks = Object.getOwnPropertyDescriptor(navigator, 'locks');
+ const media = Object.getOwnPropertyDescriptor(navigator, 'mediaDevices');
+ try {
+ Object.defineProperty(navigator, 'locks', { configurable: true, value: {} });
+ Object.defineProperty(navigator, 'mediaDevices', { configurable: true, value: { getUserMedia: vi.fn() } });
+ Object.defineProperty(window, '__AVIBE_PET_VOICE_ENABLED__', { configurable: true, value: true });
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({ available: true }) })));
+ vi.resetModules();
+ ({ PetPage } = await import('./PetPage'));
+ devBind('S'); render(<PetPage />); summon('listen');
+ const input = await screen.findByRole('textbox');
+ await userEvent.type(input, 'typed before voice');
+ await userEvent.click(await screen.findByLabelText('pet.voice.open'));
+ expect(pose()).toBe('listening');
+ await emit((h) => h.onAuthorizationChanged?.({}));
+ expect(abort).toHaveBeenCalled();
+ await act(async () => { preview('stale voice preview'); done.resolve('stale voice transcript'); });
+ expect(screen.queryByText('stale voice preview')).toBeNull();
+ expect(pose()).not.toBe('listening');
+ expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe('typed before voice');
+ expect(api.sendSessionMessage).not.toHaveBeenCalled();
+ } finally {
+ vi.doUnmock('@/lib/showPageVoiceDictation');
+ vi.unstubAllGlobals();
+ if (locks) Object.defineProperty(navigator, 'locks', locks);
+ else Reflect.deleteProperty(navigator, 'locks');
+ if (media) Object.defineProperty(navigator, 'mediaDevices', media);
+ else Reflect.deleteProperty(navigator, 'mediaDevices');
+ Reflect.deleteProperty(window, '__AVIBE_PET_VOICE_ENABLED__');
+ }
+ });
+
+ it('does not let a queued old animation report replace the new epochs hit regions', async () => {
+ const frames: FrameRequestCallback[] = [];
+ vi.stubGlobal('requestAnimationFrame', vi.fn((callback: FrameRequestCallback) => frames.push(callback)));
+ vi.stubGlobal('cancelAnimationFrame', vi.fn());
+ const { petBridge } = await import('./petBridge');
+ const report = vi.spyOn(petBridge, 'setHitRegions').mockResolvedValue(undefined);
+ try {
+ devBind('S'); render(<PetPage />);
+ await screen.findByText('Session S');
+ const oldFrames = [...frames];
+ expect(oldFrames.length).toBeGreaterThan(0);
+ await emit((h) => h.onAuthorizationChanged?.({}));
+ expect(report).toHaveBeenCalledWith([]);
+ const currentFrame = frames.at(-1)!;
+ expect(oldFrames).not.toContain(currentFrame);
+ act(() => currentFrame(performance.now()));
+ report.mockClear();
+ // Simulate callbacks already queued before cancellation. Neither an old
+ // report nor its empty cleanup may overwrite the new surface's regions.
+ act(() => oldFrames.forEach((callback) => callback(performance.now())));
+ expect(report).not.toHaveBeenCalled();
+ } finally {
+ cleanup();
+ report.mockRestore();
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it('requires a fresh intersection after authorization and ignores old read completions', async () => {
+ const intersections: ((entries: { isIntersecting: boolean }[]) => void)[] = [];
+ vi.stubGlobal('IntersectionObserver', class {
+ constructor(callback: typeof intersections[number]) { intersections.push(callback); }
+ observe() {}
+ disconnect() {}
+ });
+ const pending = deferred<boolean>();
+ markRead.mockImplementationOnce(() => pending.promise);
+ try {
+ tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('result', 'S', { read_at: null })];
+ unreadBySession = { S: 1 };
+ devBind('S'); render(<PetPage />); await showDetail();
+ const oldIntersection = intersections.at(-1)!;
+ await act(async () => oldIntersection([{ isIntersecting: true }]));
+ expect(markRead).toHaveBeenCalledTimes(1);
+ await emit((h) => h.onAuthorizationChanged?.({}));
+ await showDetail();
+ const freshIntersection = intersections.at(-1)!;
+ expect(freshIntersection).not.toBe(oldIntersection);
+ const reads = api.listSessionMessages.mock.calls.length;
+ await act(async () => {
+ oldIntersection([{ isIntersecting: true }]);
+ pending.resolve(true);
+ });
+ expect(markRead).toHaveBeenCalledTimes(1);
+ expect(api.listSessionMessages.mock.calls).toHaveLength(reads);
+ await act(async () => freshIntersection([{ isIntersecting: true }]));
+ expect(markRead).toHaveBeenCalledTimes(2);
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it('fences a late quick reply across authorization without clearing the typed draft', async () => {
+ tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('q', 'S', { content: { quick_replies: ['Yes'] } })];
+ const pending = deferred<WorkbenchMessage>();
+ api.sendSessionMessage.mockImplementationOnce(() => pending.promise);
+ devBind('S'); render(<PetPage />); await showDetail(); summon('listen');
+ await userEvent.type(await screen.findByRole('textbox'), 'my draft');
+ await userEvent.click(screen.getByText('Yes'));
+ await emit((h) => h.onAuthorizationChanged?.({}));
+ await userEvent.keyboard('{Enter}');
+ expect(api.sendSessionMessage).toHaveBeenCalledExactlyOnceWith('S', { text: 'Yes', metadata: { quick_reply_for: 'q' } });
+ await act(async () => pending.resolve(message('late-choice', 'S', { author: 'user', type: 'user', text: 'Yes' })));
+ expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe('my draft');
+ expect(document.querySelector('.pet-mini-title')?.textContent).not.toBe('Yes');
+ expect(document.querySelector('.pet-mini-detail.is-open')).toBeNull();
+ });
+
+ it.each(['update-first', 'ack-first'])('keeps quick-reply ownership when message.updated and the send response arrive %s', async (order) => {
+ const asking = message('q1', 'S', { content: { quick_replies: ['Yes', 'No'] } });
+ tails.S = [message('u', 'S', { author: 'user', type: 'user' }), asking];
+ const pending = deferred<WorkbenchMessage>();
+ api.sendSessionMessage.mockImplementationOnce(() => pending.promise);
+ devBind('S'); render(<PetPage />); await showDetail();
+ summon('listen');
+ const input = await screen.findByRole('textbox');
+ await userEvent.click(await screen.findByText('Yes'));
+ const chosen = { ...asking, content: { ...asking.content, quick_reply_chosen: 'Yes' } };
+ const update = () => {
+ tails.S = tails.S.map((row) => row.id === chosen.id ? chosen : row);
+ return emit((h) => h.onMessageUpdated?.(chosen));
+ };
+ const acknowledge = () => act(async () => {
+ const sent = message('sent', 'S', { author: 'user', type: 'user', text: 'Yes' });
+ // The post-send tail read must reflect the acknowledged durable write.
+ tails.S = [...tails.S, sent];
+ pending.resolve(sent);
+ });
+ if (order === 'update-first') {
+ await update();
+ await userEvent.type(input, 'duplicate{Enter}');
+ expect(api.sendSessionMessage).toHaveBeenCalledTimes(1);
+ await acknowledge();
+ } else {
+ await userEvent.type(input, 'duplicate{Enter}');
+ expect(api.sendSessionMessage).toHaveBeenCalledTimes(1);
+ await acknowledge();
+ await update();
+ }
+ expect(api.sendSessionMessage).toHaveBeenCalledExactlyOnceWith('S', { text: 'Yes', metadata: { quick_reply_for: 'q1' } });
+ expect(screen.queryByRole('button', { name: 'Yes', exact: true })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'No', exact: true })).toBeNull();
+ // An older update must never reclaim a newer result's quick-reply group.
+ await emit((h) => h.onMessageNew?.(message('q2', 'S', { content: { quick_replies: ['Continue', 'Wait'] } })));
+ expect(await screen.findByRole('button', { name: 'Continue', exact: true })).toBeTruthy();
+ await update();
+ expect(screen.getByRole('button', { name: 'Continue', exact: true }).hasAttribute('disabled')).toBe(false);
+ expect(api.sendSessionMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps quick replies behind the same uncertain-send lock as typed input', async () => {
+ tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('q1', 'S', { content: { quick_replies: ['Yes', 'No'] } })];
+ api.sendSessionMessage.mockRejectedValueOnce(new Error('connection lost'));
+ devBind('S'); render(<PetPage />); await showDetail();
+ await userEvent.click(await screen.findByText('Yes'));
+ expect(await screen.findByText('newSession.sendUncertain')).toBeTruthy();
+ summon('listen');
+ expect(screen.queryByRole('textbox')).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Yes', exact: true })).toBeNull();
+ // A newer result cannot bypass a send whose admission is still unknown.
+ await emit((h) => h.onMessageNew?.(message('q2', 'S', { content: { quick_replies: ['Continue', 'Wait'] } })));
+ expect(screen.queryByRole('button', { name: 'Continue', exact: true })).toBeNull();
+ await userEvent.keyboard('duplicate{Enter}');
+ expect(api.sendSessionMessage).toHaveBeenCalledExactlyOnceWith('S', { text: 'Yes', metadata: { quick_reply_for: 'q1' } });
+ });
+
+ it('keeps waiting definitions pausable without marking them as executing', async () => {
+ turn([activity('watch:w1', 'watch'), activity('task:t1', 'task')]);
+ devBind('S'); render(<PetPage />); await showDetail();
+ expect(screen.getAllByLabelText('pet.stop.confirmPause')).toHaveLength(2);
+ expect(screen.getByText('pet.activityKind.watch · pet.activityStatus.waiting')).toBeTruthy();
+ expect(screen.getByText('pet.activityKind.task · pet.activityStatus.waiting')).toBeTruthy();
+ expect(document.querySelector('.pet-mini-running-dot')).toBeNull();
+ expect(pose()).toBe('idle');
+ expect(document.querySelector('[data-busy]')?.getAttribute('data-busy')).toBe('false');
+ turn([activity('watch:w1', 'watch'), activity('task:t1', 'task'), activity('agent_run:r1', 'agent_run')]);
+ await emit((h) => h.onRunsUpdated?.({}));
+ await waitFor(() => expect(pose()).toBe('running'));
+ expect(document.querySelectorAll('.pet-mini-running-dot')).toHaveLength(1);
+ expect(screen.getAllByLabelText('pet.stop.confirmPause')).toHaveLength(2);
+ expect(screen.queryByLabelText('pet.stop.confirmStop')).toBeNull();
+ });
+
+ it.each([false, true])('keeps switching reachable without a main exchange (background work: %s)', async (hasBackgroundWork) => {
+ tails.S = [];
+ turn(hasBackgroundWork ? [activity('watch:w1', 'watch')] : []);
+ switcherSessions = [session('B', { title: 'Another session' })];
+ devBind('S'); render(<PetPage />);
+ await waitFor(() => expect(api.listSessionMessages).toHaveBeenCalledWith('S', expect.anything()));
+ summon('show');
+ if (hasBackgroundWork) {
+ expect(await screen.findByText('watch:w1')).toBeTruthy();
+ fireEvent.click(await screen.findByText('pet.switchSession'));
+ }
+ fireEvent.click(await screen.findByText('Another session'));
+ await waitFor(() => expect(devBinding().binding).toBe('B'));
+ expect(await screen.findAllByText('Session B')).toHaveLength(2);
+ });
+
+ it('keeps the unread count visible until the inbox confirms the result was read', async () => {
+ tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('r', 'S', { read_at: null })];
+ unreadBySession = { S: 1 };
+ devBind('S'); render(<PetPage />);
+ expect((await screen.findByLabelText('pet.unreadBadge')).textContent).toBe('1');
+ summon('show');
+ expect(screen.getByLabelText('pet.unreadBadge').textContent).toBe('1');
+ expect(markRead).not.toHaveBeenCalled();
+ await showDetail();
+ await waitFor(() => expect(markRead).toHaveBeenCalledWith('S', 'r'));
+ act(() => {
+ unreadBySession = {};
+ inboxVersion += 1;
+ inboxListeners.forEach((listener) => listener());
+ });
+ await waitFor(() => expect(screen.queryByLabelText('pet.unreadBadge')).toBeNull());
+ });
+
+ it('does not mark the collapsed card read; detail is explicitly opened and closes on collapse', async () => {
+ tails.S = [message('u', 'S', { author: 'user', type: 'user', text: 'Question' }), message('r', 'S', { read_at: null })];
+ unreadBySession = { S: 1 };
+ devBind('S');
+ render(<PetPage />);
+ await screen.findByText('Question');
+ expect(markRead).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByLabelText('pet.stack.expand'));
+ await waitFor(() => expect(document.querySelector('.pet-mini-detail')).toBeTruthy());
+ expect(markRead).not.toHaveBeenCalled();
+ fireEvent.click(document.querySelector('.pet-mini-card[role=button]')!);
+ await waitFor(() => expect(markRead).toHaveBeenCalledWith('S', 'r'));
+ fireEvent.click(screen.getByLabelText('pet.toggle'));
+ await waitFor(() => expect(document.querySelector('.pet-mini-detail')).toBeNull());
+ });
+
+ it('marks detail read only after its result intersects the fixed scroll viewport', async () => {
+ let intersect: ((entries: { isIntersecting: boolean }[]) => void) | undefined;
+ vi.stubGlobal('IntersectionObserver', class {
+ constructor(callback: typeof intersect) { intersect = callback; }
+ observe() {}
+ disconnect() {}
+ });
+ try {
+ tails.S = [message('u', 'S', { author: 'user', type: 'user' }), message('unseen', 'S', { read_at: null })];
+ unreadBySession = { S: 1 };
+ devBind('S'); render(<PetPage />); await showDetail();
+ expect(intersect).toBeDefined();
+ expect(markRead).not.toHaveBeenCalled();
+ await act(async () => intersect!([{ isIntersecting: true }]));
+ expect(markRead).toHaveBeenCalledWith('S', 'unseen');
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it('requires a second press, uses the native watch id, and retains the stopped row through linger and both exit beats', async () => {
+ turn([activity('watch:w1', 'watch'), activity('run:r1', 'agent_run')]);
+ devBind('S'); render(<PetPage />); await showDetail();
+ const stop = await screen.findByLabelText('pet.stop.confirmPause');
+ expect(screen.queryByLabelText('pet.stop.confirmStop')).toBeNull();
+ const pending = deferred<{ ok: boolean }>();
+ api.setHarnessWatchEnabled.mockImplementationOnce(() => pending.promise);
+ vi.useFakeTimers();
+ fireEvent.click(stop);
+ expect(api.setHarnessWatchEnabled).not.toHaveBeenCalled();
+ fireEvent.click(stop);
+ expect(api.setHarnessWatchEnabled).toHaveBeenCalledExactlyOnceWith('w1', false);
+ expect(stop.hasAttribute('disabled')).toBe(true);
+ await act(async () => pending.resolve({ ok: true }));
+ expect(screen.getByText('pet.stop.paused')).toBeTruthy();
+ turn([]);
+ // Server removal during the linger cannot cut off the local exit.
+ await act(async () => { handlers.forEach((h) => h.onRunsUpdated?.({})); });
+ expect(screen.getByText('watch:w1')).toBeTruthy();
+ await act(async () => vi.advanceTimersByTime(2499));
+ expect(document.querySelector('.is-leaving')).toBeNull();
+ await act(async () => vi.advanceTimersByTime(1));
+ expect(document.querySelector('.is-leaving')).toBeTruthy();
+ await act(async () => vi.advanceTimersByTime(499));
+ expect(screen.getByText('watch:w1')).toBeTruthy();
+ await act(async () => vi.advanceTimersByTime(1));
+ expect(screen.queryByText('watch:w1')).toBeNull();
+ });
+
+ it('expires confirmation at 3s and lets a failed pause be retried', async () => {
+ turn([activity('task:t1', 'task')]); devBind('S'); render(<PetPage />); await showDetail();
+ const stop = await screen.findByLabelText('pet.stop.confirmPause');
+ vi.useFakeTimers(); fireEvent.click(stop);
+ await act(async () => vi.advanceTimersByTime(3000));
+ expect(stop.classList.contains('is-confirm')).toBe(false);
+ api.setHarnessTaskEnabled.mockRejectedValueOnce(new Error('offline'));
+ fireEvent.click(stop); fireEvent.click(stop);
+ await act(async () => {});
+ expect(screen.getByText('pet.stop.failed')).toBeTruthy();
+ fireEvent.click(stop); fireEvent.click(stop);
+ await act(async () => {});
+ expect(api.setHarnessTaskEnabled).toHaveBeenNthCalledWith(2, 't1', false);
+ expect(screen.getByText('pet.stop.paused')).toBeTruthy();
+ });
+
+ it('holds for exactly 320ms, cancels a departed press, and falls back to text without voice support', async () => {
+ devBind('S'); render(<PetPage />); await screen.findByText('Session S');
+ const avatar = screen.getByLabelText('pet.toggle');
+ vi.useFakeTimers();
+ fireEvent.pointerDown(avatar, { button: 0, pointerId: 1 });
+ fireEvent.pointerLeave(avatar);
+ await act(async () => vi.advanceTimersByTime(400));
+ expect(screen.queryByRole('textbox')).toBeNull();
+ fireEvent.pointerDown(avatar, { button: 0, pointerId: 2 });
+ await act(async () => vi.advanceTimersByTime(319));
+ expect(screen.queryByRole('textbox')).toBeNull();
+ await act(async () => vi.advanceTimersByTime(1));
+ expect(screen.getByRole('textbox')).toBeTruthy();
+ expect(screen.queryByLabelText('pet.voice.open')).toBeNull();
+ fireEvent.pointerUp(avatar, { pointerId: 2 });
+ expect(api.sendSessionMessage).not.toHaveBeenCalled();
+ });
+});
diff --git a/ui/src/pet/PetPage.tsx b/ui/src/pet/PetPage.tsx
index 8ba9d6de7..299a1e9f7 100644
--- a/ui/src/pet/PetPage.tsx
+++ b/ui/src/pet/PetPage.tsx
@@ -1,7 +1,7 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState, useLayoutEffect, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
-import { Activity, ArrowUp, ExternalLink, KeyRound, Shuffle } from 'lucide-react';
+import { ExternalLink, KeyRound } from 'lucide-react';
import { ApiError, useApi, type SessionActivityState, type WorkbenchMessage } from '@/context/ApiContext';
import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';
@@ -9,48 +9,109 @@ import { useWorkbenchInbox } from '@/context/WorkbenchInboxContext';
import { Button } from '@/components/ui/button';
import { Markdown } from '@/components/ui/markdown';
import { QuickReplies } from '@/components/workbench/QuickReplies';
-import { StatusPill } from '@/components/visual';
-import {
- activityKindI18nKey,
- resolveActivityLabel,
- sortBackgroundActivities,
-} from '@/lib/backgroundActivity';
+import { harnessItemNativeId } from '@/lib/backgroundActivity';
import { usePageActive } from '@/lib/pageActivity';
import { usePendingVaultRequests } from '@/lib/usePendingVaultRequests';
+import { ShowPageVoiceDictation } from '@/lib/showPageVoiceDictation';
import { PetAvatar, type PetPose } from './PetAvatar';
-import {
- SETTINGS_LINK,
- petBridge,
- sessionLink,
- vaultRequestLink,
- type PetIntent,
-} from './petBridge';
-import { petComposer, usePetComposer } from './petComposer';
+import { petBridge, sessionLink, vaultRequestLink } from './petBridge';
import { petPanel, usePetPanel } from './petPanel';
-import { petShell, useOnSummon, usePetBinding } from './petShell';
+import { petComposer, usePetComposer } from './petComposer';
+import { petShell, useOnSummon, usePetBinding, usePetDismissed } from './petShell';
import { derivePetPose, derivePetState, latestExchange, openQuickReplies } from './petState';
import { useConversationAgentWorking } from './useConversationAgentWorking';
-import { usePetSession } from './usePetSession';
+import { usePetSession, type PetSurfaceEpoch } from './usePetSession';
import { usePetSetup } from './usePetSetup';
import { useSessionSwitcher } from './useSessionSwitcher';
+import './pet-mini.css';
-// An idle pet falls asleep after this long without a state change.
-const SLEEP_AFTER_MS = 5 * 60 * 1000;
-// A pointer that moves this far after pressing the pet drags the window.
-const DRAG_THRESHOLD_PX = 4;
-// Answers that prove the server refused a message, as on the new-session
-// sheet; anything else (a lost response, a 5xx, `dispatch_pending`) may have
-// started a turn, so the send is uncertain.
+const HOLD_MS = 320;
+const DISMISS_EXIT_MS = 500;
+const STOP_CONFIRM_MS = 3000;
+const STOP_LINGER_MS = 2500;
+const STACK_HEIGHT = 304; // 292px scroll box + 6px panel padding on each side.
+const EMPTY_ACTIVITIES: SessionActivityState[] = [];
+const FADE_PX = 32;
const REFUSED_SEND_STATUSES = new Set([400, 403, 404, 409, 422]);
const sendRefused = (error: unknown) => error instanceof ApiError && REFUSED_SEND_STATUSES.has(error.status);
-/**
- * `/pet`: the desktop pet window's page. Outside the Workbench shell and the
- * setup redirect; see docs/plans/2026-10-01-desktop-pet.md.
- */
+type CardKind = 'watch' | 'task' | 'agent_run' | 'backend_activity';
+type StopPhase = 'confirm' | 'stopping' | 'stopped' | 'failed';
+type PetCard = {
+ id: string;
+ title: string;
+ kind: CardKind;
+ status: string;
+ running: boolean;
+ canPause: boolean;
+ main?: boolean;
+};
+
+const isRunning = (activity: SessionActivityState) => activity.status === 'running' || activity.status === 'processing';
+const isPausable = (card: PetCard) => card.kind === 'watch' || card.kind === 'task';
+
+const activityTitle = (activity: SessionActivityState, fallback: string) => (
+ (activity.label || activity.description || fallback).trim()
+);
+
+const activityStatusKey = (status: string): string => ({
+ running: 'pet.activityStatus.running',
+ processing: 'pet.activityStatus.running',
+ queued: 'pet.activityStatus.queued',
+ pending: 'pet.activityStatus.waiting',
+ waiting: 'pet.activityStatus.waiting',
+ enabled: 'pet.activityStatus.waiting',
+ scheduled: 'pet.activityStatus.waiting',
+ disabled: 'pet.activityStatus.stopped',
+ completed: 'pet.activityStatus.completed',
+ succeeded: 'pet.activityStatus.completed',
+ failed: 'pet.activityStatus.failed',
+ error: 'pet.activityStatus.failed',
+}[status] ?? 'pet.activityStatus.unknown');
+
+function activityCard(activity: SessionActivityState, fallback: string, t: (key: string) => string): PetCard {
+ const kindKey = `pet.activityKind.${activity.item_kind ?? 'backend_activity'}`;
+ return {
+ id: activity.id,
+ title: activityTitle(activity, fallback),
+ kind: activity.item_kind ?? 'backend_activity',
+ status: `${t(kindKey)} · ${t(activityStatusKey(activity.status))}`,
+ running: isRunning(activity),
+ // Durable definitions are pausable while waiting for their next execution.
+ // They do not make Vibey busy or receive the actively-running indicator.
+ canPause: (activity.item_kind === 'watch' && (activity.status === 'enabled' || isRunning(activity)))
+ || (activity.item_kind === 'task' && (activity.status === 'scheduled' || isRunning(activity))),
+ };
+}
+
+function MicIcon() {
+ return (
+ <svg viewBox="0 0 16 16" className="size-4" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" aria-hidden>
+ <rect x="5.5" y="1.8" width="5" height="8" rx="2.5" />
+ <path d="M3.2 7.5a4.8 4.8 0 0 0 9.6 0M8 12.3v2" />
+ </svg>
+ );
+}
+
+function KeyboardIcon() {
+ return (
+ <svg viewBox="0 0 16 16" className="size-4" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" aria-hidden>
+ <rect x="1.5" y="4" width="13" height="8.5" rx="2" />
+ <path d="M4 7h.01M6.5 7h.01M9 7h.01M11.5 7h.01M5 10h6" />
+ </svg>
+ );
+}
+
+function StopIcon() {
+ return <svg viewBox="0 0 16 16" className="size-3.5" aria-hidden><rect x="3" y="3" width="10" height="10" rx="2" fill="currentColor" /></svg>;
+}
+
+function SendIcon() {
+ return <svg viewBox="0 0 16 16" className="size-3.5" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden><path d="M8 13V3M3.5 7.5 8 3l4.5 4.5" /></svg>;
+}
+
export const PetPage: React.FC = () => {
- // Listen to the shell from the first frame, before setup is known.
usePetBinding();
const { setup, recheck } = usePetSetup();
if (setup === 'checking') return null;
@@ -60,37 +121,16 @@ export const PetPage: React.FC = () => {
const PetSetupPending: React.FC<{ recheck: () => void }> = ({ recheck }) => {
const { t } = useTranslation();
- const { expanded, layout, setPanel } = usePetPanel();
- // The collapsed native frame is avatar-sized; grow it as soon as this card
- // is the page, and again on a summon (which also re-reads setup so the pet
- // surface can take over once setup is complete).
- useEffect(() => { void setPanel(true); }, [setPanel]);
- // Stable: `useOnSummon` replays a still-pending summon on each new
- // listener, and this view must not take it — PetSurface acts on it once
- // setup is complete.
- const onSetupSummon = useCallback(() => {
- recheck();
- void setPanel(true);
- }, [recheck, setPanel]);
- useOnSummon(onSetupSummon);
- const card = expanded ? (
- <div className="max-w-[220px] rounded-xl border border-border bg-card p-3 text-[12px] text-foreground shadow-lg">
- <p className="mb-2">{t('pet.setupPending')}</p>
- <Button size="sm" onClick={() => void petBridge.open(SETTINGS_LINK)}>
- {t('pet.openAvibe')}
- </Button>
- </div>
- ) : null;
+ useOnSummon(recheck);
+ const rootRef = useRef<HTMLDivElement>(null);
+ useHitRegions(rootRef);
return (
- <div
- className={clsx(
- 'flex h-full w-full gap-2 p-2',
- layout.panel_side === 'left' ? 'flex-row' : 'flex-row-reverse',
- layout.panel_edge === 'bottom' ? 'items-end' : 'items-start',
- )}
- >
- {card}
- <PetAvatar pose="idle" />
+ <div ref={rootRef} className="pet-mini-stage" data-pet-root>
+ <div className="pet-mini-setup" data-pet-hit>
+ <p>{t('pet.setupPending')}</p>
+ <Button size="sm" onClick={() => void petBridge.open('avibe://settings')}>{t('pet.openAvibe')}</Button>
+ </div>
+ <div className="pet-mini-avatar-wrap" data-pet-hit><PetAvatar pose="idle" /></div>
</div>
);
};
@@ -98,509 +138,761 @@ const PetSetupPending: React.FC<{ recheck: () => void }> = ({ recheck }) => {
const PetSurface: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
- const inbox = useWorkbenchInbox({ feed: false });
-
const binding = usePetBinding() ?? null;
const { capabilities } = useInstanceAuthorization();
- const { expanded, layout, setPanel } = usePetPanel();
- const [switcherOpen, setSwitcherOpen] = useState(false);
- // Draft, in-flight send and per-session uncertainty live for the document,
- // so an AuthGuard recheck cannot drop a lock or the text that belongs to it.
+ const inbox = useWorkbenchInbox({ feed: false });
+ const { expanded, setPanel } = usePetPanel();
const { draft, uncertain, sending, listenPending, setDraft, setUncertain } = usePetComposer(binding);
- const inputRef = useRef<HTMLTextAreaElement>(null);
-
const data = usePetSession(binding, petShell.unbind);
- // Sending is a chat capability, as in the chat page: instance can_chat and
- // the bound session's project grant. Unknown or failed reads deny.
+ const epoch = data.epoch;
const canChat = capabilities.can_chat && data.canChat === true;
const { requests: vaultRequests } = usePendingVaultRequests(binding ?? '');
const unreadCount = binding ? inbox.unreadBySession[binding] ?? 0 : 0;
-
const state = derivePetState({
session: data.session,
turn: data.running ? { foreground: 'running', in_flight: true } : data.turn,
pendingVaultRequests: vaultRequests.length,
unreadCount,
});
- // Reading every conversation's agents is the Agents page's permission.
+ const exchange = useMemo(() => latestExchange(data.messages, data.hasOlder, unreadCount), [data.messages, data.hasOlder, unreadCount]);
+ const quickReplies = openQuickReplies(data.messages);
+ const activeActivities = data.turn?.background_activities ?? EMPTY_ACTIVITIES;
+ const activeSubtasks = activeActivities.filter(isRunning);
const othersWorking = useConversationAgentWorking(capabilities.can_use_agents === true);
-
- const summon = useCallback((intent: PetIntent, bound: string | null) => {
- void setPanel(true);
- // An unbound pet shows the switcher by itself (`switcherOpen || !binding`);
- // a bound summon always lands on the session, never on a list left open.
- if (!bound) return;
+ const busy = data.running || activeSubtasks.length > 0 || othersWorking;
+ const [asleep, setAsleep] = useState(false);
+ useEffect(() => {
+ setAsleep(false);
+ if (state !== 'idle' || busy) return;
+ const timer = window.setTimeout(() => { if (epoch.isCurrent()) setAsleep(true); }, 5 * 60 * 1000);
+ return () => window.clearTimeout(timer);
+ }, [state, busy, epoch]);
+ const pose: PetPose = derivePetPose(state, { othersWorking: othersWorking || activeSubtasks.length > 0, asleep });
+ const [detailOpen, setDetailOpen] = useState(false);
+ const [composing, setComposing] = useState(false);
+ const [stops, setStops] = useState<Record<string, StopPhase>>({});
+ const dismissed = usePetDismissed();
+ const [switcherOpen, setSwitcherOpen] = useState(false);
+ const [optimisticTitle, setOptimisticTitle] = useState('');
+ const reducedMotion = useReducedMotion();
+ const [leaving, setLeaving] = useState<string[]>([]);
+ const [orderedIds, setOrderedIds] = useState<string[]>([]);
+ const [retainedCards, setRetainedCards] = useState<Record<string, PetCard>>({});
+ const stopTimers = useRef<Record<string, number>>({});
+ const inputRef = useRef<HTMLTextAreaElement>(null);
+ const pressRef = useRef<{ held: boolean; dragged: boolean; x: number; y: number; timer: number } | null>(null);
+ const dismissTimers = useRef<Record<string, number>>({});
+ const stopPhases = useRef<Record<string, StopPhase>>({});
+ const leavingIds = useRef(new Set<string>());
+ const previousBinding = useRef(binding);
+ useLayoutEffect(() => {
+ setDetailOpen(false);
setSwitcherOpen(false);
- // Voice ships in a later PR; until then a `listen` summon focuses the text
- // input once the panel and composer have actually mounted. `setPanel` waits
- // for the native frame, and a cold load still waits on the session grant.
- if (intent === 'listen') petComposer.requestListen();
- }, [setPanel]);
-
- // Act on a waiting summon, including one that arrived before this surface
- // mounted (while setup was pending or the page was loading).
- const onSummon = useCallback(() => {
- const intent = petShell.takeSummon();
- // Read the store, not the render: `pet_ready` may have set the binding in
- // the same tick that delivered this summon.
- if (intent) summon(intent, petShell.currentBinding() ?? null);
- }, [summon]);
- useOnSummon(onSummon);
-
- // A listen summon waits until the composer is actually on screen: expansion
- // is async, and a cold load still waits on the session grant. Do not consume
- // the pending listen until the textarea is mounted — AuthGuard can remount
- // the page, and the store must still hold the request until focus lands.
+ // Authorization changes remove authorized presentation, not the user's text.
+ if (previousBinding.current !== binding) {
+ setComposing(false);
+ setOptimisticTitle('');
+ previousBinding.current = binding;
+ }
+ setStops({});
+ setLeaving([]);
+ setOrderedIds([]);
+ setRetainedCards({});
+ stopPhases.current = {};
+ leavingIds.current.clear();
+ return () => {
+ Object.values(stopTimers.current).forEach(window.clearTimeout);
+ Object.values(dismissTimers.current).forEach(window.clearTimeout);
+ if (pressRef.current) window.clearTimeout(pressRef.current.timer);
+ stopTimers.current = {};
+ dismissTimers.current = {};
+ pressRef.current = null;
+ };
+ }, [binding, epoch]);
useEffect(() => {
- if (!listenPending || !expanded || !canChat || !binding || switcherOpen) return;
- const input = inputRef.current;
- if (!input) return;
- input.focus();
- petComposer.takeListen();
- }, [listenPending, expanded, canChat, binding, switcherOpen]);
+ if (!expanded) setDetailOpen(false);
+ }, [expanded]);
- // Esc collapses.
+ const mainCard = useMemo<PetCard | null>(() => {
+ const user = exchange.user;
+ const latest = exchange.results.at(-1);
+ if (!user && !latest && !optimisticTitle && !(uncertain && draft.trim())) return null;
+ const title = optimisticTitle || (uncertain ? draft.trim() : '') || user?.text?.trim() || t('pet.mainAgentTitle');
+ const subtitle = data.running
+ ? t('pet.thinking')
+ : latest?.text?.trim()
+ ? `${t('pet.repliedPrefix')} ${latest.text.trim()}`
+ : t('pet.waiting');
+ return { id: 'main-agent', title, kind: 'backend_activity', status: subtitle, running: data.running, canPause: false, main: true };
+ }, [data.running, exchange.results, exchange.user, optimisticTitle, uncertain, draft, t]);
useEffect(() => {
- if (!expanded) return undefined;
- const onKey = (event: KeyboardEvent) => {
- if (event.key === 'Escape') void setPanel(false);
- };
- window.addEventListener('keydown', onKey);
- return () => window.removeEventListener('keydown', onKey);
- }, [expanded, setPanel]);
+ if (exchange.user?.text?.trim() === optimisticTitle) setOptimisticTitle('');
+ }, [exchange.user, optimisticTitle]);
- // Blur collapses, unless there is unsent text.
+ const liveCards = useMemo(() => activeActivities.map((activity) => activityCard(activity, t('pet.untitledTask'), (key) => String(t(key as never)))), [activeActivities, t]);
+ const activities = useMemo(() => [
+ ...liveCards.map((card) => retainedCards[card.id] ?? card),
+ ...Object.values(retainedCards).filter((card) => !liveCards.some((live) => live.id === card.id)),
+ ], [liveCards, retainedCards]);
useEffect(() => {
- if (!expanded) return undefined;
- const onBlur = () => {
- if (!draft.trim()) void setPanel(false);
- };
- window.addEventListener('blur', onBlur);
- return () => window.removeEventListener('blur', onBlur);
- }, [expanded, draft, setPanel]);
-
- // Idle → asleep after a while with nothing working anywhere.
- const [asleep, setAsleep] = useState(false);
+ setOrderedIds((current) => {
+ const live = new Set(activities.map((card) => card.id));
+ const fresh = activities.filter((card) => !current.includes(card.id)).map((card) => card.id);
+ const next = expanded && current.length > 0
+ ? [...fresh, ...current.filter((id) => live.has(id))]
+ : [...activities].sort((a, b) => Number(b.running) - Number(a.running)).map((card) => card.id);
+ return next.length === current.length && next.every((id, i) => id === current[i]) ? current : next;
+ });
+ }, [activities, expanded]);
useEffect(() => {
- setAsleep(false);
- if (state !== 'idle' || othersWorking) return undefined;
- const timer = window.setTimeout(() => setAsleep(true), SLEEP_AFTER_MS);
- return () => window.clearTimeout(timer);
- }, [state, binding, othersWorking]);
- const pose: PetPose = derivePetPose(state, { othersWorking, asleep });
+ // A missing initial read or an authorization recheck is not an empty turn.
+ if (!data.turn || !binding) return;
+ const liveIds = new Set(liveCards.map((card) => card.id));
+ const next = dismissed.filter((id) => liveIds.has(id));
+ if (next.length !== dismissed.length) petShell.setDismissed(binding, next);
+ }, [liveCards, binding, data.turn, dismissed]);
- const exchange = useMemo(
- () => latestExchange(data.messages, data.hasOlder, unreadCount),
- [data.messages, data.hasOlder, unreadCount],
- );
- const quickReplies = openQuickReplies(data.messages);
+ const sortedActivities = useMemo(() => {
+ const byId = new Map(activities.map((card) => [card.id, card]));
+ const ordered = orderedIds.map((id) => byId.get(id)).filter((card): card is PetCard => Boolean(card));
+ const fresh = activities.filter((card) => !orderedIds.includes(card.id));
+ return [...fresh, ...ordered];
+ }, [activities, orderedIds]);
+ const visibleCards = useMemo(() => [
+ ...(mainCard ? [mainCard] : []),
+ ...sortedActivities.filter((card) => !dismissed.includes(card.id)),
+ ], [dismissed, mainCard, sortedActivities]);
- const { markRead } = inbox;
+ const closeComposer = useCallback(() => {
+ setComposing(false);
+ setDraft('');
+ }, [setDraft]);
+ const openComposer = useCallback((text = '') => {
+ if (!epoch.isCurrent()) return;
+ setDraft(text);
+ setComposing(true);
+ window.setTimeout(() => { if (epoch.isCurrent()) inputRef.current?.focus(); }, 0);
+ }, [setDraft, epoch]);
- // One message in flight at a time, from any entry point (text or a quick
- // reply): a second turn must not race the first. The document store, so two
- // sends in one tick are also one, and a remount cannot start a second turn.
const send = useCallback(async (text: string, metadata?: Record<string, unknown>) => {
- // Only a session this page has validated as writable accepts input; a
- // restored or just-picked binding waits for its first successful read.
- if (!canChat || !binding || data.session?.id !== binding || !text.trim()) return false;
+ if (!epoch.isCurrent() || !text.trim() || !binding || !canChat || data.session?.id !== binding) return false;
if (petComposer.isSending() || petComposer.isUncertain(binding)) return false;
petComposer.setSending(true);
try {
- const row = await api.sendSessionMessage(binding, { text, ...(metadata ? { metadata } : {}) });
- // The binding may have changed while the POST was pending: the reply
- // belongs to the session it was sent to, never to the current one.
- if (petShell.currentBinding() === binding) {
+ const row = await api.sendSessionMessage(binding, { text: text.trim(), ...(metadata ? { metadata } : {}) });
+ if (epoch.isCurrent()) {
data.noteSent(row && typeof row === 'object' && 'id' in row ? row : null);
+ setOptimisticTitle(text.trim());
}
- return true;
+ return epoch.isCurrent();
} catch (error) {
- if (!sendRefused(error)) setUncertain(binding, true);
+ if (!sendRefused(error)) {
+ // Admission uncertainty belongs to the document's send ledger, even
+ // after a recheck/remount. It must not permit another duplicate send.
+ setUncertain(binding, true);
+ if (epoch.isCurrent()) {
+ setComposing(false);
+ setDetailOpen(true);
+ void setPanel(true);
+ setOptimisticTitle(text.trim());
+ }
+ }
return false;
} finally {
+ // Release this request's document-wide lock, not a new surface's state.
petComposer.setSending(false);
}
- }, [api, binding, canChat, data, setUncertain]);
-
- // A completed send clears the draft only if it is still the same text in
- // the same session it was submitted from. A binding change already empties
- // the draft, so sent text never lingers for another session, and text typed
- // there afterwards is never cleared by the old send.
+ }, [api, binding, canChat, data, setPanel, setUncertain, epoch]);
const submit = async () => {
const submitted = draft;
- const submittedFor = binding;
- const text = submitted.trim();
- if (!text) return;
- if (!(await send(text))) return;
- if (petShell.currentBinding() !== submittedFor) return;
- petComposer.clearDraftIf(submitted);
+ if (!(await send(submitted)) || !epoch.isCurrent()) return;
+ if (petComposer.clearDraftIf(submitted)) setComposing(false);
};
-
- // QuickReplies locks the group locally; the Runtime's message.updated for the
- // answered row then closes the group in every window.
const choose = (message: WorkbenchMessage, choice: string) => send(choice, { quick_reply_for: message.id });
- const pressRef = useRef<{ x: number; y: number; dragged: boolean } | null>(null);
- const avatar = (
- <button
- type="button"
- className="shrink-0 cursor-pointer rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring"
- aria-label={t('pet.toggle')}
- aria-expanded={expanded}
- onPointerDown={(event) => {
- pressRef.current = { x: event.clientX, y: event.clientY, dragged: false };
- }}
- onPointerMove={(event) => {
- const press = pressRef.current;
- if (!press || press.dragged || event.buttons !== 1) return;
- if (Math.hypot(event.clientX - press.x, event.clientY - press.y) < DRAG_THRESHOLD_PX) return;
- press.dragged = true;
- petBridge.startDragging();
- }}
- onClick={() => {
- const dragged = pressRef.current?.dragged;
- pressRef.current = null;
- if (dragged) return;
- void setPanel(!petPanel.want());
- }}
- >
- <PetAvatar
- pose={pose}
- badge={state === 'ready' ? unreadCount : 0}
- activities={data.turn?.background_activities.length ?? 0}
- />
- </button>
- );
+ const dismiss = useCallback((id: string) => {
+ if (!epoch.isCurrent() || leavingIds.current.has(id) || id === 'main-agent') return;
+ leavingIds.current.add(id);
+ const card = visibleCards.find((item) => item.id === id);
+ if (card) setRetainedCards((current) => ({ ...current, [id]: card }));
+ setLeaving((current) => [...current, id]);
+ const remove = () => {
+ if (!epoch.isCurrent()) return;
+ if (binding) {
+ petShell.setDismissed(binding, [...new Set([...petShell.dismissed(), id])]);
+ setLeaving((current) => current.filter((item) => item !== id));
+ }
+ leavingIds.current.delete(id);
+ setRetainedCards((current) => { const next = { ...current }; delete next[id]; return next; });
+ };
+ if (reducedMotion) remove();
+ else dismissTimers.current[id] = window.setTimeout(remove, DISMISS_EXIT_MS);
+ }, [binding, reducedMotion, visibleCards, epoch]);
- const panel = expanded ? (
- <PetPanel
- binding={binding}
- title={data.session?.title ?? null}
- switcherOpen={switcherOpen || !binding}
- onToggleSwitcher={() => setSwitcherOpen((open) => !open)}
- onPick={(sessionId) => {
- setSwitcherOpen(false);
- petShell.pick(sessionId);
- }}
- exchange={exchange}
- markRead={markRead}
- onRead={data.refreshTail}
- running={data.running}
- queued={(data.turn?.pending_input_count ?? 0) > 0}
- activities={data.turn?.background_activities ?? []}
- vaultRequestIds={vaultRequests.map((request) => request.id)}
- quickReplies={quickReplies}
- onChoose={choose}
- draft={draft}
- onDraft={setDraft}
- onSubmit={() => void submit()}
- sending={sending}
- canChat={canChat}
- canSend={canChat && !uncertain && Boolean(binding) && data.session?.id === binding}
- uncertain={uncertain}
- onInspect={() => {
- // Looking at the conversation resolves the doubt: the user sees whether
- // the message went through before deciding to send again. Only a
- // successful open counts as looking; a failed one must not unlock send.
- if (!binding) return;
- const sessionId = binding;
- void petBridge.open(sessionLink(sessionId)).then(
- () => setUncertain(sessionId, false),
- () => undefined,
- );
- }}
- inputRef={inputRef}
- />
- ) : null;
+ const setStop = useCallback((card: PetCard) => {
+ if (!epoch.isCurrent() || !card.canPause || card.main) return;
+ const updatePhase = (phase?: StopPhase) => {
+ if (!epoch.isCurrent()) return;
+ if (phase) stopPhases.current[card.id] = phase;
+ else delete stopPhases.current[card.id];
+ setStops({ ...stopPhases.current });
+ };
+ const phase = stopPhases.current[card.id];
+ if (!phase || phase === 'failed') {
+ updatePhase('confirm');
+ window.clearTimeout(stopTimers.current[card.id]);
+ stopTimers.current[card.id] = window.setTimeout(() => updatePhase(), STOP_CONFIRM_MS);
+ return;
+ }
+ if (phase !== 'confirm') return;
+ window.clearTimeout(stopTimers.current[card.id]);
+ updatePhase('stopping');
+ setRetainedCards((current) => ({ ...current, [card.id]: card }));
+ const update = card.kind === 'watch' ? api.setHarnessWatchEnabled(harnessItemNativeId(card), false) : api.setHarnessTaskEnabled(harnessItemNativeId(card), false);
+ void update.then((result) => {
+ if (!epoch.isCurrent()) return;
+ if (!result.ok) throw new Error('stop failed');
+ updatePhase('stopped');
+ stopTimers.current[card.id] = window.setTimeout(() => dismiss(card.id), STOP_LINGER_MS);
+ }).catch(() => {
+ if (!epoch.isCurrent()) return;
+ updatePhase('failed');
+ setRetainedCards((current) => { const next = { ...current }; delete next[card.id]; return next; });
+ });
+ }, [api, dismiss, epoch]);
- return (
- <div
- className={clsx(
- 'flex h-full w-full gap-2 p-2',
- layout.panel_side === 'left' ? 'flex-row' : 'flex-row-reverse',
- layout.panel_edge === 'bottom' ? 'items-end' : 'items-start',
- )}
- data-state={state}
- >
- {panel}
- {avatar}
+ const voice = usePetVoice({
+ enabled: canChat && Boolean(binding) && !uncertain,
+ epoch,
+ draft,
+ onOpenComposer: openComposer,
+ });
+
+ const hotkeyHeld = useRef(false);
+ const onSummon = useCallback(() => {
+ const intent = petShell.takeSummon();
+ if (!intent) return;
+ if (intent === 'release') {
+ hotkeyHeld.current = false;
+ voice.stop(true);
+ if (!voice.listening && !composing) {
+ void setPanel(true);
+ petComposer.requestListen();
+ }
+ return;
+ }
+ void setPanel(true);
+ setSwitcherOpen(false);
+ if (intent === 'listen') {
+ hotkeyHeld.current = true;
+ petComposer.requestListen();
+ }
+ }, [setPanel, voice.stop, voice.listening, composing]);
+ useOnSummon(onSummon);
+ useEffect(() => {
+ if (!listenPending || !binding || !canChat || !expanded) return;
+ petComposer.takeListen();
+ if (uncertain) { setDetailOpen(true); return; }
+ if (voice.available && hotkeyHeld.current) voice.start();
+ else openComposer(draft);
+ }, [listenPending, binding, canChat, expanded, voice.available, voice.start, openComposer, draft, uncertain]);
+ useEffect(() => {
+ const onBlur = () => { if (!voice.listening && !draft.trim()) void setPanel(false); };
+ window.addEventListener('blur', onBlur);
+ return () => window.removeEventListener('blur', onBlur);
+ }, [voice.listening, draft, setPanel]);
+ useEffect(() => {
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key !== 'Escape') return;
+ if (voice.listening) voice.cancel();
+ else if (composing) closeComposer();
+ else if (switcherOpen) setSwitcherOpen(false);
+ else void setPanel(false);
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [closeComposer, composing, setPanel, switcherOpen, voice]);
+
+ useEffect(() => {
+ const node = inputRef.current;
+ if (!node) return;
+ node.style.height = 'auto';
+ node.style.height = `${Math.min(node.scrollHeight, 96)}px`;
+ }, [draft, composing]);
+
+ const rootRef = useRef<HTMLDivElement>(null);
+ useHitRegions(rootRef, epoch);
+ const collapsedRef = useRef<HTMLDivElement>(null);
+ const [collapsedHeight, setCollapsedHeight] = useState(0);
+ useLayoutEffect(() => {
+ const node = collapsedRef.current;
+ if (!node || expanded) return;
+ const measure = () => setCollapsedHeight(node.getBoundingClientRect().height);
+ measure();
+ const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(measure);
+ observer?.observe(node);
+ return () => observer?.disconnect();
+ }, [expanded, visibleCards.length]);
+
+ const avatar = (
+ <div className={clsx('pet-mini-avatar-wrap', voice.listening && 'is-listening')}>
+ {voice.listening && <span className="pet-mini-listen-ring" aria-hidden />}
+ <button
+ type="button"
+ className="pet-mini-avatar-button"
+ aria-label={t('pet.toggle')}
+ aria-expanded={expanded}
+ data-pet-hit
+ onClick={(event) => { if (event.detail === 0) void setPanel(!petPanel.want()); }}
+ onPointerDown={(event) => {
+ if (event.button !== 0) return;
+ const target = event.currentTarget;
+ const pointerId = event.pointerId;
+ pressRef.current = { held: false, dragged: false, x: event.clientX, y: event.clientY, timer: window.setTimeout(() => {
+ if (!epoch.isCurrent()) return;
+ const press = pressRef.current;
+ if (!press) return;
+ press.held = true;
+ target.setPointerCapture?.(pointerId);
+ if (!canChat || !binding) { void setPanel(true); return; }
+ if (uncertain) { void setPanel(true); setDetailOpen(true); return; }
+ if (voice.available) voice.start();
+ else openComposer(draft);
+ }, HOLD_MS) };
+ }}
+ onPointerMove={(event) => {
+ const press = pressRef.current;
+ if (!press || press.held || press.dragged || event.buttons !== 1) return;
+ if (Math.hypot(event.clientX - press.x, event.clientY - press.y) < 4) return;
+ press.dragged = true;
+ window.clearTimeout(press.timer);
+ void petBridge.startDragging();
+ }}
+ onPointerCancel={() => {
+ const press = pressRef.current;
+ pressRef.current = null;
+ if (press) window.clearTimeout(press.timer);
+ if (press?.held) voice.stop(true);
+ }}
+ onPointerUp={() => {
+ const press = pressRef.current;
+ pressRef.current = null;
+ if (!press) return;
+ window.clearTimeout(press.timer);
+ if (press.held) voice.stop(true);
+ else if (!press.dragged) void setPanel(!petPanel.want());
+ }}
+ onPointerLeave={() => {
+ const press = pressRef.current;
+ if (press && !press.held) {
+ window.clearTimeout(press.timer);
+ pressRef.current = null;
+ }
+ }}
+ onContextMenu={(event) => event.preventDefault()}
+ >
+ <PetAvatar pose={voice.listening ? 'listening' : pose} badge={state === 'ready' ? unreadCount : 0} activities={activeSubtasks.length} />
+ </button>
+ <MiniDock
+ enabled={canChat && Boolean(binding)}
+ listening={voice.listening}
+ typing={composing}
+ showMic={voice.available}
+ onMic={() => (voice.listening ? voice.stop(true) : voice.start())}
+ onKeyboard={() => {
+ if (uncertain) { void setPanel(true); setDetailOpen(true); return; }
+ voice.stop(true);
+ if (composing) closeComposer(); else openComposer();
+ }}
+ t={(key) => String(t(key as never))}
+ />
</div>
);
-};
-type PanelProps = {
- binding: string | null;
- title: string | null;
- switcherOpen: boolean;
- onToggleSwitcher: () => void;
- onPick: (sessionId: string) => void;
- exchange: ReturnType<typeof latestExchange>;
- markRead: (sessionId: string, untilMessageId?: string) => Promise<boolean>;
- /** Re-read the tail after a read is applied, so rendered rows converge. */
- onRead: () => void;
- running: boolean;
- queued: boolean;
- activities: SessionActivityState[];
- vaultRequestIds: string[];
- quickReplies: ReturnType<typeof openQuickReplies>;
- onChoose: (message: WorkbenchMessage, choice: string) => Promise<boolean>;
- draft: string;
- onDraft: (value: string) => void;
- onSubmit: () => void;
- sending: boolean;
- /** The bound session has been read and is writable. */
- canSend: boolean;
- /** Instance and project chat grants are both true. */
- canChat: boolean;
- /** The last send may have started a turn; resending waits for a look. */
- uncertain: boolean;
- onInspect: () => void;
- inputRef: React.RefObject<HTMLTextAreaElement | null>;
-};
-
-const PetPanel: React.FC<PanelProps> = ({ inputRef, ...props }) => {
- const { t } = useTranslation();
- const { binding } = props;
return (
- <section
- className="flex max-h-full w-[320px] min-w-0 flex-col overflow-hidden rounded-2xl border border-border bg-card text-foreground shadow-xl"
- aria-label={t('pet.panel')}
- >
- <header className="flex items-center gap-1.5 border-b border-border px-3 py-2">
- <span className="min-w-0 flex-1 truncate text-[12px] font-medium">
- {binding ? (props.title || t('pet.untitled')) : t('pet.chooseSession')}
- </span>
- {binding && (
- <Button variant="ghost" size="icon" className="size-7" aria-label={t('pet.switchSession')} onClick={props.onToggleSwitcher}>
- <Shuffle className="size-3.5" />
- </Button>
- )}
- {binding && (
- <Button variant="ghost" size="icon" className="size-7" aria-label={t('pet.openInAvibe')} onClick={() => void petBridge.open(sessionLink(binding))}>
- <ExternalLink className="size-3.5" />
- </Button>
- )}
- </header>
- {props.switcherOpen ? (
- <SessionSwitcher current={binding} onPick={props.onPick} />
- ) : binding ? (
- <>
- <ExchangeView
- exchange={props.exchange}
- running={props.running}
- binding={binding}
- markRead={props.markRead}
- onRead={props.onRead}
- />
- <ActivityLine activities={props.activities} />
- <NeedsInput
- vaultRequestIds={props.vaultRequestIds}
- quickReplies={props.canChat && !props.uncertain ? props.quickReplies : null}
- onChoose={props.onChoose}
- />
- {props.uncertain && (
- <div className="flex flex-col items-start gap-1 border-t border-border px-3 py-2 text-[12px] text-muted" role="status">
- <p>{t('newSession.sendUncertain')}</p>
- <Button variant="link" size="sm" className="px-0" onClick={props.onInspect}>
- {t('pet.openInAvibe')}
- </Button>
- </div>
+ <div ref={rootRef} className="pet-mini-stage" data-pet-root data-busy={busy} data-state={state}>
+ <div className={clsx('pet-mini-column', voice.listening && 'is-voice-active')}>
+ <div className={clsx('pet-mini-cards', voice.listening && 'is-hidden')} inert={voice.listening || undefined} aria-label={expanded ? t('pet.panel') : undefined} style={{ height: expanded ? STACK_HEIGHT : collapsedHeight }}>
+ <div ref={collapsedRef} key={expanded ? 'expanded' : 'collapsed'} className="pet-mini-swap is-switching" onAnimationEnd={(event) => { if (event.target === event.currentTarget) event.currentTarget.classList.remove('is-switching'); }}>
+ {expanded && (!binding || switcherOpen || visibleCards.length === 0) ? (
+ <SessionPicker onPick={(sessionId) => {
+ if (!epoch.isCurrent()) return;
+ petShell.pick(sessionId, epoch.isAuthorizationCurrent);
+ setSwitcherOpen(false);
+ }} />
+ ) : visibleCards.length > 0 && (
+ expanded ? (
+ <ExpandedCards
+ cards={visibleCards}
+ leaving={leaving}
+ detailOpen={detailOpen}
+ onMain={() => setDetailOpen((open) => !open)}
+ onSwitch={mainCard ? undefined : () => setSwitcherOpen(true)}
+ onDismiss={dismiss}
+ stops={stops}
+ onStop={setStop}
+ t={(key, options) => String(t(key as never, options as never))}
+ detail={binding ? <MainDetail epoch={epoch} voiceNeedsCloud={voice.cloudRequired} canChat={canChat} visible={detailOpen && !voice.listening} onSwitch={() => setSwitcherOpen(true)} binding={binding} exchange={exchange} running={data.running} queued={(data.turn?.pending_input_count ?? 0) > 0} markRead={inbox.markRead} onRead={data.refreshTail} vaultRequestIds={vaultRequests.map((request) => request.id)} quickReplies={quickReplies} onChoose={choose} uncertain={uncertain} onInspect={() => { void petBridge.open(sessionLink(binding)).then(() => { if (epoch.isCurrent()) setUncertain(binding, false); }).catch(() => undefined); }} /> : null}
+ />
+ ) : (
+ <CollapsedCards cards={visibleCards} onOpen={() => void setPanel(true)} t={(key) => String(t(key as never))} />
+ )
)}
- {props.canChat && (
- <form
- className="flex items-end gap-1.5 border-t border-border p-2"
- onSubmit={(event) => {
- event.preventDefault();
- props.onSubmit();
- }}
- >
+ </div>
+ </div>
+ <SpeechSlot open={voice.listening || composing}>
+ {voice.listening ? <Marquee text={voice.preview} listeningLabel={t('pet.voice.listening')} /> : canChat && !uncertain ? (
+ <form className="pet-mini-input" data-pet-hit onSubmit={(event) => { event.preventDefault(); void submit(); }}>
<textarea
ref={inputRef}
rows={1}
- value={props.draft}
- onChange={(event) => props.onDraft(event.target.value)}
+ value={draft}
+ onChange={(event) => setDraft(event.target.value)}
onKeyDown={(event) => {
if (event.key === 'Enter' && !event.shiftKey && !event.nativeEvent.isComposing) {
event.preventDefault();
- props.onSubmit();
+ void submit();
}
}}
placeholder={t('pet.inputPlaceholder')}
aria-label={t('pet.inputPlaceholder')}
- className="max-h-24 min-h-8 flex-1 resize-none rounded-lg border border-input bg-background px-2.5 py-1.5 text-[13px] outline-none focus-visible:ring-2 focus-visible:ring-ring"
/>
- <Button type="submit" size="icon" className="size-8" disabled={props.sending || !props.canSend || !props.draft.trim()} aria-label={t('pet.send')}>
- <ArrowUp className="size-4" />
- </Button>
+ {voice.available && <button type="button" className="pet-mini-input-button" onClick={() => voice.start()} aria-label={t('pet.voiceContinue')}><MicIcon /></button>}
+ <button type="submit" className="pet-mini-send" disabled={!draft.trim() || sending || uncertain} aria-label={t('pet.send')}><SendIcon /></button>
</form>
- )}
- {props.queued && <p className="px-3 pb-2 text-[11px] text-muted">{t('pet.queued')}</p>}
- </>
- ) : null}
- </section>
+ ) : null}
+ </SpeechSlot>
+ </div>
+ {avatar}
+ </div>
);
};
-/**
- * The latest exchange, and the one place the pet marks replies read: this view
- * is mounted only while the user can see it (panel open, switcher closed), so
- * "rendered" is decided by what is on screen rather than by panel flags.
- */
-const ExchangeView: React.FC<{
- exchange: ReturnType<typeof latestExchange>;
- running: boolean;
- binding: string;
- markRead: (sessionId: string, untilMessageId?: string) => Promise<boolean>;
- onRead: () => void;
-}> = ({ exchange, running, binding, markRead, onRead }) => {
+const SessionPicker: React.FC<{ onPick: (sessionId: string) => void }> = ({ onPick }) => {
const { t } = useTranslation();
- usePetMarkRead(binding, exchange, markRead, onRead);
+ const { sessions, loading } = useSessionSwitcher(true);
return (
- <div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-3 py-2 text-[13px]">
- {exchange.user && (
- <div className="self-end max-w-[85%] rounded-xl bg-muted-soft px-2.5 py-1.5">
- <Markdown content={exchange.user.text} softBreaks />
- </div>
- )}
- {exchange.results.map((message) => (
- <div key={message.id} className="min-w-0">
- <Markdown content={message.text} softBreaks />
+ <div className="pet-mini-panel" aria-label={t('pet.chooseSession')}>
+ <div className="pet-mini-scroll">
+ <div className="pet-mini-session-picker" data-pet-hit>
+ {sessions.length === 0 && <p className="pet-mini-detail-muted">{loading ? t('common.loading') : t('pet.noSessions')}</p>}
+ {sessions.map((session) => (
+ <button key={session.id} type="button" onClick={() => onPick(session.id)} className="pet-mini-session-option">
+ {session.title || t('pet.untitled')}
+ </button>
+ ))}
</div>
- ))}
- {running && <p className="text-[12px] text-muted">{t('pet.state.running')}</p>}
- {!exchange.unreadComplete && (
- <Button variant="link" size="sm" className="self-start px-0" onClick={() => void petBridge.open(sessionLink(binding))}>
- {t('pet.moreInAvibe')}
- </Button>
- )}
- {!exchange.user && exchange.results.length === 0 && !running && (
- <p className="text-[12px] text-muted">{t('pet.empty')}</p>
- )}
+ </div>
</div>
);
};
-const ActivityLine: React.FC<{ activities: PanelProps['activities'] }> = ({ activities }) => {
- const { t } = useTranslation();
- const sorted = useMemo(() => sortBackgroundActivities(activities), [activities]);
- if (sorted.length === 0) return null;
- const first = sorted[0];
- const label = resolveActivityLabel(first, t(`chat.activities.kind.${activityKindI18nKey(first)}`));
+function useReducedMotion() {
+ const [reduced, setReduced] = useState(() => window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false);
+ useEffect(() => {
+ const query = window.matchMedia?.('(prefers-reduced-motion: reduce)');
+ const update = () => setReduced(query?.matches ?? false);
+ query?.addEventListener('change', update);
+ return () => query?.removeEventListener('change', update);
+ }, []);
+ return reduced;
+}
+
+function useHitRegions(rootRef: React.RefObject<HTMLDivElement | null>, epoch?: PetSurfaceEpoch) {
+ useEffect(() => {
+ const root = rootRef.current;
+ if (!root) return;
+ let frame = 0;
+ let movingUntil = 0;
+ let last = '';
+ let active = true;
+ const report = () => {
+ if (!active) return;
+ if (epoch && !epoch.isCurrent()) {
+ frame = 0;
+ void petBridge.setHitRegions([]).catch(() => undefined);
+ return;
+ }
+ const rects = Array.from(root.querySelectorAll<HTMLElement>('[data-pet-hit]')).flatMap((node) => {
+ if (node.closest('[inert], .is-leaving')) return [];
+ const style = getComputedStyle(node);
+ if (style.visibility === 'hidden' || style.pointerEvents === 'none' || Number(style.opacity) === 0) return [];
+ const rect = node.getBoundingClientRect();
+ let left = Math.max(0, rect.left), top = Math.max(0, rect.top);
+ let right = Math.min(innerWidth, rect.right), bottom = Math.min(innerHeight, rect.bottom);
+ for (let parent = node.parentElement; parent && parent !== root; parent = parent.parentElement) {
+ const parentStyle = getComputedStyle(parent);
+ if (Number(parentStyle.opacity) === 0 || parentStyle.visibility === 'hidden') return [];
+ if (/(hidden|auto|scroll|clip)/.test(parentStyle.overflowX + parentStyle.overflowY)) {
+ const clip = parent.getBoundingClientRect();
+ left = Math.max(left, clip.left); right = Math.min(right, clip.right);
+ top = Math.max(top, clip.top); bottom = Math.min(bottom, clip.bottom);
+ }
+ }
+ return right > left && bottom > top ? [{ x: left, y: top, width: right - left, height: bottom - top }] : [];
+ });
+ const encoded = JSON.stringify(rects);
+ if (encoded !== last) {
+ last = encoded;
+ void petBridge.setHitRegions(rects).catch(() => undefined);
+ }
+ frame = performance.now() < movingUntil ? requestAnimationFrame(report) : 0;
+ };
+ const schedule = () => { if (!frame) frame = requestAnimationFrame(report); };
+ const motion = () => { movingUntil = performance.now() + 550; schedule(); };
+ const resize = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(schedule);
+ const observe = () => { resize?.disconnect(); resize?.observe(root); root.querySelectorAll<HTMLElement>('[data-pet-hit]').forEach((node) => resize?.observe(node)); motion(); };
+ const mutations = new MutationObserver(observe);
+ mutations.observe(root, { subtree: true, childList: true, attributes: true, attributeFilter: ['class', 'style', 'inert'] });
+ root.addEventListener('scroll', schedule, true);
+ root.addEventListener('transitionrun', motion);
+ root.addEventListener('pointerover', motion);
+ root.addEventListener('pointerout', motion);
+ observe();
+ return () => {
+ active = false;
+ cancelAnimationFrame(frame); resize?.disconnect(); mutations.disconnect();
+ root.removeEventListener('scroll', schedule, true);
+ root.removeEventListener('transitionrun', motion);
+ root.removeEventListener('pointerover', motion);
+ root.removeEventListener('pointerout', motion);
+ // Authorization rechecks can remove this surface while its native window
+ // stays alive. Release its desktop input regions together with the DOM.
+ void petBridge.setHitRegions([]).catch(() => undefined);
+ };
+ }, [rootRef, epoch]);
+}
+
+function usePetVoice({ enabled, epoch, draft, onOpenComposer }: { enabled: boolean; epoch: PetSurfaceEpoch; draft: string; onOpenComposer: (text?: string) => void }) {
+ const [asr, setAsr] = useState<{ available: boolean; checked: boolean; maxFileBytes?: number }>({ available: false, checked: false });
+ const [preview, setPreview] = useState('');
+ const [listening, setListening] = useState(false);
+ type Capture = { dictation: ShowPageVoiceDictation; ending: boolean; cancelled: boolean };
+ const captureRef = useRef<Capture | null>(null);
+ const supported = typeof navigator !== 'undefined' && Boolean(navigator.locks && navigator.mediaDevices?.getUserMedia);
+ // Remains off until the desktop main/pet captured-speech handoff has been
+ // verified on the platform. The QA harness alone sets this marker today.
+ const available = enabled && supported && asr.available && (window as unknown as { __AVIBE_PET_VOICE_ENABLED__?: boolean }).__AVIBE_PET_VOICE_ENABLED__ === true;
+ useEffect(() => {
+ if (!enabled) return;
+ let alive = true;
+ void fetch('/api/asr/status', { credentials: 'same-origin' }).then((response) => response.ok ? response.json() : null).then((value) => {
+ if (alive && epoch.isCurrent()) setAsr({ available: Boolean(value?.available), checked: value !== null, maxFileBytes: value?.max_file_bytes });
+ }).catch(() => { if (alive && epoch.isCurrent()) setAsr({ available: false, checked: false }); });
+ return () => { alive = false; };
+ }, [enabled, epoch]);
+ const stop = useCallback((commit: boolean) => {
+ const capture = captureRef.current;
+ if (!capture) return;
+ capture.ending = true;
+ if (commit) capture.dictation.finish();
+ else {
+ capture.cancelled = true;
+ captureRef.current = null;
+ capture.dictation.abort();
+ setListening(false);
+ setPreview('');
+ }
+ }, []);
+ const start = useCallback(() => {
+ if (!epoch.isCurrent() || !available || captureRef.current) return;
+ const before = draft;
+ const capture: Capture = {
+ dictation: new ShowPageVoiceDictation({ before, after: '', maxFileBytes: asr.maxFileBytes, onPreview: (text) => { if (epoch.isCurrent()) setPreview(text); } }),
+ ending: false,
+ cancelled: false,
+ };
+ captureRef.current = capture;
+ setListening(true);
+ const settle = () => {
+ if (captureRef.current !== capture || !epoch.isCurrent()) return false;
+ captureRef.current = null;
+ setListening(false);
+ setPreview('');
+ return !capture.cancelled;
+ };
+ void capture.dictation.done.then((text) => {
+ if (!settle()) return;
+ const next = text.trim();
+ onOpenComposer(next ? [before.trim(), next].filter(Boolean).join(' ') : before);
+ }).catch(settle);
+ void capture.dictation.start().then(() => {
+ if (!epoch.isCurrent()) { capture.dictation.abort(); return; }
+ // Release may precede microphone permission or pipeline startup.
+ if (capture.ending && !capture.cancelled) capture.dictation.finish();
+ }).catch(() => { settle(); capture.dictation.abort(); });
+ }, [asr.maxFileBytes, available, epoch, draft, onOpenComposer]);
+ const cancel = useCallback(() => stop(false), [stop]);
+ useEffect(() => cancel, [epoch, enabled, cancel]);
+ return { available, cloudRequired: asr.checked && !asr.available, listening, preview, start, stop, cancel };
+}
+
+const SpeechSlot: React.FC<{ open: boolean; children: ReactNode }> = ({ open, children }) => (
+ <div className={clsx('pet-mini-slot', open && 'is-open')} aria-hidden={!open} inert={!open ? true : undefined}>
+ <div className="pet-mini-slot-inner"><div className="pet-mini-slot-body">{children}</div></div>
+ </div>
+);
+
+const Marquee: React.FC<{ text: string; listeningLabel: string }> = ({ text, listeningLabel }) => {
+ const boxRef = useRef<HTMLDivElement>(null);
+ const lineRef = useRef<HTMLSpanElement>(null);
+ const [shift, setShift] = useState(0);
+ useEffect(() => {
+ const box = boxRef.current;
+ const line = lineRef.current;
+ if (!box || !line) return;
+ setShift(Math.max(0, line.scrollWidth - box.clientWidth));
+ }, [text]);
return (
- <div className="px-3 pb-2">
- <StatusPill
- tone="running"
- role="status"
- className="min-h-6 max-w-full gap-2 px-2.5 py-0.5 text-[11px] font-normal"
- indicator={<Activity className="size-3 shrink-0 text-mint-ink" aria-hidden="true" />}
- label={(
- <span className="min-w-0 truncate text-muted">
- {t('chat.activities.running', { count: sorted.length })}
- {label ? ` · ${label}` : ''}
- </span>
- )}
- />
+ <div className="pet-mini-marquee" data-pet-hit>
+ <span className="pet-mini-voice-dot" aria-hidden><span /></span>
+ <div ref={boxRef} className={clsx('pet-mini-marquee-line', shift > 0 && 'is-overflowing')}>
+ <span ref={lineRef} className="pet-mini-marquee-text" style={{ transform: `translateX(${-shift}px)` }} aria-live="polite">{text || <span className="pet-mini-muted">{listeningLabel}</span>}</span>
+ </div>
</div>
);
};
-const NeedsInput: React.FC<{
- vaultRequestIds: string[];
- quickReplies: ReturnType<typeof openQuickReplies>;
- onChoose: (message: WorkbenchMessage, choice: string) => Promise<boolean>;
-}> = ({ vaultRequestIds, quickReplies, onChoose }) => {
- const { t } = useTranslation();
- if (vaultRequestIds.length === 0 && !quickReplies) return null;
+const MiniDock: React.FC<{ enabled: boolean; listening: boolean; typing: boolean; showMic: boolean; onMic: () => void; onKeyboard: () => void; t: (key: string) => string }> = ({ enabled, listening, typing, showMic, onMic, onKeyboard, t }) => (
+ <div className={clsx('pet-mini-dock', (listening || typing) && 'is-active')} data-pet-hit>
+ {showMic && <button type="button" className={clsx(listening && 'is-listening')} onClick={onMic} aria-pressed={listening} aria-label={listening ? t('pet.voice.stop') : t('pet.voice.open')}>{listening ? <StopIcon /> : <MicIcon />}</button>}
+ {showMic && <span className="pet-mini-dock-divider" aria-hidden />}
+ <button type="button" className={clsx(typing && 'is-typing')} disabled={!enabled} onClick={onKeyboard} aria-pressed={typing} aria-label={typing ? t('pet.keyboard.close') : t('pet.keyboard.open')}><KeyboardIcon /></button>
+ </div>
+);
+
+const CollapsedCards: React.FC<{ cards: PetCard[]; onOpen: () => void; t: (key: string) => string }> = ({ cards, onOpen, t }) => {
+ const [front, ...layers] = cards;
+ if (!front) return null;
return (
- <div className="flex flex-col gap-2 px-3 pb-2">
- {vaultRequestIds.map((requestId) => (
- <Button
- key={requestId}
- variant="outline"
- size="sm"
- className="justify-start gap-2"
- onClick={() => void petBridge.open(vaultRequestLink(requestId))}
- >
- <KeyRound className="size-3.5" />
- {t('pet.vaultRequest')}
- </Button>
- ))}
- {quickReplies && (
- <QuickReplies
- key={quickReplies.message.id}
- options={quickReplies.options}
- chosen={null}
- onChoose={(choice) => onChoose(quickReplies.message, choice)}
- />
- )}
+ <button type="button" className="pet-mini-collapsed" style={{ paddingBottom: layers.length * 9 }} onClick={onOpen} aria-label={t('pet.stack.expand')}>
+ {layers.map((card, index) => {
+ const inset = 18 + 6 + index * 3;
+ return <span key={card.id} data-pet-hit className="pet-mini-layer" style={{ top: (index + 1) * 9, bottom: (layers.length - index - 1) * 9, left: inset, right: inset, zIndex: layers.length - index }} aria-hidden />;
+ })}
+ <div className="pet-mini-front" style={{ zIndex: layers.length + 1 }}><CardBody card={front} expanded={false} t={t} /></div>
+ </button>
+ );
+};
+
+const ExpandedCards: React.FC<{ cards: PetCard[]; leaving: string[]; detailOpen: boolean; onMain: () => void; onSwitch?: () => void; onDismiss: (id: string) => void; stops: Record<string, StopPhase>; onStop: (card: PetCard) => void; t: (key: string, options?: Record<string, unknown>) => string; detail: ReactNode }> = ({ cards, leaving, detailOpen, onMain, onSwitch, onDismiss, stops, onStop, t, detail }) => {
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const [edges, setEdges] = useState({ top: 0, bottom: 0 });
+ const measure = useCallback(() => {
+ const node = scrollRef.current;
+ if (!node) return;
+ setEdges({ top: Math.min(FADE_PX, Math.max(0, node.scrollTop)), bottom: Math.min(FADE_PX, Math.max(0, node.scrollHeight - node.clientHeight - node.scrollTop)) });
+ }, []);
+ useEffect(() => {
+ const node = scrollRef.current;
+ if (!node) return undefined;
+ measure();
+ if (typeof ResizeObserver === 'undefined') return undefined;
+ const observer = new ResizeObserver(measure);
+ observer.observe(node);
+ const list = node.querySelector('.pet-mini-list');
+ if (list) observer.observe(list);
+ return () => observer.disconnect();
+ }, [measure, cards.length, detailOpen]);
+ const mask = `linear-gradient(to bottom, transparent 0, #000 ${edges.top}px, #000 calc(100% - ${edges.bottom}px), transparent 100%)`;
+ return (
+ <div className="pet-mini-panel">
+ <div ref={scrollRef} onScroll={measure} className="pet-mini-scroll" style={{ maskImage: mask, WebkitMaskImage: mask }}>
+ {onSwitch && <Button variant="link" size="sm" data-pet-hit onClick={onSwitch}>{t('pet.switchSession')}</Button>}
+ <ul className="pet-mini-list">
+ {cards.map((card) => {
+ const phase = stops[card.id];
+ return (
+ <li key={card.id} className={clsx('pet-mini-row', leaving.includes(card.id) && 'is-leaving')}>
+ <div className="pet-mini-row-inner"><div className={clsx('pet-mini-row-body', card.main && 'is-main')}>
+ <div className={clsx('pet-mini-card-wrap', card.main && 'is-main')} data-pet-hit>
+ <CardBody card={card} expanded t={t} phase={phase} onDismiss={() => onDismiss(card.id)} onStop={() => onStop(card)} onClick={card.main ? onMain : undefined} />
+ {card.main && <div className={clsx('pet-mini-detail', detailOpen && 'is-open')}><div className="pet-mini-detail-clip" inert={!detailOpen || undefined}>{detail}</div></div>}
+ </div>
+ </div></div>
+ </li>
+ );
+ })}
+ </ul>
+ </div>
</div>
);
};
-const SessionSwitcher: React.FC<{
- current: string | null;
- onPick: (sessionId: string) => void;
-}> = ({ current, onPick }) => {
- const { t } = useTranslation();
- const { sessions, loading } = useSessionSwitcher(true);
+const CardBody: React.FC<{ card: PetCard; expanded: boolean; t: (key: string, options?: Record<string, unknown>) => string; phase?: StopPhase; onDismiss?: () => void; onStop?: () => void; onClick?: () => void }> = ({ card, expanded, t, phase, onDismiss, onStop, onClick }) => {
+ const running = card.running && phase !== 'stopped' && phase !== 'stopping';
+ const subtitle = phase === 'stopping' ? t(isPausable(card) ? 'pet.stop.pausing' : 'pet.stop.stopping') : phase === 'stopped' ? t(isPausable(card) ? 'pet.stop.paused' : 'pet.stop.stopped') : phase === 'failed' ? t('pet.stop.failed') : card.status;
+ const stopText = isPausable(card) ? t('pet.stop.confirmPause') : t('pet.stop.confirmStop');
return (
- <div className="flex min-h-0 flex-1 flex-col overflow-y-auto py-1">
- {sessions.length === 0 && (
- <p className="px-3 py-2 text-[12px] text-muted">{loading ? t('common.loading') : t('pet.noSessions')}</p>
- )}
- {sessions.map((session) => (
- <button
- key={session.id}
- type="button"
- className={clsx(
- 'truncate px-3 py-1.5 text-left text-[13px] hover:bg-muted-soft',
- session.id === current && 'font-medium text-primary-ink',
- )}
- onClick={() => onPick(session.id)}
- >
- {session.title || t('pet.untitled')}
+ <article className={clsx('pet-mini-card', card.main && 'is-main')} title={card.title} data-pet-hit onClick={onClick} role={onClick ? 'button' : undefined} tabIndex={onClick ? 0 : undefined} onKeyDown={onClick ? (event) => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); onClick(); } } : undefined}>
+ {expanded && !card.main && <button type="button" className="pet-mini-dismiss" data-pet-hit onClick={(event) => { event.stopPropagation(); onDismiss?.(); }} aria-label={t('pet.dismiss')}><svg viewBox="0 0 16 16" aria-hidden><path d="m4 4 8 8M12 4 4 12" /></svg></button>}
+ <div className="pet-mini-card-content">
+ {card.main && <div className="pet-mini-eyebrow">{t('pet.mainAgent')}</div>}
+ <div className="pet-mini-title">{card.title}</div>
+ <div className={clsx('pet-mini-subtitle', phase === 'stopped' && 'is-stopped')} title={subtitle}>
+ {running && <span className="pet-mini-running-dot" aria-hidden />}
+ {phase === 'stopped' && <span className="pet-mini-stopped-dot" aria-hidden />}
+ <span>{subtitle}</span>
+ </div>
+ </div>
+ {expanded && card.canPause && !card.main && phase !== 'stopped' && (
+ <button type="button" className={clsx('pet-mini-stop', phase === 'confirm' && 'is-confirm')} onClick={(event) => { event.stopPropagation(); onStop?.(); }} disabled={phase === 'stopping'} aria-label={stopText}>
+ {phase === 'confirm' ? stopText : phase === 'stopping' ? <span className="pet-mini-spinner" aria-hidden /> : <StopIcon />}
</button>
- ))}
+ )}
+ </article>
+ );
+};
+
+const MainDetail: React.FC<{ epoch: PetSurfaceEpoch; voiceNeedsCloud: boolean; canChat: boolean; visible: boolean; onSwitch: () => void; binding: string; exchange: ReturnType<typeof latestExchange>; running: boolean; queued: boolean; markRead: (sessionId: string, untilMessageId?: string) => Promise<boolean>; onRead: () => void; vaultRequestIds: string[]; quickReplies: ReturnType<typeof openQuickReplies>; onChoose: (message: WorkbenchMessage, choice: string) => Promise<boolean>; uncertain: boolean; onInspect: () => void }> = (props) => {
+ const { t } = useTranslation();
+ const lastResultRef = useRef<HTMLDivElement>(null);
+ const resultKey = `${props.binding}\u0000${props.exchange.results.at(-1)?.id ?? ''}`;
+ const [seenResult, setSeenResult] = useState<{ epoch: PetSurfaceEpoch; key: string } | null>(null);
+ useEffect(() => {
+ const node = lastResultRef.current;
+ if (!props.visible || !node) return;
+ if (typeof IntersectionObserver === 'undefined') return;
+ const observer = new IntersectionObserver(([entry]) => {
+ if (props.epoch.isCurrent()) setSeenResult(entry.isIntersecting ? { epoch: props.epoch, key: resultKey } : null);
+ }, {
+ root: node.closest('.pet-mini-scroll'),
+ });
+ observer.observe(node);
+ return () => observer.disconnect();
+ }, [props.visible, resultKey, props.epoch]);
+ usePetMarkRead(props.epoch, props.binding, props.exchange, props.markRead, props.onRead, props.visible && (typeof IntersectionObserver === 'undefined' || (seenResult?.epoch === props.epoch && seenResult.key === resultKey)));
+ return (
+ <div className="pet-mini-detail-inner">
+ <Button variant="link" size="sm" aria-label={t('pet.switchSession')} onClick={props.onSwitch}>{t('pet.switchSession')}</Button>
+ {props.exchange.user && <div className="pet-mini-detail-user"><Markdown content={props.exchange.user.text} softBreaks /></div>}
+ {props.exchange.results.map((message, index) => <div ref={index === props.exchange.results.length - 1 ? lastResultRef : undefined} key={message.id} className="pet-mini-detail-result"><Markdown content={message.text} softBreaks /></div>)}
+ {props.running && <p className="pet-mini-detail-muted">{t('pet.thinking')}</p>}
+ {props.voiceNeedsCloud && <p className="pet-mini-detail-muted">{t('pet.voice.cloudRequired')}</p>}
+ {props.queued && <p className="pet-mini-detail-muted">{t('pet.queued')}</p>}
+ {!props.exchange.unreadComplete && <Button variant="link" size="sm" className="px-0" onClick={() => void petBridge.open(sessionLink(props.binding))}>{t('pet.moreInAvibe')}</Button>}
+ {props.vaultRequestIds.map((id) => <Button key={id} variant="outline" size="sm" className="justify-start gap-2" onClick={() => void petBridge.open(vaultRequestLink(id))}><KeyRound className="size-3.5" />{t('pet.vaultRequest')}</Button>)}
+ {props.canChat && !props.uncertain && props.quickReplies && <QuickReplies key={props.quickReplies.message.id} options={props.quickReplies.options} chosen={null} onChoose={(choice) => props.onChoose(props.quickReplies!.message, choice)} />}
+ {props.uncertain && <div className="pet-mini-detail-notice" role="status"><p>{t('newSession.sendUncertain')}</p><Button variant="link" size="sm" className="px-0" onClick={props.onInspect}>{t('pet.openInAvibe')}</Button></div>}
+ <Button variant="link" size="sm" className="px-0" onClick={() => void petBridge.open(sessionLink(props.binding))}><ExternalLink className="mr-1 size-3.5" />{t('pet.openInAvibe')}</Button>
</div>
);
};
-/**
- * Mark read through the last rendered unread result, once per row, and only
- * when every unread result is in the loaded tail (otherwise reading is left to
- * the Workbench). The tail keeps `read_at: null` until its next read, so a
- * marker records what was sent. A request the server did not apply (an error
- * status or a network failure) clears it, so the next chance to read
- * (reopening the panel, the window coming back, a new tail) retries, without
- * a retry loop against a failing server.
- */
-function usePetMarkRead(
- binding: string,
- exchange: ReturnType<typeof latestExchange>,
- markRead: (sessionId: string, untilMessageId?: string) => Promise<boolean>,
- onRead: () => void,
-): void {
- const last = exchange.results[exchange.results.length - 1];
- const unreadId = last && last.read_at === null ? last.id : null;
- // Seen means visible and focused: an open panel can stay up behind another
- // app (it keeps an unsent draft), and a reply arriving then is not seen. The
- // shared page-activity signal is the same one the chat page uses.
+function usePetMarkRead(epoch: PetSurfaceEpoch, binding: string, exchange: ReturnType<typeof latestExchange>, markRead: (sessionId: string, untilMessageId?: string) => Promise<boolean>, onRead: () => void, visible: boolean) {
const active = usePageActive();
- const markedRef = useRef<string | null>(null);
+ const last = exchange.results.at(-1);
+ const unreadId = last && last.read_at === null ? last.id : null;
+ const marker = useRef<string | null>(null);
+ useEffect(() => { marker.current = null; }, [epoch]);
useEffect(() => {
- if (!unreadId || !exchange.unreadComplete || !active) return;
- const marker = `${binding}\u0000${unreadId}`;
- if (markedRef.current === marker) return;
- markedRef.current = marker;
- const forget = () => {
- if (markedRef.current === marker) markedRef.current = null;
- };
- markRead(binding, unreadId).then((applied) => {
- // An applied read converges the rendered rows from the server, so a
- // later reply never replays this one as unread.
- if (applied) onRead();
- else forget();
- }, forget);
- }, [binding, unreadId, exchange.unreadComplete, active, markRead, onRead]);
+ if (!epoch.isCurrent() || !unreadId || !exchange.unreadComplete || !active || !visible) return;
+ const key = `${binding}\u0000${unreadId}`;
+ if (marker.current === key) return;
+ marker.current = key;
+ void markRead(binding, unreadId).then((applied) => {
+ if (!epoch.isCurrent()) return;
+ if (applied) onRead(); else marker.current = null;
+ }, () => { if (epoch.isCurrent()) marker.current = null; });
+ }, [active, binding, exchange.unreadComplete, markRead, onRead, unreadId, visible, epoch]);
}
-
diff --git a/ui/src/pet/pet-mini.css b/ui/src/pet/pet-mini.css
new file mode 100644
index 000000000..f6b86543a
--- /dev/null
+++ b/ui/src/pet/pet-mini.css
@@ -0,0 +1,685 @@
+.pet-mini-stage {
+ position:fixed;
+ inset:0;
+ overflow:hidden;
+ pointer-events:none;
+ color:var(--pet-ink);
+ font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;
+ --settle:cubic-bezier(.32,.72,0,1);
+ --pet-ink:#fff;
+ --pet-card:#2a2a2e;
+ --pet-main:#34343b;
+ --pet-layer:#1a1a1e;
+ --pet-dismiss:#3a3a3e;
+ --pet-dismiss-hover:#4a4a50}
+
+.pet-mini-column {
+ position:absolute;
+ left:50%;
+ bottom:147px;
+ width:min(440px,94vw);
+ transform:translateX(-50%);
+ display:flex;
+ flex-direction:column;
+ align-items:center;
+ min-width:0;
+ pointer-events:none;
+ z-index:3}
+
+.pet-mini-cards {
+ width:100%;
+ min-width:0;
+ overflow:visible;
+ transition:height 360ms var(--settle),opacity 220ms ease,transform 260ms var(--settle)}
+
+.pet-mini-cards.is-hidden {
+ opacity:0;
+ transform:translateY(8px);
+ pointer-events:none}
+
+.pet-mini-collapsed {
+ position:relative;
+ display:block;
+ width:100%;
+ padding:0 18px;
+ text-align:left;
+ pointer-events:auto}
+
+.pet-mini-layer {
+ position:absolute;
+ border:1px solid color-mix(in srgb,var(--pet-ink) 8%,transparent);
+ border-radius:24px;
+ background:var(--pet-layer)}
+
+.pet-mini-card-wrap,.pet-mini-card {
+ min-width:0}
+
+.pet-mini-card {
+ position:relative;
+ display:flex;
+ align-items:flex-start;
+ width:100%;
+ min-width:0;
+ border:1px solid color-mix(in srgb,var(--pet-ink) 8%,transparent);
+ border-radius:28px;
+ padding:14px 20px;
+ background:var(--pet-card);
+ box-shadow:0 18px 50px rgba(0,0,0,.45);
+ text-align:left;
+ pointer-events:auto}
+
+.pet-mini-card.is-main {
+ background:var(--pet-main);
+ border-color:color-mix(in srgb,var(--mint) 45%,transparent)}
+
+.pet-mini-card-content {
+ min-width:0;
+ flex:1}
+
+.pet-mini-eyebrow {
+ margin-bottom:2px;
+ color:color-mix(in srgb,var(--mint) 80%,transparent);
+ font-size:10px;
+ font-weight:600;
+ letter-spacing:.14em;
+ line-height:15px;
+ text-transform:uppercase}
+
+.pet-mini-title,.pet-mini-subtitle {
+ min-width:0;
+ overflow:hidden;
+ text-overflow:ellipsis;
+ white-space:nowrap}
+
+.pet-mini-title {
+ font-size:15px;
+ line-height:22.5px;
+ font-weight:600;
+ letter-spacing:-.025em}
+
+.pet-mini-subtitle {
+ display:flex;
+ align-items:center;
+ min-width:0;
+ gap:6px;
+ margin-top:2px;
+ color:color-mix(in srgb,var(--pet-ink) 45%,transparent);
+ font-size:13px;
+ line-height:19.5px}
+
+.pet-mini-subtitle.is-stopped {
+ color:color-mix(in srgb,var(--pet-ink) 60%,transparent)}
+
+.pet-mini-running-dot,.pet-mini-stopped-dot {
+ width:6px;
+ height:6px;
+ flex:none;
+ border-radius:999px}
+.pet-mini-running-dot {
+ background:#34d399;
+ animation:pet-mini-pulse 2s cubic-bezier(.4,0,.6,1) infinite}
+.pet-mini-stopped-dot {
+ background:color-mix(in srgb,var(--pet-ink) 40%,transparent)}
+
+@keyframes pet-mini-pulse {
+ 50% {
+ opacity:.5}
+}
+
+.pet-mini-panel {
+ width:100%;
+ padding:6px;
+ border-radius:34px;
+ pointer-events:auto}
+
+@keyframes pet-mini-content-in {
+ from {
+ opacity:0;
+ transform:translateY(8px) scale(.98)}
+to {
+ opacity:1;
+ transform:none}
+}
+
+.pet-mini-scroll {
+ height:292px;
+ min-width:0;
+ display:flex;
+ flex-direction:column;
+ overflow-y:auto;
+ overscroll-behavior:contain;
+ padding:0 12px;
+ scrollbar-width:none}
+.pet-mini-scroll::-webkit-scrollbar {
+ display:none}
+
+.pet-mini-list {
+ display:flex;
+ flex-direction:column;
+ min-width:0;
+ width:100%;
+ flex:none;
+ margin-top:auto;
+ padding:10px 0 0;
+ list-style:none}
+
+.pet-mini-row {
+ display:grid;
+ grid-template-columns:minmax(0,1fr);
+ grid-template-rows:1fr;
+ min-width:0;
+ transition:grid-template-rows 340ms var(--settle) 140ms}
+.pet-mini-row-inner {
+ min-height:0;
+ min-width:0}
+.pet-mini-row-body {
+ min-width:0;
+ perspective:900px;
+ padding-bottom:8px}
+.pet-mini-row-body.is-main {
+ padding-bottom:16px}
+
+.pet-mini-row.is-leaving {
+ grid-template-rows:0fr;
+ pointer-events:none}
+.pet-mini-row.is-leaving .pet-mini-row-inner {
+ overflow:hidden}
+.pet-mini-row.is-leaving .pet-mini-card-wrap {
+ animation:pet-mini-exit 200ms cubic-bezier(.4,0,1,1) forwards}
+
+@keyframes pet-mini-exit {
+ to {
+ opacity:0;
+ transform:translateZ(-120px) translateY(-4px) scale(.88);
+ filter:blur(2px)}
+}
+
+.pet-mini-dismiss {
+ position:absolute;
+ left:-6px;
+ top:-6px;
+ z-index:2;
+ display:flex;
+ width:20px;
+ height:20px;
+ align-items:center;
+ justify-content:center;
+ border:0;
+ border-radius:999px;
+ background:var(--pet-dismiss);
+ color:color-mix(in srgb,var(--pet-ink) 70%,transparent);
+ cursor:pointer}
+.pet-mini-dismiss:hover {
+ background:var(--pet-dismiss-hover);
+ color:var(--pet-ink)}
+.pet-mini-dismiss svg {
+ width:11px;
+ height:11px;
+ stroke:currentColor;
+ stroke-width:1.8;
+ stroke-linecap:round}
+
+.pet-mini-stop {
+ display:flex;
+ flex:none;
+ width:32px;
+ height:32px;
+ align-items:center;
+ justify-content:center;
+ margin:2px -4px 0 12px;
+ border:0;
+ border-radius:999px;
+ background:color-mix(in srgb,var(--pet-ink) 10%,transparent);
+ color:color-mix(in srgb,var(--pet-ink) 80%,transparent);
+ cursor:pointer}
+.pet-mini-stop.is-confirm {
+ width:auto;
+ padding:0 12px;
+ border-radius:999px;
+ background:#f43f5e;
+ color:var(--pet-ink);
+ font-size:12px;
+ font-weight:600;
+ animation:pet-mini-stop-in 180ms var(--settle)}
+.pet-mini-stop:disabled {
+ cursor:default;
+ opacity:.6}
+.pet-mini-spinner {
+ width:14px;
+ height:14px;
+ border:2px solid color-mix(in srgb,var(--pet-ink) 25%,transparent);
+ border-top-color:color-mix(in srgb,var(--pet-ink) 80%,transparent);
+ border-radius:999px;
+ animation:pet-mini-spin .7s linear infinite}
+@keyframes pet-mini-spin {
+ to {
+ transform:rotate(360deg)}
+}
+@keyframes pet-mini-stop-in {
+ from {
+ opacity:0;
+ transform:scale(.85)}
+to {
+ opacity:1;
+ transform:scale(1)}
+}
+
+.pet-mini-detail {
+ display:grid;
+ grid-template-columns:minmax(0,1fr);
+ grid-template-rows:0fr;
+ opacity:0;
+ transition:grid-template-rows 280ms var(--settle),opacity 200ms ease}
+.pet-mini-detail.is-open {
+ grid-template-rows:1fr;
+ opacity:1}
+.pet-mini-detail-clip {
+ min-height:0;
+ min-width:0;
+ overflow:hidden}
+.pet-mini-detail-inner {
+ min-width:0;
+ padding:14px;
+ color:color-mix(in srgb,var(--pet-ink) 78%,transparent);
+ font-size:12px}
+.pet-mini-detail-user {
+ margin-bottom:8px;
+ max-width:88%;
+ margin-left:auto;
+ border-radius:16px;
+ background:color-mix(in srgb,var(--pet-ink) 8%,transparent);
+ padding:8px 10px}
+.pet-mini-detail-result {
+ min-width:0;
+ margin-bottom:8px}
+.pet-mini-detail-muted,.pet-mini-detail-notice {
+ color:color-mix(in srgb,var(--pet-ink) 50%,transparent)}
+.pet-mini-detail-notice {
+ border-top:1px solid color-mix(in srgb,var(--pet-ink) 8%,transparent);
+ padding-top:8px}
+
+.pet-mini-slot {
+ display:grid;
+ grid-template-columns:minmax(0,1fr);
+ width:100%;
+ grid-template-rows:0fr;
+ transition:grid-template-rows 300ms var(--settle);
+ pointer-events:none}
+.pet-mini-slot.is-open {
+ grid-template-rows:1fr;
+ pointer-events:auto}
+.pet-mini-slot-inner {
+ min-width:0;
+ min-height:0;
+ overflow:hidden}
+.pet-mini-slot.is-open .pet-mini-slot-inner {
+ animation:pet-mini-slot-unclip 0s linear 300ms forwards}
+@keyframes pet-mini-slot-unclip {
+ to {
+ overflow:visible}
+}
+.pet-mini-slot-body {
+ width:100%;
+ padding:0 18px;
+ opacity:0;
+ transform:translateY(8px) scale(.97);
+ transition:opacity 180ms ease,transform 300ms var(--settle)}
+.pet-mini-slot.is-open .pet-mini-slot-body {
+ opacity:1;
+ transform:none;
+ transition-delay:60ms}
+
+.pet-mini-marquee,.pet-mini-input {
+ display:flex;
+ width:100%;
+ min-width:0;
+ align-items:center;
+ border-radius:22px;
+ background:var(--pet-card);
+ box-shadow:0 12px 32px rgba(0,0,0,.45)}
+.pet-mini-marquee {
+ gap:8px;
+ padding:8px 16px 8px 12px}
+.pet-mini-voice-dot {
+ position:relative;
+ display:flex;
+ width:10px;
+ height:10px;
+ flex:none}
+.pet-mini-voice-dot:before,.pet-mini-voice-dot span {
+ position:absolute;
+ inset:0;
+ border-radius:999px;
+ background:#fb7185}
+.pet-mini-voice-dot:before {
+ animation:pet-mini-ping 1.4s ease-in-out infinite;
+ opacity:.6}
+.pet-mini-voice-dot span {
+ display:block}
+@keyframes pet-mini-ping {
+ 50% {
+ transform:scale(1.7);
+ opacity:0}
+}
+
+.pet-mini-marquee-line {
+ flex:1;
+ min-width:0;
+ overflow:hidden}
+.pet-mini-marquee-line.is-overflowing {
+ mask-image:linear-gradient(to right,transparent 0,#000 28px);
+ -webkit-mask-image:linear-gradient(to right,transparent 0,#000 28px)}
+.pet-mini-marquee-text {
+ display:inline-block;
+ min-width:max-content;
+ color:var(--pet-ink);
+ font-size:13px;
+ transition:transform 300ms ease-out}
+.pet-mini-muted {
+ color:color-mix(in srgb,var(--pet-ink) 45%,transparent)}
+
+.pet-mini-input {
+ align-items:flex-end;
+ gap:6px;
+ border:1px solid color-mix(in srgb,var(--pet-ink) 10%,transparent);
+ padding:6px 6px 6px 14px}
+.pet-mini-input textarea {
+ min-width:0;
+ max-height:96px;
+ min-height:32px;
+ flex:1;
+ resize:none;
+ border:0;
+ background:transparent;
+ padding:6px 0;
+ color:var(--pet-ink);
+ font:inherit;
+ font-size:13px;
+ outline:0}
+.pet-mini-input textarea::placeholder {
+ color:color-mix(in srgb,var(--pet-ink) 35%,transparent)}
+.pet-mini-input-button,.pet-mini-send {
+ display:flex;
+ width:32px;
+ height:32px;
+ flex:none;
+ align-items:center;
+ justify-content:center;
+ border:0;
+ border-radius:999px;
+ cursor:pointer}
+.pet-mini-input-button {
+ background:color-mix(in srgb,var(--pet-ink) 10%,transparent);
+ color:color-mix(in srgb,var(--pet-ink) 80%,transparent)}
+.pet-mini-send {
+ background:#fff;
+ color:#000}
+.pet-mini-send:disabled {
+ background:color-mix(in srgb,var(--pet-ink) 10%,transparent);
+ color:color-mix(in srgb,var(--pet-ink) 30%,transparent);
+ cursor:default}
+
+.pet-mini-session-picker {
+ display:flex;
+ min-height:100%;
+ flex-direction:column;
+ justify-content:flex-start;
+ gap:2px;
+ padding:4px}
+.pet-mini-session-option {
+ min-width:0;
+ border:0;
+ border-radius:12px;
+ background:transparent;
+ padding:9px 10px;
+ color:var(--pet-ink);
+ text-align:left;
+ font-size:13px;
+ overflow:hidden;
+ text-overflow:ellipsis;
+ white-space:nowrap;
+ cursor:pointer}
+.pet-mini-session-option:hover {
+ background:color-mix(in srgb,var(--pet-ink) 8%,transparent)}
+
+.pet-mini-avatar-wrap {
+ position:absolute;
+ left:50%;
+ bottom:36px;
+ display:flex;
+ flex-direction:column;
+ align-items:center;
+ pointer-events:auto;
+ transform:translateX(-50%)}
+.pet-mini-avatar-button {
+ position:relative;
+ z-index:1;
+ width:115px;
+ height:115px;
+ flex:none;
+ padding:0;
+ border:0;
+ border-radius:999px;
+ background:transparent;
+ cursor:pointer;
+ touch-action:none}
+.pet-mini-avatar-wrap .pet-avatar {
+ width:115px;
+ height:115px}
+.pet-mini-avatar-wrap .pet-avatar__pose {
+ width:115px;
+ height:115px}
+.pet-mini-listen-ring {
+ position:absolute;
+ top:-8px;
+ left:50%;
+ z-index:0;
+ width:138px;
+ height:138px;
+ margin-left:-69px;
+ border-radius:999px;
+ background:radial-gradient(circle,rgba(251,113,133,.28) 0%,rgba(251,113,133,0) 70%);
+ animation:pet-mini-listen 1.6s ease-in-out infinite;
+ pointer-events:none}
+@keyframes pet-mini-listen {
+ 0%,100% {
+ transform:scale(.92);
+ opacity:.7}
+50% {
+ transform:scale(1.12);
+ opacity:1}
+}
+
+.pet-mini-dock {
+ position:absolute;
+ top:103px;
+ z-index:2;
+ display:flex;
+ align-items:center;
+ gap:4px;
+ border-radius:999px;
+ background:var(--pet-card);
+ padding:4px;
+ box-shadow:0 8px 24px rgba(0,0,0,.45);
+ opacity:0;
+ transform:translateY(-6px) scale(.92);
+ pointer-events:none;
+ transition:opacity 180ms ease,transform 220ms var(--settle)}
+.pet-mini-avatar-wrap:hover .pet-mini-dock,.pet-mini-avatar-wrap:focus-within .pet-mini-dock,.pet-mini-dock.is-active {
+ opacity:1;
+ transform:none;
+ pointer-events:auto}
+.pet-mini-dock button {
+ display:flex;
+ width:32px;
+ height:32px;
+ align-items:center;
+ justify-content:center;
+ border:0;
+ border-radius:999px;
+ background:transparent;
+ color:color-mix(in srgb,var(--pet-ink) 80%,transparent);
+ cursor:pointer}
+.pet-mini-dock button:hover {
+ background:color-mix(in srgb,var(--pet-ink) 10%,transparent)}
+.pet-mini-dock button.is-listening {
+ background:#f43f5e;
+ color:var(--pet-ink)}
+.pet-mini-dock button.is-typing {
+ background:#fff;
+ color:#000}
+.pet-mini-dock-divider {
+ width:1px;
+ height:16px;
+ background:color-mix(in srgb,var(--pet-ink) 10%,transparent)}
+.pet-mini-setup {
+ position:absolute;
+ bottom:300px;
+ left:50%;
+ z-index:2;
+ width:min(260px,90vw);
+ transform:translateX(-50%);
+ pointer-events:auto;
+ border:1px solid color-mix(in srgb,var(--pet-ink) 8%,transparent);
+ border-radius:24px;
+ background:var(--pet-card);
+ padding:16px;
+ box-shadow:0 18px 50px rgba(0,0,0,.45);
+ font-size:12px}
+
+@media (hover:none) {
+ .pet-mini-dock {
+ opacity:1;
+ transform:none;
+ pointer-events:auto}
+}
+@media(prefers-reduced-motion:reduce) {
+ .pet-mini-cards,.pet-mini-slot,.pet-mini-slot-body,.pet-mini-detail,.pet-mini-row,.pet-mini-panel {
+ transition:none;
+ animation:none}
+.pet-mini-cards.is-hidden {
+ transition:none}
+.pet-mini-row.is-leaving .pet-mini-card-wrap {
+ animation:none;
+ opacity:0}
+.pet-mini-listen-ring,.pet-mini-voice-dot:before,.pet-mini-running-dot,.pet-mini-spinner {
+ animation:none}
+.pet-mini-marquee-text {
+ transition:none}
+}
+
+
+.pet-mini-front {
+ position: relative;
+ }
+
+.pet-mini-swap {
+ width: 100%;
+ min-width: 0;
+ animation: pet-mini-content-in 360ms var(--settle);
+ }
+
+.pet-mini-subtitle > span:last-child {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+.pet-mini-card-wrap.is-main {
+ border: 1px solid color-mix(in srgb,var(--mint) 45%,transparent);
+ border-radius: 28px;
+ background: var(--pet-main);
+ box-shadow: 0 18px 50px rgba(0,0,0,.45);
+ }
+
+.pet-mini-card-wrap.is-main > .pet-mini-card {
+ border: 0;
+ background: transparent;
+ box-shadow: none;
+ }
+
+.pet-mini-card[role=button] {
+ cursor: pointer;
+ }
+
+.pet-mini-card[role=button]:focus-visible, .pet-mini-avatar-button:focus-visible {
+ outline: 2px solid var(--mint);
+ outline-offset: 2px;
+ }
+
+.pet-mini-voice-dot:before {
+ content: '';
+ }
+
+.pet-mini-stop:not(:disabled):hover {
+ background: color-mix(in srgb,var(--pet-ink) 16%,transparent);
+ }
+
+.pet-mini-stop.is-confirm, .pet-mini-dock button.is-listening {
+ color: #fff;
+ }
+
+.pet-mini-stop.is-confirm:hover {
+ background: #fb7185;
+ }
+
+.pet-mini-send, .pet-mini-dock button.is-typing {
+ color: #000;
+ }
+
+.pet-mini-stage button:disabled {
+ cursor: default;
+ }
+
+@media (prefers-color-scheme: light) {
+
+ .pet-mini-stage {
+ --pet-ink: #17171c;
+ --pet-card: var(--surface);
+ --pet-main: var(--surface-3);
+ --pet-layer: var(--surface-3);
+ --pet-dismiss: #e2e2e8;
+ --pet-dismiss-hover: #d2d2dc;
+ }
+
+}
+
+:root[data-theme=light] .pet-mini-stage {
+ --pet-ink: #17171c;
+ --pet-card: var(--surface);
+ --pet-main: var(--surface-3);
+ --pet-layer: var(--surface-3);
+ --pet-dismiss: #e2e2e8;
+ --pet-dismiss-hover: #d2d2dc;
+ }
+
+:root[data-theme=dark] .pet-mini-stage {
+ --pet-ink: #fff;
+ --pet-card: #2a2a2e;
+ --pet-main: #34343b;
+ --pet-layer: #1a1a1e;
+ --pet-dismiss: #3a3a3e;
+ --pet-dismiss-hover: #4a4a50;
+ }
+
+@media (prefers-reduced-motion: reduce) {
+
+ .pet-mini-stage *, .pet-mini-stage *::before {
+ animation: none !important;
+ transition: none !important;
+ }
+
+ .pet-mini-slot.is-open .pet-mini-slot-inner {
+ overflow: visible;
+ }
+
+}
+
+
+/* Clip the outer height only while switching between stack and list. */
+.pet-mini-cards:has(.pet-mini-swap.is-switching) { overflow: hidden; }
+
+@media (prefers-reduced-motion: reduce) {
+ .pet-mini-cards:has(.pet-mini-swap.is-switching) { overflow: visible; }
+}
diff --git a/ui/src/pet/petBridge.ts b/ui/src/pet/petBridge.ts
index 58a96472b..d3ca0cad0 100644
--- a/ui/src/pet/petBridge.ts
+++ b/ui/src/pet/petBridge.ts
@@ -30,11 +30,11 @@ import { openLinkInNewContext } from '@/lib/pwaNavigation';
* order, so the page applies only a revision newer than the last it applied.
*
* Outside the shell (a browser tab during development) the bridge keeps the
- * binding in localStorage and lays the panel out to the right, so the route
+ * binding in localStorage with the same fixed mini layout, so the route
* stays usable without the native window.
*/
-export type PetIntent = 'listen' | 'show';
+export type PetIntent = 'listen' | 'show' | 'release';
export type PetLayout = {
panel_side: 'left' | 'right';
@@ -49,6 +49,7 @@ export type PetBinding = {
export type PetReady = PetBinding & {
summon_pending: { intent: PetIntent } | null;
+ dismissed_ids: string[];
};
export const PET_SUMMON_EVENT = 'avibe:pet-summon';
@@ -67,7 +68,7 @@ const shellInvoke = (): TauriInternals['invoke'] | null => {
return internals?.invoke ? internals.invoke.bind(internals) : null;
};
-const isIntent = (value: unknown): value is PetIntent => value === 'listen' || value === 'show';
+const isIntent = (value: unknown): value is PetIntent => value === 'listen' || value === 'show' || value === 'release';
const parseBinding = (value: unknown): PetBinding => {
const result = value as { binding?: unknown; revision?: unknown } | null;
@@ -109,12 +110,15 @@ export const petBridge = {
ready: async (): Promise<PetReady> => {
const invoke = shellInvoke();
- if (!invoke) return { ...readDevBinding(), summon_pending: null };
+ if (!invoke) return { ...readDevBinding(), summon_pending: null, dismissed_ids: [] };
const result = (await invoke('pet_ready')) as { summon_pending?: { intent?: unknown } | null } | null;
const pending = result?.summon_pending;
return {
...parseBinding(result),
summon_pending: pending && isIntent(pending.intent) ? { intent: pending.intent } : null,
+ dismissed_ids: Array.isArray((result as { dismissed_ids?: unknown } | null)?.dismissed_ids)
+ ? (result as { dismissed_ids: unknown[] }).dismissed_ids.filter((id): id is string => typeof id === 'string')
+ : [],
};
},
@@ -128,6 +132,18 @@ export const petBridge = {
};
},
+ setHitRegions: async (rects: Array<{ x: number; y: number; width: number; height: number }>): Promise<void> => {
+ const invoke = shellInvoke();
+ if (!invoke) return;
+ await invoke('pet_hit_regions', { rects });
+ },
+
+ setDismissedIds: async (sessionId: string, ids: string[]): Promise<void> => {
+ const invoke = shellInvoke();
+ if (!invoke) return;
+ await invoke('pet_set_dismissed', { sessionId, ids });
+ },
+
bind: async (sessionId: string): Promise<PetBinding> => {
const invoke = shellInvoke();
if (!invoke) return writeDevBinding(sessionId);
diff --git a/ui/src/pet/petComposer.ts b/ui/src/pet/petComposer.ts
index 9fee30614..07b2dff2b 100644
--- a/ui/src/pet/petComposer.ts
+++ b/ui/src/pet/petComposer.ts
@@ -56,9 +56,10 @@ export const petComposer = {
notify();
},
clearDraftIf(value: string) {
- if (draft !== value) return;
+ if (draft !== value) return false;
draft = '';
notify();
+ return true;
},
requestListen() {
if (pendingListen) return;
diff --git a/ui/src/pet/petPanel.test.tsx b/ui/src/pet/petPanel.test.tsx
index d4498c033..8ecec647d 100644
--- a/ui/src/pet/petPanel.test.tsx
+++ b/ui/src/pet/petPanel.test.tsx
@@ -11,7 +11,7 @@ vi.mock('react-i18next', () => ({
const api = {
getConfig: vi.fn(async () => ({ mode: 'self_host', setup_state: { needs_setup: true } })),
- getSessionResult: vi.fn(async () => ({ status: 200, session: null })),
+ getMainSession: vi.fn(async () => ({ status: 200, session: null })),
listSessionMessages: vi.fn(async () => ({ messages: [], next_after_id: null, next_before_id: null })),
getTurnState: vi.fn(async () => ({
in_flight: false, foreground: 'idle', native_turn_started: false,
@@ -52,31 +52,16 @@ afterEach(() => {
});
describe('setup-pending expansion', () => {
- it('grows the native frame before showing the setup-pending card', async () => {
- let resolveGrow: (value: unknown) => void = () => undefined;
- const grow = new Promise((resolve) => { resolveGrow = resolve; });
- const invoke = vi.fn((command: string) => {
- if (command === 'pet_ready') return Promise.resolve({ binding: null, revision: 0, summon_pending: null });
- if (command === 'pet_set_expanded') {
- if (invoke.mock.calls.filter(([c]) => c === 'pet_set_expanded').length > 8) {
- throw new Error('pet_set_expanded loop');
- }
- return grow;
- }
- return Promise.resolve(null);
- });
+ it('shows setup in the fixed window without a resize and rechecks on summon', async () => {
+ const invoke = vi.fn((command: string) => Promise.resolve(command === 'pet_ready'
+ ? { binding: null, revision: 0, summon_pending: null, dismissed_ids: [] } : null));
Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });
Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });
render(<PetPage />);
- await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_set_expanded', { expanded: true }));
- expect(screen.queryByText('pet.setupPending')).toBeNull();
- await act(async () => resolveGrow({ panel_side: 'left', panel_edge: 'bottom' }));
expect(await screen.findByText('pet.setupPending')).toBeTruthy();
- const expands = invoke.mock.calls.filter(([command]) => command === 'pet_set_expanded').length;
- act(() => {
- window.dispatchEvent(new CustomEvent(PET_SUMMON_EVENT, { detail: { intent: 'show' } }));
- });
- await act(async () => new Promise((resolve) => setTimeout(resolve, 40)));
- expect(invoke.mock.calls.filter(([command]) => command === 'pet_set_expanded')).toHaveLength(expands + 1);
+ expect(invoke.mock.calls.some(([command]) => command === 'pet_set_expanded')).toBe(false);
+ const before = api.getConfig.mock.calls.length;
+ act(() => window.dispatchEvent(new CustomEvent(PET_SUMMON_EVENT, { detail: { intent: 'show' } })));
+ await waitFor(() => expect(api.getConfig.mock.calls.length).toBeGreaterThan(before));
});
});
diff --git a/ui/src/pet/petPanel.ts b/ui/src/pet/petPanel.ts
index c3ec34708..d620af169 100644
--- a/ui/src/pet/petPanel.ts
+++ b/ui/src/pet/petPanel.ts
@@ -8,9 +8,8 @@ const DEFAULT_LAYOUT: PetLayout = { panel_side: 'left', panel_edge: 'bottom' };
* The native frame's expansion, held once per document outside React so the
* setup-pending card and the pet surface share it across their unmounts.
*
- * Closing hides the panel at once (a moment of transparent frame is
- * harmless); opening shows it only once the shell has grown the frame, so
- * content is never marked seen while still clipped. Native resizes are sent
+ * Closing hides the panel at once; opening waits for the shell to confirm
+ * the panel state. The v2 window has a fixed size. Native state writes are sent
* one at a time in the order they were asked, so an older `pet_set_expanded`
* cannot apply after a newer one; only the latest request updates React. A
* failed request restores the last confirmed expansion, so a redundant
diff --git a/ui/src/pet/petShell.ts b/ui/src/pet/petShell.ts
index 49461f6fa..d534a4581 100644
--- a/ui/src/pet/petShell.ts
+++ b/ui/src/pet/petShell.ts
@@ -29,6 +29,7 @@ let outstanding = 0;
let latestChange: string | null = null;
let changes: Promise<void> = Promise.resolve();
let pendingSummon: PetIntent | null = null;
+let dismissedIds: string[] = [];
let started = false;
// Bumped by every live summon, so a summon `pet_ready()` returns is used only
// if no live one has arrived since it was asked.
@@ -40,6 +41,8 @@ const show = () => {
const next = outstanding > 0 ? latestChange : reported?.binding;
if (next === binding) return;
binding = next;
+ dismissedIds = [];
+ (window as unknown as { __AVIBE_PET_BINDING__?: string | null }).__AVIBE_PET_BINDING__ = next;
storeListeners.forEach((listener) => listener());
};
@@ -55,13 +58,18 @@ const noteSummon = (intent: PetIntent) => {
};
/** A change made by this page: shown now, sent after the ones before it. */
-const change = (next: string | null, send: () => Promise<PetBinding>, failed: () => void) => {
+const change = (next: string | null, send: () => Promise<PetBinding>, failed: () => void, maySend?: () => boolean) => {
outstanding += 1;
latestChange = next;
show();
changes = changes
- .then(send)
- .then(report, failed)
+ .then(() => maySend?.() === false ? null : send())
+ .then((confirmed) => {
+ // An IPC already sent changes the shell's authoritative binding. Keep
+ // mirroring its revision even if authorization changed meanwhile; the
+ // surface must validate that binding afresh before displaying any data.
+ if (confirmed) report(confirmed);
+ }, failed)
.finally(() => {
outstanding -= 1;
show();
@@ -80,7 +88,12 @@ const start = () => {
});
const liveSummonsAtRequest = liveSummons;
void petBridge.ready().then((ready) => {
+ const applies = !reported || ready.revision >= reported.revision;
report(ready);
+ if (applies && binding === ready.binding) {
+ dismissedIds = ready.dismissed_ids ?? [];
+ storeListeners.forEach((listener) => listener());
+ }
if (ready.summon_pending && liveSummons === liveSummonsAtRequest) noteSummon(ready.summon_pending.intent);
}).catch(() => {
// Without an answer the pet starts unbound; the shell's next report wins.
@@ -90,7 +103,7 @@ const start = () => {
export const petShell = {
/** Bind `sessionId`. If the shell cannot, the pet shows what it holds. */
- pick: (sessionId: string) => change(sessionId, () => petBridge.bind(sessionId), () => undefined),
+ pick: (sessionId: string, isAuthorizationCurrent?: () => boolean) => change(sessionId, () => petBridge.bind(sessionId), () => undefined, isAuthorizationCurrent),
/**
* Clear an invalid binding (compare-and-clear). Unlike a failed pick, a
@@ -116,6 +129,14 @@ export const petShell = {
/** The binding now, for callbacks that must not read a stale render. */
currentBinding: (): string | null | undefined => binding,
+ dismissed: (): string[] => dismissedIds,
+ setDismissed: (sessionId: string, ids: string[]) => {
+ if (sessionId !== binding) return;
+ dismissedIds = ids;
+ storeListeners.forEach((listener) => listener());
+ // Persist writes in order, so an older dismiss cannot resurrect a later one.
+ changes = changes.then(() => petBridge.setDismissedIds(sessionId, ids)).catch(() => undefined);
+ },
};
export function usePetBinding(): string | null | undefined {
@@ -146,3 +167,10 @@ export function useOnSummon(listener: () => void): void {
};
}, [listener]);
}
+
+export function usePetDismissed(): string[] {
+ return useSyncExternalStore(
+ (listener) => { storeListeners.add(listener); return () => { storeListeners.delete(listener); }; },
+ () => dismissedIds,
+ );
+}
diff --git a/ui/src/pet/usePetSession.ts b/ui/src/pet/usePetSession.ts
index 91a55efba..1952d9789 100644
--- a/ui/src/pet/usePetSession.ts
+++ b/ui/src/pet/usePetSession.ts
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
useApi,
@@ -13,6 +13,15 @@ import { onPageReactivated } from '@/lib/pageActivity';
import { useLatestRef } from '@/lib/useLatestRef';
import { FencedSource } from './fencedSource';
+import { petShell } from './petShell';
+
+export type PetSurfaceEpoch = {
+ binding: string | null;
+ authorizationGeneration: number;
+ isCurrent: () => boolean;
+ /** A pick intentionally changes binding; its queued IPC still needs this gate. */
+ isAuthorizationCurrent: () => boolean;
+};
export const PET_TAIL_LIMIT = 30;
// Same cadences as the chat page: reconcile a dropped turn.end without ever
@@ -24,6 +33,7 @@ const ACTIVITY_RECONCILE_INTERVAL_MS = 10 * 1000;
export const SEND_GRACE_MS = 4000;
export type PetSessionData = {
+ epoch: PetSurfaceEpoch;
session: WorkbenchSession | null;
/** Project-level chat grant from GET session; null until a read lands. */
canChat: boolean | null;
@@ -73,6 +83,24 @@ const mergeRow = (tail: Tail, row: WorkbenchMessage): Tail => {
*/
export function usePetSession(sessionId: string | null, onInvalid: (sessionId: string) => void): PetSessionData {
const api = useApi();
+ const [authorizationGeneration, setAuthorizationGeneration] = useState(0);
+ const authorizationNow = useRef(0);
+ const mounted = useRef(true);
+ useEffect(() => {
+ mounted.current = true;
+ return () => { mounted.current = false; };
+ }, []);
+ const identity = useMemo(() => ({ binding: sessionId, authorizationGeneration }), [sessionId, authorizationGeneration]);
+ const currentIdentity = useLatestRef(identity);
+ const epoch = useMemo<PetSurfaceEpoch>(() => {
+ const isAuthorizationCurrent = () => mounted.current && authorizationNow.current === identity.authorizationGeneration;
+ return {
+ ...identity,
+ isAuthorizationCurrent,
+ isCurrent: () => isAuthorizationCurrent() && currentIdentity.current === identity
+ && (petShell.currentBinding() ?? null) === identity.binding,
+ };
+ }, [identity, currentIdentity]);
const [session, setSession] = useState<WorkbenchSession | null>(null);
const [canChat, setCanChat] = useState<boolean | null>(null);
@@ -98,7 +126,7 @@ export function usePetSession(sessionId: string | null, onInvalid: (sessionId: s
const sources = useMemo(() => ({
session: new FencedSource<string, WorkbenchSessionReadResult>({
- read: (key) => api.getSessionResult(key),
+ read: () => api.getMainSession(),
apply: (key, { status, session: row, capabilities }) => {
// A binding is valid only while S is writable: missing, archived and
// Runtime-owned sessions all clear it.
@@ -146,17 +174,21 @@ export function usePetSession(sessionId: string | null, onInvalid: (sessionId: s
sources.tail.setKey(sessionId);
sources.turn.setKey(sessionId);
if (sessionId) refreshAll();
+ return () => {
+ sources.session.setKey(null);
+ sources.tail.setKey(null);
+ sources.turn.setKey(null);
+ };
}, [sessionId, sources, refreshAll]);
// Report an invalid binding once, and only while it is still the binding.
useEffect(() => {
- if (invalid && invalid === sessionId) onInvalid(invalid);
- }, [invalid, sessionId, onInvalid]);
+ if (epoch.isCurrent() && invalid && invalid === sessionId) onInvalid(invalid);
+ }, [invalid, sessionId, onInvalid, epoch]);
// Live triggers and the reconnect gap fallback.
useEffect(() => {
- if (!sessionId) return undefined;
- const mine = (id: string | null | undefined) => id === sessionId;
+ const mine = (id: string | null | undefined) => Boolean(sessionId && id === sessionId);
return api.connectWorkbenchEvents({
onConnected: refreshAll,
onMessageNew: (row) => {
@@ -205,10 +237,15 @@ export function usePetSession(sessionId: string | null, onInvalid: (sessionId: s
// once, then re-read (a refresh also drops any read in flight); a lost
// session reads 403 and clears the binding.
onAuthorizationChanged: () => {
+ // Invalidate callbacks synchronously, before React commits the reset.
+ authorizationNow.current += 1;
+ setAuthorizationGeneration(authorizationNow.current);
setSession(null);
setCanChat(null);
setTail(EMPTY_TAIL);
setTurn(null);
+ setInGrace(false);
+ setInvalid(null);
refreshAll();
},
onQueueUpdated: ({ session_id }) => {
@@ -236,11 +273,12 @@ export function usePetSession(sessionId: string | null, onInvalid: (sessionId: s
useEffect(() => {
if (sendCount === 0) return undefined;
const timer = window.setTimeout(() => {
+ if (!epoch.isCurrent()) return;
setInGrace(false);
sources.turn.refresh();
}, SEND_GRACE_MS);
return () => window.clearTimeout(timer);
- }, [sendCount, sources]);
+ }, [sendCount, sources, epoch]);
// Interval reconcile only while work is present and the window is visible.
useEffect(() => {
@@ -252,6 +290,7 @@ export function usePetSession(sessionId: string | null, onInvalid: (sessionId: s
}, [sessionId, working, hasBackground, sources]);
const noteSent = useCallback((row: WorkbenchMessage | null) => {
+ if (!epoch.isCurrent()) return;
setInGrace(true);
setSendCount((count) => count + 1);
if (row && row.session_id === sessionId && row.id) {
@@ -260,11 +299,12 @@ export function usePetSession(sessionId: string | null, onInvalid: (sessionId: s
}
sources.tail.refresh();
sources.turn.refresh();
- }, [sources, sessionId]);
+ }, [sources, sessionId, epoch]);
- const refreshTail = useCallback(() => sources.tail.refresh(), [sources]);
+ const refreshTail = useCallback(() => { if (epoch.isCurrent()) sources.tail.refresh(); }, [sources, epoch]);
return {
+ epoch,
session,
canChat,
messages: tail.messages,