Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(desktop): drag the pet to the top and flip its column below (#2945)
Max5aa044e79078
diff --git a/desktop/runtime-host/src/pet.rs b/desktop/runtime-host/src/pet.rsindex 3c7eb59e4..b38705999 100644--- a/desktop/runtime-host/src/pet.rs+++ b/desktop/runtime-host/src/pet.rs@@ -373,23 +373,33 @@ impl WorkArea {PET_SIZE * self.unit}- fn pet_at(&self, anchor: (f64, f64)) -> LogicalRect {+ /// Where `frame` puts the window for a pet at `anchor` on this display.+ pub fn window_rect(&self, anchor: (f64, f64), frame: PetFrame) -> LogicalRect {+ let (x, y) = frame.origin(anchor, self.unit);LogicalRect {- x: restored_window_origin(anchor, self.unit).0,- y: restored_window_origin(anchor, self.unit).1,+ x,+ y,width: WINDOW_WIDTH * self.unit,- height: WINDOW_HEIGHT * self.unit,+ height: frame.height * self.unit,}}}-// Shared with pet-mini.css: image top-left (172.5, 449), dock at y=552.+// Shared with pet-mini.css. Bottom layout: image top-left (172.5, 449), dock at+// y=552. Top layout: image top-left (172.5, 12), dock at y=115.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;+/// The image's inset from the window's top in the top layout; it keeps the+/// listening glow (8px above the image) inside the window.+const PET_TOP: f64 = 12.0;// pet-mini.css: the dock starts 103px below the image top and is 40px high.const PET_AND_DOCK_HEIGHT: f64 = 143.0;+/// The strip a dragged window shrinks to: Vibey and its dock, `PET_TOP` above+/// the image and `PET_BOTTOM` below it, at full width. Both layouts draw Vibey+/// at the same place in it, and it is all a drag must keep on the display.+pub const DRAG_HEIGHT: f64 = PET_TOP + PET_SIZE + PET_BOTTOM;/// Distance from the work area's corner for a pet with no saved place.const DEFAULT_MARGIN: f64 = 24.0;@@ -407,9 +417,9 @@ pub enum PanelEdge {Bottom,}-/// Where the panel sits relative to the pet, shared by the native frame and-/// the page. `edge: bottom` aligns the panel's bottom with the pet's, so the-/// panel grows upward.+/// Which side of Vibey the column opens on, shared by the native frame and the+/// page. `edge: bottom` puts Vibey at the bottom of the window, so the column+/// grows upward; `edge: top` puts Vibey at the top and the column grows down.#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]pub struct PetLayout {pub panel_side: PanelSide,@@ -425,23 +435,68 @@ impl Default for PetLayout {}}-pub fn window_size(_expanded: bool) -> (f64, f64) {- (WINDOW_WIDTH, WINDOW_HEIGHT)+impl PetLayout {+ fn edge(panel_edge: PanelEdge) -> Self {+ Self {+ panel_edge,+ ..Self::default()+ }+ }}-/// 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)+/// The native window around the pet: its layout and its height in the pet+/// display's points. The width is always `WINDOW_WIDTH`, and nothing in the+/// page's interaction states changes either.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct PetFrame {+ pub layout: PetLayout,+ pub height: f64,}-pub fn window_origin(anchor: (f64, f64), expanded: bool, layout: PetLayout) -> (f64, f64) {- let (dx, dy) = pet_offset(expanded, layout);- (anchor.0 - dx, anchor.1 - dy)+impl Default for PetFrame {+ fn default() -> Self {+ Self {+ layout: PetLayout::default(),+ height: WINDOW_HEIGHT,+ }+ }}-pub fn anchor_from_window(origin: (f64, f64), expanded: bool, layout: PetLayout) -> (f64, f64) {- let (dx, dy) = pet_offset(expanded, layout);- (origin.0 + dx, origin.1 + dy)+impl PetFrame {+ /// The dragged strip (see `DRAG_HEIGHT`). It keeps `layout`, which places+ /// the image at the same point in it either way.+ pub fn dragging(layout: PetLayout) -> Self {+ Self {+ layout,+ height: DRAG_HEIGHT,+ }+ }++ pub fn size(&self) -> (f64, f64) {+ (WINDOW_WIDTH, self.height)+ }++ /// The image's top-left inside the window, in window points.+ pub fn pet_offset(&self) -> (f64, f64) {+ let x = (WINDOW_WIDTH - PET_SIZE) / 2.0;+ match self.layout.panel_edge {+ PanelEdge::Bottom => (x, self.height - PET_BOTTOM - PET_SIZE),+ PanelEdge::Top => (x, PET_TOP),+ }+ }++ /// The window origin that puts the image on `anchor`, on a display whose+ /// points are `unit` long in the anchor's space.+ pub fn origin(&self, anchor: (f64, f64), unit: f64) -> (f64, f64) {+ let (dx, dy) = self.pet_offset();+ (anchor.0 - dx * unit, anchor.1 - dy * unit)+ }++ /// The anchor (the image's top-left) of a window at `origin`.+ pub fn anchor(&self, origin: (f64, f64), unit: f64) -> (f64, f64) {+ let (dx, dy) = self.pet_offset();+ (origin.0 + dx * unit, origin.1 + dy * unit)+ }}/// Moves a point between two views of one physical desktop, each that desktop@@ -453,13 +508,40 @@ pub fn rescale(point: (f64, f64), from_scale: f64, to_scale: f64) -> (f64, f64)(point.0 * factor, point.1 * factor)}-/// 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 window for a pet at `anchor` on `area` (decision 2026-10-23). The+/// column opens upward, as it always has, while the full window fits above+/// Vibey, or while there is at least as much room above as below; otherwise+/// it flips and opens downward. Either way the window extends from Vibey+/// toward the column only as far as the work area goes, up to its full height,+/// so no part of it is ever off the display: macOS never lets a window rise+/// above the menu bar, so a frame that did would move Vibey instead.+pub fn settle_frame(anchor: (f64, f64), area: &WorkArea) -> PetFrame {+ let unit = area.unit;+ let above = (anchor.1 - area.area.y) / unit;+ let below = (area.area.bottom() - anchor.1) / unit - PET_AND_DOCK_HEIGHT;+ let full_above = WINDOW_HEIGHT - PET_BOTTOM - PET_SIZE;+ if above >= full_above || above >= below {+ return upward_frame(anchor, area);+ }+ PetFrame {+ layout: PetLayout::edge(PanelEdge::Top),+ height: (PET_TOP + PET_AND_DOCK_HEIGHT + below).clamp(DRAG_HEIGHT, WINDOW_HEIGHT),+ }+}++/// The window with the column opening upward whatever the room, as tall as+/// the room above Vibey allows: for a page that predates the top layout (a+/// shell can adopt an older running Runtime). Vibey still stays put.+pub fn upward_frame(anchor: (f64, f64), area: &WorkArea) -> PetFrame {+ let above = (anchor.1 - area.area.y) / area.unit;+ PetFrame {+ layout: PetLayout::default(),+ height: (above + PET_SIZE + PET_BOTTOM).clamp(DRAG_HEIGHT, WINDOW_HEIGHT),+ }}pub fn default_anchor(work_area: &WorkArea) -> PetAnchor {- let (dx, dy) = pet_offset(false, PetLayout::default());+ let (dx, dy) = PetFrame::default().pet_offset();PetAnchor {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,@@ -482,33 +564,28 @@ pub fn area_for(areas: &[WorkArea], anchor: (f64, f64)) -> Option<&WorkArea> {.or_else(|| areas.first())}-/// Where a collapsed pet window starts so the pet sits on `anchor`, on a-/// display whose points are `unit` long in the anchor's space.-pub fn restored_window_origin(anchor: (f64, f64), unit: f64) -> (f64, f64) {- let (dx, dy) = pet_offset(false, PetLayout::default());- (anchor.0 - dx * unit, anchor.1 - dy * unit)-}-/// Keeps a restored pet whole on a connected display. A pet already inside a/// work area stays exactly where it was. Otherwise it moves into the area it/// overlaps most; with no overlap, into its own display if that is still-/// connected, else the first area (the primary display). Use the fixed window-/// on a display that fits it, otherwise preserve access to the image and dock.+/// connected, else the first area (the primary display).+///+/// What must be inside is what a drag must keep on the display: Vibey and the+/// dock with the strip's margins above and below them (`DRAG_HEIGHT`), which+/// leaves room for the window's edge on the column's side in either layout+/// (`settle_frame`). It spans the window's width on a display that fits the+/// whole window, else Vibey's.pub fn clamp_anchor(anchor: &PetAnchor, work_areas: &[WorkArea]) -> PetAnchor {let at = (anchor.x, anchor.y);- 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)+ let unit = area.unit;+ let strip = area.window_rect(at, PetFrame::dragging(PetLayout::default()));+ if area.area.width >= WINDOW_WIDTH * unit && area.area.height >= WINDOW_HEIGHT * unit {+ strip} else {LogicalRect {- height: PET_AND_DOCK_HEIGHT * area.unit,- ..image(area)+ x: anchor.x,+ width: PET_SIZE * unit,+ ..strip}}};@@ -518,6 +595,12 @@ pub fn clamp_anchor(anchor: &PetAnchor, work_areas: &[WorkArea]) -> PetAnchor {..anchor.clone()};}+ let image = |area: &WorkArea| LogicalRect {+ x: anchor.x,+ y: anchor.y,+ width: PET_SIZE * area.unit,+ height: PET_SIZE * area.unit,+ };let overlapping = work_areas.iter().map(|area| (area.area.overlap(&image(area)), area))@@ -544,6 +627,337 @@ pub fn clamp_anchor(anchor: &PetAnchor, work_areas: &[WorkArea]) -> PetAnchor {}}+/// The window for a pet at `anchor`, on the display it is on (else the+/// first): `settle_frame` there, or the full window with no display at all.+pub fn frame_at(anchor: (f64, f64), areas: &[WorkArea]) -> PetFrame {+ area_for(areas, anchor).map_or_else(PetFrame::default, |area| settle_frame(anchor, area))+}++/// Where a dropped pet comes to rest, and the window for it there. A drag can+/// leave the pet partly off every display (Windows lets a window go), so it+/// comes back whole like a restored one, recording the display it is on.+///+/// `monitor` is the display the pet was on before (or the saved one): where+/// the drop overlaps no work area, it comes back there rather than onto the+/// primary display.+pub fn place_dropped(dropped: (f64, f64), areas: &[WorkArea], monitor: Option<String>) -> (PetAnchor, PetFrame) {+ let anchor = clamp_anchor(+ &PetAnchor {+ x: dropped.0,+ y: dropped.1,+ monitor,+ },+ areas,+ );+ let frame = frame_at((anchor.x, anchor.y), areas);+ (anchor, frame)+}++/// Where a pet moved by something other than the shell's own drag comes to+/// rest, and its window: the platform after a display change, or an older+/// page dragging the window natively. Like a drop (`place_dropped`), except+/// that a page without the top layout always gets the upward window.+pub fn place_moved(+ moved: (f64, f64),+ areas: &[WorkArea],+ monitor: Option<String>,+ page_layouts: bool,+) -> (PetAnchor, PetFrame) {+ let (anchor, frame) = place_dropped(moved, areas, monitor);+ if page_layouts {+ return (anchor, frame);+ }+ let at = (anchor.x, anchor.y);+ let frame = area_for(areas, at).map_or_else(PetFrame::default, |area| upward_frame(at, area));+ (anchor, frame)+}++/// The layout the page should draw, and its revision. The shell is its only+/// source (spec §9.1): the page reads it from `pet_ready` and from the layout+/// event, keeps only a newer revision, and acknowledges each one it draws.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]+pub struct LayoutSnapshot {+ pub revision: u64,+ pub layout: PetLayout,+}++/// What the shell does with the native window after a `FrameState` step.+#[derive(Clone, Copy, Debug, PartialEq)]+pub enum FrameStep {+ /// The window stays as it is.+ Keep,+ /// Put the window at `anchor` (window points) as `frame`, now.+ Apply { frame: PetFrame, anchor: (f64, f64) },+ /// Tell the page to draw `snapshot`; its frame waits for the page's+ /// acknowledgement of that revision, or for `expire(publication)`. Every+ /// publication has a new id, so a later one voids an earlier one's timer.+ Publish { snapshot: LayoutSnapshot, publication: u64 },+}++#[derive(Clone, Copy, Debug, PartialEq)]+struct Held {+ frame: PetFrame,+ anchor: (f64, f64),+ revision: u64,+ /// The latest publication of this frame; only its timer may expire it.+ publication: u64,+}++/// What the document in the pet window can draw.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum PageKind {+ /// A document is loading and has not said yet (`pet_ready`).+ Loading,+ /// It draws the shell's layout snapshots and acknowledges them.+ Layouts,+ /// It predates the top layout: it only draws the upward column and never+ /// acknowledges anything.+ Legacy,+}++#[derive(Clone, Copy, Debug, PartialEq)]+struct Drag {+ before: PetFrame,+ anchor: (f64, f64),+}++/// The pet window's frame, owned by the shell, and the layout its page must+/// draw. Every source of change is an event here: a new window, a document+/// loading or ready, a drag starting, ending or failing, a move, an+/// acknowledgement, a timeout. The shell only carries out the returned step.+///+/// - A change of layout is never shown in the full window before the page+/// has drawn it: the frame is held until that revision is acknowledged.+/// While the page's kind is unknown (loading) nothing held is released; an+/// older page gets the upward window instead, at once.+/// - Every drag ends idle or holding: a drag that does not end with a+/// placement goes back to the frame and anchor it started from.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct FrameState {+ current: PetFrame,+ drag: Option<Drag>,+ held: Option<Held>,+ snapshot: LayoutSnapshot,+ page: PageKind,+ publications: u64,+}++impl FrameState {+ pub fn new(frame: PetFrame) -> Self {+ Self {+ current: frame,+ drag: None,+ held: None,+ snapshot: LayoutSnapshot {+ revision: 1,+ layout: frame.layout,+ },+ page: PageKind::Loading,+ publications: 0,+ }+ }++ /// A new window, whose document is loading. Revisions and publications+ /// keep growing, so an answer or a timer meant for the old window can+ /// never match the new one.+ pub fn rebuild(&mut self, frame: PetFrame) {+ let (revision, publications) = (self.snapshot.revision + 1, self.publications);+ *self = Self::new(frame);+ self.snapshot.revision = revision;+ self.publications = publications;+ }++ pub fn current(&self) -> PetFrame {+ self.current+ }++ pub fn snapshot(&self) -> LayoutSnapshot {+ self.snapshot+ }++ pub fn page(&self) -> PageKind {+ self.page+ }++ /// Whether frames are chosen as for a page that draws layouts: also while+ /// the page is loading, because nothing is released until it says.+ pub fn draws_layouts(&self) -> bool {+ self.page != PageKind::Legacy+ }++ /// The shell's own drag, or a frame waiting for its page: both place the+ /// window themselves, so nothing else may.+ pub fn busy(&self) -> bool {+ self.drag.is_some() || self.held.is_some()+ }++ /// The window's document is loading (a reload, or a navigation).+ pub fn page_loading(&mut self) {+ self.page = PageKind::Loading;+ }++ /// The document said what it draws (`pet_ready`); the window now shows+ /// the pet at `anchor`, and `upward` is the upward window for a pet at a+ /// given anchor. A frame held for a page that draws layouts is published+ /// again (its expiry starts over). An older page gets the upward window,+ /// now, in place of a held frame or of a current one in the top layout.+ pub fn page_ready(+ &mut self,+ kind: PageKind,+ anchor: (f64, f64),+ upward: impl Fn((f64, f64)) -> PetFrame,+ ) -> FrameStep {+ self.page = kind;+ if kind == PageKind::Layouts {+ return self.publish();+ }+ // Mid-drag, the frame a failed drag would go back to becomes upward too.+ if let Some(drag) = self.drag.as_mut() {+ if drag.before.layout != PetLayout::default() {+ drag.before = upward(drag.anchor);+ }+ return FrameStep::Keep;+ }+ if let Some(held) = self.held.take() {+ return self.apply(upward(held.anchor), held.anchor);+ }+ if self.current.layout == PetLayout::default() {+ return FrameStep::Keep;+ }+ self.apply(upward(anchor), anchor)+ }++ /// Starts the shell's drag from a pet at `anchor`: returns the strip to+ /// apply, or `None` while another drag runs or a frame waits for its page.+ pub fn begin_drag(&mut self, anchor: (f64, f64)) -> Option<PetFrame> {+ // Only a page known to draw layouts drags through the shell: until it+ // has said so, a drop could only be held with nobody to release it.+ if self.busy() || self.page != PageKind::Layouts {+ return None;+ }+ self.drag = Some(Drag {+ before: self.current,+ anchor,+ });+ self.current = PetFrame::dragging(self.current.layout);+ Some(self.current)+ }++ /// The drag ended with the pet at `anchor`, framed `next` (chosen as+ /// `draws_layouts` says). It is held until the page draws its revision,+ /// unless the page is an older one, which gets it at once.+ pub fn end_drag(&mut self, next: PetFrame, anchor: (f64, f64)) -> FrameStep {+ if self.drag.take().is_none() {+ return FrameStep::Keep;+ }+ if self.page == PageKind::Legacy {+ self.apply(next, anchor)+ } else {+ self.hold(next, anchor)+ }+ }++ /// The drag did not end with a placement (the native drag did not start,+ /// or the window could not be read when it ended): back to the frame and+ /// anchor it started from. Without a drag it changes nothing.+ pub fn abort_drag(&mut self) -> FrameStep {+ let Some(drag) = self.drag.take() else {+ return FrameStep::Keep;+ };+ // The frame it goes back to may no longer be the layout the page draws+ // (an older page became ready meanwhile, then a newer one): like any+ // other change of layout, the page draws it first.+ if self.draws_layouts() && drag.before.layout != self.snapshot.layout {+ return self.hold(drag.before, drag.anchor);+ }+ self.apply(drag.before, drag.anchor)+ }++ /// Something other than the shell's drag moved the window; `next` is the+ /// window for where it now is (chosen as `draws_layouts` says). Ignored+ /// while the shell places it itself.+ pub fn follow(&mut self, next: PetFrame, anchor: (f64, f64), moved: bool) -> FrameStep {+ if self.busy() {+ return FrameStep::Keep;+ }+ if self.draws_layouts() && next.layout != self.current.layout {+ return self.hold(next, anchor);+ }+ if !moved && next == self.current {+ return FrameStep::Keep;+ }+ self.apply(next, anchor)+ }++ /// The page drew `revision`. Only the waiting frame's own revision, from a+ /// page that draws layouts, releases it; anything else changes nothing.+ pub fn ack(&mut self, revision: u64) -> FrameStep {+ self.release(revision)+ }++ /// The timer of `publication` ran out without an acknowledgement: its+ /// frame applies anyway, if that is still the latest publication of the+ /// frame waiting and the page has said it draws layouts.+ pub fn expire(&mut self, publication: u64) -> FrameStep {+ match self.held {+ Some(held) if held.publication == publication => self.release(held.revision),+ _ => FrameStep::Keep,+ }+ }++ fn release(&mut self, revision: u64) -> FrameStep {+ match self.held {+ Some(held) if held.revision == revision && self.page == PageKind::Layouts => {+ self.held = None;+ self.current = held.frame;+ FrameStep::Apply {+ frame: held.frame,+ anchor: held.anchor,+ }+ }+ _ => FrameStep::Keep,+ }+ }++ fn hold(&mut self, frame: PetFrame, anchor: (f64, f64)) -> FrameStep {+ self.snapshot = LayoutSnapshot {+ revision: self.snapshot.revision + 1,+ layout: frame.layout,+ };+ self.held = Some(Held {+ frame,+ anchor,+ revision: self.snapshot.revision,+ publication: 0,+ });+ self.publish()+ }++ /// Publishes the waiting frame's snapshot under a new publication id.+ fn publish(&mut self) -> FrameStep {+ let Some(held) = self.held.as_mut() else {+ return FrameStep::Keep;+ };+ self.publications += 1;+ held.publication = self.publications;+ FrameStep::Publish {+ snapshot: self.snapshot,+ publication: self.publications,+ }+ }++ fn apply(&mut self, frame: PetFrame, anchor: (f64, f64)) -> FrameStep {+ if frame.layout != self.snapshot.layout {+ self.snapshot = LayoutSnapshot {+ revision: self.snapshot.revision + 1,+ layout: frame.layout,+ };+ }+ self.current = frame;+ FrameStep::Apply { frame, anchor }+ }+}+/// Window-local logical coordinates; shadows deliberately do not enlarge these.#[derive(Clone, Copy, Debug, Deserialize)]pub struct HitRect {@@ -923,55 +1337,744 @@ mod tests {}#[test]- fn the_anchor_is_the_pet_image_whichever_way_the_panel_opened() {+ fn the_anchor_is_the_pet_image_in_every_frame() {let anchor = (1000.0, 700.0);- for expanded in [false, true] {+ for unit in [1.0, 1.25, 2.0] {for panel_side in [PanelSide::Left, PanelSide::Right] {for panel_edge in [PanelEdge::Top, PanelEdge::Bottom] {let layout = PetLayout { panel_side, panel_edge };- let origin = window_origin(anchor, expanded, layout);- assert_eq!(anchor_from_window(origin, expanded, layout), anchor);- let (width, height) = window_size(expanded);- let (dx, dy) = pet_offset(expanded, layout);- assert!(dx >= 0.0 && dx + PET_SIZE <= width && dy >= 0.0 && dy + PET_SIZE <= height);+ for frame in [+ PetFrame {+ layout,+ height: WINDOW_HEIGHT,+ },+ PetFrame { layout, height: 420.0 },+ PetFrame::dragging(layout),+ ] {+ let origin = frame.origin(anchor, unit);+ assert_eq!(frame.anchor(origin, unit), anchor);+ let (width, height) = frame.size();+ let (dx, dy) = frame.pet_offset();+ assert!(dx >= 0.0 && dy >= 0.0 && dx + PET_SIZE <= width);+ assert!(dy + PET_AND_DOCK_HEIGHT <= height, "the dock is inside the window");+ }}}}- // Expansion changes no geometry in the fixed mini window.+ // The dragged strip draws Vibey at the same place in either layout,+ // so a flip on drop needs no move while the window is the strip.assert_eq!(- window_origin(anchor, false, PetLayout::default()),- window_origin(anchor, true, PetLayout::default())+ PetFrame::dragging(PetLayout::edge(PanelEdge::Top)).pet_offset(),+ PetFrame::dragging(PetLayout::edge(PanelEdge::Bottom)).pet_offset());+ assert_eq!(DRAG_HEIGHT, 163.0);+ // The default (bottom) frame keeps today's image box.+ assert_eq!(PetFrame::default().pet_offset(), (172.5, 449.0));+ assert_eq!(PetFrame::default().size(), (WINDOW_WIDTH, WINDOW_HEIGHT));}#[test]- 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,- };- for anchor in [(1300.0, 780.0), (20.0, 40.0), (700.0, 450.0)] {- let layout = choose_layout(anchor, screen);- assert_eq!(layout, PetLayout::default());+ fn the_column_opens_toward_its_room_and_the_window_never_leaves_the_display() {+ // A 13-inch MacBook's work area below the menu bar, a 125% 1366x768+ // laptop above a taskbar, and a tall external display.+ for area in [+ area("laptop", 0.0, 33.0, 1470.0, 923.0),+ area("small", 0.0, 0.0, 1093.0, 574.0),+ area("tall", 1470.0, -400.0, 1440.0, 1415.0),+ WorkArea {+ unit: 2.0,+ ..area("dense", 0.0, 0.0, 2880.0, 1800.0)+ },+ ] {+ let unit = area.unit;+ let top = area.area.y + PET_TOP * unit;+ let bottom = area.area.bottom() - (PET_SIZE + PET_BOTTOM) * unit;+ let mut y = top;+ while y <= bottom {+ let anchor = (area.area.x + 400.0 * unit, y);+ let frame = settle_frame(anchor, &area);+ let window = area.window_rect(anchor, frame);+ assert!(area.area.contains(&window), "{:?} at {y}: {window:?}", area.name);+ assert_eq!(+ frame.anchor(frame.origin(anchor, unit), unit),+ anchor,+ "Vibey stays put"+ );+ assert!((DRAG_HEIGHT..=WINDOW_HEIGHT).contains(&frame.height));+ let above = (y - area.area.y) / unit;+ let below = (area.area.bottom() - y) / unit - PET_AND_DOCK_HEIGHT;+ let flipped = frame.layout.panel_edge == PanelEdge::Top;+ assert_eq!(flipped, above < 449.0 && below > above, "{:?} at {y}", area.name);+ // The column gets the full window whenever its side has room.+ let room = if flipped {+ PET_TOP + PET_AND_DOCK_HEIGHT + below+ } else {+ above + 151.0+ };+ assert_eq!(frame.height, room.min(WINDOW_HEIGHT));+ y += 7.0 * unit;+ }}- let area = WorkArea {- name: Some("primary".into()),- area: screen,- unit: 1.0,- };- let anchor = default_anchor(&area);- let origin = window_origin((anchor.x, anchor.y), false, PetLayout::default());++ let laptop = area("laptop", 0.0, 33.0, 1470.0, 923.0);+ // Dragged to the very top: the column drops below Vibey, full height.+ let at_top = settle_frame((600.0, 45.0), &laptop);+ assert_eq!(+ at_top,+ PetFrame {+ layout: PetLayout::edge(PanelEdge::Top),+ height: WINDOW_HEIGHT+ }+ );+ assert_eq!(laptop.window_rect((600.0, 45.0), at_top).y, 33.0);+ // Room for the full column above: today's layout and window.+ assert_eq!(settle_frame((600.0, 600.0), &laptop), PetFrame::default());+ // Between the two, the larger side wins and the window stops at the+ // menu bar instead of moving Vibey down.+ let middle = settle_frame((600.0, 433.0), &laptop);+ assert_eq!(+ middle,+ PetFrame {+ layout: PetLayout::default(),+ height: 551.0+ }+ );+ assert_eq!(laptop.window_rect((600.0, 433.0), middle).y, 33.0);+ assert_eq!(settle_frame((600.0, 333.0), &laptop).layout.panel_edge, PanelEdge::Top);++ let anchor = default_anchor(&laptop);+ let origin = PetFrame::default().origin((anchor.x, anchor.y), 1.0);assert_eq!(origin,(- screen.right() - WINDOW_WIDTH - DEFAULT_MARGIN,- screen.bottom() - WINDOW_HEIGHT - DEFAULT_MARGIN+ laptop.area.right() - WINDOW_WIDTH - DEFAULT_MARGIN,+ laptop.area.bottom() - WINDOW_HEIGHT - DEFAULT_MARGIN+ )+ );+ assert_eq!(settle_frame((anchor.x, anchor.y), &laptop), PetFrame::default());+ }++ #[test]+ fn a_page_without_the_top_layout_gets_an_upward_window_that_keeps_vibey_put() {+ let laptop = area("laptop", 0.0, 33.0, 1470.0, 923.0);+ for y in [45.0, 200.0, 433.0, 700.0] {+ let frame = upward_frame((600.0, y), &laptop);+ assert_eq!(frame.layout, PetLayout::default());+ let window = laptop.window_rect((600.0, y), frame);+ assert!(laptop.area.contains(&window), "{y}: {window:?}");+ assert_eq!(frame.anchor(frame.origin((600.0, y), 1.0), 1.0), (600.0, y));+ }+ // Near the top the window is only the strip; with room it is whole.+ assert_eq!(upward_frame((600.0, 45.0), &laptop).height, DRAG_HEIGHT);+ assert_eq!(upward_frame((600.0, 700.0), &laptop), PetFrame::default());+ // Where the column opens upward anyway, both choices agree.+ assert_eq!(+ settle_frame((600.0, 433.0), &laptop),+ upward_frame((600.0, 433.0), &laptop)+ );+ }++ #[test]+ fn a_pet_moved_outside_a_shell_drag_gets_the_window_for_where_it_now_is() {+ let laptop = area("laptop", 0.0, 33.0, 1470.0, 923.0);+ let short = area("short", 0.0, 0.0, 1093.0, 574.0);+ // An older page dragged its strip-high window down: the upward+ // window grows back to its full height.+ let (anchor, frame) = place_moved((600.0, 700.0), std::slice::from_ref(&laptop), None, false);+ assert_eq!((anchor.x, anchor.y), (600.0, 700.0));+ assert_eq!(frame, PetFrame::default());+ // Near the top an older page still opens upward; a current one flips.+ assert_eq!(+ place_moved((600.0, 45.0), std::slice::from_ref(&laptop), None, false)+ .1+ .layout,+ PetLayout::default()+ );+ assert_eq!(+ place_moved((600.0, 45.0), std::slice::from_ref(&laptop), None, true)+ .1+ .layout+ .panel_edge,+ PanelEdge::Top+ );+ // The display it was on is gone: it lands whole on the remaining one,+ // in a window that fits its height (a display narrower than the full+ // window keeps Vibey, not the transparent sides, inside).+ let (anchor, frame) = place_moved((3000.0, 900.0), std::slice::from_ref(&short), None, true);+ let window = short.window_rect((anchor.x, anchor.y), frame);+ assert!(window.y >= short.area.y && window.bottom() <= short.area.bottom());+ assert!(anchor.x + PET_SIZE <= short.area.right());+ assert_eq!(anchor.monitor.as_deref(), Some("short"));+ }++ /// A page in the model: the document now showing, what it draws, and+ /// what it drew.+ #[derive(Clone, Copy)]+ struct Page {+ document: u32,+ kind: PageKind,+ drawn: Option<LayoutSnapshot>,+ }++ enum Message {+ /// Shell to page: a snapshot (layout event), for the document it was+ /// sent to. The page draws and acknowledges only a newer revision.+ Snapshot(u32, LayoutSnapshot),+ /// Shell to page: the `pet_ready` reply's snapshot, which the page+ /// always acknowledges (it may have drawn that revision from an event+ /// that arrived while the shell still took it for loading).+ ReadySnapshot(u32, LayoutSnapshot),+ /// The document finishes loading and calls `pet_ready`; the first+ /// `attempts` calls fail (and are retried) without reaching the shell.+ Ready(u32, PageKind, u32),+ /// Page to shell: `pet_settle(revision)` for the layout it drew.+ Ack(u64, PetLayout),+ }++ const UPWARD: PetFrame = PetFrame {+ layout: PetLayout {+ panel_side: PanelSide::Left,+ panel_edge: PanelEdge::Bottom,+ },+ height: 380.0,+ };++ #[test]+ fn the_frame_state_keeps_its_invariants_whatever_the_interleaving() {+ let frames = [+ PetFrame::default(),+ PetFrame {+ layout: PetLayout::edge(PanelEdge::Top),+ height: WINDOW_HEIGHT,+ },+ PetFrame {+ layout: PetLayout::default(),+ height: 420.0,+ },+ PetFrame {+ layout: PetLayout::edge(PanelEdge::Top),+ height: 300.0,+ },+ ];+ let upward = |_: (f64, f64)| UPWARD;+ // A small deterministic generator: many seeds, no shared randomness.+ for seed in 1..2000u64 {+ let mut next = seed;+ let mut roll = |n: u64| {+ next = next.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);+ (next >> 33) % n+ };+ let mut state = FrameState::new(frames[0]);+ let mut page = Page {+ document: 0,+ kind: PageKind::Layouts,+ drawn: None,+ };+ let mut queue: Vec<Message> = vec![Message::Ready(0, PageKind::Layouts, 0)];+ let mut published = vec![0];+ let mut latest = 0;+ // A frame for wherever the pet is, chosen as the shell would.+ let place = |state: &FrameState, pick: u64| {+ if state.draws_layouts() {+ frames[pick as usize]+ } else {+ UPWARD+ }+ };+ for _ in 0..80 {+ let revision = state.snapshot().revision;+ let step = match roll(10) {+ 0 => {+ let kind = state.page();+ if let Some(strip) = state.begin_drag((1.0, 1.0)) {+ assert_eq!(strip.height, DRAG_HEIGHT);+ assert_eq!(+ kind,+ PageKind::Layouts,+ "seed {seed}: a shell drag while the page's kind was not known"+ );+ }+ FrameStep::Keep+ }+ 1 => {+ let frame = place(&state, roll(4));+ let step = if roll(3) == 0 {+ state.abort_drag()+ } else {+ state.end_drag(frame, (2.0, 2.0))+ };+ // However a drag ends, the machine is idle or holding.+ assert!(state.drag.is_none(), "seed {seed}: a drag ended still dragging");+ step+ }+ 2 => {+ let frame = place(&state, roll(4));+ state.follow(frame, (3.0, 3.0), roll(2) == 0)+ }+ 3 => {+ // The document reloads: a newer page, or sometimes an older one.+ let kind = if roll(4) == 0 {+ PageKind::Legacy+ } else {+ PageKind::Layouts+ };+ page = Page {+ document: page.document + 1,+ kind,+ drawn: None,+ };+ state.page_loading();+ queue.push(Message::Ready(page.document, kind, roll(3) as u32));+ FrameStep::Keep+ }+ 4 => {+ // Any timer, current or voided, may fire.+ let timer = published[roll(published.len() as u64) as usize];+ let step = state.expire(timer);+ released(&state, step, seed);+ if matches!(step, FrameStep::Apply { .. }) {+ assert_eq!(timer, latest, "seed {seed}: a voided timer released a frame");+ }+ step+ }+ _ => {+ if queue.is_empty() {+ FrameStep::Keep+ } else {+ let index = roll(queue.len() as u64) as usize;+ deliver(&mut state, &mut page, &mut queue, index, &upward, seed)+ }+ }+ };+ if let FrameStep::Publish { snapshot, publication } = step {+ queue.push(Message::Snapshot(page.document, snapshot));+ assert!(publication > latest, "seed {seed}: publication ids only grow");+ published.push(publication);+ latest = publication;+ }+ assert!(+ state.snapshot().revision >= revision,+ "seed {seed}: revisions only grow"+ );+ if !state.busy() {+ assert_eq!(+ state.snapshot().layout,+ state.current().layout,+ "seed {seed}: idle in another layout"+ );+ }+ }+ // Quiescence: the drag ends one way or the other, everything is+ // delivered, and the page draws the layout of the window shown.+ let step = if roll(2) == 0 {+ state.abort_drag()+ } else {+ let frame = place(&state, roll(4));+ state.end_drag(frame, (4.0, 4.0))+ };+ assert!(state.drag.is_none(), "seed {seed}: a drag ended still dragging");+ if let FrameStep::Publish { snapshot, .. } = step {+ queue.push(Message::Snapshot(page.document, snapshot));+ }+ while !queue.is_empty() {+ deliver(&mut state, &mut page, &mut queue, 0, &upward, seed);+ }+ assert!(+ !state.busy(),+ "seed {seed}: a frame is still held after its page answered"+ );+ match page.kind {+ PageKind::Layouts => {+ let drawn = page.drawn.expect("the current document read a snapshot");+ assert_eq!(drawn, state.snapshot(), "seed {seed}");+ assert_eq!(drawn.layout, state.current().layout, "seed {seed}");+ }+ PageKind::Legacy => assert_eq!(state.current().layout, PetLayout::default(), "seed {seed}"),+ PageKind::Loading => unreachable!(),+ }+ }+ }++ /// Delivers `queue[index]`, as the shell or the page would handle it.+ fn deliver(+ state: &mut FrameState,+ page: &mut Page,+ queue: &mut Vec<Message>,+ index: usize,+ upward: &impl Fn((f64, f64)) -> PetFrame,+ seed: u64,+ ) -> FrameStep {+ match queue.remove(index) {+ Message::Snapshot(document, snapshot) => {+ let newer = page.drawn.is_none_or(|drawn| snapshot.revision > drawn.revision);+ if document == page.document && page.kind == PageKind::Layouts && newer {+ page.drawn = Some(snapshot);+ queue.push(Message::Ack(snapshot.revision, snapshot.layout));+ }+ FrameStep::Keep+ }+ Message::ReadySnapshot(document, snapshot) => {+ if document == page.document && page.kind == PageKind::Layouts {+ let drawn = match page.drawn {+ Some(drawn) if drawn.revision > snapshot.revision => drawn,+ _ => snapshot,+ };+ page.drawn = Some(drawn);+ queue.push(Message::Ack(drawn.revision, drawn.layout));+ }+ FrameStep::Keep+ }+ Message::Ready(document, kind, attempts) => {+ if document != page.document {+ return FrameStep::Keep;+ }+ if attempts > 0 {+ // The call failed on its way: the page retries it later.+ queue.push(Message::Ready(document, kind, attempts - 1));+ return FrameStep::Keep;+ }+ let step = state.page_ready(kind, (9.0, 9.0), upward);+ if kind == PageKind::Layouts {+ // `pet_ready`'s reply carries the snapshot.+ queue.push(Message::ReadySnapshot(document, state.snapshot()));+ }+ step+ }+ Message::Ack(acked, drawn) => {+ let before = *state;+ let step = state.ack(acked);+ if let FrameStep::Apply { frame, .. } = step {+ assert_eq!(+ frame.layout, drawn,+ "seed {seed}: a held frame came back in another layout"+ );+ released(state, step, seed);+ } else {+ assert_eq!(*state, before, "seed {seed}: a stale acknowledgement changed something");+ }+ step+ }+ }+ }++ /// A held frame released (by an acknowledgement or an expiry): never in+ /// the top layout unless the page has said it draws layouts.+ fn released(state: &FrameState, step: FrameStep, seed: u64) {+ if let FrameStep::Apply { frame, .. } = step {+ if frame.layout.panel_edge == PanelEdge::Top {+ assert_eq!(+ state.page(),+ PageKind::Layouts,+ "seed {seed}: a flipped frame was released while the page could not draw it"+ );+ }+ }+ }++ #[test]+ fn a_frame_change_waits_for_its_page_only_when_the_layout_changes() {+ let top = PetFrame {+ layout: PetLayout::edge(PanelEdge::Top),+ height: WINDOW_HEIGHT,+ };+ let upward = |_: (f64, f64)| UPWARD;+ let mut state = FrameState::new(PetFrame::default());+ assert_eq!(state.page_ready(PageKind::Layouts, (0.0, 0.0), upward), FrameStep::Keep);+ // A shorter window in the same layout applies at once.+ let shorter = PetFrame {+ height: 420.0,+ ..PetFrame::default()+ };+ assert_eq!(+ state.follow(shorter, (1.0, 2.0), true),+ FrameStep::Apply {+ frame: shorter,+ anchor: (1.0, 2.0)+ }+ );+ assert_eq!(state.snapshot().revision, 1);+ // Another layout is held and published.+ let FrameStep::Publish { snapshot, .. } = state.follow(top, (1.0, 2.0), true) else {+ panic!()+ };+ assert_eq!(+ snapshot,+ LayoutSnapshot {+ revision: 2,+ layout: top.layout+ }+ );+ assert!(state.busy());+ assert_eq!(+ state.follow(PetFrame::default(), (0.0, 0.0), true),+ FrameStep::Keep,+ "held: nothing else places it"+ );+ assert_eq!(+ state.begin_drag((0.0, 0.0)),+ None,+ "no drag while a frame waits for its page"+ );+ assert_eq!(state.ack(1), FrameStep::Keep);+ assert_eq!(+ state.ack(2),+ FrameStep::Apply {+ frame: top,+ anchor: (1.0, 2.0)+ }+ );+ assert_eq!(+ state.ack(2),+ FrameStep::Keep,+ "a duplicate acknowledgement changes nothing"+ );+ // Every drop is held for a page that draws layouts, even in the same+ // layout, so its full window returns only after the page has drawn.+ let strip = state.begin_drag((1.0, 2.0)).unwrap();+ assert_eq!(strip.height, DRAG_HEIGHT);+ assert_eq!(state.begin_drag((1.0, 2.0)), None);+ let FrameStep::Publish { snapshot, publication } = state.end_drag(top, (3.0, 4.0)) else {+ panic!()+ };+ assert_eq!(snapshot.revision, 3);+ assert_eq!(+ state.expire(publication),+ FrameStep::Apply {+ frame: top,+ anchor: (3.0, 4.0)+ }+ );+ // A drag that does not end with a placement goes back where it began.+ state.begin_drag((3.0, 4.0));+ assert_eq!(+ state.abort_drag(),+ FrameStep::Apply {+ frame: top,+ anchor: (3.0, 4.0)+ }+ );+ assert!(!state.busy());+ assert_eq!(state.abort_drag(), FrameStep::Keep);+ // A new window keeps revisions growing, and its page is loading.+ state.rebuild(top);+ assert_eq!(+ state.snapshot(),+ LayoutSnapshot {+ revision: 4,+ layout: top.layout+ }+ );+ assert_eq!(state.page(), PageKind::Loading);+ }++ #[test]+ fn nothing_held_is_released_before_the_page_says_what_it_draws() {+ let top = PetFrame {+ layout: PetLayout::edge(PanelEdge::Top),+ height: WINDOW_HEIGHT,+ };+ let upward = |anchor: (f64, f64)| PetFrame {+ height: anchor.1,+ ..PetFrame::default()+ };+ // No shell drag before the page has said it draws layouts.+ let mut state = FrameState::new(PetFrame::default());+ assert_eq!(state.begin_drag((0.0, 0.0)), None, "loading: no shell drag");+ state.page_ready(PageKind::Layouts, (0.0, 0.0), upward);+ // A drag that started under it, dropped while a replacement document+ // loads: held, through its timer and the old document's answer.+ state.begin_drag((0.0, 0.0)).unwrap();+ state.page_loading();+ let FrameStep::Publish { snapshot, publication } = state.end_drag(top, (5.0, 200.0)) else {+ panic!()+ };+ assert_eq!(state.expire(publication), FrameStep::Keep);+ assert_eq!(+ state.ack(snapshot.revision),+ FrameStep::Keep,+ "the old document's answer does not count"+ );+ // A page that draws layouts: published again under a new id, which+ // voids the first timer; its own answer releases the frame.+ let mut layouts = state;+ let FrameStep::Publish {+ snapshot: again,+ publication: renewed,+ } = layouts.page_ready(PageKind::Layouts, (0.0, 0.0), upward)+ else {+ panic!()+ };+ assert_eq!(again, snapshot);+ assert!(renewed > publication);+ assert_eq!(+ layouts.expire(publication),+ FrameStep::Keep,+ "the voided timer fires after the re-publication"+ );+ assert_eq!(+ layouts.ack(snapshot.revision),+ FrameStep::Apply {+ frame: top,+ anchor: (5.0, 200.0)+ }+ );+ // The renewed timer, had it fired first, would have released it.+ let mut timed = state;+ let FrameStep::Publish {+ publication: renewed, ..+ } = timed.page_ready(PageKind::Layouts, (0.0, 0.0), upward)+ else {+ panic!()+ };+ assert!(matches!(timed.expire(renewed), FrameStep::Apply { .. }));+ // An older page: the upward window for the same spot, at once.+ let mut legacy = state;+ assert_eq!(+ legacy.page_ready(PageKind::Legacy, (0.0, 0.0), upward),+ FrameStep::Apply {+ frame: PetFrame {+ height: 200.0,+ ..PetFrame::default()+ },+ anchor: (5.0, 200.0)+ }+ );+ assert!(!legacy.busy());+ assert_eq!(legacy.snapshot().layout, PetLayout::default());+ // A window already in the top layout, when an older page becomes+ // ready, becomes the upward window at the spot the window shows.+ let mut flipped = FrameState::new(top);+ assert_eq!(+ flipped.page_ready(PageKind::Legacy, (8.0, 150.0), upward),+ FrameStep::Apply {+ frame: PetFrame {+ height: 150.0,+ ..PetFrame::default()+ },+ anchor: (8.0, 150.0)+ }+ );+ // An older page never drags through the shell, and its moves apply at once.+ assert_eq!(legacy.begin_drag((5.0, 200.0)), None);+ assert!(matches!(+ legacy.follow(UPWARD, (7.0, 7.0), true),+ FrameStep::Apply { .. }+ ));+ }++ #[test]+ fn a_pet_dropped_off_every_display_returns_to_the_one_it_came_from() {+ // Windows lets a drag end with Vibey above a secondary display, on no+ // work area at all.+ let areas = [+ area("primary", 0.0, 0.0, 1920.0, 1040.0),+ area("secondary", 1920.0, 0.0, 1920.0, 1040.0),+ ];+ let above = (2600.0, -600.0);+ let (anchor, frame) = place_dropped(above, &areas, Some("secondary".into()));+ assert_eq!(anchor.monitor.as_deref(), Some("secondary"));+ assert!(areas[1]+ .area+ .contains(&areas[1].window_rect((anchor.x, anchor.y), frame)));+ assert_eq!(anchor.x, 2600.0, "only pulled down onto it");+ // Without its display it would land on the primary one.+ assert_eq!(place_dropped(above, &areas, None).0.monitor.as_deref(), Some("primary"));+ // A display that is gone gives way to the primary one.+ assert_eq!(+ place_dropped(above, &areas[..1], Some("secondary".into()))+ .0+ .monitor+ .as_deref(),+ Some("primary")+ );+ // A drop that overlaps a display keeps that one, whatever it came from.+ assert_eq!(+ place_dropped((500.0, 300.0), &areas, Some("secondary".into()))+ .0+ .monitor+ .as_deref(),+ Some("primary")+ );+ assert_eq!(+ place_moved(above, &areas, Some("secondary".into()), true)+ .0+ .monitor+ .as_deref(),+ Some("secondary")+ );+ }++ #[test]+ fn a_dropped_pet_stays_where_it_lands_unless_it_left_every_display() {+ let areas = [+ area("laptop", 0.0, 33.0, 1470.0, 923.0),+ area("external", 1470.0, -400.0, 1440.0, 1415.0),+ ];+ // Dropped at the top of the laptop: it stays, and its column flips.+ let (anchor, frame) = place_dropped((600.0, 45.0), &areas, None);+ assert_eq!(+ (anchor.x, anchor.y, anchor.monitor.as_deref()),+ (600.0, 45.0, Some("laptop"))+ );+ assert_eq!(frame.layout.panel_edge, PanelEdge::Top);+ // Halfway up the external display: today's layout, the full window.+ let (anchor, frame) = place_dropped((2000.0, 300.0), &areas, None);+ assert_eq!(+ (anchor.x, anchor.y, anchor.monitor.as_deref()),+ (2000.0, 300.0, Some("external"))+ );+ assert_eq!(frame, PetFrame::default());+ // Partly off the laptop's top-left corner: it comes back whole, just+ // inside, with its column below it.+ let (anchor, frame) = place_dropped((-80.0, 10.0), &areas, None);+ assert_eq!((anchor.x, anchor.y), (172.5, 33.0 + 12.0));+ assert_eq!(frame.layout.panel_edge, PanelEdge::Top);+ assert!(areas[0]+ .area+ .contains(&areas[0].window_rect((anchor.x, anchor.y), frame)));+ // Without any display information nothing moves.+ assert_eq!(+ place_dropped((5.0, 6.0), &[], None),+ (+ PetAnchor {+ x: 5.0,+ y: 6.0,+ monitor: None+ },+ PetFrame::default()));}+ #[test]+ fn a_display_change_settles_the_same_spot_in_the_new_display_points() {+ // The saved pet sits near the top of a 100% display, which is then+ // replaced by a 200% one of the same point size: the same anchor+ // flips and fills the same points, now twice as many pixels.+ let anchor = (500.0, 60.0);+ let plain = area("display", 0.0, 0.0, 1440.0, 900.0);+ let dense = WorkArea {+ unit: 2.0,+ ..plain.clone()+ };+ let before = settle_frame(anchor, &plain);+ assert_eq!(before.layout.panel_edge, PanelEdge::Top);+ // On the dense display the strip needs twice the room above Vibey.+ let clamped = clamp_anchor(+ &PetAnchor {+ x: anchor.0,+ y: anchor.1 - 50.0,+ monitor: Some("display".into()),+ },+ std::slice::from_ref(&dense),+ );+ assert_eq!(clamped.y, PET_TOP * 2.0);+ let after = settle_frame((clamped.x, clamped.y), &dense);+ assert_eq!(after.layout.panel_edge, PanelEdge::Top);+ assert!(dense.area.contains(&dense.window_rect((clamped.x, clamped.y), after)));+ assert_eq!(after.height, WINDOW_HEIGHT.min(PET_TOP + (900.0 - clamped.y) / 2.0));+ }+#[test]fn a_restore_keeps_a_visible_pet_and_clamps_one_whose_display_is_gone() {let areas = [@@ -997,7 +2100,11 @@ mod tests {monitor: None,};let pulled = clamp_anchor(&straddling, &areas);- assert_eq!((pulled.x, pulled.y), (172.5, 474.0));+ assert_eq!(+ (pulled.x, pulled.y),+ (172.5, 400.0),+ "only pulled sideways: near the top it flips"+ );// With no overlap, its own display wins over the primary one.let lost = PetAnchor {@@ -1045,7 +2152,7 @@ mod tests {width: PET_SIZE,height: PET_AND_DOCK_HEIGHT,}));- assert_eq!(restored.y, 407.0, "the dock, not only the image, must fit");+ assert_eq!(restored.y, 399.0, "the dock and the strip's margin below it must fit");}}@@ -1063,7 +2170,7 @@ mod tests {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_eq!((low_laptop.x, low_laptop.y), (100.0, 399.0));assert!(areas[0].area.contains(&LogicalRect {x: low_laptop.x,y: low_laptop.y,@@ -1079,7 +2186,10 @@ mod tests {&areas,);assert_eq!(external.monitor.as_deref(), Some("full"));- assert!(areas[1].area.contains(&areas[1].pet_at((external.x, external.y))));+ let at = (external.x, external.y);+ assert!(areas[1]+ .area+ .contains(&areas[1].window_rect(at, settle_frame(at, &areas[1]))));}#[test]@@ -1135,21 +2245,21 @@ mod tests {},&areas,);+ // Near the display's top it stays exactly where it was dragged.let physical = rescale((restored.x, restored.y), primary, 1.0);- assert!((physical.0 - 3000.0).abs() < 1e-9 && (physical.1 - 673.5).abs() < 1e-9);+ assert!((physical.0 - 3000.0).abs() < 1e-9 && (physical.1 - 200.0).abs() < 1e-9);assert_eq!(restored.monitor.as_deref(), Some("side"));assert_eq!(area_for(&areas, saved).and_then(|area| area.name.as_deref()),Some("side"));- // The window starts the pet's 8-point padding, at the side display's- // scale, above and left of it.- let window_at = rescale(- restored_window_origin((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);+ // The window starts the image's offset, at the side display's scale,+ // above and left of it: its column opens below Vibey there.+ let at = (restored.x, restored.y);+ let frame = settle_frame(at, &areas[1]);+ assert_eq!(frame.layout.panel_edge, PanelEdge::Top);+ let window_at = rescale(frame.origin(at, window / primary), primary, 1.0);+ assert!((window_at.0 - (3000.0 - 258.75)).abs() < 1e-9 && (window_at.1 - (200.0 - 18.0)).abs() < 1e-9);}#[test]@@ -1162,24 +2272,23 @@ mod tests {};let areas = [area("primary", 0.0, 0.0, 1920.0, 1080.0), side.clone()];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,+ side.area.right() - (WINDOW_WIDTH - PetFrame::default().pet_offset().0) * side.unit,+ side.area.bottom() - (WINDOW_HEIGHT - PetFrame::default().pet_offset().1) * side.unit,);- // Overlapping the right edge: pulled in by the fixed window extent.+ // Overlapping the right edge: pulled in by the window's width, and+ // left at its height, where its column opens below it.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));assert_eq!(- (pulled.x, pulled.y),- (- edge.0,- side.area.y + pet_offset(false, PetLayout::default()).1 * side.unit- )+ settle_frame((pulled.x, pulled.y), &side).layout.panel_edge,+ PanelEdge::Top);- // Inside by the image size but not by the full window is not whole.+ // Inside by the image size but not by the window's width is not whole.let almost = PetAnchor {x: side.area.right() - 100.0,y: side.area.bottom() - 100.0,@@ -1196,7 +2305,7 @@ 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());+ let (dx, dy) = PetFrame::default().pet_offset();assert_eq!((corner.x, corner.y),(diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.tomlindex 2affe1fb6..26ffb214c 100644--- a/desktop/src-tauri/Cargo.toml+++ b/desktop/src-tauri/Cargo.toml@@ -51,6 +51,13 @@ url.workspace = trueasync-trait.workspace = truetauri = { version = "2", features = ["tray-icon", "macos-private-api", "test"] }+[target.'cfg(windows)'.dependencies]+# The pet's drag: the primary button's state and a one-step window frame.+windows-sys = { version = "0.61", features = [+ "Win32_UI_Input_KeyboardAndMouse",+ "Win32_UI_WindowsAndMessaging",+] }+[target.'cfg(windows)'.dev-dependencies]# Reads a native menu item's text, where muda keeps its accelerator.windows-sys = { version = "0.61", features = ["Win32_UI_WindowsAndMessaging"] }diff --git a/desktop/src-tauri/build.rs b/desktop/src-tauri/build.rsindex 0b467ea46..b69547b3d 100644--- a/desktop/src-tauri/build.rs+++ b/desktop/src-tauri/build.rs@@ -16,6 +16,8 @@ fn main() {"computer_use_open_permission","pet_ready","pet_set_expanded",+ "pet_drag",+ "pet_settle","pet_hit_regions","pet_set_dismissed","pet_bind",diff --git a/desktop/src-tauri/capabilities/pet.json b/desktop/src-tauri/capabilities/pet.jsonindex 50b59cc15..72b6a396a 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, 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).",+ "description": "The desktop pet window's whole native surface: report readiness, record panel state and hit regions, drag itself through the shell (which shrinks the window for the drag and chooses the layout on release), 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-drag",+ "allow-pet-settle","allow-pet-hit-regions","allow-pet-set-dismissed","allow-pet-bind",diff --git a/desktop/src-tauri/permissions/autogenerated/pet_drag.toml b/desktop/src-tauri/permissions/autogenerated/pet_drag.tomlnew file mode 100644index 000000000..56da8391a--- /dev/null+++ b/desktop/src-tauri/permissions/autogenerated/pet_drag.toml@@ -0,0 +1,11 @@+# Automatically generated - DO NOT EDIT!++[[permission]]+identifier = "allow-pet-drag"+description = "Enables the pet_drag command without any pre-configured scope."+commands.allow = ["pet_drag"]++[[permission]]+identifier = "deny-pet-drag"+description = "Denies the pet_drag command without any pre-configured scope."+commands.deny = ["pet_drag"]diff --git a/desktop/src-tauri/permissions/autogenerated/pet_settle.toml b/desktop/src-tauri/permissions/autogenerated/pet_settle.tomlnew file mode 100644index 000000000..c6c3181ed--- /dev/null+++ b/desktop/src-tauri/permissions/autogenerated/pet_settle.toml@@ -0,0 +1,11 @@+# Automatically generated - DO NOT EDIT!++[[permission]]+identifier = "allow-pet-settle"+description = "Enables the pet_settle command without any pre-configured scope."+commands.allow = ["pet_settle"]++[[permission]]+identifier = "deny-pet-settle"+description = "Denies the pet_settle command without any pre-configured scope."+commands.deny = ["pet_settle"]diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rsindex de700e1cb..6a24c9bd8 100644--- a/desktop/src-tauri/src/lib.rs+++ b/desktop/src-tauri/src/lib.rs@@ -24,6 +24,7 @@ use std::time::Duration;mod native_frame;mod notifications;mod pet;+mod pet_native;mod update_install;mod updater;@@ -2190,7 +2191,7 @@ pub fn run() {}if let RunEvent::WindowEvent {label,- event: WindowEvent::Moved(_),+ event: WindowEvent::Moved(_) | WindowEvent::ScaleFactorChanged { .. },..} = event{@@ -2229,6 +2230,8 @@ pub fn run() {computer_use_open_permission,pet::pet_ready,pet::pet_set_expanded,+ pet::pet_drag,+ pet::pet_settle,pet::pet_hit_regions,pet::pet_set_dismissed,pet::pet_bind,diff --git a/desktop/src-tauri/src/pet.rs b/desktop/src-tauri/src/pet.rsindex 31f5e7449..02d4ec94b 100644--- a/desktop/src-tauri/src/pet.rs+++ b/desktop/src-tauri/src/pet.rs@@ -16,9 +16,9 @@ use std::time::Duration;use avibe_runtime_host::deep_link::parse_deep_link;use avibe_runtime_host::pet::{- anchor_from_window, area_for, clamp_anchor, default_anchor, hovering, rescale, restored_window_origin,- shortcut_label, valid_session_id, window_size, HitRect, LogicalRect, PetAnchor, PetBinding, PetIntent, PetLayout,- PetReady, PetStore, WorkArea, SHORTCUT_PRESETS,+ area_for, clamp_anchor, default_anchor, frame_at, hovering, place_moved, rescale, shortcut_label, upward_frame,+ valid_session_id, FrameState, FrameStep, HitRect, LayoutSnapshot, LogicalRect, PageKind, PetAnchor, PetBinding,+ PetFrame, PetIntent, PetLayout, PetReady, PetStore, WorkArea, SHORTCUT_PRESETS,};use avibe_runtime_host::LoopbackOrigin;use serde::{Deserialize, Serialize};@@ -27,6 +27,7 @@ use tauri::{AppHandle, Manager, Monitor, PhysicalPosition, WebviewUrl, WebviewWiuse tauri_plugin_global_shortcut::GlobalShortcutExt;use url::Url;+use crate::pet_native::{primary_button_down, set_frame, start_drag};use crate::{native_catalog_for_locales, Shell, DESKTOP_SHELL_MARKER, MAIN_WINDOW};pub const PET_WINDOW: &str = "pet";@@ -36,8 +37,20 @@ const PET_PATH: &str = "/pet";const SUMMON_EVENT: &str = "avibe:pet-summon";const BOUND_EVENT: &str = "avibe:pet-bound";const HOVER_EVENT: &str = "avibe:pet-hover";+const LAYOUT_EVENT: &str = "avibe:pet-layout";/// A drag settles before its anchor is saved, as the main window's frame does.const MOVE_SETTLE: Duration = Duration::from_millis(400);+/// How often a drag checks whether the button is still down.+const DRAG_POLL: Duration = Duration::from_millis(16);+/// Tells the page, before its scripts run, that this shell drags the pet+/// itself (`pet_drag`), so the page chooses the drag path the moment it is+/// pressed. Older shells have no marker and the page uses `start_dragging`.+pub const PET_DRAG_MARKER: &str =+ "if (window.self === window.top) Object.defineProperty(window, '__AVIBE_PET_DRAG__', { value: true });";+/// How long a dropped pet waits for its page to draw the chosen layout before+/// the shell restores the full window on its own.+const SETTLE_TIMEOUT: Duration = Duration::from_millis(1000);+const WINDOW_GONE: &str = "The desktop pet window is gone.";/// Tells the Workbench, before its scripts run, that this shell can show a/// session in the pet. An older shell has no `pet_bind`, so the page offers@@ -60,7 +73,8 @@ fn native_pet_catalog() -> NativePetCatalog {#[derive(Clone, Copy)]struct Frame {expanded: bool,- layout: PetLayout,+ /// The native frame and the layout the page draws (`FrameState`).+ state: FrameState,}pub struct Pet {@@ -72,6 +86,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>,+ /// Advances with every drag and every new window, so a stale drag's steps+ /// change nothing.+ drag_generation: AtomicU64,hit_regions: Mutex<Vec<HitRect>>,poll_generation: AtomicU64,poll_wake: Arc<tokio::sync::Notify>,@@ -84,10 +101,11 @@ impl Pet {window_origin: Mutex::new(None),frame: Mutex::new(Frame {expanded: false,- layout: PetLayout::default(),+ state: FrameState::new(PetFrame::default()),}),shortcut_error: Mutex::new(None),move_generation: Arc::new(AtomicU64::new(0)),+ drag_generation: AtomicU64::new(0),hit_regions: Mutex::new(Vec::new()),poll_generation: AtomicU64::new(0),poll_wake: Arc::new(tokio::sync::Notify::new()),@@ -103,6 +121,7 @@ impl Pet {}fn page_loading(&self) {+ lock(&self.frame).state.page_loading();self.store().page_loading();lock(&self.hit_regions).clear();}@@ -329,18 +348,21 @@ fn build_window(app: &AppHandle, origin: &LoopbackOrigin) -> Option<WebviewWindolet areas = work_areas(app, scale);let saved = pet.store().anchor().cloned();let anchor = initial_anchor(saved.as_ref(), &areas);- let layout = PetLayout::default();- *lock(&pet.frame) = Frame {- expanded: false,- layout,- };- let (width, height) = window_size(false);let at = (anchor.x, anchor.y);let unit = area_for(&areas, at).map_or(1.0, |area| area.unit);- let (x, y) = restored_window_origin(at, unit);+ let frame = frame_at(at, &areas);+ pet.drag_generation.fetch_add(1, Ordering::SeqCst);+ {+ let mut current = lock(&pet.frame);+ current.expanded = false;+ current.state.rebuild(frame);+ }+ let (width, height) = frame.size();+ let (x, y) = frame.origin(at, unit);pet.page_loading();let builder = WebviewWindowBuilder::new(app, PET_WINDOW, WebviewUrl::External(url)).initialization_script(DESKTOP_SHELL_MARKER)+ .initialization_script(PET_DRAG_MARKER).on_new_window(|_, _| tauri::webview::NewWindowResponse::Deny).title("Avibe").inner_size(width, height)@@ -463,7 +485,9 @@ pub fn hide(app: &AppHandle) {}}-/// Saves where the user dragged the pet once the drag settles.+/// Once a move settles: saves where the pet is and, unless the shell's own+/// drag is placing it, gives it the window for that spot (the platform moved+/// it after a display change, or an older page dragged it natively).pub fn window_moved(app: &AppHandle) {let Some(pet) = app.try_state::<Pet>() else {return;@@ -481,31 +505,98 @@ pub fn window_moved(app: &AppHandle) {let Some(window) = handle.get_webview_window(PET_WINDOW) else {return;};- let (Some(anchor), Ok(window_scale)) = (current_anchor(&handle, &window), window.scale_factor()) else {- return;- };- let scale = anchor_scale(&handle, Some(window_scale));- let anchor = rescale(anchor, window_scale, scale);- let areas = work_areas(&handle, scale);- let monitor = area_for(&areas, anchor).and_then(|area| area.name.clone());- handle.state::<Pet>().store().set_anchor(PetAnchor {- x: anchor.0.round(),- y: anchor.1.round(),- monitor,- });+ follow_move(&handle, &window);});});}-fn current_anchor(app: &AppHandle, window: &WebviewWindow) -> Option<(f64, f64)> {+/// Puts the window where `place_moved` says for its spot now, through+/// `FrameState::follow`: the same layout applies at once, another one waits+/// for the page to draw it.+fn follow_move(app: &AppHandle, window: &WebviewWindow) {+ let pet = app.state::<Pet>();+ let current = {+ let frame = lock(&pet.frame);+ if frame.state.busy() {+ return;+ }+ frame.state.current()+ };+ let (Some(at), Ok(window_scale)) = (window_anchor(window, current), window.scale_factor()) else {+ return;+ };+ let scale = anchor_scale(app, Some(window_scale));+ let page_layouts = lock(&pet.frame).state.draws_layouts();+ let (anchor, next) = place_moved(+ rescale(at, window_scale, scale),+ &work_areas(app, scale),+ saved_monitor(app),+ page_layouts,+ );+ pet.store().set_anchor(PetAnchor {+ x: anchor.x.round(),+ y: anchor.y.round(),+ monitor: anchor.monitor.clone(),+ });+ let held = rescale((anchor.x, anchor.y), scale, window_scale);+ // A window this shell just placed comes back here: sub-point differences+ // are its own rounding, not a move.+ let close = |a: f64, b: f64| (a - b).abs() < 0.5;+ let moved = !close(held.0, at.0) || !close(held.1, at.1);+ let next = if close(next.height, current.height) {+ PetFrame {+ height: current.height,+ ..next+ }+ } else {+ next+ };+ let step = lock(&pet.frame).state.follow(next, held, moved);+ perform(app, window, step);+}++/// Carries out a `FrameStep`: moves the window now, or publishes the layout+/// to the document showing now, whichever document started the change. A+/// published frame applies on that revision's `pet_settle`, or on its own+/// after `SETTLE_TIMEOUT`.+fn perform(app: &AppHandle, window: &WebviewWindow, step: FrameStep) {+ match step {+ FrameStep::Keep => {}+ FrameStep::Apply { frame, anchor } => set_frame(window, frame.origin(anchor, 1.0), frame.size()),+ FrameStep::Publish { snapshot, publication } => {+ // An older page ignores the event; one still loading may already listen.+ dispatch(window, LAYOUT_EVENT, &serde_json::json!(snapshot));+ // The timer is this publication's: once the frame is published+ // again (the page reloaded), it no longer releases anything.+ let app = app.clone();+ tauri::async_runtime::spawn(async move {+ tokio::time::sleep(SETTLE_TIMEOUT).await;+ let _ = on_main_thread(&app, move |app| {+ let Some(window) = app.get_webview_window(PET_WINDOW) else {+ return;+ };+ let step = lock(&app.state::<Pet>().frame).state.expire(publication);+ perform(app, &window, step);+ })+ .await;+ });+ }+ }+}++/// The display `pet.json` last placed the pet on.+fn saved_monitor(app: &AppHandle) -> Option<String> {+ app.state::<Pet>()+ .store()+ .anchor()+ .and_then(|anchor| anchor.monitor.clone())+}++/// The anchor of `window` drawn as `frame`, in the window's logical points.+fn window_anchor(window: &WebviewWindow, frame: PetFrame) -> Option<(f64, f64)> {let scale = window.scale_factor().ok()?;let position = window.outer_position().ok()?.to_logical::<f64>(scale);- let frame = *lock(&app.state::<Pet>().frame);- Some(anchor_from_window(- (position.x, position.y),- frame.expanded,- frame.layout,- ))+ Some(frame.anchor((position.x, position.y), 1.0))}/// The scale `pet.json`'s anchor is stored in. macOS places every window in@@ -598,11 +689,29 @@ fn is_workbench_caller(label: &str, active: Option<&LoopbackOrigin>, url: &Url)label == MAIN_WINDOW && active.is_some_and(|origin| origin.matches_url_origin(url))}-/// Called once the `/pet` page has its listeners installed.+#[derive(Serialize)]+pub struct ReadyResult {+ #[serde(flatten)]+ ready: PetReady,+ /// The layout to draw and its revision (absent from older shells), the+ /// same snapshot the layout event carries.+ layout: PetLayout,+ layout_revision: u64,+}++/// Called once the `/pet` page has its listeners installed. `layouts` says+/// the page draws the top layout; a page that predates it (a shell can adopt+/// an older running Runtime) gets the upward window at the same spot.#[tauri::command]-pub fn pet_ready(window: WebviewWindow) -> Result<PetReady, String> {+pub fn pet_ready(window: WebviewWindow, layouts: Option<bool>) -> Result<ReadyResult, String> {ensure_pet_page(&window)?;let pet = window.state::<Pet>();+ let kind = if layouts == Some(true) {+ PageKind::Layouts+ } else {+ PageKind::Legacy+ };+ page_ready(window.app_handle(), &window, kind);// A new document starts collapsed, so the frame does too.let expanded = lock(&pet.frame).expanded;if expanded {@@ -616,7 +725,12 @@ pub fn pet_ready(window: WebviewWindow) -> Result<PetReady, String> {pet.poll_wake.notify_one();let _ = window.set_focus();}- Ok(ready)+ let snapshot = lock(&pet.frame).state.snapshot();+ Ok(ReadyResult {+ ready,+ layout: snapshot.layout,+ layout_revision: snapshot.revision,+ })}/// Records the page state without moving or resizing the fixed mini window.@@ -628,9 +742,186 @@ pub fn pet_set_expanded(window: WebviewWindow, expanded: bool) -> Result<PetLayofn set_expanded(window: &WebviewWindow, expanded: bool) -> Result<PetLayout, String> {let pet = window.state::<Pet>();- let layout = PetLayout::default();- *lock(&pet.frame) = Frame { expanded, layout };- Ok(layout)+ let mut frame = lock(&pet.frame);+ frame.expanded = expanded;+ // Older pages read the layout here; current ones take it only from the+ // revisioned snapshot.+ Ok(frame.state.snapshot().layout)+}++/// Drags the pet with the pointer (decision 2026-10-23) and returns once the+/// drop has been placed.+///+/// The window shrinks to the strip around Vibey and the dock for the drag, so+/// Vibey can reach the top of the work area (macOS keeps a window below the+/// menu bar), and both layouts draw Vibey at the same place in it. On release+/// the shell keeps the pet whole on a display, chooses the frame there and+/// saves the anchor. A page that draws layouts gets the drop's revisioned+/// snapshot through the layout event, and the full window comes back on that+/// revision's `pet_settle` (or after `SETTLE_TIMEOUT`); the reply carries no+/// layout, so the page has one source for it.+#[tauri::command]+pub async fn pet_drag(window: WebviewWindow) -> Result<(), String> {+ ensure_pet_page(&window)?;+ let app = window.app_handle().clone();+ let generation = on_main_thread(&app, {+ let window = window.clone();+ move |app| begin_drag(app, &window)+ })+ .await??;+ wait_for_release(&app, generation).await;+ let placed = on_main_thread(&app, {+ let window = window.clone();+ move |app| end_drag(app, &window, generation)+ })+ .await;+ // The one way a drag ends without a placement: whatever failed, it goes+ // back to the frame and anchor it started from (`FrameState::abort_drag`).+ if !matches!(placed, Ok(Ok(()))) {+ let _ = on_main_thread(&app, move |app| abandon_drag(app, generation)).await;+ }+ placed?+}++fn abandon_drag(app: &AppHandle, generation: u64) {+ let pet = app.state::<Pet>();+ if pet.drag_generation.load(Ordering::SeqCst) != generation {+ return;+ }+ let step = lock(&pet.frame).state.abort_drag();+ if let Some(window) = app.get_webview_window(PET_WINDOW) {+ perform(app, &window, step);+ }+}++/// The document said what it draws: the machine decides what that changes+/// for the window, given where the pet is now and the upward window there.+fn page_ready(app: &AppHandle, window: &WebviewWindow, kind: PageKind) {+ let pet = app.state::<Pet>();+ let current = lock(&pet.frame).state.current();+ let (Some(at), Ok(window_scale)) = (window_anchor(window, current), window.scale_factor()) else {+ lock(&pet.frame)+ .state+ .page_ready(kind, (0.0, 0.0), |_| PetFrame::default());+ return;+ };+ let scale = anchor_scale(app, Some(window_scale));+ let areas = work_areas(app, scale);+ let upward = |anchor: (f64, f64)| {+ let saved = rescale(anchor, window_scale, scale);+ area_for(&areas, saved).map_or_else(PetFrame::default, |area| upward_frame(saved, area))+ };+ let step = lock(&pet.frame).state.page_ready(kind, at, upward);+ perform(app, window, step);+}++/// The page drew the layout of `revision`. That revision's waiting frame (if+/// it is still the waiting one) comes back now; any other acknowledgement+/// changes nothing. Answers with the snapshot the page should now draw.+#[tauri::command]+pub fn pet_settle(window: WebviewWindow, revision: u64) -> Result<LayoutSnapshot, String> {+ ensure_pet_page(&window)?;+ let app = window.app_handle();+ let pet = window.state::<Pet>();+ let (step, snapshot) = {+ let mut frame = lock(&pet.frame);+ let step = frame.state.ack(revision);+ (step, frame.state.snapshot())+ };+ perform(app, &window, step);+ Ok(snapshot)+}++async fn on_main_thread<T: Send + 'static>(+ app: &AppHandle,+ work: impl FnOnce(&AppHandle) -> T + Send + 'static,+) -> Result<T, String> {+ let (send, receive) = tokio::sync::oneshot::channel();+ let handle = app.clone();+ app.run_on_main_thread(move || {+ let _ = send.send(work(&handle));+ })+ .map_err(|_| WINDOW_GONE.to_owned())?;+ receive.await.map_err(|_| WINDOW_GONE.to_owned())+}++fn begin_drag(app: &AppHandle, window: &WebviewWindow) -> Result<u64, String> {+ let pet = app.state::<Pet>();+ let mut frame = lock(&pet.frame);+ let anchor = window_anchor(window, frame.state.current()).ok_or(WINDOW_GONE)?;+ let Some(strip) = frame.state.begin_drag(anchor) else {+ // Placing it already, or its page has not said it draws the top+ // layout (it drags the window natively then).+ return Err("The desktop pet cannot be dragged by the shell now.".to_owned());+ };+ set_frame(window, strip.origin(anchor, 1.0), strip.size());+ let generation = pet.drag_generation.fetch_add(1, Ordering::SeqCst) + 1;+ drop(frame);+ if let Err(error) = start_drag(window) {+ // No drag will end: the drag finaliser puts the window back.+ let step = lock(&pet.frame).state.abort_drag();+ perform(app, window, step);+ return Err(error);+ }+ Ok(generation)+}++/// Until the primary button is up. Where the shell cannot read the button, a+/// drag is over once the window has stopped moving for `MOVE_SETTLE`.+async fn wait_for_release(app: &AppHandle, generation: u64) {+ let pet = app.state::<Pet>();+ let moves = pet.move_generation.clone();+ let mut last_move = (moves.load(Ordering::SeqCst), tokio::time::Instant::now());+ loop {+ tokio::time::sleep(DRAG_POLL).await;+ if pet.drag_generation.load(Ordering::SeqCst) != generation {+ return;+ }+ match on_main_thread(app, |_| primary_button_down()).await {+ Err(_) | Ok(Some(false)) => return,+ Ok(Some(true)) => {}+ Ok(None) => {+ let moved = moves.load(Ordering::SeqCst);+ if moved != last_move.0 {+ last_move = (moved, tokio::time::Instant::now());+ } else if last_move.1.elapsed() >= MOVE_SETTLE {+ return;+ }+ }+ }+ }+}++fn end_drag(app: &AppHandle, window: &WebviewWindow, generation: u64) -> Result<(), String> {+ let pet = app.state::<Pet>();+ if pet.drag_generation.load(Ordering::SeqCst) != generation {+ return Err(WINDOW_GONE.to_owned());+ }+ let strip = lock(&pet.frame).state.current();+ let (Some(dropped), Ok(window_scale)) = (window_anchor(window, strip), window.scale_factor()) else {+ return Err(WINDOW_GONE.to_owned());+ };+ let scale = anchor_scale(app, Some(window_scale));+ let saved = rescale(dropped, window_scale, scale);+ // The document may have reloaded during the drag: the machine knows what+ // the one showing now draws (or that it is still loading).+ let page_layouts = lock(&pet.frame).state.draws_layouts();+ // A drag never saves where it is, so the saved display is the one the pet+ // was on before it: a drop off every display goes back there.+ let (anchor, next) = place_moved(saved, &work_areas(app, scale), saved_monitor(app), page_layouts);+ let at = (anchor.x, anchor.y);+ pet.store().set_anchor(PetAnchor {+ x: anchor.x.round(),+ y: anchor.y.round(),+ monitor: anchor.monitor,+ });+ let held = rescale(at, scale, window_scale);+ if held != dropped {+ set_frame(window, strip.origin(held, 1.0), strip.size());+ }+ let step = lock(&pet.frame).state.end_drag(next, held);+ perform(app, window, step);+ Ok(())}#[tauri::command]@@ -795,6 +1086,7 @@ pub fn pet_open(window: WebviewWindow, link: String) -> Result<(), String> {#[cfg(test)]mod tests {use super::*;+ use avibe_runtime_host::pet::{settle_frame, DRAG_HEIGHT, WINDOW_HEIGHT};#[test]fn window_build_placement_keeps_the_image_and_dock_reachable_on_small_displays() {@@ -870,8 +1162,10 @@ mod tests {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 at = (anchor.x, anchor.y);+ let frame = settle_frame(at, target);+ let origin = frame.origin(at, target.unit);+ let (dx, dy) = frame.pet_offset();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;@@ -893,8 +1187,16 @@ mod tests {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));+ // The window reaches from Vibey toward its column no further than+ // the work area, above or below, whichever way the column opens.+ let window = target.window_rect(at, frame);+ assert!(window.y >= target.area.y - 1e-9, "{case}");+ assert!(+ window.y + window.height <= target.area.y + target.area.height + 1e-9,+ "{case}"+ );+ assert!((DRAG_HEIGHT..=WINDOW_HEIGHT).contains(&frame.height), "{case}");+ assert_eq!(frame.size().0, 460.0);}assert_eq!(initial_anchor(None, &[]),diff --git a/desktop/src-tauri/src/pet_native.rs b/desktop/src-tauri/src/pet_native.rsnew file mode 100644index 000000000..b4e2cea19--- /dev/null+++ b/desktop/src-tauri/src/pet_native.rs@@ -0,0 +1,164 @@+//! The two platform facts the pet's drag needs that Tauri does not expose:+//! whether the primary mouse button is still down, and a window frame change+//! that moves and resizes in one step. Called on the main thread.++use tauri::WebviewWindow;++/// Whether the button holding a drag is still down, or `None` where the+/// shell cannot tell. A native window drag swallows the button's release, so+/// the page never sees it; this is how the shell learns the drag is over.+pub fn primary_button_down() -> Option<bool> {+ // AppKit reports physical buttons, and a Mac mouse can make its right side+ // the primary one: the drag is over once no button is down.+ #[cfg(target_os = "macos")]+ {+ Some(objc2_app_kit::NSEvent::pressedMouseButtons() != 0)+ }+ #[cfg(windows)]+ {+ use windows_sys::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, VK_LBUTTON, VK_RBUTTON};+ use windows_sys::Win32::UI::WindowsAndMessaging::{GetSystemMetrics, SM_SWAPBUTTON};+ // The state of the physical button the user treats as primary.+ // SAFETY: plain Win32 queries with no pointers.+ let button = if unsafe { GetSystemMetrics(SM_SWAPBUTTON) } != 0 {+ VK_RBUTTON+ } else {+ VK_LBUTTON+ };+ Some(unsafe { GetAsyncKeyState(i32::from(button)) } as u16 & 0x8000 != 0)+ }+ #[cfg(not(any(target_os = "macos", windows)))]+ {+ None+ }+}++/// Puts the window at `origin` (its top-left) with `size`, both in the+/// window's logical points, in one step where the platform allows it, so the+/// page is never drawn in a frame that has moved but not yet resized.+pub fn set_frame(window: &WebviewWindow, origin: (f64, f64), size: (f64, f64)) {+ #[cfg(target_os = "macos")]+ if set_frame_macos(window, origin, size) {+ return;+ }+ #[cfg(windows)]+ if set_frame_windows(window, origin, size) {+ return;+ }+ let _ = window.set_size(tauri::LogicalSize::new(size.0, size.1));+ let _ = window.set_position(tauri::LogicalPosition::new(origin.0, origin.1));+}++/// Starts the native window drag from where the pointer is now. On macOS the+/// drag keeps the press's offset measured from the window's bottom edge, so a+/// press that came before a resize would drag the window by the change in+/// height; the shell gives AppKit a press measured in the current frame.+pub fn start_drag(window: &WebviewWindow) -> Result<(), String> {+ #[cfg(target_os = "macos")]+ if start_drag_macos(window) {+ return Ok(());+ }+ window.start_dragging().map_err(|error| error.to_string())+}++#[cfg(target_os = "macos")]+fn start_drag_macos(window: &WebviewWindow) -> bool {+ use objc2::rc::Retained;+ use objc2::runtime::AnyObject;+ use objc2::{msg_send, ClassType, MainThreadMarker};+ use objc2_app_kit::{NSApplication, NSEvent, NSEventModifierFlags, NSEventType, NSWindow};+ use objc2_foundation::NSPoint;++ let (Some(mtm), Ok(pointer)) = (MainThreadMarker::new(), window.ns_window()) else {+ return false;+ };+ // SAFETY: as in `set_frame_macos`.+ let Some(native) = (unsafe { Retained::retain(pointer.cast::<NSWindow>()) }) else {+ return false;+ };+ let mouse = NSEvent::mouseLocation();+ let frame = native.frame();+ let current = NSApplication::sharedApplication(mtm).currentEvent();+ let (flags, timestamp) = current.map_or((NSEventModifierFlags::empty(), 0.0), |event| {+ (event.modifierFlags(), event.timestamp())+ });+ // SAFETY: the documented NSEvent constructor, with a nil graphics context.+ let press: Option<Retained<NSEvent>> = unsafe {+ msg_send![+ NSEvent::class(),+ mouseEventWithType: NSEventType::LeftMouseDown,+ location: NSPoint::new(mouse.x - frame.origin.x, mouse.y - frame.origin.y),+ modifierFlags: flags,+ timestamp: timestamp,+ windowNumber: native.windowNumber(),+ context: std::ptr::null_mut::<AnyObject>(),+ eventNumber: 0isize,+ clickCount: 1isize,+ pressure: 1.0f32+ ]+ };+ let Some(press) = press else {+ return false;+ };+ native.performWindowDragWithEvent(&press);+ true+}++#[cfg(target_os = "macos")]+fn set_frame_macos(window: &WebviewWindow, origin: (f64, f64), size: (f64, f64)) -> bool {+ use objc2::rc::Retained;+ use objc2::MainThreadMarker;+ use objc2_app_kit::NSWindow;+ use objc2_foundation::{NSPoint, NSRect, NSSize};++ let (Some(_mtm), Ok(pointer), Ok(position), Ok(scale)) = (+ MainThreadMarker::new(),+ window.ns_window(),+ window.outer_position(),+ window.scale_factor(),+ ) else {+ return false;+ };+ // SAFETY: Tauri hands out the live NSWindow of this window, on the main+ // thread, which `MainThreadMarker::new()` just confirmed.+ let Some(native) = (unsafe { Retained::retain(pointer.cast::<NSWindow>()) }) else {+ return false;+ };+ // AppKit measures y up from the primary display's bottom; Tauri measures+ // it down from that display's top. The current frame in both gives the+ // primary display's height without asking AppKit for its screens.+ let current = native.frame();+ let top = position.to_logical::<f64>(scale).y;+ let primary_height = current.origin.y + current.size.height + top;+ native.setFrame_display(+ NSRect::new(+ NSPoint::new(origin.0, primary_height - origin.1 - size.1),+ NSSize::new(size.0, size.1),+ ),+ true,+ );+ true+}++#[cfg(windows)]+fn set_frame_windows(window: &WebviewWindow, origin: (f64, f64), size: (f64, f64)) -> bool {+ use windows_sys::Win32::UI::WindowsAndMessaging::{SetWindowPos, SWP_NOACTIVATE, SWP_NOZORDER};++ let (Ok(hwnd), Ok(scale)) = (window.hwnd(), window.scale_factor()) else {+ return false;+ };+ let physical = |value: f64| (value * scale).round() as i32;+ // SAFETY: the handle is this live window's, and SetWindowPos takes no+ // pointers beyond it.+ unsafe {+ SetWindowPos(+ hwnd.0 as _,+ std::ptr::null_mut(),+ physical(origin.0),+ physical(origin.1),+ physical(size.0),+ physical(size.1),+ SWP_NOZORDER | SWP_NOACTIVATE,+ ) != 0+ }+}diff --git a/desktop/src-tauri/tests/shell_boundaries.rs b/desktop/src-tauri/tests/shell_boundaries.rsindex 90633c89d..d20511a19 100644--- a/desktop/src-tauri/tests/shell_boundaries.rs+++ b/desktop/src-tauri/tests/shell_boundaries.rs@@ -404,6 +404,8 @@ fn every_shell_command_is_declared_so_its_permission_exists() {"computer_use_open_permission","pet_ready","pet_set_expanded",+ "pet_drag",+ "pet_settle","pet_hit_regions","pet_set_dismissed","pet_bind",@@ -657,6 +659,36 @@ fn every_main_window_sends_new_browsing_contexts_to_the_system_browser() {}}+#[test]+fn the_pet_learns_the_shell_drags_it_from_one_top_level_marker() {+ let source = shipping_source("src/pet.rs");+ let builder = source+ .split("fn build_window(")+ .nth(1)+ .expect("pet window builder")+ .split("\n}\n")+ .next()+ .expect("builder body");+ assert!(+ builder.contains(".initialization_script(PET_DRAG_MARKER)"),+ "the pet window must define the drag marker before its scripts run"+ );+ let marker = source+ .split("const PET_DRAG_MARKER: &str =")+ .nth(1)+ .expect("marker script")+ .split("\";\n")+ .next()+ .expect("marker literal");+ assert!(marker.contains("if (window.self === window.top)"));+ assert!(marker.contains("Object.defineProperty(window, '__AVIBE_PET_DRAG__', { value: true })"));+ let reader = read_to_string(&crate_dir().join("../../ui/src/pet/petBridge.ts"));+ assert!(+ reader.contains("__AVIBE_PET_DRAG__ === true"),+ "the pet page must read the same marker the shell defines"+ );+}+#[test]fn the_workbench_learns_it_runs_in_the_shell_from_one_top_level_marker() {let source = shipping_source("src/lib.rs");@@ -1143,6 +1175,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-drag",+ "allow-pet-settle","allow-pet-hit-regions","allow-pet-set-dismissed","allow-pet-bind",diff --git a/docs/plans/2026-10-01-desktop-pet.md b/docs/plans/2026-10-01-desktop-pet.mdindex 3a876a5ad..6d2de85b2 100644--- a/docs/plans/2026-10-01-desktop-pet.md+++ b/docs/plans/2026-10-01-desktop-pet.md@@ -83,7 +83,10 @@ window kind; see "G8 lifecycle" below.transparent areas around it do not swallow clicks. Expanded, the windowgrows to fit the panel, anchored at the pet. The panel flips to the side withroom near screen edges. The shell performs the resize.-- The user moves it by dragging the pet (`start-dragging`).+- The user moves it by dragging the pet (`start-dragging`). The mini drags+ through the shell instead, so Vibey can reach the top of the display and+ the column can flip below it; see+ [the mini spec §9.1](2026-10-12-desktop-mini-main-agent.md#91-window).- **Position is the pet anchor, not the window frame.** The window's originmoves whenever the panel opens to the left or above the pet. A raw windowposition saved while expanded would restore the collapsed pet displaced bydiff --git a/docs/plans/2026-10-12-desktop-mini-main-agent.md b/docs/plans/2026-10-12-desktop-mini-main-agent.mdindex 731f9da4d..424e45aa8 100644--- a/docs/plans/2026-10-12-desktop-mini-main-agent.md+++ b/docs/plans/2026-10-12-desktop-mini-main-agent.md@@ -67,7 +67,9 @@ the main agent; there is no Follow up on cards.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.+ in the window. Near the top of the display it opens **downward** instead+ (owner decision, 2026-10-23, §9.1): Vibey and the dock sit at the top of the+ window and the whole column is mirrored below them.- **Column width:** `min(440px, 94vw)`. Every card, the marquee and the inputbubble are **the same width**: the column minus 18px on each side.- Expanded: 6px panel padding plus 12px scroll padding.@@ -620,34 +622,116 @@ already communicate activity. Keep the upper-right red unread badge.### 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.+- **One width, and no resize for any interaction state.** The window is+ 460 logical px wide. Collapsing, expanding, the speech slot and the cards+ never resize it; click-through (§9.2) makes the empty area harmless. Its+ height is decided only where the pet is placed (below), at most **600**.+ - This replaces the collapsed 88 × 88 / expanded side-panel geometry.+- **Placement:** the stored anchor is Vibey's image top-left. Dragging Vibey+ drags the window.+- **Which way the column opens (owner decision, 2026-10-23).** On a display+ with room for the full 600px window above Vibey's image (449px), the column+ opens upward, as before: Vibey sits at the bottom of the window. Otherwise+ the column opens toward the side with more room: below the dock when there+ is more room below than above (Vibey and the dock at the top of the window,+ the image 12px from its top), else upward. Ties stay upward.+ - The window reaches from Vibey toward the column only as far as the work+ area goes, up to 600px, so no part of it is ever off the display. macOS+ never lets this window's top rise above the menu bar (verified: even a+ programmatic frame is pushed back down at its floating level), so a frame+ that did would move Vibey instead.+ - The page draws the layout the shell reports (`panel_edge: top | bottom`)+ and mirrors the whole column for `top`: the speech slot stays nearest+ Vibey, the stack's layers peek toward Vibey, the history opens on the far+ side of its toggle row with Open in Avibe on the far corner, the bubble's+ tail points at Vibey, and content enters moving toward Vibey. Focus order+ is unchanged.+- **The shell owns the frame and the layout (decision 2026-10-23, after the+ #2945 breaker).** One state machine in the shell (`FrameState`) holds the+ window frame and the layout snapshot `{revision, layout}`, the page's only+ source for which edge to draw. A frame change that keeps the layout applies+ at once. One that changes it, and every drop, gets a new revision and waits.+ The shell publishes the snapshot to the document showing now+ (`avibe:pet-layout`), whichever document started the change; a document+ that loads reads the same snapshot from `pet_ready`. The page draws only a+ newer revision, then acknowledges it (`pet_settle(revision)`), and the+ waiting frame comes back only on its own revision. Stale acknowledgements+ change nothing; after 1s without one the frame applies anyway. That 1s+ belongs to one publication: when the machine publishes the held snapshot+ again (a document loaded meanwhile), the earlier timer releases nothing and+ the new one starts over. No reply+ carries a layout to current pages (`pet_set_expanded` still answers one for+ older pages). The page always acknowledges the snapshot in its `pet_ready`+ reply, even a revision it already drew from an event.+ - The machine also knows what the document draws: *loading* (from the+ moment a document starts loading until its `pet_ready`), *layouts*, or+ *legacy*. While it is loading nothing held is released, expiry included;+ when it is ready, a page that draws layouts gets the held snapshot again,+ and an older page gets the upward window at once, in place of a held frame+ or a current one in the top layout (mid-drag, in place of the frame a+ failed drag returns to).+ - Every drag ends idle or holding: one that does not end with a placement+ (the native drag did not start, the window could not be read on release,+ the window was replaced, the release could not be handled) goes back to+ the frame and anchor it started from, held like any other change of layout+ if that layout is no longer the one the page draws.+- **Dragging.** A 600px window cannot take Vibey near the menu bar, so the+ drag goes through the shell (`pet_drag`): it shrinks the window to the+ **drag strip** around Vibey and the dock (12px above the image, 36px below+ it: 163px at full width), keeping Vibey under the pointer, and starts the+ native drag. Both layouts draw Vibey at the same place in the strip, and the+ page hides the column in any window that short (a sliver otherwise). If the+ native drag cannot start, the window goes back as it was.+ - The shell says it can drag the pet before any page script runs: an+ initialization script defines `window.__AVIBE_PET_DRAG__`. Shells without+ the marker keep the page's old `start_dragging` path. The shell drags+ only a document whose `pet_ready` has told it the document draws layouts,+ and refuses `pet_drag` from one it still takes for loading (or legacy).+ The page drags through the shell only once its `pet_ready` has succeeded;+ before that a press drags the window natively, which the shell treats+ like any other move (below). A failed `pet_ready` is asked again after+ 250ms, doubling up to 8s, until it succeeds.+ - On release (the shell reads the buttons: no button down in+ `pressedMouseButtons` on macOS, whose bits are physical and whose primary+ side can be the right one; the primary button in `GetAsyncKeyState` on+ Windows; where it cannot, a drag ends once the window has not moved for+ 400ms), the shell keeps the pet whole on a display (as on restore),+ chooses the window for that spot, saves the anchor and publishes the drop+ as above.+ - A page that predates the top layout (the shell can adopt an older running+ Runtime) does not declare `layouts` in `pet_ready`; it only ever gets the+ upward window at the same spot, as tall as the room above allows, so+ Vibey stays put and nothing is mis-drawn.+- **Nothing is drawn before the layout is known.** Under a shell with the+ marker, the page keeps its stage invisible (and so reports no hit regions)+ until it has the shell's first snapshot from `pet_ready`, so a pet restored+ in the top layout never shows a frame in the other one as it loads. If+ `pet_ready` fails or has not answered after 4s, the page draws the default+ layout anyway (and keeps asking, as above). The window itself is created and shown as before: a hidden+ macOS window would pause the page's animation frames, and with them its+ first acknowledgement. Older pages, which do not read the marker, draw at+ once as before.+- **Every other move gets the window for its spot.** When the platform moves+ the window (a display is removed, a work area or scale changes) or an older+ page drags it natively, the shell, once the move settles for 400ms, keeps+ the pet whole on a display and applies the window for that spot through the+ same state machine. An older page still cannot drag Vibey above the 600px+ window's reach: only the shell's drag shrinks the window.+- **What must stay on a display.** Restore on launch, a dropped pet and a+ display or scale change keep the drag strip inside a connected work area:+ at the window's width on a display that fits the full 460 × 600 window,+ else at Vibey's width. The window for that spot then follows the rule above.+ - **Which display (decision 2026-10-12, from the #2508 breaker):** the one+ Vibey overlaps most, else its saved display if it is connected, else the+ primary. 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. The saved display for a drop or a move is the one+ saved before it (a drag saves nothing on its way), so a pet dropped off+ every display, as Windows allows just above a secondary one, returns to+ the display it came from.+ - A short display gets a shorter window, never a window past its edge. The+ expanded list keeps its fixed box, so on such a display its far end can+ still be cut at the window's edge, as before.### 9.2 Click-through (verified in a spike)@@ -812,7 +896,12 @@ GET /api/sessions/main- [ ] Dismiss: 200ms exit, then a 340ms gap close after a 140ms delay; no endjump; 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+- [ ] Window: fixed width, never resized by an interaction; Vibey anchored at+ the bottom, or at the top with the column mirrored below when it has+ been dragged there (§9.1), the window never past the work area.+- [ ] Vibey drags all the way to the top of the work area and back; the+ column flips on drop without showing the other layout at full size.+- [ ] Clicks pass througheverywhere except the reported regions on macOS and Windows (shadowsincluded); polling backs off and stops when hidden.- [ ] With the input or dictation open, a Vibey click opens the history abovediff --git a/ui/e2e/pet-mini/fixture.tsx b/ui/e2e/pet-mini/fixture.tsxindex c6921212d..cee4153d5 100644--- a/ui/e2e/pet-mini/fixture.tsx+++ b/ui/e2e/pet-mini/fixture.tsx@@ -3,6 +3,7 @@ import { PetAvatar, type PetPose } from '../../src/pet/PetAvatar';import { PetPage } from '../../src/pet/PetPage';import { PetWindow } from '../../src/pet/PetWindow';import { petBridge } from '../../src/pet/petBridge';+import { petPanel } from '../../src/pet/petPanel';import { ApiProvider } from '../../src/context/ApiContext';import { InstanceAuthorizationProvider } from '../../src/context/InstanceAuthorizationProvider';import { WorkbenchInboxProvider } from '../../src/context/WorkbenchInboxProvider';@@ -30,6 +31,8 @@ const pinnedPose = requestedPose && PINNED_POSES.includes(requestedPose as PetPodeclare global {interface Window {petLayoutHitRegions: Parameters<typeof petBridge.setHitRegions>[0];+ petHitReports: number;+ petFixtureLayout: (revision: number, edge: 'top' | 'bottom') => void;setPetLayoutVisible: (visible: boolean) => void;petFixtureSends: { sessionId: string; payload: unknown }[];petFixtureOpens: string[];@@ -44,12 +47,17 @@ declare global {}}window.petLayoutHitRegions = [];-petBridge.setHitRegions = async (rects) => { window.petLayoutHitRegions = rects; };+window.petHitReports = 0;+petBridge.setHitRegions = async (rects) => { window.petLayoutHitRegions = rects; window.petHitReports += 1; };+// Apply a layout snapshot the way the shell's event does.+window.petFixtureLayout = (revision, edge) => { petPanel.applySnapshot({ revision, layout: { panel_side: 'left', panel_edge: edge } }); };window.petFixtureSends = [];window.petFixtureOpens = [];window.petFixtureStops = [];window.petFixtureMarkReads = [];petBridge.open = async (link) => { window.petFixtureOpens.push(link); };+// `edge=top`: the layout a shell chooses near the top of the display (§9.1).+if (params.get('edge') === 'top') petPanel.applySnapshot({ revision: 1, layout: { panel_side: 'left', panel_edge: 'top' } });const hasMain = params.get('main') !== 'false';const layers = Number(params.get('layers') ?? 3);const personal = params.get('scenario') === 'personal';diff --git a/ui/e2e/pet-mini/layout.spec.ts b/ui/e2e/pet-mini/layout.spec.tsindex 0ca311b85..d02b0b349 100644--- a/ui/e2e/pet-mini/layout.spec.ts+++ b/ui/e2e/pet-mini/layout.spec.ts@@ -1345,3 +1345,115 @@ for (const asr of [true, false]) {expect(order).toEqual(asr ? ['语音输入', '|', '输入消息'] : ['输入消息']);});}++// Spec §9.1: near the top of the display the shell flips the window; Vibey and+// the dock sit at its top and the column opens below them, mirrored.+for (const theme of ['light', 'dark']) {+ test(`the top layout opens the column below Vibey and the dock, mirrored (${theme})`, async ({ page }) => {+ await page.goto('/e2e/pet-mini/fixture.html?scenario=personal&lang=zh&history=long&activities=3&edge=top');+ await page.evaluate((theme) => { document.documentElement.dataset.theme = theme; }, theme);+ const avatar = page.locator('.pet-mini-avatar-button');+ await expect(page.locator('.pet-mini-collapsed')).toBeVisible();+ await settleMotion(page);+ const anchor = (await avatar.boundingBox())!;+ expect(anchor.y).toBeCloseTo(12, 0);+ expect(anchor.x + anchor.width / 2).toBeCloseTo(230, 0);+ const below = 163 - 7; // the column's top, less the bubble's tail+ const fits = async (selector: string) => {+ const box = (await page.locator(selector).first().boundingBox())!;+ expect(box.y).toBeGreaterThanOrEqual(below - 1);+ expect(box.y + box.height).toBeLessThanOrEqual(600 + 1);+ return box;+ };+ // Collapsed: the layers peek out above the front card, toward Vibey.+ const front = await fits('.pet-mini-front');+ const layer = (await page.locator('.pet-mini-layer').first().boundingBox())!;+ expect(layer.y).toBeLessThan(front.y);++ // History: the toggle row is nearest Vibey, the history opens below it,+ // the tail points up, and the stack stays below the bubble.+ await avatar.click();+ await expect(page.locator('.pet-mini-detail')).toHaveClass(/is-open/);+ await settleMotion(page);+ const toggle = await fits('.pet-mini-reply-toggle');+ const history = await fits('.pet-mini-bubble-history');+ const bubble = await fits('.pet-mini-reply-bubble');+ const stack = await fits('.pet-mini-collapsed');+ expect(toggle.y).toBeLessThan(history.y);+ expect(bubble.y + bubble.height).toBeLessThanOrEqual(stack.y + 1);+ expect(await page.locator('.pet-mini-reply-bubble').evaluate((node) => getComputedStyle(node, '::after').top)).toBe('-7px');+ const open = (await page.locator('.pet-mini-history-open').boundingBox())!;+ expect(open.y).toBeGreaterThan(history.y + history.height / 2);+ await expect.poll(() => bubbleIsRegion(page)).toBe(true);++ // The list opens below the speech slot, inside the window.+ await page.locator('.pet-mini-collapsed').click();+ await expect(page.locator('.pet-mini-scroll')).toBeVisible();+ await settleMotion(page);+ await fits('.pet-mini-scroll');+ await avatar.click();+ await expect(page.locator('.pet-mini-collapsed')).toBeVisible();++ // Input with the history: the input is nearest Vibey, the bubble below it.+ await avatar.hover();+ await page.getByRole('button', { name: '输入消息', exact: true }).click();+ await page.getByRole('textbox').fill('帮我看一下这周的进展');+ await avatar.click();+ await expect(page.locator('.pet-mini-detail')).toHaveClass(/is-open/);+ await settleMotion(page);+ const input = await fits('.pet-mini-input');+ const over = await fits('.pet-mini-reply-bubble');+ expect(input.y + input.height + 7).toBeLessThanOrEqual(over.y + 1);+ await fits('.pet-mini-collapsed');+ expect(await avatar.boundingBox()).toEqual(anchor);+ });+}++// Spec §9.1: while the shell drags, the window is only the strip around Vibey+// and the dock; the column has no room there and must not show as a sliver.+test('the column hides while the window is only the drag strip, and returns with the full window', async ({ page }) => {+ await page.goto('/e2e/pet-mini/fixture.html?scenario=personal&lang=zh&history=long&activities=3&queued=1');+ await expect(page.locator('.pet-mini-collapsed')).toBeVisible();+ await page.setViewportSize({ width: 460, height: 163 });+ await expect(page.locator('.pet-mini-column')).toHaveCSS('visibility', 'hidden');+ const avatar = (await page.locator('.pet-mini-avatar-button').boundingBox())!;+ expect(avatar.y).toBeCloseTo(12, 0);+ await expect.poll(() => page.evaluate(() => window.petLayoutHitRegions.every((rect) => rect.y >= 0 && rect.y + rect.height <= 163))).toBe(true);+ await page.setViewportSize({ width: 460, height: 600 });+ await expect(page.locator('.pet-mini-column')).toHaveCSS('visibility', 'visible');+});++// Spec §9.1: a layout flip moves Vibey and the column without resizing+// anything, and the desktop's input regions must follow; frequent stage+// attribute changes (busy, state) must not flood the shell with reports.+test('a layout flip re-reports the input regions, and stage attribute churn stays coalesced', async ({ page }) => {+ // No card stack and no transitions: the flip changes nothing but the+ // stage's own attribute.+ await page.emulateMedia({ reducedMotion: 'reduce' });+ await page.goto('/e2e/pet-mini/fixture.html?scenario=personal&lang=zh&history=long&activities=0');+ await expect(page.locator('.pet-mini-avatar-button')).toBeVisible();+ await settleMotion(page);+ await page.waitForTimeout(700);+ const vibey = () => page.evaluate(() => {+ const box = document.querySelector('.pet-mini-avatar-button')!.getBoundingClientRect();+ return window.petLayoutHitRegions.some((rect) => Math.abs(rect.y - box.top) <= 1 && Math.abs(rect.height - box.height) <= 1);+ });+ await expect.poll(vibey).toBe(true);+ await page.evaluate(() => window.petFixtureLayout(2, 'top'));+ await expect(page.locator('.pet-mini-stage')).toHaveAttribute('data-edge', 'top');+ expect((await page.locator('.pet-mini-avatar-button').boundingBox())!.y).toBeCloseTo(12, 0);+ await expect.poll(vibey).toBe(true);+ // A burst of stage attribute changes that move nothing sends no report.+ await settleMotion(page);+ await page.waitForTimeout(700);+ const before = await page.evaluate(() => window.petHitReports);+ await page.evaluate(async () => {+ const stage = document.querySelector('.pet-mini-stage')!;+ for (let frame = 0; frame < 10; frame += 1) {+ for (let i = 0; i < 20; i += 1) stage.setAttribute('data-probe', String(frame * 20 + i));+ await new Promise((resolve) => requestAnimationFrame(resolve));+ }+ });+ await page.waitForTimeout(100);+ expect(await page.evaluate(() => window.petHitReports)).toBe(before);+});diff --git a/ui/src/pet/PetPage.test.tsx b/ui/src/pet/PetPage.test.tsxindex a10029e38..fab7fbb38 100644--- a/ui/src/pet/PetPage.test.tsx+++ b/ui/src/pet/PetPage.test.tsx@@ -17,7 +17,7 @@ import type {import { ApiError } from '@/context/ApiContext';-import { PET_BOUND_EVENT, PET_HOVER_EVENT, PET_SUMMON_EVENT } from './petBridge';+import { PET_BOUND_EVENT, PET_HOVER_EVENT, PET_LAYOUT_EVENT, PET_SUMMON_EVENT } from './petBridge';import { SEND_GRACE_MS } from './usePetSession';vi.mock('react-i18next', () => ({@@ -3145,3 +3145,216 @@ describe('Vibey bubble visibility (spec §4.2)', () => {expect(screen.getByLabelText('pet.recentTurns').getAttribute('aria-expanded')).toBe('false');});});++describe('dragging the pet to the top of the display (spec §9.1)', () => {+ // A shell that drags the pet says so before page scripts run (the marker);+ // `invoke` answers the pet commands.+ const shell = (invoke: (command: string, args?: unknown) => Promise<unknown>, drags = true) => {+ Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });+ Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { invoke }, configurable: true });+ if (drags) Object.defineProperty(window, '__AVIBE_PET_DRAG__', { value: true, configurable: true });+ };+ afterEach(() => { Reflect.deleteProperty(window, '__AVIBE_PET_DRAG__'); });+ const edge = () => document.querySelector('.pet-mini-stage')?.getAttribute('data-edge');+ const top = { panel_side: 'left', panel_edge: 'top' };+ const bottom = { panel_side: 'left', panel_edge: 'bottom' };+ const ready = (layout = bottom, revision = 1) => ({ binding: 'S', revision: 1, summon_pending: null, layout, layout_revision: revision });+ const publish = (revision: number, layout: typeof top) => act(() => {+ window.dispatchEvent(new CustomEvent(PET_LAYOUT_EVENT, { detail: { revision, layout } }));+ });+ const drag = (avatar: HTMLElement) => {+ fireEvent.pointerDown(avatar, { button: 0, pointerId: 1, clientX: 10, clientY: 10 });+ fireEvent.pointerMove(avatar, { buttons: 1, pointerId: 1, clientX: 30, clientY: 10 });+ };+ // Every `pet_settle(revision)` with the edge drawn when it was sent.+ const settles = (invoke: ReturnType<typeof vi.fn>) => (invoke as unknown as { settled: [number, string | null | undefined][] }).settled;+ const recording = (answer: (command: string, args?: { revision?: number }) => unknown) => {+ const settled: [number, string | null | undefined][] = [];+ const invoke = vi.fn(async (command: string, args?: { revision?: number }) => {+ if (command === 'pet_settle') settled.push([args!.revision!, edge()]);+ return answer(command, args);+ });+ Object.assign(invoke, { settled });+ return invoke;+ };++ it('draws the snapshot from pet_ready, then acknowledges that revision', async () => {+ const invoke = recording((command) => command === 'pet_ready' ? ready(top, 4) : { revision: 4, layout: top });+ shell(invoke);+ mainSession('S'); render(<PetPage />);+ await screen.findByText('Session S');+ await waitFor(() => expect(edge()).toBe('top'));+ await waitFor(() => expect(settles(invoke)).toContainEqual([4, 'top']));+ expect(invoke).toHaveBeenCalledWith('pet_ready', { layouts: true });+ });++ it('draws nothing until the shell\'s first snapshot, whichever layout it is', async () => {+ const readyAnswer = deferred<unknown>();+ shell(vi.fn((command: string) => command === 'pet_ready' ? readyAnswer.promise : Promise.resolve({ revision: 2, layout: top })));+ mainSession('S'); render(<PetPage />);+ await screen.findByText('Session S');+ const pending = () => document.querySelector('.pet-mini-stage')?.hasAttribute('data-layout-pending');+ expect(pending()).toBe(true);+ await act(async () => readyAnswer.resolve(ready(top, 2)));+ await waitFor(() => expect(pending()).toBe(false));+ expect(edge()).toBe('top');++ // A first snapshot in the default layout shows the stage as well, even on+ // a surface that nothing else re-renders (setup pending).+ cleanup();+ vi.resetModules();+ ({ PetPage } = await import('./PetPage'));+ setupDone = false;+ const defaultAnswer = deferred<unknown>();+ shell(vi.fn((command: string) => command === 'pet_ready' ? defaultAnswer.promise : Promise.resolve({ revision: 1, layout: bottom })));+ render(<PetPage />);+ await screen.findByText('pet.setupPending');+ await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));+ expect(pending()).toBe(true);+ await act(async () => defaultAnswer.resolve(ready(bottom, 1)));+ await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));+ expect(pending()).toBe(false);+ expect(edge()).toBe('bottom');+ setupDone = true;+ });++ it('asks pet_ready again after it fails, drawing the default layout and dragging natively meanwhile', async () => {+ let failures = 2;+ const invoke = recording((command, args) => {+ if (command === 'pet_ready') return failures-- > 0 ? Promise.reject(new Error('not yet')) : ready(top, 3);+ if (command === 'pet_drag') return new Promise(() => {});+ return { revision: args?.revision ?? 3, layout: top };+ });+ shell(invoke);+ mainSession('S'); render(<PetPage />);+ await screen.findByText('Session S');+ const pending = () => document.querySelector('.pet-mini-stage')?.hasAttribute('data-layout-pending');+ const called = (name: string) => invoke.mock.calls.filter(([command]) => command === name).length;+ await waitFor(() => expect(pending()).toBe(false));+ expect(edge()).toBe('bottom');+ drag(screen.getByLabelText('pet.recentTurns'));+ await waitFor(() => expect(called('plugin:window|start_dragging')).toBe(1));+ expect(called('pet_drag')).toBe(0);+ // Two failures back off 250ms, then 500ms; the third answer is drawn and acknowledged.+ await waitFor(() => expect(settles(invoke)).toContainEqual([3, 'top']), { timeout: 3000 });+ expect(called('pet_ready')).toBe(3);+ drag(screen.getByLabelText('pet.recentTurns'));+ await waitFor(() => expect(called('pet_drag')).toBe(1));+ });++ it('draws a published snapshot before acknowledging it, and ignores an older one', async () => {+ const invoke = recording((command, args) => command === 'pet_ready' ? ready() : { revision: args?.revision ?? 1, layout: top });+ shell(invoke);+ mainSession('S'); render(<PetPage />);+ await screen.findByText('Session S');+ await waitFor(() => expect(settles(invoke)).toContainEqual([1, 'bottom']));+ await publish(3, top);+ await waitFor(() => expect(settles(invoke)).toContainEqual([3, 'top']));+ // A snapshot older than the one drawn (a reordered event) changes nothing.+ await publish(2, bottom);+ await act(async () => new Promise((resolve) => setTimeout(resolve, 40)));+ expect(edge()).toBe('top');+ expect(settles(invoke).map(([revision]) => revision)).not.toContain(2);+ });++ it('acknowledges the pet_ready snapshot even when an event already drew that revision', async () => {+ const readyAnswer = deferred<unknown>();+ const invoke = recording((command, args) => command === 'pet_ready' ? readyAnswer.promise : { revision: args?.revision ?? 3, layout: top });+ shell(invoke);+ mainSession('S'); render(<PetPage />);+ await screen.findByText('Session S');+ // The shell published revision 3 while it still took this document for loading.+ await publish(3, top);+ await waitFor(() => expect(settles(invoke)).toEqual([[3, 'top']]));+ await act(async () => readyAnswer.resolve(ready(top, 3)));+ await waitFor(() => expect(settles(invoke)).toEqual([[3, 'top'], [3, 'top']]));+ });++ it('draws a newer snapshot the shell answers with, when its event never arrived', async () => {+ const invoke = recording((command) => command === 'pet_ready' ? ready() : { revision: 5, layout: top });+ shell(invoke);+ mainSession('S'); render(<PetPage />);+ await screen.findByText('Session S');+ await waitFor(() => expect(settles(invoke)).toContainEqual([5, 'top']));+ expect(edge()).toBe('top');+ });++ it('a press drags the window natively until pet_ready answers, then through the shell, and its layout arrives as a snapshot', async () => {+ const readyAnswer = deferred<unknown>();+ const invoke = recording((command, args) => {+ if (command === 'pet_ready') return readyAnswer.promise;+ if (command === 'pet_drag') return new Promise(() => {});+ return { revision: args?.revision ?? 1, layout: top };+ });+ shell(invoke);+ mainSession('S'); render(<PetPage />);+ await screen.findByText('Session S');+ const called = (name: string) => invoke.mock.calls.filter(([command]) => command === name).length;+ // The shell does not yet know this page draws the top layout.+ drag(screen.getByLabelText('pet.recentTurns'));+ await waitFor(() => expect(called('plugin:window|start_dragging')).toBe(1));+ expect(called('pet_drag')).toBe(0);+ await act(async () => readyAnswer.resolve(ready()));+ drag(screen.getByLabelText('pet.recentTurns'));+ await waitFor(() => expect(called('pet_drag')).toBe(1));+ expect(called('plugin:window|start_dragging')).toBe(1);+ await publish(2, top);+ await waitFor(() => expect(settles(invoke)).toContainEqual([2, 'top']));+ // The drag was not a click: the history stays closed.+ expect(document.querySelector('.pet-mini-detail.is-open')).toBeNull();+ });++ it('drags with the window\'s own start_dragging under a shell without the marker', async () => {+ const invoke = vi.fn(async (command: string) => command === 'pet_ready'+ ? { binding: 'S', revision: 1, summon_pending: null }+ : bottom);+ shell(invoke, false);+ mainSession('S'); render(<PetPage />);+ await screen.findByText('Session S');+ drag(screen.getByLabelText('pet.recentTurns'));+ await waitFor(() => expect(invoke).toHaveBeenCalledWith('plugin:window|start_dragging'));+ expect(invoke.mock.calls.some(([command]) => command === 'pet_drag' || command === 'pet_settle')).toBe(false);+ expect(edge()).toBe('bottom');+ });++ it('takes no layout from the panel reply: only snapshots', async () => {+ const invoke = recording((command, args) => {+ if (command === 'pet_ready') return ready();+ if (command === 'pet_set_expanded') return top;+ return { revision: args?.revision ?? 1, layout: bottom };+ });+ shell(invoke);+ tails.S = [message('u', 'S', { author: 'user', type: 'user', text: 'hello' }), message('r', 'S', { text: 'Old reply' })];+ mainSession('S'); render(<PetPage />);+ await waitFor(() => expect(document.querySelector('.pet-mini-reply-bubble')?.textContent).toContain('Old reply'));+ await userEvent.click(screen.getByLabelText('pet.recentTurns'));+ await waitFor(() => expect(invoke).toHaveBeenCalledWith('pet_set_expanded', { expanded: true }));+ await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));+ expect(edge()).toBe('bottom');+ });++ it('peeks the stack layers out toward Vibey in either layout', async () => {+ canUseAgents = true;+ const row = workingIn('running').agents[0];+ runningAgents = { ...workingIn('running'), agents: ['A', 'B', 'C'].map((id) => ({ ...row, session_id: id })) };+ const layers = () => [...document.querySelectorAll<HTMLElement>('.pet-mini-layer')].map((layer) => [layer.style.top, layer.style.bottom]);+ let reply = bottom;+ shell(vi.fn(async (command: string, args?: { revision?: number }) => command === 'pet_ready'+ ? ready(reply)+ : { revision: args?.revision ?? 1, layout: reply }));+ mainSession('S'); const view = render(<PetPage />);+ await waitFor(() => expect(document.querySelectorAll('.pet-mini-layer')).toHaveLength(2));+ // Below the front card: the nearest layer peeks 9px, the next 18px.+ expect(layers()).toEqual([['9px', '9px'], ['18px', '0px']]);+ expect(document.querySelector<HTMLElement>('.pet-mini-collapsed')!.style.paddingBottom).toBe('18px');+ view.unmount();+ reply = top;+ vi.resetModules();+ ({ PetPage } = await import('./PetPage'));+ render(<PetPage />);+ await waitFor(() => expect(edge()).toBe('top'));+ await waitFor(() => expect(document.querySelectorAll('.pet-mini-layer')).toHaveLength(2));+ expect(layers()).toEqual([['9px', '9px'], ['0px', '18px']]);+ expect(document.querySelector<HTMLElement>('.pet-mini-collapsed')!.style.paddingTop).toBe('18px');+ });+});diff --git a/ui/src/pet/PetPage.tsx b/ui/src/pet/PetPage.tsxindex 3db5a5ed7..a0678ca6b 100644--- a/ui/src/pet/PetPage.tsx+++ b/ui/src/pet/PetPage.tsx@@ -22,7 +22,7 @@ import { VoiceTranscriptionError } from '@/lib/voiceTranscription';import { PetAvatar, type PetPose } from './PetAvatar';import { PetOpenButton } from './PetOpenButton';import { REPLY_LINGER_RESUME_MS, useReplyLinger } from './useReplyLinger';-import { onPetHover, petBridge, sessionLink, vaultRequestLink } from './petBridge';+import { onPetHover, petBridge, sessionLink, vaultRequestLink, type PetLayout } from './petBridge';import { petPanel, usePetPanel } from './petPanel';import { petComposer, usePetComposer } from './petComposer';import { petShell, useOnSummon, usePetBinding, usePetDismissed } from './petShell';@@ -153,10 +153,11 @@ export const PetPage: React.FC = () => {const PetSetupPending: React.FC<{ recheck: () => void }> = ({ recheck }) => {const { t } = useTranslation();useOnSummon(recheck);+ const { layout, awaiting } = usePetPanel();const rootRef = useRef<HTMLDivElement>(null);useHitRegions(rootRef);return (- <div ref={rootRef} className="pet-mini-stage" data-pet-root>+ <div ref={rootRef} className="pet-mini-stage" data-pet-root data-edge={layout.panel_edge} data-layout-pending={awaiting || undefined}><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>@@ -226,7 +227,7 @@ const PetSurface: React.FC = () => {const binding = usePetBinding();const { capabilities } = useInstanceAuthorization();const inbox = useWorkbenchInbox();- const { expanded, setPanel } = usePetPanel();+ const { expanded, layout, awaiting: awaitingLayout, setPanel } = usePetPanel();const { draft, references: draftReferences, uncertain, sending, listenPending, setDraft, setUncertain } = usePetComposer(binding);const data = usePetSession(binding);const epoch = data.epoch;@@ -829,7 +830,8 @@ const PetSurface: React.FC = () => {if (Math.hypot(event.clientX - press.x, event.clientY - press.y) < 4) return;press.dragged = true;window.clearTimeout(press.timer);- void petBridge.startDragging();+ // The drop's layout arrives as the shell's snapshot (petShell).+ void petBridge.drag().catch(() => undefined);}}onPointerCancel={() => {const press = pressRef.current;@@ -882,7 +884,7 @@ const PetSurface: React.FC = () => {);return (- <div ref={rootRef} className="pet-mini-stage" data-pet-root data-busy={busy} data-state={state}>+ <div ref={rootRef} className="pet-mini-stage" data-pet-root data-busy={busy} data-state={state} data-edge={layout.panel_edge} data-layout-pending={awaitingLayout || undefined}><div className={clsx('pet-mini-column', voice.busy && 'is-voice-active')} style={{ '--pet-collapsed-height': `${collapsedHeight}px`, '--pet-input-space': bubbleDrawn && inputShown ? `calc(${inputHeight}px + var(--pet-input-gap))` : '0px' } as CSSProperties}><div className={clsx('pet-mini-cards', voice.busy && 'is-hidden')} inert={voice.busy || undefined} aria-label={cardsExpanded ? t('pet.panel') : undefined} style={{ height: cardsListed ? (visibleCards.length > 0 ? STACK_HEIGHT : 'auto') : collapsedHeight }}><div ref={collapsedRef} key={singleCard ? 'single' : cardsExpanded ? 'expanded' : 'collapsed'} className="pet-mini-swap is-switching" onAnimationEnd={(event) => { if (event.target === event.currentTarget) event.currentTarget.classList.remove('is-switching'); }}>@@ -899,7 +901,7 @@ const PetSurface: React.FC = () => {t={(key, options) => String(t(key as never, options as never))}/>) : (- <CollapsedCards cards={visibleCards} onOpen={openCards} t={(key, options) => String(t(key as never, options as never))} />+ <CollapsedCards cards={visibleCards} edge={layout.panel_edge} onOpen={openCards} t={(key, options) => String(t(key as never, options as never))} />))}</div>@@ -1046,6 +1048,11 @@ function useHitRegions(rootRef: React.RefObject<HTMLDivElement | null>, epoch?: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'] });+ // Any attribute of the stage itself can move or show what is drawn (the+ // layout's `data-edge`, `data-layout-pending`), without a resize. Reports+ // stay one per frame (`schedule`) and are sent only when they change.+ const stage = new MutationObserver(schedule);+ stage.observe(root, { attributes: true });root.addEventListener('scroll', schedule, true);root.addEventListener('transitionrun', motion);root.addEventListener('pointerover', motion);@@ -1053,7 +1060,7 @@ function useHitRegions(rootRef: React.RefObject<HTMLDivElement | null>, epoch?:observe();return () => {active = false;- cancelAnimationFrame(frame); resize?.disconnect(); mutations.disconnect();+ cancelAnimationFrame(frame); resize?.disconnect(); mutations.disconnect(); stage.disconnect();root.removeEventListener('scroll', schedule, true);root.removeEventListener('transitionrun', motion);root.removeEventListener('pointerover', motion);@@ -1214,7 +1221,9 @@ const MiniDock: React.FC<{ enabled: boolean; listening: boolean; finishing?: boo</div>);-const CollapsedCards: React.FC<{ cards: PetCard[]; onOpen: () => void; t: (key: string, options?: Record<string, unknown>) => string }> = ({ cards, onOpen, t }) => {+// The layers peek out toward Vibey: below the front card, or above it when the+// column opens downward.+const CollapsedCards: React.FC<{ cards: PetCard[]; edge: PetLayout['panel_edge']; onOpen: () => void; t: (key: string, options?: Record<string, unknown>) => string }> = ({ cards, edge, onOpen, t }) => {const [front, ...remainingCards] = cards;if (!front) return null;const layers = remainingCards.slice(0, MAX_COLLAPSED_LAYERS);@@ -1224,13 +1233,14 @@ const CollapsedCards: React.FC<{ cards: PetCard[]; onOpen: () => void; t: (key:<buttontype="button"className="pet-mini-collapsed"- style={{ paddingBottom: layers.length * 9 }}+ style={edge === 'top' ? { paddingTop: layers.length * 9 } : { paddingBottom: layers.length * 9 }}onClick={onOpen}aria-label={t('pet.stack.expand', { count, displayCount })}>{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 />;+ const near = (index + 1) * 9, far = (layers.length - index - 1) * 9;+ return <span key={card.id} data-pet-hit className="pet-mini-layer" style={{ top: edge === 'top' ? far : near, bottom: edge === 'top' ? near : far, left: inset, right: inset, zIndex: layers.length - index }} aria-hidden />;})}<div className="pet-mini-front" style={{ zIndex: layers.length + 1 }}><CardBodydiff --git a/ui/src/pet/pet-mini.css b/ui/src/pet/pet-mini.cssindex 251f4bdda..01fe09258 100644--- a/ui/src/pet/pet-mini.css+++ b/ui/src/pet/pet-mini.css@@ -6,6 +6,11 @@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);+ /* Content rises toward Vibey as it enters; the top layout flips both. */+ --pet-rise:8px;+ /* The history's height bound reserves Vibey and the dock (147px), the bubble+ header (62px) and the far inset (16px). */+ --pet-history-reserve:225px;--pet-ink:#fff;--pet-card:#2a2a2e;--pet-main:#34343b;@@ -36,7 +41,7 @@.pet-mini-cards.is-hidden {opacity:0;- transform:translateY(8px);+ transform:translateY(var(--pet-rise));pointer-events:none}.pet-mini-collapsed {@@ -130,7 +135,7 @@@keyframes pet-mini-content-in {from {opacity:0;- transform:translateY(8px) scale(.98)}+ transform:translateY(var(--pet-rise)) scale(.98)}to {opacity:1;transform:none}@@ -328,7 +333,7 @@ to {width:100%;padding:0 18px;opacity:0;- transform:translateY(8px) scale(.97);+ transform:translateY(var(--pet-rise)) scale(.97);transition:opacity 180ms ease,transform 300ms var(--settle)}.pet-mini-slot.is-open .pet-mini-slot-body {opacity:1;@@ -869,7 +874,7 @@ to {/* Share the list's 292px box, bounded by the fixed avatar/dock reservation(147px), bubble header (62px), top inset (16px), the measured stack, andthe measured input below an open history (with its gap). */- max-height:min(292px,max(0px,calc(100dvh - 225px - var(--pet-collapsed-height,0px) - var(--pet-input-space,0px))));+ max-height:min(292px,max(0px,calc(100dvh - var(--pet-history-reserve) - var(--pet-collapsed-height,0px) - var(--pet-input-space,0px))));overflow:auto;overscroll-behavior:contain;/* Hidden like the card list (§3.2); the edge fades show there is more. */@@ -925,3 +930,68 @@ to {outline:2px solid var(--mint);outline-offset:2px}.pet-mini-swap:has(.pet-mini-collapsed) { padding-bottom:14px }++/* Top layout (decision 2026-10-23, spec §9.1): with too little room above+ Vibey, the shell flips the window. Vibey and the dock sit at its top and the+ column opens below the dock, growing downward; everything else mirrors+ vertically, so what was nearest Vibey stays nearest Vibey. The column's DOM+ order is unchanged (focus order too); it is reversed on screen. */+.pet-mini-stage[data-edge=top] {+ --pet-rise:-8px;+ /* Vibey and the dock (163px), the bubble header (62px), the far inset. */+ --pet-history-reserve:241px}+.pet-mini-stage[data-edge=top] .pet-mini-avatar-wrap {+ top:12px;+ bottom:auto}+.pet-mini-stage[data-edge=top] .pet-mini-column {+ top:163px;+ bottom:auto;+ flex-direction:column-reverse}+.pet-mini-stage[data-edge=top] .pet-mini-setup {+ top:175px;+ bottom:auto}+.pet-mini-stage[data-edge=top] .pet-mini-swap:has(.pet-mini-collapsed) {+ padding-top:14px;+ padding-bottom:0}+.pet-mini-stage[data-edge=top] .pet-mini-list {+ margin-top:0;+ margin-bottom:auto}+.pet-mini-stage[data-edge=top] .pet-mini-slot-body {+ display:flex;+ flex-direction:column-reverse}+.pet-mini-stage[data-edge=top] .pet-mini-bubble-over-input {+ margin-top:var(--pet-input-gap);+ margin-bottom:0}+.pet-mini-stage[data-edge=top] .pet-mini-reply-bubble:after {+ top:-7px;+ bottom:auto;+ transform:rotate(225deg)}+.pet-mini-stage[data-edge=top] .pet-mini-reply-bubble.is-main {+ flex-direction:column}+.pet-mini-stage[data-edge=top] .pet-mini-reply-bubble.is-main .pet-mini-detail-clip:after {+ top:0;+ bottom:auto}+.pet-mini-stage[data-edge=top] .pet-mini-bubble-history {+ border-radius:0 0 21px 21px}+.pet-mini-stage[data-edge=top] .pet-mini-bubble-history .pet-mini-detail-inner {+ padding:8px 14px 40px}+.pet-mini-stage[data-edge=top] .pet-mini-history-open {+ top:auto;+ bottom:7px}+/* The history opens below the toggle row, so the chevrons point the other way. */+.pet-mini-stage[data-edge=top] .pet-mini-reply-toggle svg {+ transform:rotate(180deg)}+.pet-mini-stage[data-edge=top] .pet-mini-reply-toggle[aria-expanded=true] svg {+ transform:none}+/* A window only as tall as the strip around Vibey and the dock (163px: the+ shell's drag, §9.1) has no room for the column, which would show as a+ sliver at its edge. It comes back with the full window. */+@media (max-height:163.5px) {+ .pet-mini-column {+ visibility:hidden}+}+/* Under a shell that owns the layout, nothing is drawn until its first+ snapshot says which edge (spec §9.1), so a flipped pet never shows a frame+ in the other layout as it loads. */+.pet-mini-stage[data-layout-pending] {+ visibility:hidden}diff --git a/ui/src/pet/petBridge.ts b/ui/src/pet/petBridge.tsindex a9e94edfa..531edf39e 100644--- a/ui/src/pet/petBridge.ts+++ b/ui/src/pet/petBridge.ts@@ -18,13 +18,23 @@ export type PetBinding = {revision: number;};+/** The layout to draw and its revision; the shell is its only source. */+export type LayoutSnapshot = {+ revision: number;+ layout: PetLayout;+};+export type PetReady = PetBinding & {summon_pending: { intent: PetIntent } | null;+ /** Only shells that drag the pet send one. */+ snapshot?: LayoutSnapshot;};export const PET_SUMMON_EVENT = 'avibe:pet-summon';export const PET_BOUND_EVENT = 'avibe:pet-bound';export const PET_HOVER_EVENT = 'avibe:pet-hover';+/** The shell's layout snapshot `{ revision, layout }`: the page draws it. */+export const PET_LAYOUT_EVENT = 'avibe:pet-layout';/** A window-local rect that takes the mouse; `hover` marks Vibey's hover zone. */export type PetHitRect = { x: number; y: number; width: number; height: number; hover?: boolean };@@ -44,6 +54,22 @@ const shellInvoke = (): TauriInternals['invoke'] | null => {const isIntent = (value: unknown): value is PetIntent => value === 'listen' || value === 'show' || value === 'release';+const parseLayout = (value: unknown): PetLayout => {+ const layout = value as Partial<PetLayout> | null;+ return {+ panel_side: layout?.panel_side === 'right' ? 'right' : 'left',+ panel_edge: layout?.panel_edge === 'top' ? 'top' : 'bottom',+ };+};++const parseSnapshot = (value: unknown): LayoutSnapshot | null => {+ const snapshot = value as { revision?: unknown; layout?: unknown } | null;+ const revision = snapshot?.revision;+ return typeof revision === 'number' && Number.isInteger(revision) && revision >= 0+ ? { revision, layout: parseLayout(snapshot?.layout) }+ : null;+};+const parseBinding = (value: unknown): PetBinding => {const result = value as { binding?: unknown; revision?: unknown } | null;const revision = result?.revision;@@ -57,6 +83,9 @@ const parseBinding = (value: unknown): PetBinding => {};let devMemory: PetBinding = { binding: null, revision: 0 };+// Whether this document's `pet_ready` has succeeded: only then does the shell+// know it draws the top layout, and only then may the shell drag it.+let shellKnowsLayouts = false;const readDevBinding = (): PetBinding => {try {@@ -72,25 +101,42 @@ export const petBridge = {/** True inside the native pet window. */native: (): boolean => shellInvoke() !== null,+ /**+ * Whether the shell drags the pet and owns its layout. It says so before+ * any page script runs (`__AVIBE_PET_DRAG__`); older shells have no marker.+ */+ shellOwnsLayout: (): boolean => shellInvoke() !== null+ && (window as unknown as { __AVIBE_PET_DRAG__?: unknown }).__AVIBE_PET_DRAG__ === true,++ /**+ * Whether `drag` goes through the shell, which shrinks the window to Vibey:+ * only once this page's `pet_ready` has told the shell the page draws the+ * top layout. Until then a press drags the window natively.+ */+ shellDrags: (): boolean => shellKnowsLayouts && petBridge.shellOwnsLayout(),+ready: async (): Promise<PetReady> => {const invoke = shellInvoke();if (!invoke) return { ...readDevBinding(), summon_pending: null };- const result = (await invoke('pet_ready')) as { summon_pending?: { intent?: unknown } | null } | null;+ // `layouts`: this page draws the column below Vibey (`panel_edge: top`).+ const result = (await invoke('pet_ready', { layouts: true })) as {+ summon_pending?: { intent?: unknown } | null; layout?: unknown; layout_revision?: unknown;+ } | null;const pending = result?.summon_pending;- return {+ const snapshot = parseSnapshot({ revision: result?.layout_revision, layout: result?.layout });+ const ready = {...parseBinding(result),summon_pending: pending && isIntent(pending.intent) ? { intent: pending.intent } : null,+ ...(snapshot ? { snapshot } : {}),};+ shellKnowsLayouts = true;+ return ready;},setExpanded: async (expanded: boolean): Promise<PetLayout> => {const invoke = shellInvoke();if (!invoke) return DEFAULT_LAYOUT;- const layout = (await invoke('pet_set_expanded', { expanded })) as Partial<PetLayout> | null;- return {- panel_side: layout?.panel_side === 'right' ? 'right' : 'left',- panel_edge: layout?.panel_edge === 'top' ? 'top' : 'bottom',- };+ return parseLayout(await invoke('pet_set_expanded', { expanded }));},setHitRegions: async (rects: PetHitRect[]): Promise<void> => {@@ -112,9 +158,29 @@ export const petBridge = {return devMemory;},- /** Moves the native window with the pointer (`start-dragging`). */- startDragging: (): void => {- void shellInvoke()?.('plugin:window|start_dragging');+ /**+ * Moves the native window with the pointer: through the shell when it drags+ * the pet (resolves once the drop is placed; its layout arrives as a+ * snapshot), else with the window's own `start_dragging`.+ */+ drag: async (): Promise<void> => {+ const invoke = shellInvoke();+ if (!invoke) return;+ if (!petBridge.shellDrags()) {+ void invoke('plugin:window|start_dragging');+ return;+ }+ await invoke('pet_drag');+ },++ /**+ * Tells the shell this page drew `revision`; a frame waiting for it comes+ * back. Answers with the snapshot the page should draw now.+ */+ settle: async (revision: number): Promise<LayoutSnapshot | null> => {+ const invoke = shellInvoke();+ if (!invoke) return null;+ return parseSnapshot(await invoke('pet_settle', { revision }));},/** Opens an `avibe://` link in the main window. */@@ -151,13 +217,20 @@ export const onPetHover = (handler: (hover: boolean) => void): (() => void) => {/** Subscribe to shell events; returns the unsubscribe function. */export const onPetEvents = (handlers: {summon?: (intent: PetIntent) => void;+ layout?: (snapshot: LayoutSnapshot) => void;}): (() => void) => {const summon = (event: Event) => {const intent = (event as CustomEvent<{ intent?: unknown }>).detail?.intent;handlers.summon?.(isIntent(intent) ? intent : 'show');};+ const layout = (event: Event) => {+ const snapshot = parseSnapshot((event as CustomEvent<unknown>).detail);+ if (snapshot) handlers.layout?.(snapshot);+ };window.addEventListener(PET_SUMMON_EVENT, summon);+ window.addEventListener(PET_LAYOUT_EVENT, layout);return () => {window.removeEventListener(PET_SUMMON_EVENT, summon);+ window.removeEventListener(PET_LAYOUT_EVENT, layout);};};diff --git a/ui/src/pet/petPanel.ts b/ui/src/pet/petPanel.tsindex d620af169..89580dc7f 100644--- a/ui/src/pet/petPanel.ts+++ b/ui/src/pet/petPanel.ts@@ -1,6 +1,6 @@import { useCallback, useSyncExternalStore } from 'react';-import { petBridge, type PetLayout } from './petBridge';+import { petBridge, type LayoutSnapshot, type PetLayout } from './petBridge';const DEFAULT_LAYOUT: PetLayout = { panel_side: 'left', panel_edge: 'bottom' };@@ -17,6 +17,11 @@ const DEFAULT_LAYOUT: PetLayout = { panel_side: 'left', panel_edge: 'bottom' };*/let expanded = false;let layout: PetLayout = DEFAULT_LAYOUT;+// The revision of `layout` (0: none from the shell yet).+let layoutRevision = 0;+// Under a shell that owns the layout, nothing is drawn until its first+// snapshot arrives, or until waiting for it is given up (`stopWaiting`).+let waitingGivenUp = false;let requestId = 0;let wantExpanded = false;let confirmedExpanded = false;@@ -34,15 +39,43 @@ export const petPanel = {current: (): boolean => expanded,want: (): boolean => wantExpanded,layout: (): PetLayout => layout,+ /** The revision of the layout drawn (0 before the shell's first). */+ revision: (): number => layoutRevision,+ /** Waiting for the shell's first layout: draw nothing yet (spec §9.1). */+ awaitingLayout: (): boolean => layoutRevision === 0 && !waitingGivenUp && petBridge.shellOwnsLayout(),+ /** `pet_ready` failed or never answered: draw the default layout. */+ stopWaiting: () => {+ if (waitingGivenUp || layoutRevision > 0) return;+ waitingGivenUp = true;+ notify();+ },+ /**+ * The shell's layout, its only source (spec §9.1). Only a newer revision is+ * drawn; answers whether it was.+ */+ applySnapshot: (snapshot: LayoutSnapshot): boolean => {+ if (snapshot.revision <= layoutRevision) return false;+ layoutRevision = snapshot.revision;+ if (snapshot.layout.panel_edge !== layout.panel_edge || snapshot.layout.panel_side !== layout.panel_side) {+ layout = snapshot.layout;+ }+ // Every accepted revision: what subscribers read also depends on it+ // (`awaitingLayout`), not only on the layout.+ notify();+ return true;+ },};export function usePetPanel(): {expanded: boolean;layout: PetLayout;+ /** Nothing is drawn while the shell's first layout is on its way. */+ awaiting: boolean;setPanel: (next: boolean) => Promise<void>;} {const currentExpanded = useSyncExternalStore(subscribe, () => expanded);const currentLayout = useSyncExternalStore(subscribe, () => layout);+ const awaiting = useSyncExternalStore(subscribe, petPanel.awaitingLayout);const setPanel = useCallback(async (next: boolean) => {wantExpanded = next;const request = ++requestId;@@ -52,10 +85,10 @@ export function usePetPanel(): {}const run = async () => {try {- const applied = await petBridge.setExpanded(next);+ await petBridge.setExpanded(next);if (request !== requestId) return;confirmedExpanded = next;- layout = applied;+ // The reply's layout is for older pages; this one draws snapshots only.expanded = next;notify();} catch {@@ -69,5 +102,5 @@ export function usePetPanel(): {chain = wait.then(() => undefined, () => undefined);await wait;}, []);- return { expanded: currentExpanded, layout: currentLayout, setPanel };+ return { expanded: currentExpanded, layout: currentLayout, awaiting, setPanel };}diff --git a/ui/src/pet/petShell.ts b/ui/src/pet/petShell.tsindex 8eb62d3c1..44a767945 100644--- a/ui/src/pet/petShell.ts+++ b/ui/src/pet/petShell.ts@@ -1,10 +1,15 @@import { useEffect, useSyncExternalStore } from 'react';-import { onPetEvents, petBridge, type PetBinding, type PetIntent } from './petBridge';+import { onPetEvents, petBridge, type LayoutSnapshot, type PetBinding, type PetIntent, type PetReady } from './petBridge';+import { petPanel } from './petPanel';import type { PetSurfaceEpoch } from './usePetSession';/** Document-local main resolution and pending summons. Legacy shell bindings* remain readable for compatibility, but never select the conversation. */+const FIRST_LAYOUT_TIMEOUT_MS = 4000;+// A failed `pet_ready` is asked again after this, doubling up to the cap.+const READY_RETRY_MS = 250;+const READY_RETRY_MAX_MS = 8000;let binding: string | null = null;let legacyBinding: PetBinding | null = null;let pendingSummon: PetIntent | null = null;@@ -43,13 +48,54 @@ const start = () => {liveSummons += 1;noteSummon(intent);},+ // The shell chose a layout (a drop, even one another document started, or+ // a display change).+ layout: drawSnapshot,});const liveSummonsAtRequest = liveSummons;- readyPromise = petBridge.ready().then((ready) => {+ // The page draws nothing until the shell's first layout; if that never+ // comes, it draws the default one after FIRST_LAYOUT_TIMEOUT.+ const waiting = window.setTimeout(petPanel.stopWaiting, FIRST_LAYOUT_TIMEOUT_MS);+ const onReady = (ready: PetReady) => {+ window.clearTimeout(waiting);legacyBinding = ready;readyLoaded = true;+ // A frame may already be waiting for this document (it loaded mid-drop).+ // The reply is always acknowledged, even for a revision this document+ // already drew from an event: the shell may have taken it for loading then.+ if (ready.snapshot) {+ if (petPanel.applySnapshot(ready.snapshot)) acknowledge(ready.snapshot.revision);+ else acknowledge(petPanel.revision());+ } else petPanel.stopWaiting();if (ready.summon_pending && liveSummons === liveSummonsAtRequest) noteSummon(ready.summon_pending.intent);- }).catch(() => undefined);+ };+ // Until the shell has heard this document draws the top layout, it cannot+ // release a frame held for it, so a failed pet_ready is asked again. The+ // page draws the default layout meanwhile and drags the window natively.+ const ask = (attempt: number): Promise<void> => petBridge.ready().then(onReady, () => {+ window.clearTimeout(waiting);+ petPanel.stopWaiting();+ const delay = Math.min(READY_RETRY_MS * 2 ** attempt, READY_RETRY_MAX_MS);+ return new Promise<void>((resolve) => { window.setTimeout(resolve, delay); }).then(() => ask(attempt + 1));+ });+ readyPromise = ask(0);+};++/**+ * Draws a newer layout snapshot, then tells the shell this revision is drawn+ * so a frame waiting for it comes back. The shell answers with its latest+ * snapshot, which is drawn in turn if it is newer still (an event that never+ * reached this document).+ */+const drawSnapshot = (snapshot: LayoutSnapshot) => {+ if (petPanel.applySnapshot(snapshot)) acknowledge(snapshot.revision);+};++/** After the drawn revision has been painted, tell the shell. */+const acknowledge = (revision: number) => {+ requestAnimationFrame(() => requestAnimationFrame(() => {+ void petBridge.settle(revision).then((latest) => { if (latest) drawSnapshot(latest); }).catch(() => undefined);+ }));};const setDismissed = (ids: string[]) => {