A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.
Swift ai-agentsanthropicantigravityclaudeclaude-codecodexcursordynamic-islandgemini-cliiosiphonlinuxmacosmacos-appmenubar-appnotchopen-sourceswiftswiftuiwindows
Merge port/desktop-mochi: the wardrobe, greeting v2 and Mochi on the desktop
Claude7fb1541c4308
diff --cc windows/README.mdindex 331e7d39,a157f62b..41ac6421--- a/windows/README.md+++ b/windows/README.md@@@ -43,75 -43,24 +43,85 @@@ installs for the current user only —| Click the small island | It opens || Click Mochi | It gets annoyed. Three times in a row and it goes dizzy || Rest the pointer on Mochi for two seconds | Hearts |+ | Right-click Mochi | The wardrobe: rest the pointer on an outfit to try it on, click to keep it. **Auto** dresses him for the season (witch hat in October, Santa hat in December…) |+ | Drag Mochi out of the island | He moves onto your desktop and hangs out there, in his outfit, watching your cursor. Drop him back on the island to bring him home |+ | On the desktop: click / right-click / double-click Mochi | Poke him / the wardrobe / he flies home. Drag him to move him || Drag a file onto the island | Mochi turns into a box, swallows it, then offers to answer questions about it |+| Click a file in the session ticker | Its diff opens in the island; ↗ opens the file in VS Code, ‹ or `Esc` goes back || `Esc` | Closes the island |- | Tray icon | Open, Weekly recap, Settings…, Pause, Quit |-| Tray icon | Open, Wardrobe…, Settings…, Pause, Quit |++| Tray icon | Open, Weekly recap, Wardrobe…, Settings…, Pause, Quit |+| `Ctrl+Alt+Space` | Opens the chat, from any app |+| `Ctrl+Alt+A` | Jumps to the waiting permission or question |+| `Ctrl+Alt+T` | Brings the session's window forward ("Open terminal") |+| `Ctrl+Alt+→` / `Ctrl+Alt+←` | Next / previous pill |+| `Ctrl+Alt+S` | Mutes or unmutes Mochi |+| `Ctrl+Alt+G` | Opens the wardrobe |+| `Ctrl+Alt+N` | Opens and closes the island (off until you turn it on) |+| In the open island: `Ctrl+→` `Ctrl+←`, `Ctrl+1`–`Ctrl+9` | Switch pills |+| In the open island: `Ctrl+Enter`, `Ctrl+K` | Send, start a new chat |+| In the open island: `Ctrl+,`, `Ctrl+P` | Settings, keep the island open |++### Keyboard shortcuts++Every global shortcut can be changed or turned off in **Settings… → Shortcuts**:+click it and press the new keys. A combination another app already holds is+flagged *In use*, and two Coucou shortcuts on the same keys are flagged *Used+twice*. While you record a new one, Coucou lets go of its own so the keys reach+the recorder.++The defaults are not the Mac's `⌃⌥` letters. On Windows, `Ctrl+Alt` is `AltGr`,+so a global `Ctrl+Alt+E` would swallow every `€` typed on a French or German+keyboard. The defaults were checked against the AltGr layer of the French,+German, Spanish, Italian, Portuguese and Brazilian (ABNT2) layouts — that is why+pill switching uses the arrows rather than `[` `]`, and mute is `S` rather than+`M` (`AltGr+M` is `µ` in German). On top of that, Coucou asks Windows what each+`Ctrl+Alt` combination types on the layouts you have installed and leaves any+that types a character unregistered, flagged *Types “ą”* in Settings: Polish,+for one, puts `ą` on `AltGr+A` and `ś` on `AltGr+S`. The recorder refuses such+a combination too.++Older Intel graphics drivers rotate the screen on `Ctrl+Alt+←` / `→`; if yours+still does, those two show up as *In use*.Everything else happens on its own: a Claude Code permission request opens the-island with **Deny / Allow**, a finished session shows what it did, and+island with **Deny / Allow**, a question from Claude Code shows its options to+pick from, a finished session shows what it did, andyour integrations sit in the coloured pills next to Mochi.+A permission card or a question stays until you answer it: the mouse leaving+never folds it, it comes up even when the island is already open or another+pill is in front, and the pill you were on comes back once you answer. To keep+it for later, fold it with the **⌃** in its corner (or `Esc` in the island): the+island shrinks to its compact size and stays on screen, nothing is answered, and+opening it again shows the card. **Open terminal** brings the window the session+runs in to the front.++ When Mochi lives on the desktop, he flies back to the island with a permission+ request or a question and returns to his spot once you have answered; he does a+ little jump when a task finishes, and dozes off when nothing has happened for+ two minutes and your cursor is elsewhere — asleep, he costs nothing: no cursor+ polling, a few frames a second. He remembers his spot between launches; if it+ was on a display that is no longer connected, he stays in the island.++**Live diff.** Every file Claude edits (Edit, MultiEdit, Write) shows up in the+session ticker with its **+N −M** lines; click it for the diff. Same limits as the+Mac: past 200 KB or 4 000 lines only the counts are kept, at most 50 diffs per+session, and they are forgotten an hour after the last edit or when the session+ends. When Claude finishes, the card keeps the first paragraph of its final+answer on one line, still, until the next prompt.++## Your pills++**Settings… → Active pills** lists the tools you use, from the same catalog as+the Mac app. Pick your **main tool** — VS Code, Cursor, Codex or Antigravity —+which is always there and doesn't take a slot, then declare up to four more:+agents (Gemini CLI, Copilot CLI, Muse Code, OpenCode, Amp, Hermes, Claude+Desktop), the chat providers (Anthropic, Google AI, OpenAI, Ollama, LM Studio),+and the services under **Integrations**. A pill fed by hooks says whether its+hooks are installed, never asks for a key; a local model server's pill says+whether the chat is connected to it. A session on a pill you didn't+declare still shows up, for as long as it runs.+## Claude Code<img src="screenshots/settings.png" width="562" alt="The settings window">@@@ -351,67 -170,18 +362,76 @@@ own windowthe top edge instead of hiding in a notch.- Permission approval works from **any** terminal; the Mac build only listens toVS Code sessions.-- Not in this version: sending a file by email, dragging Mochi onto a window to- attach it as context, and jumping to a specific terminal window — "Open- terminal" opens the working folder in VS Code when `code` is on your `PATH`.+- "Open terminal" finds the session's window by walking up from the relay's+ process to the terminal or editor that runs it. A session in a classic+ console window (`cmd.exe` or PowerShell without Windows Terminal) has no such+ ancestor — conhost owns that window — so its folder opens in VS Code instead,+ as it does when `code` is on your `PATH` and nothing was found.+- No global keyboard shortcuts yet: a waiting card is folded with its **⌃** or+ `Esc` in the island, and reopened by clicking the island or Open in the tray.+- Apple Music, the one pill from the Mac catalog with nothing behind it here,+ is left out.+- Not in this version: sending a dropped file by email and dragging Mochi onto+ a window to attach it as context. On the Mac, email goes through Resend or+ Apple Mail's scripting; neither has a safe equivalent that attaches a file+ here, and the drop card would need a third button it doesn't have.- Cal.com shows the next bookings as a list rather than the Mac's calendar.-- The wardrobe opens with a right-click on Mochi or from the tray menu; the- Mac's keyboard shortcut for it isn't there. In the compact island a tall hat+- The Cursor pill carries both Cursor Agent's own hooks and Claude Code running+ in Cursor's terminal.+- Hermes: Coucou writes the plugin but does not run the `hermes` CLI, so it is+ turned on once by hand. Hermes runs natively on Linux; on Windows it is+ untested.+- Plan usage: the user's previous status line runs through Git Bash on Windows+ (`/bin/sh` on Linux and Mac); without Git Bash it is not run, rather than+ guessed at with `cmd`. The Codex CLI is looked for on `PATH` and in npm's,+ Volta's, Bun's and pnpm's folders (and nvm's on Linux).+- The chat's model picker opens inside the chat card instead of a popover, and+ it also offers OpenRouter and any OpenAI-compatible server, which the Mac+ does not. Google AI, OpenAI and OpenRouter can see an image you dropped (sent+ inline), where the Mac sends its name only.+- Live diff: the relay forwards an edit's text whole only once the edit is done+ (PostToolUse), up to 256 KB per string and 512 KB per event. A bigger edit+ shows its "Modifie · file" step without counts rather than wrong ones. The+ diff's ↗ needs `code` on your `PATH`; without it, it opens the file's folder —+ never the file itself. Counts and diffs come from Claude Code's Edit,+ MultiEdit and Write, on whichever pill its session is on (VS Code, Cursor,+ Claude Desktop); other agents' edits show as plain steps.+- The GitHub lists are clicked, not walked with the arrow keys, and there is no+ iPhone to keep fetching them while the pill is off.+- Keyboard shortcuts use `Ctrl+Alt` where the Mac uses `⌃⌥`, with different+ keys (see [Keyboard shortcuts](#keyboard-shortcuts)), and `Ctrl` where the+ Mac uses `⌘` inside the island. "Bring the terminal forward" is "Open- terminal" here. Not in this version: sending Mochi to the desktop, attaching- the front window (their ids are kept for later), moving through a card's++ terminal" here. Not in this version: sending Mochi to the desktop from the++ keyboard (drag him out instead) and attaching the front window (their ids are++ kept for later), moving through a card's+ list (`⌘↑` `⌘↓` `⌘O`) and the diff (`⌘E`). The island only reads its own+ shortcuts while it has the keyboard: in the chat, or after a global shortcut+ opened it. **Go to alert** brings up any agent's waiting card on its own pill;+ **Toggle the island** folds a waiting card rather than dropping it, like `Esc`+ in the island.+- Weekly recap:+ - Sharing happens inside the island instead of a separate panel, and Save+ writes straight into Pictures (or Downloads) instead of asking where. There+ is no system Share sheet; Copy uses the web clipboard.+ - Questions are counted when an agent asks one (`AskUserQuestion`), whether+ it is then answered in the island or in the terminal. Permissions count the+ Allow and Deny clicks on the island's card, for every agent that gets one.+ - There is no sleep/wake notification to listen to without a background+ loop, so after the machine wakes the Monday card waits for the first agent+ to start or for you to hover the island.+ - The card is 24 px taller than the Mac's: it also lists top agent, project,+ busiest day, longest session, permissions and questions, which the Mac+ leaves to the image. A turn cut short by the session ending still counts.+ - Tray → Pause doesn't stop the history (it stays on the machine anyway);+ switch it off in Settings → General.++- The wardrobe opens with a right-click on Mochi, from the tray menu, or with++ its global shortcut (`Ctrl+Alt+G` by default). In the compact island a tall hat+ is cut by the top edge of the screen, as it is by the notch on a Mac.+ - Mochi on the desktop doesn't dance: there is no music integration to dance+ to. Dropping him on a window doesn't attach it to the chat, and the Mac's+ ⌃⌥D shortcut isn't there — drag him out, double-click him home. While he+ sleeps, the transparent square around him (120 px) takes the first mouse+ move, which wakes him and gives the rest back to the desktop.## Linux@@@ -452,41 -207,20 +472,48 @@@ What changes on Linux- **Click-through** is the window's input region, kept equal to the islandshape, so the compositor sends every other click to what is underneath.- **Mochi's eyes** follow the pointer only while it is over the island: Wayland- gives no app the cursor position anywhere else.+ gives no app the cursor position anywhere else. On the desktop, likewise,+ they follow it only while it is over him, and "the cursor is far away" (so+ he may fall asleep) means it hasn't been over him for a few seconds.+ - **Mochi on the desktop** is a layer-shell surface on the island's display+ (KDE Plasma, COSMIC, Hyprland, Sway…), placed with margins and dragged within+ that display; on X11 it is an ordinary always-on-top window that goes+ anywhere. **GNOME on Wayland** has no layer-shell and lets no app place its+ own window, so there Mochi can't leave the island: dragging him does nothing.- **Claude Code hooks** go through `~/.local/share/coucou/bin/coucou-hook` and aUnix socket at `$XDG_RUNTIME_DIR/coucou.sock`. Both ends check that the other- runs as the same user.+ runs as the same user. Every other agent uses the same relay, single-quoted+ for `sh`, and its config under `~` (see Supported agents). A config that is a+ symlink (dotfiles) is written through to its target, with its permissions+ kept.+- **Global shortcuts** are X11 key grabs, so they work in an X11 session.+ On X11, AltGr is a modifier of its own and never clashes with `Ctrl+Alt`;+ combinations the desktop already uses (GNOME's `Ctrl+Alt+T` terminal and+ `Ctrl+Alt+←`/`→` workspace switching) show up as *In use*. Wayland has no+ key grabs — the GlobalShortcuts portal isn't supported yet — so nothing is+ registered there, and **Settings → Shortcuts** lists commands to bind in your+ desktop's own keyboard settings instead:+ `coucou --shortcut openChat` (or the AppImage's path) runs the action in the+ Coucou that is already open. The ids are `toggleIsland`, `openChat`,+ `goToAlert`, `jumpToTerminal`, `nextPill`, `prevPill`, `muteToggle` and+ `wardrobeToggle`.- **Keys** live in the Secret Service (GNOME Keyring, KWallet).+- **Plan usage**: the status line relay is `~/.local/share/coucou/bin/coucou-hook+ --statusline` and runs your previous status line with `/bin/sh -c`, like Claude+ Code. Codex is found on `$PATH`, in `~/.local/bin`, npm's global prefix, Volta,+ Bun, pnpm, or nvm (newest Node first), since a desktop launch often has a+ shorter `$PATH` than your shell.+- **Mochi's greeting** uses the full name in your account's GECOS field+ (`chfn` sets it); without one the chat stays neutral.- **Files**: preferences in `~/.config/coucou/`, the log at- `~/.local/share/coucou/coucou.log`.+ `~/.local/share/coucou/coucou.log`, the weekly recap history beside it in+ `recap.json`. A saved recap image goes to the pictures folder named in+ `~/.config/user-dirs.dirs`, else `~/Pictures`, else `~/Downloads`.+- **Copying the recap image** needs a WebKitGTK with image clipboard support;+ where it is missing, the island says so and Save still works.- What the Windows build leaves out, this one does too: sending a file by- email, dragging Mochi onto a window, and jumping to a specific terminal- window — "Open terminal" opens the folder in VS Code.+ email and dragging Mochi onto a window.+- **Open terminal** opens the folder in VS Code: Wayland lets no app bring+ another app's window forward, and X11 would need a window-manager client this+ build doesn't carry.+- No **Claude Desktop** pill: the Claude app has no Linux build.diff --cc windows/src-tauri/src/lib.rsindex 37a95e18,948d7685..8259608b--- a/windows/src-tauri/src/lib.rs+++ b/windows/src-tauri/src/lib.rs@@@ -1,31 -1,17 +1,32 @@@// Coucou for Windows — app wiring and the commands the island calls.+mod agent_hooks;+mod agents;+mod chat;mod claude;- mod config_file;+mod codex_plan;++mod config_file;+ mod desktop;mod files;+mod github;mod hooks;+mod identity;mod integrations;mod island;+mod local_chat;mod log;+mod net;+mod openai_compat;mod pipe;mod platform;+mod recap;mod secrets;+mod session_window;mod settings;+mod shortcuts;mod tray;+#[cfg(windows)]+mod webview_drop;use std::process::Command;use std::sync::atomic::Ordering;@@@ -82,10 -66,13 +83,14 @@@ fn save_settings(app: AppHandle, sharedlet mut current = shared.settings.lock().unwrap();let screen_changed = current.screen != settings.screen;let autostart_changed = current.autostart != settings.autostart;+ let shortcuts_changed = current.shortcuts != settings.shortcuts;- *current = settings.clone();+ // Where Mochi sits on the desktop is desktop.rs's to say, not a webview's.+ let mut settings = settings.clone();+ settings.desktop_mochi = current.desktop_mochi.clone();+ *current = settings;- (screen_changed, autostart_changed)+ (screen_changed, autostart_changed, shortcuts_changed)};+ let settings = shared.settings.lock().unwrap().clone();if let Err(err) = settings::save(&settings) {log::line(format!("could not save settings: {err}"));}@@@ -649,34 -408,27 +654,46 @@@ pub fn run()open_n8n,open_settings_window,set_paused,+ shortcuts_status,+ shortcuts_suspend,+ recap::recap_history,+ recap::recap_prefs,+ recap::recap_set_enabled,+ recap::recap_set_hide_projects,+ recap::recap_mark_shown,+ recap::recap_clear,+ recap::recap_save_png,+ recap::recap_reveal_saved,+ desktop::desktop_mochi_info,+ desktop::desktop_mochi_pick_up,+ desktop::desktop_mochi_carry,+ desktop::desktop_mochi_carry_end,+ desktop::desktop_mochi_drag_begin,+ desktop::desktop_mochi_drag_move,+ desktop::desktop_mochi_drag_end,+ desktop::desktop_mochi_fly_out,+ desktop::desktop_mochi_fly_home,+ desktop::desktop_mochi_set_asleep,]).setup(move |app| {let handle = app.handle().clone();tray::build(&handle)?;// Before the island: see create_settings_window.create_settings_window(&handle);+ // Same rule for Mochi's desktop window.+ desktop::setup(&handle);if let Some(win) = island::window(&handle) {+ // Where Tauri takes the drop itself (Linux), its paths are the+ // ones ingest_file may copy (files.rs).+ win.on_window_event(|event| {+ if let tauri::WindowEvent::DragDrop(tauri::DragDropEvent::Drop { paths, .. }) = event {+ files::allow_dropped(paths.iter().map(|p| p.to_string_lossy().to_string()));+ }+ });platform::make_non_activating(&win);+ #[cfg(windows)]+ webview_drop::install(&handle);island::apply_geometry(&handle, &loaded.screen, false);let _ = win.show();}diff --cc windows/src-tauri/src/platform/linux.rsindex 49119f29,d4e4581d..38dff741--- a/windows/src-tauri/src/platform/linux.rs+++ b/windows/src-tauri/src/platform/linux.rs@@@ -373,12 -221,7 +383,11 @@@ pub fn unblock_webview_drops(_app: &App/// up to the window manager.pub fn make_non_activating(win: &WebviewWindow) {let Ok(gw) = win.gtk_window() else { return };+ // The pointer watch reports the pointer leaving on every kind of window:+ // a regular one (GNOME, X11) misses `mouseout` just as a layer surface does.+ ISLAND_GTK.with(|cell| *cell.borrow_mut() = Some(gw.clone()));+ watch_pointer_leave(win);- // COUCOU_LAYER_SHELL=0 is the way out on a compositor where it misbehaves.- let wanted = std::env::var("COUCOU_LAYER_SHELL").map(|v| v != "0").unwrap_or(true);+ let wanted = layer_shell_wanted();let supported = unsafe { layer::gtk_layer_is_supported() } != 0;if !wanted || !supported || gw.is_realized() {let why = if !wanted {@@@ -575,33 -310,174 +584,201 @@@ fn apply_input_region(gw: &impl IsA<gtk}}+// ── Global shortcuts ──────────────────────────────────────────────────────────++/// Global shortcuts are X11 key grabs. A Wayland session has no such thing: a+/// grab made through XWayland only sees keys typed into other X11 windows, so+/// it would look registered and never fire. The XDG GlobalShortcuts portal is+/// the Wayland way and isn't wired up yet, so on Wayland nothing is registered+/// and Settings explains how to bind `coucou --shortcut <id>` in the desktop's+/// own keyboard settings instead.+pub fn global_shortcuts_blocked() -> Option<&'static str> {+ let set = |var: &str| std::env::var_os(var).is_some_and(|v| !v.is_empty());+ let wayland = set("WAYLAND_DISPLAY")+ || std::env::var("XDG_SESSION_TYPE").is_ok_and(|v| v.eq_ignore_ascii_case("wayland"));+ if wayland {+ Some("wayland")+ } else if !set("DISPLAY") {+ Some("no-display")+ } else {+ None+ }+}++/// On X11, AltGr is a modifier of its own (ISO_Level3_Shift): Ctrl+Alt+key+/// never stands for it, so no combination takes a character away.+pub fn ctrl_alt_types(_vk: u16, _shift: bool) -> Option<String> {+ None+}++ // ── Desktop Mochi window ──────────────────────────────────────────────────────+ //+ // Where the window may go decides everything here:+ // * X11 places any window where it is asked: an ordinary always-on-top+ // window, moved with set_position;+ // * a layer-shell compositor won't move a toplevel, but anchors a layer+ // surface wherever its margins say, on the island's display;+ // * GNOME on Wayland has neither, so the feature is off there.+ // In every case the input region is Mochi's body, so clicks anywhere else go+ // to the desktop underneath without any cursor polling.++ /// Which of the three applies. Must run on the GTK main thread.+ pub fn desktop_mode() -> super::DesktopMode {+ use gtk::glib::prelude::ObjectExt;+ let wayland = gtk::gdk::Display::default()+ .map(|d| d.type_().name().contains("Wayland"))+ .unwrap_or(false);+ let layer = layer_shell_wanted() && unsafe { layer::gtk_layer_is_supported() } != 0;+ if layer {+ super::DesktopMode::Layer+ } else if !wayland {+ super::DesktopMode::Window+ } else {+ super::DesktopMode::Off+ }+ }++ /// The input shape last asked for the desktop Mochi, re-applied on every map.+ static MOCHI_SHAPE: Mutex<super::MouseShape> = Mutex::new(super::MouseShape::Empty);++ /// Sets the window up for `mode` before it is ever shown. False means it can't+ /// be used (a layer surface can't be made from a window already shown).+ pub fn prepare_desktop_window(win: &WebviewWindow, mode: super::DesktopMode) -> bool {+ let Ok(gw) = win.gtk_window() else { return false };+ gw.set_accept_focus(false);+ match mode {+ super::DesktopMode::Layer => {+ if gw.is_realized() {+ crate::log::line("desktop Mochi: window already shown, no layer surface");+ return false;+ }+ gw.set_titlebar(None::<>k::Widget>);+ let ptr = gtk_window_ptr(&gw);+ unsafe {+ layer::gtk_layer_init_for_window(ptr);+ layer::gtk_layer_set_namespace(ptr, c"coucou-mochi".as_ptr());+ // Above windows, below fullscreen video — like a floating panel.+ layer::gtk_layer_set_layer(ptr, layer::LAYER_TOP);+ layer::gtk_layer_set_anchor(ptr, layer::EDGE_TOP, 1);+ layer::gtk_layer_set_anchor(ptr, layer::EDGE_LEFT, 1);+ // -1: margins count from the display's corner, panels or not,+ // the same origin the island uses.+ layer::gtk_layer_set_exclusive_zone(ptr, -1);+ layer::gtk_layer_set_keyboard_mode(ptr, layer::KEYBOARD_NONE);+ }+ // Same first-frame problem as the island (see make_non_activating).+ let remapped = std::cell::Cell::new(false);+ gw.connect_map_event(move |w, _| {+ apply_mouse_shape(w, *MOCHI_SHAPE.lock().unwrap());+ if !remapped.replace(true) {+ let w = w.clone();+ gtk::glib::idle_add_local_once(move || {+ w.hide();+ w.show_all();+ apply_mouse_shape(&w, *MOCHI_SHAPE.lock().unwrap());+ });+ }+ gtk::glib::Propagation::Proceed+ });+ true+ }+ super::DesktopMode::Window => {+ gw.connect_map_event(|w, _| {+ apply_mouse_shape(w, *MOCHI_SHAPE.lock().unwrap());+ gtk::glib::Propagation::Proceed+ });+ true+ }+ _ => false,+ }+ }++ /// Which part of the desktop Mochi takes the mouse. Main thread.+ pub fn set_desktop_shape(win: &WebviewWindow, shape: super::MouseShape) {+ *MOCHI_SHAPE.lock().unwrap() = shape;+ let Ok(gw) = win.gtk_window() else { return };+ apply_mouse_shape(&gw, shape);+ }++ fn apply_mouse_shape(gw: &impl IsA<gtk::Widget>, shape: super::MouseShape) {+ use gtk::cairo::{RectangleInt, Region};+ if shape == super::MouseShape::Whole {+ gw.input_shape_combine_region(None);+ return;+ }+ let Some(gdk_window) = gw.window() else { return };+ match shape {+ super::MouseShape::Whole => {}+ super::MouseShape::Empty => {+ let region = Region::create_rectangle(&RectangleInt::new(0, 0, 0, 0));+ gdk_window.input_shape_combine_region(®ion, 0, 0);+ }+ super::MouseShape::Disc { cx, cy, r } => {+ // A region is made of rectangles: stack 2 px rows into a disc.+ let region = Region::create_rectangle(&RectangleInt::new(0, 0, 0, 0));+ let mut y = (cy - r).floor();+ while y < cy + r {+ let mid = y + 1.0 - cy;+ let half = (r * r - mid * mid).max(0.0).sqrt();+ let row = RectangleInt::new(+ (cx - half).floor() as i32,+ y as i32,+ (2.0 * half).ceil() as i32,+ 2,+ );+ let _ = region.union_rectangle(&row);+ y += 2.0;+ }+ gdk_window.input_shape_combine_region(®ion, 0, 0);+ }+ }+ }++ /// Layer surface only: puts the top-left corner at (x, y), logical pixels from+ /// the display's corner. Main thread.+ pub fn set_layer_margins(win: &WebviewWindow, x: f64, y: f64) {+ let Ok(gw) = win.gtk_window() else { return };+ let ptr = gtk_window_ptr(&gw);+ unsafe {+ layer::gtk_layer_set_margin(ptr, layer::EDGE_LEFT, x.round() as i32);+ layer::gtk_layer_set_margin(ptr, layer::EDGE_TOP, y.round() as i32);+ }+ }++ /// Layer surface only: `on` stretches it over the whole display — how a drag+ /// gets exact pointer positions on Wayland, where a surface that moves under+ /// the pointer can't tell where it is — and `off` folds it back to Mochi's+ /// size in the corner. Main thread.+ pub fn set_layer_overlay(win: &WebviewWindow, on: bool) {+ let Ok(gw) = win.gtk_window() else { return };+ let ptr = gtk_window_ptr(&gw);+ unsafe {+ layer::gtk_layer_set_anchor(ptr, layer::EDGE_RIGHT, on as i32);+ layer::gtk_layer_set_anchor(ptr, layer::EDGE_BOTTOM, on as i32);+ if on {+ layer::gtk_layer_set_margin(ptr, layer::EDGE_LEFT, 0);+ layer::gtk_layer_set_margin(ptr, layer::EDGE_TOP, 0);+ }+ }+ }++ /// Layer surface only: puts the desktop Mochi on the island's display and+ /// returns that display's logical size. Main thread.+ pub fn layer_display(island: &WebviewWindow, mochi: &WebviewWindow) -> Option<(f64, f64)> {+ let island_gw = island.gtk_window().ok()?;+ let display = gtk::gdk::Display::default()?;+ let monitor = island_gw+ .window()+ .and_then(|w| display.monitor_at_window(&w))+ .or_else(|| display.primary_monitor())+ .or_else(|| display.monitor(0))?;+ if let Ok(gw) = mochi.gtk_window() {+ unsafe { layer::gtk_layer_set_monitor(gtk_window_ptr(&gw), monitor.to_glib_none().0) };+ }+ let g = monitor.geometry();+ Some((g.width() as f64, g.height() as f64))+ }+#[cfg(test)]mod tests {use super::*;diff --cc windows/src-tauri/src/platform/windows.rsindex c7a84e01,604ed2dc..8e7efc07--- a/windows/src-tauri/src/platform/windows.rs+++ b/windows/src-tauri/src/platform/windows.rs@@@ -344,170 -234,30 +344,198 @@@ pub fn set_activating(win: &WebviewWind/// Click-through here is the poll's WS_EX_TRANSPARENT toggle, not a region.pub fn set_input_region(_win: &WebviewWindow, _rect: Option<(f64, f64, f64, f64)>) {}+/// The cursor poll already parks itself with the island (island.rs): nothing to do.+pub fn set_pointer_watch(_active: bool) {}++/// `set_position` already places a Win32 window on the right display.+pub fn pin_to_monitor(_win: &WebviewWindow, _x: i32, _y: i32) {}++// ── Session windows ("Open terminal") ─────────────────────────────────────────+//+// See session_window.rs: the relay's ancestors lead to the terminal or editor+// window a Claude Code session runs in.++/// The process on the other end of a relay connection.+pub fn pipe_client_pid(handle: RawHandle) -> Option<u32> {+ let mut pid = 0u32;+ unsafe { GetNamedPipeClientProcessId(HANDLE(handle), &mut pid).ok()? };+ (pid != 0).then_some(pid)+}++/// Every process, by ID: its parent and its executable's name.+fn process_table() -> HashMap<u32, Proc> {+ let mut out = HashMap::new();+ unsafe {+ let Ok(snapshot) = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) else { return out };+ let mut entry = PROCESSENTRY32W {+ dwSize: std::mem::size_of::<PROCESSENTRY32W>() as u32,+ ..Default::default()+ };+ let mut more = Process32FirstW(snapshot, &mut entry).is_ok();+ while more {+ let len = entry.szExeFile.iter().position(|c| *c == 0).unwrap_or(entry.szExeFile.len());+ out.insert(+ entry.th32ProcessID,+ Proc {+ parent: entry.th32ParentProcessID,+ exe: String::from_utf16_lossy(&entry.szExeFile[..len]),+ },+ );+ more = Process32NextW(snapshot, &mut entry).is_ok();+ }+ let _ = CloseHandle(snapshot);+ }+ out+}++/// The ancestors of a process, nearest first, below the desktop shell.+pub fn process_ancestors(pid: u32) -> Vec<u32> {+ session_window::ancestors(&process_table(), pid)+}++/// Visible top-level windows that are nobody's dialog and have a title:+/// (handle, process ID, title).+fn top_windows() -> Vec<(isize, u32, String)> {+ unsafe extern "system" fn collect(hwnd: HWND, lparam: LPARAM) -> BOOL {+ let list = unsafe { &mut *(lparam.0 as *mut Vec<(isize, u32, String)>) };+ unsafe {+ if !IsWindowVisible(hwnd).as_bool() || GetWindow(hwnd, GW_OWNER).is_ok() {+ return true.into();+ }+ let mut pid = 0u32;+ GetWindowThreadProcessId(hwnd, Some(&mut pid as *mut u32));+ let mut text = [0u16; 512];+ let len = GetWindowTextW(hwnd, &mut text);+ if len > 0 {+ list.push((hwnd.0 as isize, pid, String::from_utf16_lossy(&text[..len as usize])));+ }+ }+ true.into()+ }+ let mut list: Vec<(isize, u32, String)> = Vec::new();+ unsafe {+ let _ = EnumWindows(Some(collect), LPARAM(&mut list as *mut _ as isize));+ }+ list+}++/// The first of `pids` that owns a window.+pub fn first_with_window(pids: &[u32]) -> Option<u32> {+ let windows = top_windows();+ pids.iter().copied().find(|pid| windows.iter().any(|(_, owner, _)| owner == pid))+}++fn bring_forward(raw: isize) -> bool {+ let hwnd = HWND(raw as *mut _);+ unsafe {+ if IsIconic(hwnd).as_bool() {+ let _ = ShowWindow(hwnd, SW_RESTORE);+ }+ // Allowed: the click on the island that asked for this was the last input.+ SetForegroundWindow(hwnd).as_bool()+ }+}++/// Brings `pid`'s window forward — the one titled after `folder` if there are several.+pub fn focus_process_window(pid: u32, folder: &str) -> bool {+ let candidates: Vec<(isize, String)> = top_windows()+ .into_iter()+ .filter(|(_, owner, _)| *owner == pid)+ .map(|(hwnd, _, title)| (hwnd, title))+ .collect();+ session_window::pick_window(&candidates, folder).is_some_and(|hwnd| bring_forward(*hwnd))+}++/// Brings forward the window of a running app, by executable name.+fn focus_app(exe: &str) -> bool {+ let pids: Vec<u32> = process_table()+ .into_iter()+ .filter(|(_, p)| p.exe.eq_ignore_ascii_case(exe))+ .map(|(pid, _)| pid)+ .collect();+ top_windows()+ .into_iter()+ .find(|(_, owner, _)| pids.contains(owner))+ .is_some_and(|(hwnd, _, _)| bring_forward(hwnd))+}++/// The Claude desktop app: brought forward when it runs (Claude Code's own+/// `claude.exe` has no window of its own, so it is never the one picked),+/// started from where its installer puts it otherwise.+pub fn open_claude_desktop() -> bool {+ if focus_app("claude.exe") {+ return true;+ }+ let Some(base) = std::env::var_os("LOCALAPPDATA") else { return false };+ let exe = PathBuf::from(base).join("AnthropicClaude").join("claude.exe");+ exe.is_file() && Command::new(exe).spawn().is_ok()+}++// ── Global shortcuts ──────────────────────────────────────────────────────────++/// RegisterHotKey works in every Windows session.+pub fn global_shortcuts_blocked() -> Option<&'static str> {+ None+}++/// The character Ctrl+Alt(+Shift)+`vk` types on one of the installed keyboard+/// layouts, if any. Windows reads Ctrl+Alt as AltGr, so registering such a+/// combination as a global shortcut would stop the user typing that character+/// (AltGr+E is € on most European layouts, AltGr+A is ą in Polish).+pub fn ctrl_alt_types(vk: u16, shift: bool) -> Option<String> {+ let mut layouts = [HKL::default(); 32];+ let count = unsafe { GetKeyboardLayoutList(Some(&mut layouts[..])) };+ let count = usize::try_from(count).unwrap_or(0).min(layouts.len());++ let mut state = [0u8; 256];+ state[VK_CONTROL.0 as usize] = 0x80;+ state[VK_MENU.0 as usize] = 0x80;+ if shift {+ state[VK_SHIFT.0 as usize] = 0x80;+ }+ for &layout in &layouts[..count] {+ let scan = unsafe { MapVirtualKeyExW(u32::from(vk), MAPVK_VK_TO_VSC, Some(layout)) };+ let mut buf = [0u16; 8];+ // Flag 0x4: leave the keyboard state alone, so a dead key met here+ // doesn't change what the user types next (Windows 10 1607 and later).+ let n = unsafe { ToUnicodeEx(u32::from(vk), scan, &state, &mut buf, 0x4, Some(layout)) };+ let typed = match n {+ // A dead key (´ ^ ¨…) is still something the user types with it.+ n if n < 0 => String::from_utf16_lossy(&buf[..1]),+ 0 => continue,+ n => String::from_utf16_lossy(&buf[..(n as usize).min(buf.len())]),+ };+ if typed.chars().any(|c| !c.is_control()) {+ return Some(typed);+ }+ }+ None+}+++ // ── Desktop Mochi window ──────────────────────────────────────────────────────++ /// Windows places a window wherever it is asked, and the cursor poll is there.+ pub fn desktop_mode() -> super::DesktopMode {+ super::DesktopMode::Poll+ }++ /// Same window styles as the island: never takes focus, never in Alt-Tab (it+ /// is created without a taskbar button).+ pub fn prepare_desktop_window(win: &WebviewWindow, _mode: super::DesktopMode) -> bool {+ make_non_activating(win);+ true+ }++ /// The cursor poll toggles WS_EX_TRANSPARENT from the body hit test instead.+ pub fn set_desktop_shape(_win: &WebviewWindow, _shape: super::MouseShape) {}++ /// Layer-shell only (Linux).+ pub fn set_layer_margins(_win: &WebviewWindow, _x: f64, _y: f64) {}++ /// Layer-shell only (Linux).+ pub fn set_layer_overlay(_win: &WebviewWindow, _on: bool) {}++ /// Layer-shell only (Linux): the logical size of the display the island is on.+ pub fn layer_display(_island: &WebviewWindow, _mochi: &WebviewWindow) -> Option<(f64, f64)> {+ None+ }diff --cc windows/src-tauri/src/settings.rsindex ffc43368,0cf69499..5826b514--- a/windows/src-tauri/src/settings.rs+++ b/windows/src-tauri/src/settings.rs@@@ -26,30 -23,30 +26,54 @@@ pub struct Settingspub hooks_installed: bool,/// Claude model used by the chat. Changeable in the settings window.pub model: String,+ /// Show the Claude plan pill (5 h and weekly limits) in the island's header.+ /// Off until the user turns it on, so the header stays as it shipped.+ pub show_plan_in_notch: bool,+ /// Coucou's status line relay is the one in Claude Code's settings.json.+ /// Like `hooks_installed`, the real state wins at launch over what was stored.+ pub plan_relay_installed: bool,+ /// Show the Codex plan pill (5 h / weekly limits from `codex app-server`).+ /// Off by default; nothing is installed for it.+ pub show_codex_plan_in_notch: bool,+ /// Who the chat talks to: "anthropic", a cloud provider of+ /// openai_compat.rs ("openai", "google", "openrouter"), or a model server+ /// of local_chat.rs ("ollama", "lmstudio", "custom"). Picked in the chat view.+ pub chat_provider: String,+ /// The model picked for each provider other than Anthropic (whose model is+ /// `model`), by provider id.+ pub chat_models: BTreeMap<String, String>,+ /// Addresses of the model servers once connected; empty means not connected.+ pub ollama_url: String,+ pub lmstudio_url: String,+ /// Any other OpenAI-compatible server; its key, if any, is in the keychain.+ pub custom_url: String,+ /// Global shortcuts the user changed, by action id; the others keep their+ /// default (see shortcuts.rs).+ pub shortcuts: crate::shortcuts::Bindings,+ /// Mochi's outfit, picked in the wardrobe: "auto" (dresses for the+ /// season), "none" or an outfit id — the Mac's raw values. The island reads+ /// anything it doesn't know as "auto", so the value is stored as it comes.+ pub mochi_outfit: String,+ /// Mochi on the desktop: whether he lives there, and his spot. Owned by+ /// the Rust side (desktop.rs) — what a webview sends back is ignored.+ pub desktop_mochi: DesktopMochiPref,+ }++ #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]+ #[serde(rename_all = "camelCase", default)]+ pub struct DesktopMochiPref {+ /// He was on the desktop when the app quit: he flies back out at launch.+ pub on_desktop: bool,+ /// Top-left corner of his window where the user last left him.+ pub spot: Option<DesktopSpot>,+ }++ #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+ pub struct DesktopSpot {+ pub x: f64,+ pub y: f64,+ /// What x and y are measured in (`DesktopMode::space`).+ pub space: String,}fn default_model() -> String {@@@ -74,15 -70,8 +98,17 @@@ impl Default for Settingsautostart: false,hooks_installed: false,model: default_model(),+ show_plan_in_notch: false,+ plan_relay_installed: false,+ show_codex_plan_in_notch: false,+ chat_provider: crate::chat::ANTHROPIC.into(),+ chat_models: BTreeMap::new(),+ ollama_url: String::new(),+ lmstudio_url: String::new(),+ custom_url: String::new(),+ shortcuts: Default::default(),+ mochi_outfit: "auto".into(),+ desktop_mochi: DesktopMochiPref::default(),}}}@@@ -345,15 -333,8 +371,17 @@@ mod tests"autostart": true,"hooksInstalled": true,"model": "some-model",+ "showPlanInNotch": true,+ "planRelayInstalled": true,+ "showCodexPlanInNotch": true,+ "chatProvider": "ollama",+ "chatModels": { "ollama": "llama3.2", "openai": "gpt-x" },+ "ollamaUrl": "http://127.0.0.1:11434",+ "lmstudioUrl": "http://127.0.0.1:1234",+ "customUrl": "https://llm.example.com",- "shortcuts": { "openChat": { "keys": "Ctrl+Shift+K", "enabled": false } }++ "shortcuts": { "openChat": { "keys": "Ctrl+Shift+K", "enabled": false } },+ "mochiOutfit": "witchHat",+ "desktopMochi": { "onDesktop": true, "spot": { "x": 1500.5, "y": -300.0, "space": "screen" } }}"#;fn custom() -> Value {@@@ -682,15 -700,8 +750,17 @@@"autostart","hooksInstalled","model",+ "showPlanInNotch",+ "planRelayInstalled",+ "showCodexPlanInNotch",+ "chatProvider",+ "chatModels",+ "ollamaUrl",+ "lmstudioUrl",+ "customUrl",+ "shortcuts",+ "mochiOutfit",+ "desktopMochi",]);let _ = std::fs::remove_dir_all(&dir);diff --cc windows/src-tauri/src/tray.rsindex 5be80b18,559f6b4e..e7f06c05--- a/windows/src-tauri/src/tray.rs+++ b/windows/src-tauri/src/tray.rs@@@ -1,4 -1,4 +1,4 @@@- // Notification-area icon: Open, Weekly recap, Settings, Pause, Quit.-// Notification-area icon: Open, Wardrobe, Settings, Pause, Quit.++// Notification-area icon: Open, Weekly recap, Wardrobe, Settings, Pause, Quit.use tauri::menu::{Menu, MenuItem, PredefinedMenuItem};use tauri::tray::TrayIconBuilder;@@@ -8,14 -8,14 +8,15 @@@ use crate::island::WINDOW_LABELpub fn build(app: &AppHandle) -> tauri::Result<()> {let open = MenuItem::with_id(app, "open", "Open Coucou", true, None::<&str>)?;+ let recap = MenuItem::with_id(app, "recap", "Weekly recap", true, None::<&str>)?;+ let wardrobe = MenuItem::with_id(app, "wardrobe", "Wardrobe…", true, None::<&str>)?;let settings = MenuItem::with_id(app, "settings", "Settings…", true, None::<&str>)?;let pause = MenuItem::with_id(app, "pause", "Pause", true, None::<&str>)?;let quit = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?;let sep1 = PredefinedMenuItem::separator(app)?;let sep2 = PredefinedMenuItem::separator(app)?;- let menu = Menu::with_items(app, &[&open, &recap, &sep1, &settings, &pause, &sep2, &quit])?;- let menu = Menu::with_items(app, &[&open, &sep1, &wardrobe, &settings, &pause, &sep2, &quit])?;++ let menu = Menu::with_items(app, &[&open, &recap, &sep1, &wardrobe, &settings, &pause, &sep2, &quit])?;let mut builder = TrayIconBuilder::with_id("coucou").tooltip("Coucou")diff --cc windows/src/core/bridge.tsindex 01328da6,faa26d40..8217a100--- a/windows/src/core/bridge.ts+++ b/windows/src/core/bridge.ts@@@ -3,10 -3,9 +3,10 @@@// `npm run dev` alone.import { invoke } from "@tauri-apps/api/core";- import { listen } from "@tauri-apps/api/event";+ import { emitTo, listen } from "@tauri-apps/api/event";import { getCurrentWebview } from "@tauri-apps/api/webview";import type { Settings } from "./state";+import type { RecapHistory, RecapPrefs } from "../recap/summary";export const IS_TAURI =typeof window !== "undefined" && "__TAURI_INTERNALS__" in window;@@@ -157,38 -100,45 +157,77 @@@ export const Bridge =/** Tray → Pause. Stops the integration pollers, not just the island. */setPaused: (paused: boolean) => call<void>("set_paused", { paused }),+ // ── Global shortcuts ──────────────────────────────────────────────────────+ /** How each global shortcut went when Rust last registered them. */+ shortcutsStatus: () => call<ShortcutsReport>("shortcuts_status"),+ /** Lets go of every global shortcut while Settings records a new one. */+ shortcutsSuspend: (suspended: boolean) => call<void>("shortcuts_suspend", { suspended }),+++ // ── Weekly recap ──────────────────────────────────────────────────────────+ /** Turns and decisions from `since` (Unix seconds) on, plus the recap prefs. */+ recapHistory: (since: number) => call<RecapHistory>("recap_history", { since: Math.floor(since) }),+ recapPrefs: () => call<RecapPrefs>("recap_prefs"),+ recapSetEnabled: (enabled: boolean) => call<void>("recap_set_enabled", { enabled }),+ recapSetHideProjects: (hide: boolean) => call<void>("recap_set_hide_projects", { hide }),+ /** `week` is the Monday (YYYY-MM-DD) the recap opened on its own for. */+ recapMarkShown: (week: string) => call<void>("recap_mark_shown", { week }),+ recapClear: () => call<void>("recap_clear"),+ /** Writes the PNG (a data URL) into Pictures or Downloads; returns its path. */+ recapSavePng: (data: string, week: string) => callOrThrow<string>("recap_save_png", { data, week }),+ /** Opens the folder of the image saved last. */+ recapRevealSaved: () => call<void>("recap_reveal_saved"),+++ // ── Mochi on the desktop (src-tauri/src/desktop.rs) ───────────────────────+ desktopInfo: () => call<DesktopInfo>("desktop_mochi_info"),+ /** Dragged out of the island: (x, y) is the pointer in island-window coordinates. */+ desktopPickUp: (x: number, y: number) => call<boolean>("desktop_mochi_pick_up", { x, y }),+ /** Linux: the pointer moved during that drag (Windows carries him from Rust). */+ desktopCarry: (x: number, y: number) => call<void>("desktop_mochi_carry", { x, y }),+ desktopCarryEnd: (x: number, y: number) => call<void>("desktop_mochi_carry_end", { x, y }),+ /** A drag started on the desktop Mochi; resolves to his top-left corner. */+ desktopDragBegin: () => call<[number, number] | null>("desktop_mochi_drag_begin"),+ /** X11: top-left corner, physical pixels. */+ desktopDragMove: (x: number, y: number) => call<void>("desktop_mochi_drag_move", { x, y }),+ desktopDragEnd: (x: number, y: number) => call<void>("desktop_mochi_drag_end", { x, y }),+ /** From the island to his spot. False: no spot on any connected display. */+ desktopFlyOut: () => call<boolean>("desktop_mochi_fly_out"),+ /** To the island, then hidden. `forget`: he lives in the island again. */+ desktopFlyHome: (forget: boolean) => call<boolean>("desktop_mochi_fly_home", { forget }),+ /** Asleep, the cursor poll stops. */+ desktopSetAsleep: (asleep: boolean) => call<void>("desktop_mochi_set_asleep", { asleep }),};+export type ShortcutStatus =+ | "active" | "off" | "inUse" | "duplicate" | "invalid"+ | "typesCharacter" | "unsupported" | "notPorted";++export interface ShortcutsReport {+ actions: { id: string; status: ShortcutStatus; typed?: string }[];+ /** "wayland" or "no-display" when no global shortcut can be registered. */+ blocked: string | null;+ /** `<executable> --shortcut`: append an action id for a desktop shortcut. */+ command: string;+}++ /** How the desktop Mochi's window works here (platform::DesktopMode). */+ export type DesktopMode = "poll" | "window" | "layer" | "off";++ export interface DesktopInfo {+ mode: DesktopMode;+ /** He was on the desktop when the app last quit. */+ onDesktop: boolean;+ }++ /** An event for one window only (island ⇄ desktop Mochi). Never throws. */+ export async function emitToWindow(label: string, event: string, payload?: unknown) {+ if (!IS_TAURI) return;+ try {+ await emitTo(label, event, payload);+ } catch (err) {+ console.error(`[coucou] emit ${event} failed`, err);+ }+ }+export interface IntegrationUpdate {id: string;data: Record<string, unknown>;diff --cc windows/src/core/layout.tsindex b2697e8e,0f0b2997..9853591e--- a/windows/src/core/layout.ts+++ b/windows/src/core/layout.ts@@@ -22,7 -22,7 +22,8 @@@ export type IslandViewName| "note"| "settings"| "greeting"- | "recap";++ | "recap"+ | "wardrobe";export type BotStateName =| "idle"@@@ -87,10 -87,7 +88,11 @@@ export const VIEW_LAYOUTS: Record<Islannote: { height: 160, botX: 60, botY: null, botDiameter: 50, agentMode: "column" },settings: { height: 160, botX: 54, botY: null, botDiameter: 46, agentMode: "none" },greeting: { height: 150, botX: 320, botY: 90, botDiameter: 0, agentMode: "none" },+ // Mac: 160. The extra 24 hold the two lines with top agent, project, busiest+ // day, longest session, permissions and questions, which the Mac card leaves+ // to the shared image.+ recap: { height: 184, botX: 62, botY: null, botDiameter: 58, agentMode: "column" },+ wardrobe: { height: 160, botX: 68, botY: null, botDiameter: 58, agentMode: "none" },};// The upload views above are only the fallback geometry. Once a file is actuallydiff --cc windows/src/core/state.tsindex c99a1306,674b611d..e4a6878a--- a/windows/src/core/state.ts+++ b/windows/src/core/state.ts@@@ -2,14 -2,7 +2,15 @@@import type { BotEmoteName, BotStateName, IslandMode, IslandViewName } from "./layout";import type { EyeShape } from "../mochi/engine";+import {+ DEFAULT_MAIN_PILL, HOST_OS, availablePills, orderPills, pillDefinition, sanitizeDeclared,+ toggleDeclared, type HostOs, type PillDefinition,+} from "./pills";+import type { CodexPlanUsage, PlanUsage } from "./plan";+import type { ProviderId } from "./providers";+import type { FileDiff } from "./diff";+import type { Bindings } from "./shortcuts";+ import { DEFAULT_OUTFIT, type Outfit } from "../mochi/wardrobe";export type AgentSource = "claudeCode" | "n8n" | "agent";export type PillBadge = "approval" | "finished" | "error";@@@ -109,22 -93,16 +110,32 @@@ export interface SettingshooksInstalled: boolean;/** Claude model used by the chat. */model: string;+ /** Show the Claude plan pill (5 h and weekly limits) in the island's header. */+ showPlanInNotch: boolean;+ /** Coucou's status line relay is installed in Claude Code's settings. */+ planRelayInstalled: boolean;+ /** Show the Codex plan pill in the island's header. */+ showCodexPlanInNotch: boolean;+ /** Who the chat talks to (see core/providers.ts); picked in the chat view. */+ chatProvider: ProviderId;+ /** The model picked for each provider other than Anthropic, by provider id. */+ chatModels: Record<string, string>;+ /** Model server addresses once connected; empty means not connected. */+ ollamaUrl: string;+ lmstudioUrl: string;+ customUrl: string;+ /** Global shortcuts the user changed, by action id (see core/shortcuts.ts). */+ shortcuts: Bindings;+ /**+ * Mochi's outfit: "auto" (dresses for the season), "none" or an outfit id.+ * Same raw values as the Mac's "mochiOutfit"; read it through parseOutfit.+ */+ mochiOutfit: string;+ /** Mochi on the desktop. Rust owns it: whatever the page sends back is ignored. */+ desktopMochi?: {+ onDesktop: boolean;+ spot: { x: number; y: number; space: string } | null;+ };}export const DEFAULT_SETTINGS: Settings = {@@@ -140,15 -117,7 +151,16 @@@autostart: false,hooksInstalled: false,model: "claude-opus-5",+ showPlanInNotch: false,+ planRelayInstalled: false,+ showCodexPlanInNotch: false,+ chatProvider: "anthropic",+ chatModels: {},+ ollamaUrl: "",+ lmstudioUrl: "",+ customUrl: "",+ shortcuts: {},+ mochiOutfit: DEFAULT_OUTFIT,};type Listener = () => void;@@@ -190,19 -152,14 +202,27 @@@ class AppStateintegrations: Record<string, IntegrationInfo> = {};+ /** Claude's 5 h / weekly limits, from the status line (null until the first call). */+ planUsage: PlanUsage | null = null;+ /** Codex's limits, from `codex app-server` (null until it has answered). */+ codexPlanUsage: CodexPlanUsage | null = null;+ /** A plan card is open in place of the overview's left card. */+ showingPlanDetail = false;+ /** Which one: the Codex card rather than Claude's. */+ planDetailIsCodex = false;+ /** Per-pill file diffs, in order of reception. Steps carry their ids. */+ sessionDiffs = new Map<string, FileDiff[]>();+ private sessionDiffTimers = new Map<string, number>();+ /** Never reset, so an id can never point at a newer diff than the one tapped. */+ private nextDiffId = 0;+ /**+ * Mochi is out of the island — on the desktop, flying, or being dragged+ * there — so the island's own Mochi is hidden (AppState.mochiOnDesktop).+ */+ mochiOnDesktop = false;++ /** Outfit shown on Mochi while the pointer rests on a wardrobe button. */+ wardrobePreview: Outfit | null = null;lastActivity = performance.now();diff --cc windows/src/island/island.tsindex af0814fd,bcd8b4f8..43279c29--- a/windows/src/island/island.ts+++ b/windows/src/island/island.ts@@@ -15,16 -14,20 +15,21 @@@ import { State } from "../core/state"import { BotEngine, hexToRGB } from "../mochi/engine";import { Greeting } from "../mochi/greeting";import { createMiniBot, pruneMiniBots, syncMiniBotStates, tickMiniBots } from "../mochi/minibots";+ import { SeasonCache, parseOutfit } from "../mochi/wardrobe";import { UploadCanvas } from "../upload/canvas";import { USC, UploadSeq } from "../upload/sequence";+import { closePlanCard, openPlanColor, planCardOpen } from "../views/usage";import { buildHeader, buildViews, type ViewActions, type ViewHost } from "../views/views";import { h } from "../views/dom";import { IslandStateMachine } from "./fsm";+import { refreshHookPills } from "./integrations";+ import { DesktopLink } from "./desktop";+ import { DRAG_THRESHOLD } from "../mochi/desktop-logic";const BOT_OVERHANG = 40;+const CLAUDE_DESKTOP_ID = "agent_claude-desktop";+ /** Extra canvas on each side of Mochi, for the witch hat's brim and the Santa hat's tip. */+ const BOT_SIDE = 24;-/** The pill whose Mochi wears the outfit; any other focused pill takes its own look. */-const MAIN_PILL = "integration_claude";/** Same margin as the Rust hit test (src-tauri/src/island.rs). */const HIT_MARGIN = 14;@@@ -87,11 -95,9 +96,14 @@@ export class Islandprivate prevViewBeforeConfused: IslandViewName = "overview";private lastSyncedView: IslandViewName | null = null;+ /** The launch greeting ended, or the island came out of hidden — two of the+ * moments the Monday recap may open (see src/recap/recap.ts). */+ onGreetingDone: (() => void) | null = null;+ onWake: (() => void) | null = null;++ /** Where a press on Mochi started: moving past DRAG_THRESHOLD drags him out. */+ private botPress: { x: number; y: number } | null = null;+/** Drop sequence bookkeeping: last tick played, and whether the ✓ has fired. */private uploadTens = 0;private uploadDone = false;@@@ -395,6 -367,28 +426,37 @@@this.fsm.reveal();}+ /** Right-click on Mochi: wardrobe open ↔ back to the usual view. */+ toggleWardrobe() {+ if (State.paused || State.mode === "hidden") return;+ // The greeting and the drop sequence draw a Mochi of their own.+ if (State.mode === "expanded" && (State.view === "greeting" || this.uploadActive)) return;+ if (State.mode === "expanded" && State.view === "wardrobe") this.setView(State.defaultView());+ else this.setView("wardrobe");+ }++ /**+ * Right-click on the desktop Mochi (macOS openWardrobeFromDesktop): opens the+ * wardrobe from any state, or goes back if it is already open.+ */+ wardrobeFromDesktop() {++ this.wardrobeAnywhere();++ }++++ /**++ * The wardrobe from any state — compact or hidden island included — or back++ * to the usual view if it is already open. The desktop Mochi's right-click++ * and the wardrobe shortcut (`open-wardrobe`) both land here.++ */++ wardrobeAnywhere() {+ if (State.mode === "expanded" && State.view === "wardrobe") {+ this.setView(State.defaultView());+ return;+ }+ if (State.paused) return;+ this.alert("wardrobe");+ }+/** An alert stopped waiting for an answer: let the island auto-close again. */dropPin() {this.fsm.pinned = false;@@@ -646,14 -609,37 +718,43 @@@}});+ // No browser menu over Mochi: his right-click is the wardrobe. Everywhere+ // else (the chat field) the webview keeps its own menu.+ this.islandEl.addEventListener("contextmenu", (e) => {+ if (this.isBotHit(e.clientX, e.clientY)) e.preventDefault();+ });++ // Dragging Mochi out of the island puts him on the desktop.+ window.addEventListener("mousemove", (e) => {+ if (this.desktop.carrying) {+ this.desktop.carry(e.clientX, e.clientY);+ return;+ }+ const press = this.botPress;+ if (!press) return;+ if (!(e.buttons & 1)) {+ this.botPress = null;+ return;+ }+ if (Math.hypot(e.clientX - press.x, e.clientY - press.y) <= DRAG_THRESHOLD) return;+ this.botPress = null;+ if (!this.canDragOut()) return;+ this.cancelBotHover();+ this.desktop.pickUp(e.clientX, e.clientY);+ });+ window.addEventListener("mouseup", (e) => {+ this.botPress = null;+ if (this.desktop.carrying) this.desktop.carryEnd(e.clientX, e.clientY);+ });++ // Only keys typed into the island itself land here, never Escape typed in+ // a terminal — so it may fold a waiting card away, as Escape in the notch+ // does on macOS.window.addEventListener("keydown", (e) => {- if (e.key === "Escape" && State.mode === "expanded" && !State.isPinned) this.collapse();+ if (e.key === "Escape" && State.mode === "expanded") {+ if (State.pendingApproval) this.foldApproval();+ else if (!State.isPinned) this.collapse();+ }State.lastActivity = performance.now();});@@@ -927,9 -906,18 +1039,19 @@@this.engine.slotHVel = 0;}}- // Only the main Mochi is dressed: a focused integration pill shows its own- // colours, unless the wardrobe is open (BotCanvasView.showOutfit, macOS).++ // Only the main Mochi is dressed — the one of the main tool's pill (Settings →++ // Active pills): a focused integration pill shows its own colours, unless++ // the wardrobe is open (BotCanvasView.showOutfit, macOS).+ // In the wardrobe the hovered outfit swaps in at once, without the drop-in.+ const inWardrobe = State.mode === "expanded" && State.view === "wardrobe";- const mainFocused = State.focusId == null || State.focusId === MAIN_PILL;++ const mainFocused = State.focusId == null || State.focusId === State.mainPillId;+ const showOutfit = mainFocused || State.mode !== "expanded" || inWardrobe;+ const outfit = State.wardrobePreview ?? this.seasons.get(parseOutfit(State.settings.mochiOutfit));+ this.engine.setOutfit(showOutfit ? outfit : "none", !inWardrobe);+this.engine.update(dt);- ctx.setTransform(dpr, 0, 0, dpr, 0, 0);- ctx.clearRect(0, 0, w, hCss);+ ctx.setTransform(dpr, 0, 0, dpr, BOT_SIDE * dpr, 0);+ ctx.clearRect(-BOT_SIDE, 0, wCss, hCss);this.engine.draw(ctx, w, hCss);}@@@ -965,14 -950,16 +1087,20 @@@const expanded = State.mode === "expanded";const greetingActive = expanded && State.view === "greeting";- this.contentEl.style.opacity = expanded && !greetingActive ? "1" : "0";- this.contentEl.style.pointerEvents = expanded && !greetingActive ? "auto" : "none";+ const live = expanded && !greetingActive;+ this.contentEl.style.opacity = live ? "1" : "0";+ // While the drop sequence owns the body its buttons are painted on the canvas+ // underneath, so only the header may keep taking clicks up here.+ this.contentEl.style.pointerEvents = live && !this.uploadActive ? "auto" : "none";+ this.header.el.style.pointerEvents = live ? "auto" : "none";this.greetingCanvas.style.display = greetingActive ? "block" : "none";+ // Leaving the greeting, however it ends, lets its sound fade out.+ if (this.greetingShown && !greetingActive) this.greeting.leave();+ this.greetingShown = greetingActive;+ // A wardrobe try-on never outlives the wardrobe.+ if (State.wardrobePreview && !(expanded && State.view === "wardrobe")) State.wardrobePreview = null;+this.header.sync();for (const [name, view] of this.views) {const on = name === State.view;diff --cc windows/src/island/shortcuts.tsindex a4d58eed,00000000..6d77a224mode 100644,000000..100644--- a/windows/src/island/shortcuts.ts+++ b/windows/src/island/shortcuts.ts@@@ -1,170 -1,0 +1,178 @@@+// Keyboard shortcuts → island. Port of IslandWindowController.handleHotKey and+// handleIslandKey from the macOS app.+//+// Global shortcuts are caught by Rust and arrive as a `shortcut` event with+// the action id (the wardrobe goes out as `open-wardrobe` instead, for the+// wardrobe view to pick up). The in-island keys are read here, while the+// island has the keyboard: it takes it for the chat, and when a global+// shortcut opens it.++import { Bridge, onEvent } from "../core/bridge";+import type { BotEmoteName, IslandViewName } from "../core/layout";+import { cyclePill, islandKeyAction, pillByNumber, type IslandKeyAction } from "../core/shortcuts";+import { Sound } from "../core/sound";+import { State } from "../core/state";++const CLAUDE_DESKTOP_ID = "agent_claude-desktop";++/** What the shortcuts need from the island. */+export interface ShortcutHost {+ alert(view: IslandViewName): void;+ setView(view: IslandViewName): void;+ collapse(): void;+ emote(name: BotEmoteName): void;+ setPinned(on: boolean): void;+ /** Gives the island the keyboard, so the in-island keys work (Mac: makeKey). */+ takeKeyboard(): void;++ /** The wardrobe from any state, or back if it is open (Island.wardrobeAnywhere). */++ wardrobeAnywhere(): void;+}++function focusPill(host: ShortcutHost, id: string | null, open: boolean) {+ if (!id) return;+ State.setFocus(id);+ Sound.play("blip");+ if (open) host.alert("overview");+ else host.setView("overview");+}++/** A global shortcut was pressed. `resume` lifts Pause, as the tray's Open does. */+export function runGlobalShortcut(host: ShortcutHost, action: string, resume: () => void) {+ switch (action) {+ case "toggleIsland":+ if (State.mode === "expanded") {+ host.collapse();+ } else {+ resume();+ // A waiting card is what the island opens on (State.defaultView).+ host.alert(State.defaultView());+ host.takeKeyboard();+ }+ break;++ case "openChat":+ resume();+ host.alert("prompt");+ break;++ case "goToAlert": {+ const asking = State.tasks.find((t) => t.state === "question");+ const pending = State.pendingApproval;+ if (pending) {+ // The one card every agent's request uses: its own pill to the front,+ // its card (permission or question) up. Nothing is answered from here.+ resume();+ State.setFocus(pending.pillId);+ host.alert(pending.questions ? "question" : "approval");+ host.takeKeyboard();+ } else if (asking) {+ resume();+ State.setFocus(asking.id);+ host.alert("question");+ host.takeKeyboard();+ } else {+ // Nothing is waiting: Mochi says so.+ host.emote("annoyed");+ Sound.play("error");+ }+ break;+ }++ // The Mac brings the terminal app forward; here it is the existing "Open+ // terminal": the session's own window when it was found, else its folder+ // in VS Code; the Claude app for a Claude Desktop session.+ case "jumpToTerminal": {+ const task = State.focusTask;+ if (task?.id === CLAUDE_DESKTOP_ID) void Bridge.openClaudeDesktop();+ else void Bridge.openSession(task?.sessionId ?? null, task?.sessionCwd ?? null);+ if (State.mode === "expanded") host.collapse();+ break;+ }++ case "nextPill":+ case "prevPill":+ resume();+ focusPill(+ host,+ cyclePill(State.tasks.map((t) => t.id), State.focusTask?.id ?? null, action === "nextPill" ? 1 : -1),+ true,+ );+ break;++ case "muteToggle": {+ const on = !State.settings.soundEnabled;+ State.settings.soundEnabled = on;+ Sound.setEnabled(on);+ void Bridge.saveSettings(State.settings);+ if (on) Sound.play("tick");+ host.emote(on ? "happy" : "annoyed");+ State.notify();+ break;+ }++ // wardrobeToggle never comes this way (Rust sends `open-wardrobe`), and+ // attachFrontWindow / desktopToggle aren't in this version.+ default:+ break;+ }+}++/** A key the island acts on while it has the keyboard. */+export function runIslandKey(host: ShortcutHost, action: IslandKeyAction) {+ const ids = State.tasks.map((t) => t.id);+ switch (action.kind) {+ case "cycle":+ focusPill(host, cyclePill(ids, State.focusTask?.id ?? null, action.delta), false);+ break;+ case "pill":+ focusPill(host, pillByNumber(ids, action.number), false);+ break;+ case "newChat":+ // Not while an answer is on its way: it would land in the new chat.+ if (State.stateOverride === "thinking") return;+ State.chatHistory = [];+ State.droppedFile = null;+ State.promptContext = null;+ void Bridge.chatReset();+ Sound.play("blip");+ host.setView("prompt");+ break;+ case "settings":+ void Bridge.openSettingsWindow();+ break;+ case "pin":+ // A permission card keeps the island pinned until it is answered.+ if (State.pendingApproval) return;+ host.setPinned(!State.isPinned);+ break;+ }+}++function inTextField(target: EventTarget | null): boolean {+ const el = target as { tagName?: string; isContentEditable?: boolean } | null;+ return el?.tagName === "INPUT" || el?.tagName === "TEXTAREA" || el?.isContentEditable === true;+}++export function registerShortcutHandlers(host: ShortcutHost, resume: () => void) {+ void onEvent<string>("shortcut", (action) => runGlobalShortcut(host, action, resume));++ // The wardrobe shortcut comes as its own event (shortcuts.rs): it opens the++ // wardrobe (mochi/wardrobe.ts, views/wardrobe.ts), or closes it again.++ void onEvent<null>("open-wardrobe", () => {++ resume();++ host.wardrobeAnywhere();++ });++ // Capture phase: the chat field stops its own key events from bubbling.+ window.addEventListener(+ "keydown",+ (e: KeyboardEvent) => {+ if (State.mode !== "expanded") return;+ const action = islandKeyAction(e, { view: State.view, inTextField: inTextField(e.target) });+ if (!action) return;+ e.preventDefault();+ e.stopPropagation();+ runIslandKey(host, action);+ },+ true,+ );+}diff --cc windows/src/main.tsindex 9457960e,fc292721..c76f76b8--- a/windows/src/main.ts+++ b/windows/src/main.ts@@@ -25,9 -23,9 +25,10 @@@ async function main()island.applySettings();State.loadIntegrationTasks();if (boot && !boot.cursorPoll) island.followPageCursor();+ await island.desktop.init();await onEvent<{ x: number; y: number }>("cursor", ({ x, y }) => island.onCursor(x, y));+ await onEvent<boolean>("pointer-inside", (inside) => island.setPointerInside(inside));/** Pause has to reach Rust too, or the pollers keep calling out. */const setPaused = (on: boolean) => {@@@ -46,10 -44,10 +47,14 @@@setPaused(false);island.alert(State.defaultView());break;+ case "recap":+ setPaused(false);+ void Recap.open(island);+ break;+ case "wardrobe":+ setPaused(false);+ island.alert("wardrobe");+ break;case "pause":setPaused(!State.paused);if (State.paused) island.fsm.forceHidden();diff --cc windows/src/mochi/desktop-logic.tsindex 00000000,fc8d5e6a..0bd6c91amode 000000,100644..100644--- a/windows/src/mochi/desktop-logic.ts+++ b/windows/src/mochi/desktop-logic.ts@@@ -1,0 -1,307 +1,310 @@@+ // Mochi on the desktop — the pure logic, port of+ // NotchBuddy/Sources/App/DesktopMochiLogic.swift and of the life cycle in+ // DesktopMochiController (DesktopMochi.swift). No DOM, no Tauri: the island+ // wires it up in src/island/desktop.ts, the desktop window draws him in+ // src/desktop/main.ts, and Rust owns the window (src-tauri/src/desktop.rs).+ //+ // Coordinates are y-down everywhere on a PC, so the Mac's DesktopSpace flip is+ // not needed: a point on the desktop is used as the OS reports it.++ import type { BotEmoteName, BotStateName } from "../core/layout";+ import type { Outfit } from "./wardrobe";++ /** What the island tells the desktop window, whenever it changes. */+ export interface DesktopSnapshot {+ state: BotStateName;+ /** He is always the main Mochi, so always dressed (try-ons included). */+ outfit: Outfit;+ soundEnabled: boolean;+ soundVolume: number;+ /** Tray → Pause: he dozes off and stays asleep. */+ paused: boolean;+ }++ /** Events between the two windows. Rust adds `desktop-mochi-dropped`. */+ export const DESKTOP_EVENTS = {+ /** island → desktop window */+ state: "desktop-mochi-state",+ emote: "desktop-mochi-emote",+ /** desktop window → island */+ ready: "desktop-mochi-ready",+ home: "desktop-mochi-home",+ wardrobe: "desktop-mochi-wardrobe",+ dizzy: "desktop-mochi-dizzy",+ /** Rust → island: a drag ended, `{ from: "island" | "desktop", home }`. */+ dropped: "desktop-mochi-dropped",+ /** Rust → desktop window */+ cursor: "desktop-cursor",+ visible: "desktop-visible",+ flight: "desktop-flight",+ } as const;++ // ── Constants (DesktopMochiLogic) ────────────────────────────────────────────++ /** Side of the desktop window, logical pixels. */+ export const PANEL_SIZE = 120;+ /** Seconds without agent activity before he may fall asleep. */+ export const SLEEP_TIMEOUT = 120;+ /** He only dozes off once the pointer is at least this far from him. */+ export const SLEEP_MOUSE_DISTANCE = 150;+ /** Clickable body radius, as a fraction of the window side. */+ export const BODY_RADIUS_FRACTION = 0.24;++ /** Surprised, then off to the island (DesktopMochi.swift: 0.45 s). */+ export const RETRACT_DELAY_MS = 450;+ /** Pause in the island after the alert is answered, before flying back (0.6 s). */+ export const RETURN_DELAY_MS = 600;+ /** Single click → poke, unless it turns out to be a double click. */+ export const DOUBLE_CLICK_MS = 300;+ /** A press that moves farther than this is a drag, not a click. */+ export const DRAG_THRESHOLD = 3;++ // ── Pure helpers ─────────────────────────────────────────────────────────────++ export interface Point {+ x: number;+ y: number;+ }++ /**+ * Whether Mochi should be asleep: no agent activity for longer than+ * SLEEP_TIMEOUT (strictly), and the pointer not close to him.+ */+ export function shouldSleep(sinceAgentActive: number, mouseDistanceToCenter: number): boolean {+ return sinceAgentActive > SLEEP_TIMEOUT && mouseDistanceToCenter >= SLEEP_MOUSE_DISTANCE;+ }++ /** Hit test of the round body inside the square window (window-local). */+ export function isOverBody(local: Point, panelSize = PANEL_SIZE): boolean {+ const c = panelSize / 2;+ const r = panelSize * BODY_RADIUS_FRACTION;+ const dx = local.x - c;+ const dy = local.y - c;+ return dx * dx + dy * dy <= r * r;+ }++ /** Eye-tracking origin: the window centre, in the same space as the cursor. */+ export function lookOrigin(panelMinX: number, panelMinY: number, panelSize = PANEL_SIZE): Point {+ return { x: panelMinX + panelSize / 2, y: panelMinY + panelSize / 2 };+ }++ /** BotCanvasView.lookX / lookY: x right +, y up +. */+ export function gaze(bot: Point, mouse: Point): { lookX: number; lookY: number } {+ return {+ lookX: Math.tanh((mouse.x - bot.x) / 260),+ lookY: -Math.tanh((mouse.y - bot.y) / 200),+ };+ }++ /** An alert went up during a flight: once landed, he turns right back. */+ export function shouldRetractOnLanding(alertActive: boolean): boolean {+ return alertActive;+ }++ /** Agent work keeps him awake; idle and sleeping don't. */+ export function agentActive(state: BotStateName): boolean {+ return state !== "idle" && state !== "sleeping";+ }++ /**- * What sends him back to the island: a permission waiting for a click, or an- * agent asking a question. (The Mac's pendingApproval / pendingQuestion.)++ * What sends him back to the island (the Mac's pendingApproval /++ * pendingQuestion): the island's card waiting for an answer — a permission++ * from any agent, or a question Claude Code asked (#216, the same card with++ * `questions`), folded or not — or an agent asking a question by notification.+ */+ export function alertActive(s: {- pendingApproval: unknown;++ pendingApproval: { questions?: unknown } | null;+ tasks: ReadonlyArray<{ state: BotStateName }>;+ }): boolean {- return s.pendingApproval != null || s.tasks.some((t) => t.state === "question");++ if (s.pendingApproval != null) return true;++ return s.tasks.some((t) => t.state === "question");+ }++ /**+ * Linux has no global cursor (Wayland), so his window only hears the pointer+ * while it is over his body. That counts as "near" for this long afterwards.+ */+ export const POINTER_MEMORY_MS = 4000;++ /**+ * Distance from the pointer to his centre, for shouldSleep. With a cursor+ * poll (Windows) it is measured; without one, the pointer is near while it was+ * over him a moment ago, and far otherwise.+ */+ export function pointerDistance(+ cursorPoll: boolean,+ cursor: Point | null,+ sincePointerMs: number,+ panelSize = PANEL_SIZE,+ ): number {+ if (cursorPoll) {+ return cursor ? Math.hypot(cursor.x - panelSize / 2, cursor.y - panelSize / 2) : Infinity;+ }+ return sincePointerMs < POINTER_MEMORY_MS ? 0 : Infinity;+ }++ /**+ * Layer-shell drag: the surface is stretched over the display, so the pointer+ * reads in display coordinates — once the compositor has applied it. Until+ * then the pointer is still relative to the small surface at `origin`.+ */+ export function layerDragTopLeft(origin: Point, client: Point, grab: Point, overlayApplied: boolean): Point {+ const base = overlayApplied ? { x: 0, y: 0 } : origin;+ return { x: base.x + client.x - grab.x, y: base.y + client.y - grab.y };+ }++ /** X11 drag: screen coordinates are global there; the window moves in physical pixels. */+ export function windowDragTopLeft(origin: Point, screen: Point, screenAtPress: Point, dpr: number): Point {+ return {+ x: origin.x + (screen.x - screenAtPress.x) * dpr,+ y: origin.y + (screen.y - screenAtPress.y) * dpr,+ };+ }++ // ── Life cycle (DesktopMochiController) ──────────────────────────────────────++ export type DesktopPhase =+ /** No window on screen. */+ | "home"+ /** Window flying from the island to his spot. */+ | "flyingOut"+ /** On the desktop: the normal state. */+ | "onDesktop"+ /** An alert just went up: surprised, about to fly to the island. */+ | "retracting"+ /** The alert was answered while he was flying to the island. */+ | "alertResolvedDuringRetract"+ /** In the island, showing the alert; back out once it is answered. */+ | "atNotchForAlert";++ /** Everything the life cycle does to the world, injected so it can be tested. */+ export interface DesktopPorts {+ /** Shows the window at the island and flies it to his spot. False: no spot. */+ flyOut(): Promise<boolean>;+ /** Flies the window to the island and hides it. `forget`: he lives there again. */+ flyHome(forget: boolean): Promise<boolean>;+ /** The island's own Mochi hides while he is out. */+ setAway(away: boolean): void;+ /** An emote on the desktop Mochi. */+ emote(emote: BotEmoteName, duration?: number): void;+ play(sound: string): void;+ alertActive(): boolean;+ /** The island must be on screen for him to show the alert there. */+ revealIsland(): void;+ later(fn: () => void, ms: number): void;+ }++ export class DesktopMochiController {+ phase: DesktopPhase = "home";+ /** He lives on the desktop (the `onDesktop` preference). */+ enabled = false;++ private lastState: BotStateName | null = null;+ private port: DesktopPorts;++ constructor(port: DesktopPorts) {+ this.port = port;+ }++ /** Launch, and back from an alert: fly out to his spot if he lives there. */+ async launchFlyIfNeeded(): Promise<void> {+ if (!this.enabled || this.phase !== "home") return;+ // An alert is up: wait in the island, the alert's end flies him out.+ if (this.port.alertActive()) {+ this.phase = "atNotchForAlert";+ return;+ }+ this.phase = "flyingOut";+ this.port.setAway(true);+ const ok = await this.port.flyOut();+ if (this.phase !== "flyingOut") return;+ if (!ok) {+ // His spot is on a display that is gone: he stays home.+ this.phase = "home";+ this.enabled = false;+ this.port.setAway(false);+ return;+ }+ this.landed();+ }++ /** Dropped on the desktop after a drag out of the island (Rust placed him). */+ installed() {+ if (this.phase !== "home") return;+ this.enabled = true;+ this.port.setAway(true);+ this.port.emote("happy", 0.6);+ this.port.play("pop");+ this.landed();+ }++ /** Double click, or dropped on the island: home for good. */+ async flyHome(): Promise<void> {+ // Also in the instant between an alert and his flight to the island: the+ // user's "home" wins, and the pending retract finds nothing left to do.+ const out = ["onDesktop", "retracting", "alertResolvedDuringRetract"];+ if (!out.includes(this.phase)) return;+ this.phase = "home";+ this.enabled = false;+ await this.port.flyHome(true);+ this.port.play("peek");+ this.port.setAway(false);+ }++ /** Call whenever the alert condition may have changed; only edges count. */+ private alertWas = false;+ updateAlert(active: boolean) {+ if (active === this.alertWas) return;+ this.alertWas = active;+ if (active) {+ if (this.phase === "onDesktop") this.beginRetract();+ return;+ }+ if (this.phase === "atNotchForAlert") {+ this.phase = "home";+ this.port.later(() => void this.launchFlyIfNeeded(), RETURN_DELAY_MS);+ } else if (this.phase === "retracting") {+ this.phase = "alertResolvedDuringRetract";+ }+ }++ /** Call with the effective state; a task finishing gets a happy jump. */+ updateState(state: BotStateName) {+ const prev = this.lastState;+ this.lastState = state;+ if (prev == null || prev === state) return;+ if (state === "finished" && this.phase === "onDesktop") this.port.emote("happy", 1.2);+ }++ private landed() {+ this.phase = "onDesktop";+ // An alert may have gone up during the flight, when nothing reacts to it.+ this.alertWas = this.port.alertActive();+ if (shouldRetractOnLanding(this.alertWas)) this.beginRetract();+ }++ private beginRetract() {+ this.port.emote("surprised");+ this.phase = "retracting";+ this.port.later(() => {+ if (this.phase === "retracting") {+ void this.retractForAlert();+ } else if (this.phase === "alertResolvedDuringRetract") {+ // Answered before he even took off: he never left his spot.+ this.phase = "onDesktop";+ }+ }, RETRACT_DELAY_MS);+ }++ private async retractForAlert() {+ await this.port.flyHome(false);+ this.port.setAway(false);+ if (this.phase === "alertResolvedDuringRetract") {+ this.phase = "home";+ await this.launchFlyIfNeeded();+ } else if (this.phase === "retracting") {+ this.phase = "atNotchForAlert";+ this.port.revealIsland();+ }+ }+ }diff --cc windows/src/style.cssindex 1d3b6fa3,28c7c392..941e78dd--- a/windows/src/style.css+++ b/windows/src/style.css@@@ -1829,432 -1366,64 +1829,494 @@@ input[type="range"]::-webkit-slider-thupadding-top: 8px;}+/* ── Plan usage: the pills in the header and the card behind them ────────────+ ClaudePlanHeaderPill / ClaudePlanCardView / CodexPlanCardView on the Mac.+ Nothing here applies until a pill is turned on in Settings. */++/* Off: takes no room, so the header is exactly as it shipped. */+.plan-pills {+ display: none;+ align-items: center;+ gap: 5px;+ /* .header-actions spaces its items 14px apart; the Mac puts 8px between+ the pills and the gear. */+ margin-right: -6px;+}++.plan-pills.on {+ display: flex;+}++/* Both pills: the Mac tightens the right side (icons 10px apart, pills 5px+ from the gear, 8px from the edge). */+.header-actions.both-plans {+ gap: 10px;+ padding-right: 8px;+}++.header-actions.both-plans .plan-pills {+ margin-right: -5px;+}++.header-actions .plan-pill {+ --plan: #6b7079;+ display: flex;+ align-items: center;+ gap: 4px;+ padding: 4px 8px;+ border: 1px solid color-mix(in srgb, var(--plan) 14%, transparent);+ border-radius: 999px;+ background: #0e0f11;+ color: var(--dim-3);+ font: 600 10px var(--font);+ line-height: 12px;+ white-space: nowrap;+ cursor: default;+ transition: background 0.18s, border-color 0.18s, color 0.18s;+}++.header-actions .plan-pill:hover,+.header-actions .plan-pill.active {+ background: color-mix(in srgb, var(--plan) 18%, transparent);+ border-color: color-mix(in srgb, var(--plan) 55%, transparent);+ color: color-mix(in srgb, var(--plan) 70%, white);+}++.plan-pill-dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+}++.plan-card {+ position: relative;+ z-index: 1;+ padding-top: 10px;+}++.plan-head {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 0 36px 0 108px;+ white-space: nowrap;+}++.plan-head > * {+ flex: 0 0 auto;+}++.plan-title {+ font: 600 12px var(--font);+ color: var(--ink);+}++.plan-head > .plan-sub {+ flex: 0 1 auto; /* the one part that gives way, with an ellipsis */+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ font: 400 11px var(--font);+ color: var(--dim-2);+}++.plan-rows {+ display: flex;+ flex-direction: column;+ gap: 5px;+ padding: 8px 12px 0 108px;+}++.plan-row {+ display: flex;+ align-items: center;+ gap: 5px;+ font: 400 11px var(--font);+ white-space: nowrap;+}++.plan-label {+ flex: 0 0 40px;+ color: var(--dim-3);+}++.plan-bar {+ flex: 0 0 50px;+ height: 4px;+ border-radius: 2px;+ background: rgba(255, 255, 255, 0.08);+ overflow: hidden;+}++.plan-fill {+ display: block;+ height: 100%;+ border-radius: 2px;+}++.plan-pct {+ flex: 0 0 30px;+ text-align: right;+ font-weight: 600;+ font-variant-numeric: tabular-nums;+ color: #c5c8cd;+}++.plan-reset-icon {+ display: inline-flex;+ color: var(--dim-3);+}++.plan-reset {+ font-size: 10px;+ color: var(--dim-3);+}++.plan-none {+ color: var(--dim-3);+}++.plan-credits {+ font-weight: 600;+ color: #c5c8cd;+}++/* ── GitHub pulse (GitHubPulseCardView / GitHubDetailView) ─────────────── */++.gh-spark {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ border: 0;+ padding: 0;+ background: transparent;+ font: 400 11px var(--font);+ color: var(--dim-2);+ white-space: nowrap;+ cursor: default;+ min-width: 0;+}++.gh-mini {+ display: inline-flex;+ gap: 2px;+}++.gh-mini i,+.gh-cell {+ width: 7px;+ height: 7px;+ border-radius: 1.5px;+ flex: 0 0 auto;+}++.int-stats.gh-rows {+ gap: 4px;+ padding-top: 6px;+}++.gh-stat {+ border: 0;+ padding: 0;+ background: transparent;+ width: 100%;+ text-align: left;+ cursor: default;+}++.gh-detail-head {+ display: flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+}++.gh-back {+ display: inline-flex;+ align-items: center;+ gap: 3px;+ border: 0;+ padding: 0;+ background: transparent;+ font: 600 12px var(--font);+ color: var(--ink);+ white-space: nowrap;+ cursor: default;+ flex: 0 0 auto;+}++.gh-head-right {+ margin-left: auto;+ border: 0;+ padding: 0;+ background: transparent;+ font: 400 11px var(--font);+ color: var(--dim-2);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ min-width: 0;+ cursor: default;+}++.gh-list {+ display: flex;+ flex-direction: column;+ max-height: 60px; /* three 20 px rows; the rest scrolls */+ overflow-y: auto;+ margin-top: 4px;+ scrollbar-width: none;+}++.gh-list::-webkit-scrollbar {+ display: none;+}++.gh-list.fade {+ -webkit-mask-image: linear-gradient(to bottom, #000 0%, #000 80%, transparent 100%);+ mask-image: linear-gradient(to bottom, #000 0%, #000 80%, transparent 100%);+}++.gh-row {+ display: flex;+ align-items: center;+ gap: 5px;+ height: 20px;+ flex: 0 0 20px;+ padding: 0 4px 0 0;+ border: 0;+ border-radius: 4px;+ background: transparent;+ text-align: left;+ cursor: default;+ min-width: 0;+}++.gh-row:hover {+ background: rgba(255, 255, 255, 0.05);+}++.gh-gap {+ width: 5px;+ flex: 0 0 5px;+}++.gh-ref {+ font: 400 10.5px var(--font);+ color: #9398a1;+ white-space: nowrap;+ flex: 0 0 auto;+}++.gh-title {+ font: 400 11px var(--font);+ color: #c5c8cd;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ min-width: 0;+}++.gh-draft {+ font: 400 9.5px var(--font);+ color: var(--dim-3);+ flex: 0 0 auto;+}++.gh-word {+ margin-left: auto;+ padding-left: 4px;+ font: 400 10px var(--font);+ white-space: nowrap;+ flex: 0 0 auto;+}++.gh-empty {+ font: 400 10.5px var(--font);+ color: var(--dim-3);+ padding-top: 8px;+}++.gh-grid {+ display: flex;+ gap: 1.5px;+ padding-top: 5px;+}++.gh-week {+ display: flex;+ flex-direction: column;+ gap: 1.5px;+}++.gh-cell.empty {+ background: transparent;+}++/* ── Weekly recap ───────────────────────────────────────────────────────── */+/* WeeklyRecapCardView: text from x = 116, indigo wash, chips of 17 px values. */++.recap-stack {+ padding: 4px 16px 4px 116px;+ gap: 4px;+}++.recap-head {+ display: flex;+ align-items: baseline;+ gap: 6px;+}++.recap-title {+ font: 600 11px var(--font);+ color: #818cf8;+}++.recap-range {+ font: 400 10px var(--font);+ color: var(--dim-2);+ white-space: nowrap;+}++.recap-chips {+ display: flex;+ gap: 14px;+ white-space: nowrap;+}++.recap-chip .v {+ font: 700 17px var(--font);+ color: var(--ink-2);+}++.recap-chip .l {+ font: 400 9px var(--font);+ color: var(--dim-2);+}++.recap-meta {+ display: flex;+ gap: 5px;+ font: 400 11px var(--font);+ color: var(--dim-2);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.recap-meta .n {+ color: var(--ink-2);+ font-weight: 600;+ overflow: hidden;+ text-overflow: ellipsis;+}++.recap-meta .sep {+ color: var(--dim-4);+}++.recap-stack .actions {+ margin-top: 3px;+}++.recap-share {+ flex-direction: row;+ align-items: center;+ justify-content: flex-start;+ gap: 16px;+ padding: 8px 16px 8px 116px;+}++.recap-thumb {+ flex: 0 0 64px;+ width: 64px;+ height: 114px;+ border-radius: 8px;+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);+}++.recap-share-side {+ display: flex;+ flex-direction: column;+ gap: 8px;+ min-width: 0;+}++.recap-status {+ display: flex;+ align-items: baseline;+ gap: 8px;+ min-height: 14px;+ font: 400 11px var(--font);+ color: var(--dim);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.recap-link {+ color: #818cf8;+ padding: 0;+}+++ /* ── Wardrobe (right-click on Mochi) — WardrobeView on macOS ─────────────── */++ .wardrobe-stack {+ padding: 12px 16px 12px 104px;+ gap: 10px;+ }++ .wardrobe-head {+ display: flex;+ align-items: baseline;+ gap: 6px;+ min-width: 0;+ }++ .wardrobe-title {+ font: 600 12px var(--font);+ color: var(--ink);+ flex: 0 0 auto;+ }++ .wardrobe-note {+ margin-left: auto;+ font: 400 11px var(--font);+ color: var(--dim-2);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ .wardrobe-grid {+ display: flex;+ flex-wrap: wrap;+ gap: 5px;+ }++ .wardrobe-item {+ width: 30px;+ height: 30px;+ padding: 0;+ border-radius: 7px;+ border: 1px solid rgba(255, 255, 255, 0.08);+ background: rgba(255, 255, 255, 0.06);+ display: grid;+ place-items: center;+ cursor: default;+ transition: background 0.12s ease-out, border-color 0.12s ease-out;+ }++ .wardrobe-item:hover {+ background: rgba(255, 255, 255, 0.1);+ }++ .wardrobe-item.on {+ border-color: rgba(255, 255, 255, 0.4);+ }++ .wardrobe-item canvas {+ width: 28px;+ height: 28px;+ pointer-events: none;+ }diff --cc windows/src/views/views.tsindex 72a9d459,484909b7..7f61e57e--- a/windows/src/views/views.ts+++ b/windows/src/views/views.ts@@@ -11,14 -11,8 +11,16 @@@ import { createMiniBot, pruneMiniBotsimport { buildPrompt } from "./chat";import { buildChoose, buildUpload, buildUploading } from "./upload";import { renderIntegrationCard, type IntegrationCardHooks } from "./integrations";+import { pillDefinition, sessionSubtitle } from "../core/pills";+import {+ PlanCard, buildPlanPill, claudePillVisible, codexPillVisible, planCardOpen, refreshCodexPlanUsage,+} from "./usage";+import { buildDiffCard } from "./diff";+import { lastTextStep } from "../core/diff";+import { Bridge } from "../core/bridge";+import { buildRecap } from "./recap";+ import { buildWardrobe } from "./wardrobe";+ import type { Outfit, OutfitSelection } from "../mochi/wardrobe";export interface ViewActions {setView(v: IslandViewName): void;@@@ -753,7 -507,7 +759,8 @@@ export function buildViewsmap.set("upload", buildUpload());map.set("uploading", buildUploading());map.set("choose", buildChoose(actions));+ map.set("recap", buildRecap(actions));+ map.set("wardrobe", buildWardrobe(actions));// Not in the Windows v1: sending a file by email, window attach + web result.map.set("mail", buildPlaceholder("Sending by email isn't in this version.", ""));map.set("searching", buildPlaceholder("Claude is searching…", ""));diff --cc windows/tests/desktop.test.mjsindex 00000000,2a34b319..e093d52cmode 000000,100644..100644--- a/windows/tests/desktop.test.mjs+++ b/windows/tests/desktop.test.mjs@@@ -1,0 -1,349 +1,357 @@@+ // Mochi on the desktop: the pure logic and the life cycle (src/mochi/desktop-logic.ts).+ // The first half mirrors tests/DesktopMochiTests.swift; the geometry of the+ // window itself (clamping, saved spots, the island's home zone) is tested in+ // src-tauri/src/desktop.rs, where it lives.++ import { test } from "node:test";+ import assert from "node:assert/strict";+ import {+ BODY_RADIUS_FRACTION, DesktopMochiController, PANEL_SIZE, RETRACT_DELAY_MS, RETURN_DELAY_MS,+ agentActive, alertActive, gaze, isOverBody, layerDragTopLeft, lookOrigin, pointerDistance,+ shouldRetractOnLanding, shouldSleep, windowDragTopLeft,+ } from "../src/mochi/desktop-logic.ts";++ // ── shouldSleep ───────────────────────────────────────────────────────────────++ test("shouldSleep: idle long enough and the pointer far away", () => {+ assert.equal(shouldSleep(5, 300), false, "active agent must not sleep");+ assert.equal(shouldSleep(200, 50), false, "mouse near panel must not sleep");+ assert.equal(shouldSleep(200, 200), true, "long idle + far mouse must sleep");+ assert.equal(shouldSleep(120, 300), false, "exactly at timeout must not sleep");+ assert.equal(shouldSleep(120.1, 300), true, "just over timeout must sleep");+ assert.equal(shouldSleep(200, 150), true, "at distance threshold must sleep");+ });++ test("agent work keeps him awake, idle and sleeping don't", () => {+ for (const s of ["working", "thinking", "searching", "approval", "question", "finished", "error"]) {+ assert.equal(agentActive(s), true, s);+ }+ assert.equal(agentActive("idle"), false);+ assert.equal(agentActive("sleeping"), false);+ });++ test("pointer distance: measured with a cursor poll, remembered without one", () => {+ assert.equal(pointerDistance(true, { x: 60, y: 60 }, 0), 0);+ assert.equal(pointerDistance(true, { x: 60 + 150, y: 60 }, 0), 150);+ assert.equal(pointerDistance(true, null, 0), Infinity, "no cursor yet: far");+ // Linux: near while the pointer was over him a moment ago.+ assert.equal(pointerDistance(false, null, 100), 0);+ assert.equal(pointerDistance(false, { x: 60, y: 60 }, 60_000), Infinity);+ });++ // ── isOverBody ────────────────────────────────────────────────────────────────++ test("isOverBody: the round body, not the square window", () => {+ const s = 120;+ const r = s * BODY_RADIUS_FRACTION; // 28.8+ assert.equal(isOverBody({ x: 60, y: 60 }, s), true, "center must be inside body");+ assert.equal(isOverBody({ x: 60 + r - 0.5, y: 60 }, s), true, "inside radius must hit");+ assert.equal(isOverBody({ x: 60 + r + 0.5, y: 60 }, s), false, "outside radius must miss");+ assert.equal(isOverBody({ x: 0, y: 0 }, s), false, "corner must miss");+ const diag = r / Math.SQRT2 - 0.5;+ assert.equal(isOverBody({ x: 60 + diag, y: 60 + diag }, s), true, "diagonal inside must hit");+ assert.equal(PANEL_SIZE, 120);+ });++ // ── lookOrigin / gaze ─────────────────────────────────────────────────────────++ const sign = (v) => (v === 0 ? 0 : v < 0 ? -1 : 1);++ /** The Mac test's AppKit points (y up from the menu-bar screen's bottom) → y down. */+ const topDown = (p, desktopTop) => ({ x: p.x, y: desktopTop - p.y });++ test("lookOrigin: the window centre, in desktop coordinates", () => {+ // Panel at (200, 300) from the top-left of the desktop.+ assert.deepEqual(lookOrigin(200, 300, 120), { x: 260, y: 360 });+ // On a secondary screen to the right: x stays global, not screen-relative.+ assert.deepEqual(lookOrigin(1540, 100, 120), { x: 1600, y: 160 });+ });++ test("gaze signs across a real arrangement of screens", () => {+ // Menu-bar MacBook 1512×982 at (0,0); external 2560×1440 above it at+ // (-500, 982); portrait 1080×1920 on the left at (-1080, -600). AppKit+ // coordinates as in the Swift test, turned y-down like a PC reports them.+ const top = 982;+ const look = (bot, mouse) => {+ const g = gaze(topDown(bot, top), topDown(mouse, top));+ return [sign(g.lookX), sign(g.lookY)];+ };+ // Mochi in the island at the top of the external screen above.+ const islandOnTop = { x: 780, y: 2422 - 16 };+ assert.deepEqual(look(islandOnTop, { x: 1400, y: 100 }), [1, -1], "cursor on the MacBook below-right");+ assert.deepEqual(look(islandOnTop, { x: -1000, y: 0 }), [-1, -1], "cursor on the portrait screen");+ assert.deepEqual(look(islandOnTop, { x: 780, y: 2500 }), [0, 1], "cursor above Mochi");+ // Mochi on the desktop of the portrait screen, cursor on the external screen above.+ const panelMin = topDown({ x: -700, y: -200 + 120 }, top); // AppKit minY is the bottom edge+ const desktopOnLeft = lookOrigin(panelMin.x, panelMin.y, 120);+ const mouseAbove = topDown({ x: 1000, y: 2000 }, top);+ assert.ok(mouseAbove.x > desktopOnLeft.x && mouseAbove.y < desktopOnLeft.y,+ "desktop Mochi looks right and up at a cursor on another screen");+ const g = gaze(desktopOnLeft, mouseAbove);+ assert.ok(g.lookX > 0 && g.lookY > 0);+ });++ // ── shouldRetractOnLanding / alerts ───────────────────────────────────────────++ test("shouldRetractOnLanding", () => {+ assert.equal(shouldRetractOnLanding(true), true, "must retract when alert is active on landing");+ assert.equal(shouldRetractOnLanding(false), false, "must not retract when no alert on landing");+ });++ test("a permission or a question sends him back to the island", () => {+ assert.equal(alertActive({ pendingApproval: null, tasks: [{ state: "working" }] }), false);+ assert.equal(alertActive({ pendingApproval: { requestId: "r" }, tasks: [] }), true);+ assert.equal(alertActive({ pendingApproval: null, tasks: [{ state: "idle" }, { state: "question" }] }), true);++ // The question card (#216) is the same card with `questions`: it flies him home too.++ const question = {++ requestId: "q", sessionId: "s", pillId: "integration_claude", tool: "AskUserQuestion", command: "",++ questions: [{ question: "Which?", options: [{ label: "A", description: "" }], multiSelect: false }],++ };++ assert.equal(alertActive({ pendingApproval: question, tasks: [{ state: "idle" }] }), true);++ // Any agent's permission card counts, Codex's included.++ assert.equal(alertActive({ pendingApproval: { requestId: "r", pillId: "agent_codex" }, tasks: [] }), true);+ });++ // ── Linux drags ───────────────────────────────────────────────────────────────++ test("layer-shell drag: display coordinates once the overlay is up", () => {+ const origin = { x: 500, y: 300 };+ const grab = { x: 60, y: 62 };+ // Not applied yet: the pointer is still relative to the small surface.+ assert.deepEqual(layerDragTopLeft(origin, { x: 70, y: 62 }, grab, false), { x: 510, y: 300 });+ // Applied: the pointer reads in display coordinates.+ assert.deepEqual(layerDragTopLeft(origin, { x: 900, y: 462 }, grab, true), { x: 840, y: 400 });+ });++ test("X11 drag: screen delta, in physical pixels", () => {+ assert.deepEqual(+ windowDragTopLeft({ x: 1000, y: 600 }, { x: 520, y: 310 }, { x: 500, y: 300 }, 2),+ { x: 1040, y: 620 },+ );+ });++ // ── Life cycle ────────────────────────────────────────────────────────────────++ /** A world the controller acts on, with manual flights and timers. */+ function world({ alert = false, flyOutOk = true } = {}) {+ const log = [];+ const timers = [];+ const flights = [];+ const w = {+ alert,+ away: false,+ log,+ /** Lands the oldest pending flight. */+ async land(result) {+ const f = flights.shift();+ assert.ok(f, "a flight should be in the air");+ f.resolve(result ?? f.defaultResult);+ await new Promise((r) => setImmediate(r));+ },+ get flying() {+ return flights.map((f) => f.kind);+ },+ /** Runs the timers due within `ms`. */+ async tick(ms) {+ const due = timers.filter((t) => t.ms <= ms);+ for (const t of due) timers.splice(timers.indexOf(t), 1);+ for (const t of due) t.fn();+ await new Promise((r) => setImmediate(r));+ },+ port: {+ flyOut: () => new Promise((resolve) => flights.push({ kind: "out", resolve, defaultResult: flyOutOk })),+ flyHome: (forget) => {+ log.push(forget ? "home-forget" : "home-keep");+ return new Promise((resolve) => flights.push({ kind: "home", resolve, defaultResult: true }));+ },+ setAway: (a) => {+ w.away = a;+ },+ emote: (e) => log.push(`emote:${e}`),+ play: (s) => log.push(`sound:${s}`),+ alertActive: () => w.alert,+ revealIsland: () => log.push("reveal"),+ later: (fn, ms) => timers.push({ fn, ms }),+ },+ };+ w.c = new DesktopMochiController(w.port);+ return w;+ }++ test("launch: flies out to his spot only if he lives on the desktop", async () => {+ const w = world();+ await w.c.launchFlyIfNeeded();+ assert.equal(w.c.phase, "home", "not enabled: stays home");+ assert.deepEqual(w.flying, []);++ w.c.enabled = true;+ void w.c.launchFlyIfNeeded();+ assert.equal(w.c.phase, "flyingOut");+ assert.equal(w.away, true, "the island's Mochi hides as he leaves");+ await w.land();+ assert.equal(w.c.phase, "onDesktop");+ });++ test("launch: a spot on a display that is gone keeps him home", async () => {+ const w = world({ flyOutOk: false });+ w.c.enabled = true;+ void w.c.launchFlyIfNeeded();+ await w.land();+ assert.equal(w.c.phase, "home");+ assert.equal(w.c.enabled, false);+ assert.equal(w.away, false);+ });++ test("launch during an alert waits in the island, then flies out once answered", async () => {+ const w = world({ alert: true });+ w.c.enabled = true;+ w.c.updateAlert(true);+ await w.c.launchFlyIfNeeded();+ assert.equal(w.c.phase, "atNotchForAlert");+ assert.deepEqual(w.flying, []);++ w.alert = false;+ w.c.updateAlert(false);+ assert.equal(w.c.phase, "home");+ await w.tick(RETURN_DELAY_MS);+ assert.deepEqual(w.flying, ["out"]);+ await w.land();+ assert.equal(w.c.phase, "onDesktop");+ });++ test("alert on the desktop: surprised, flies to the island, comes back once answered", async () => {+ const w = world();+ w.c.enabled = true;+ void w.c.launchFlyIfNeeded();+ await w.land();++ w.alert = true;+ w.c.updateAlert(true);+ assert.equal(w.c.phase, "retracting");+ assert.ok(w.log.includes("emote:surprised"));+ await w.tick(RETRACT_DELAY_MS);+ assert.deepEqual(w.flying, ["home"]);+ assert.ok(w.log.includes("home-keep"), "he keeps his spot");+ await w.land();+ assert.equal(w.c.phase, "atNotchForAlert");+ assert.equal(w.away, false, "the island's Mochi shows the alert");+ assert.ok(w.log.includes("reveal"));+ assert.equal(w.c.enabled, true);++ w.alert = false;+ w.c.updateAlert(false);+ await w.tick(RETURN_DELAY_MS);+ await w.land();+ assert.equal(w.c.phase, "onDesktop");+ });++ test("alert answered before he takes off: he never leaves his spot", async () => {+ const w = world();+ w.c.enabled = true;+ void w.c.launchFlyIfNeeded();+ await w.land();++ w.alert = true;+ w.c.updateAlert(true);+ w.alert = false;+ w.c.updateAlert(false);+ assert.equal(w.c.phase, "alertResolvedDuringRetract");+ await w.tick(RETRACT_DELAY_MS);+ assert.equal(w.c.phase, "onDesktop");+ assert.deepEqual(w.flying, []);+ });++ test("alert answered during the flight to the island: straight back out", async () => {+ const w = world();+ w.c.enabled = true;+ void w.c.launchFlyIfNeeded();+ await w.land();++ w.alert = true;+ w.c.updateAlert(true);+ await w.tick(RETRACT_DELAY_MS);+ assert.deepEqual(w.flying, ["home"]);+ w.alert = false;+ w.c.updateAlert(false);+ assert.equal(w.c.phase, "alertResolvedDuringRetract");+ await w.land();+ assert.deepEqual(w.flying, ["out"], "relaunched as soon as he reached the island");+ await w.land();+ assert.equal(w.c.phase, "onDesktop");+ });++ test("an alert that went up during the flight out sends him right back", async () => {+ const w = world();+ w.c.enabled = true;+ void w.c.launchFlyIfNeeded();+ w.alert = true;+ w.c.updateAlert(true); // ignored mid-flight+ assert.equal(w.c.phase, "flyingOut");+ await w.land();+ assert.equal(w.c.phase, "retracting");+ await w.tick(RETRACT_DELAY_MS);+ assert.deepEqual(w.flying, ["home"]);+ });++ test("dropped on the desktop from the island: lands with a pop", () => {+ const w = world();+ w.c.installed();+ assert.equal(w.c.phase, "onDesktop");+ assert.equal(w.c.enabled, true);+ assert.equal(w.away, true);+ assert.ok(w.log.includes("sound:pop"));+ assert.ok(w.log.includes("emote:happy"));+ });++ test("dropped on the desktop while an alert is up: turns right back", () => {+ const w = world({ alert: true });+ w.c.installed();+ assert.equal(w.c.phase, "retracting");+ });++ test("double click or dropped on the island: home for good", async () => {+ const w = world();+ w.c.installed();+ void w.c.flyHome();+ assert.equal(w.c.phase, "home");+ assert.equal(w.c.enabled, false);+ assert.ok(w.log.includes("home-forget"));+ await w.land();+ assert.equal(w.away, false);+ assert.ok(w.log.includes("sound:peek"));++ // An alert now leaves him in the island.+ w.alert = true;+ w.c.updateAlert(true);+ assert.equal(w.c.phase, "home");+ });++ test("sent home in the instant before an alert takes him: home wins", async () => {+ const w = world();+ w.c.installed();+ w.alert = true;+ w.c.updateAlert(true);+ assert.equal(w.c.phase, "retracting");+ void w.c.flyHome();+ assert.equal(w.c.phase, "home");+ await w.land();+ await w.tick(RETRACT_DELAY_MS);+ assert.deepEqual(w.flying, [], "the retract has nothing left to do");+ w.alert = false;+ w.c.updateAlert(false);+ await w.tick(RETURN_DELAY_MS);+ assert.deepEqual(w.flying, [], "and he doesn't come back out");+ });++ test("a finished task gets a happy jump, only on the desktop", () => {+ const w = world();+ w.c.updateState("working");+ w.c.updateState("finished");+ assert.ok(!w.log.includes("emote:happy"), "home: the island's Mochi celebrates");+ w.c.installed();+ w.log.length = 0;+ w.c.updateState("working");+ w.c.updateState("finished");+ w.c.updateState("finished");+ assert.deepEqual(w.log, ["emote:happy"]);+ });diff --cc windows/tests/shortcuts.test.mjsindex d7e740f9,00000000..e76e5348mode 100644,000000..100644--- a/windows/tests/shortcuts.test.mjs+++ b/windows/tests/shortcuts.test.mjs@@@ -1,433 -1,0 +1,439 @@@+// Keyboard shortcuts: the pure logic (src/core/shortcuts.ts, mirroring the+// Mac's tests/ShortcutTests.swift) and what the island does with them+// (src/island/shortcuts.ts), driven through the real bridge.++import { beforeEach, test } from "node:test";+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import { calls, emit, sent } from "./tauri.mjs";+import {+ ALTGR_CHARACTERS, ISLAND_SHORTCUTS, KEY_NAMES, SHORTCUTS, SHORTCUT_TEXT, activeKeys, altGrClashes,+ cyclePill, displayKeys, duplicates, effective, formatKeys, islandKeyAction, navigate, normalizeKeys,+ parseKeys, pillByNumber, recordPress,+} from "../src/core/shortcuts.ts";+import { registerShortcutHandlers, runGlobalShortcut, runIslandKey } from "../src/island/shortcuts.ts";+import { DEFAULT_SETTINGS, State } from "../src/core/state.ts";++const MAC_IDS = [+ "toggleIsland", "openChat", "goToAlert", "jumpToTerminal", "attachFrontWindow",+ "nextPill", "prevPill", "muteToggle", "desktopToggle", "wardrobeToggle",+];++// ── Defaults (testDefaultsExhaustive, testAllDefaultsHaveModifier, testNoDefaultDuplicates) ──++test("every Mac action has a default, in the Mac's order, with its Mac id", () => {+ assert.deepEqual(SHORTCUTS.map((d) => d.id), MAC_IDS);+ for (const d of SHORTCUTS) assert.ok(SHORTCUT_TEXT[d.id], `${d.id} has no label`);+});++test("every default parses, is canonical and holds Ctrl+Alt", () => {+ for (const d of SHORTCUTS) {+ const c = parseKeys(d.defaultKeys);+ assert.ok(c, `${d.id} default does not parse`);+ assert.ok(c.ctrl && c.alt && !c.meta, `${d.id} default is not Ctrl+Alt`);+ assert.equal(formatKeys(c), d.defaultKeys, `${d.id} default is not in canonical form`);+ }+});++test("no two defaults share a combination", () => {+ assert.deepEqual(duplicates(SHORTCUTS.map((d) => [d.id, d.defaultKeys])), new Set());+});++test("no default types a character with AltGr on the checked European layouts", () => {+ for (const layout of ["French (AZERTY)", "German (QWERTZ)", "Spanish", "Italian", "Portuguese", "Brazilian (ABNT2)"]) {+ assert.ok(ALTGR_CHARACTERS[layout], layout);+ }+ for (const d of SHORTCUTS) {+ assert.deepEqual(altGrClashes(d.defaultKeys), [], `${d.id} = ${d.defaultKeys}`);+ }+ // The Mac's own letters would not have been safe.+ assert.deepEqual(altGrClashes("Ctrl+Alt+M"), ["German (QWERTZ)"]);+ assert.ok(altGrClashes("Ctrl+Alt+E").length >= 5);+ assert.ok(altGrClashes("Ctrl+Alt+0").includes("French (AZERTY)"));+ // Not Ctrl+Alt: not AltGr.+ assert.deepEqual(altGrClashes("Ctrl+Shift+E"), []);+});++test("the defaults are the same on both sides of the bridge", () => {+ const rust = readFileSync(new URL("../src-tauri/src/shortcuts.rs", import.meta.url), "utf8");+ const rows = [...rust.matchAll(/^\s*action\("(\w+)", "([^"]+)", (true|false), (true|false)\),/gm)]+ .map(([, id, keys, on, ported]) => ({ id, keys, on: on === "true", ported: ported === "true" }));+ assert.deepEqual(+ rows,+ SHORTCUTS.map((d) => ({ id: d.id, keys: d.defaultKeys, on: d.enabledByDefault, ported: d.ported })),+ );+});++// testEnabledByDefault+test("only the island toggle is off by default; the two not ported yet are reserved", () => {+ for (const d of SHORTCUTS) {+ assert.equal(d.enabledByDefault, d.id !== "toggleIsland", d.id);+ assert.equal(d.ported, !["attachFrontWindow", "desktopToggle"].includes(d.id), d.id);+ }+ assert.deepEqual(activeKeys({}).map(([id]) => id), [+ "openChat", "goToAlert", "jumpToTerminal", "nextPill", "prevPill", "muteToggle", "wardrobeToggle",+ ]);+});++// ── Parsing and formatting (testCarbonModifiers, testDisplayString, testKeyCodeToString) ──++test("modifiers parse one by one and all together", () => {+ assert.deepEqual(parseKeys("Ctrl+Shift+N"), { ctrl: true, alt: false, shift: true, meta: false, key: "N" });+ assert.deepEqual(parseKeys("Ctrl+Alt+A"), { ctrl: true, alt: true, shift: false, meta: false, key: "A" });+ assert.deepEqual(parseKeys("Super+Shift+Alt+Ctrl+k"), { ctrl: true, alt: true, shift: true, meta: true, key: "K" });+ // The spellings Rust accepts.+ assert.equal(normalizeKeys("control+option+arrowright"), "Ctrl+Alt+Right");+ assert.equal(normalizeKeys("CmdOrCtrl+Alt+KeyQ"), "Ctrl+Alt+Q");+ assert.equal(normalizeKeys("Ctrl+Alt+Digit7"), "Ctrl+Alt+7");+ assert.equal(normalizeKeys("Ctrl+Alt+]"), "Ctrl+Alt+BracketRight");+});++test("a bare key, Shift alone, a modifier with no key, or nonsense is not a shortcut", () => {+ for (const bad of ["", "A", "Shift+A", "Ctrl+Alt", "Ctrl+Alt+", "Ctrl+Alt+Nope", "A+Ctrl", "Ctrl+A+B", "Ctrl+Escape"]) {+ assert.equal(parseKeys(bad), null, JSON.stringify(bad));+ }+});++test("what a person reads", () => {+ assert.equal(displayKeys("Ctrl+Shift+N"), "Ctrl+Shift+N");+ assert.equal(displayKeys("Ctrl+Alt+Space"), "Ctrl+Alt+Space");+ assert.equal(displayKeys("Ctrl+Alt+Right"), "Ctrl+Alt+→");+ assert.equal(displayKeys("Ctrl+Alt+Left"), "Ctrl+Alt+←");+ assert.equal(displayKeys("Super+Comma"), "Win+,");+ assert.equal(displayKeys("Ctrl+Alt+BracketLeft"), "Ctrl+Alt+[");+ assert.equal(displayKeys(""), "—");+ // Each modifier once.+ assert.equal(displayKeys("Ctrl+Ctrl+Alt+A").match(/Ctrl/g).length, 1);+});++test("every key name survives a round trip", () => {+ for (const key of KEY_NAMES) {+ assert.equal(normalizeKeys(`Ctrl+Alt+${key}`), `Ctrl+Alt+${key}`, key);+ }+});++// ── Conflicts (testDuplicateDetection) ───────────────────────────────────────++test("duplicates flag both actions, and only the same modifiers and key", () => {+ assert.deepEqual(duplicates([]), new Set());+ assert.deepEqual(duplicates([["goToAlert", "Ctrl+Alt+A"]]), new Set());+ assert.deepEqual(duplicates([["goToAlert", "Ctrl+Alt+A"], ["jumpToTerminal", "Ctrl+Alt+T"]]), new Set());+ assert.deepEqual(+ duplicates([["goToAlert", "Ctrl+Alt+A"], ["jumpToTerminal", "ctrl+alt+a"]]),+ new Set(["goToAlert", "jumpToTerminal"]),+ );+ assert.deepEqual(duplicates([["goToAlert", "Ctrl+Alt+A"], ["jumpToTerminal", "Ctrl+Shift+A"]]), new Set());+});++// ── Stored bindings (testLoadSaveRoundTrip) ───────────────────────────────────++test("a stored binding wins, the rest keep their default, and off ones hold no keys", () => {+ const stored = {+ openChat: { keys: "Ctrl+Alt+K", enabled: true },+ goToAlert: { keys: "Ctrl+Alt+A", enabled: false },+ toggleIsland: { keys: "Ctrl+Alt+N", enabled: true },+ };+ const chat = SHORTCUTS.find((d) => d.id === "openChat");+ assert.deepEqual(effective(chat, stored), { keys: "Ctrl+Alt+K", enabled: true });+ assert.deepEqual(effective(chat, undefined), { keys: "Ctrl+Alt+Space", enabled: true });+ const ids = activeKeys(stored).map(([id]) => id);+ assert.ok(ids.includes("toggleIsland"));+ assert.ok(!ids.includes("goToAlert"));+ // Same JSON shape as Rust's Bindings.+ assert.deepEqual(JSON.parse(JSON.stringify(stored)).openChat, { keys: "Ctrl+Alt+K", enabled: true });+ assert.deepEqual(DEFAULT_SETTINGS.shortcuts, {});+});++// ── Recording a press ─────────────────────────────────────────────────────────++const press = (over) => ({+ key: "", code: "", ctrlKey: false, altKey: false, shiftKey: false, metaKey: false, ...over,+});++test("the recorder turns a press into canonical keys", () => {+ assert.deepEqual(recordPress(press({ key: " ", code: "Space", ctrlKey: true, altKey: true })),+ { kind: "keys", keys: "Ctrl+Alt+Space" });+ assert.deepEqual(recordPress(press({ key: "ArrowRight", code: "ArrowRight", ctrlKey: true, altKey: true })),+ { kind: "keys", keys: "Ctrl+Alt+Right" });+ // AZERTY: the key labelled A sits where QWERTY has Q. The label wins, as it+ // does for RegisterHotKey.+ assert.deepEqual(recordPress(press({ key: "a", code: "KeyQ", ctrlKey: true, altKey: true })),+ { kind: "keys", keys: "Ctrl+Alt+A" });+ assert.deepEqual(recordPress(press({ key: "K", code: "KeyK", ctrlKey: true, shiftKey: true })),+ { kind: "keys", keys: "Ctrl+Shift+K" });+ assert.deepEqual(recordPress(press({ key: "F9", code: "F9", metaKey: true })),+ { kind: "keys", keys: "Super+F9" });+});++test("the recorder waits for a key, cancels, clears, and refuses what can't be a shortcut", () => {+ assert.deepEqual(recordPress(press({ key: "Control", code: "ControlLeft", ctrlKey: true })), { kind: "pending" });+ assert.deepEqual(recordPress(press({ key: "AltGraph", code: "AltRight", ctrlKey: true, altKey: true })), { kind: "pending" });+ assert.deepEqual(recordPress(press({ key: "Escape", code: "Escape" })), { kind: "cancel" });+ assert.deepEqual(recordPress(press({ key: "Backspace", code: "Backspace" })), { kind: "clear" });+ assert.deepEqual(recordPress(press({ key: "a", code: "KeyA" })), { kind: "needsModifier" });+ assert.deepEqual(recordPress(press({ key: "A", code: "KeyA", shiftKey: true })), { kind: "needsModifier" });+ assert.deepEqual(recordPress(press({ key: "Unidentified", code: "Lang1", ctrlKey: true })), { kind: "unsupported" });+});++test("a Ctrl+Alt press that types a character on this keyboard is refused", () => {+ // German: AltGr+E = €, AltGr+Q = @. French: AltGr+0 = @.+ assert.deepEqual(recordPress(press({ key: "€", code: "KeyE", ctrlKey: true, altKey: true })),+ { kind: "typesCharacter", typed: "€", keys: "Ctrl+Alt+E" });+ assert.deepEqual(recordPress(press({ key: "@", code: "KeyQ", ctrlKey: true, altKey: true })),+ { kind: "typesCharacter", typed: "@", keys: "Ctrl+Alt+Q" });+ assert.deepEqual(recordPress(press({ key: "@", code: "Digit0", ctrlKey: true, altKey: true })),+ { kind: "typesCharacter", typed: "@", keys: "Ctrl+Alt+0" });+ assert.equal(recordPress(press({ key: "Dead", code: "BracketLeft", ctrlKey: true, altKey: true })).kind, "typesCharacter");+ // Ctrl+Shift is never AltGr.+ assert.deepEqual(recordPress(press({ key: "€", code: "KeyE", ctrlKey: true, shiftKey: true })),+ { kind: "keys", keys: "Ctrl+Shift+E" });+});++// ── In the island (testCardNavigation and the island keys) ───────────────────++test("card navigation clamps, and starts from either end", () => {+ assert.equal(navigate(null, +1, 3), 0);+ assert.equal(navigate(null, -1, 3), 2);+ assert.equal(navigate(0, -1, 3), 0);+ assert.equal(navigate(2, +1, 3), 2);+ assert.equal(navigate(1, +1, 3), 2);+ assert.equal(navigate(1, -1, 3), 0);+ assert.equal(navigate(1, 0, 3), 1);+ assert.equal(navigate(null, +1, 0), null);+ assert.equal(navigate(0, +1, 0), null);+});++test("pills cycle around and are picked by number", () => {+ const ids = ["a", "b", "c"];+ assert.equal(cyclePill(ids, "a", 1), "b");+ assert.equal(cyclePill(ids, "c", 1), "a");+ assert.equal(cyclePill(ids, "a", -1), "c");+ assert.equal(cyclePill(ids, "gone", 1), "b");+ assert.equal(cyclePill([], "a", 1), null);+ assert.equal(pillByNumber(ids, 1), "a");+ assert.equal(pillByNumber(ids, 3), "c");+ assert.equal(pillByNumber(ids, 4), null);+ assert.equal(pillByNumber(ids, 0), null);+});++test("Ctrl stands in for ⌘ inside the island", () => {+ const ctx = { view: "overview", inTextField: false };+ const ctrl = (key, code = "") => press({ key, code, ctrlKey: true });+ assert.deepEqual(islandKeyAction(ctrl("ArrowRight"), ctx), { kind: "cycle", delta: 1 });+ assert.deepEqual(islandKeyAction(ctrl("ArrowLeft"), ctx), { kind: "cycle", delta: -1 });+ assert.deepEqual(islandKeyAction(ctrl("&", "Digit1"), ctx), { kind: "pill", number: 1 });+ assert.deepEqual(islandKeyAction(ctrl("9", "Digit9"), ctx), { kind: "pill", number: 9 });+ assert.equal(islandKeyAction(ctrl("0", "Digit0"), ctx), null);+ assert.deepEqual(islandKeyAction(ctrl("p", "KeyP"), ctx), { kind: "pin" });+ assert.deepEqual(islandKeyAction(ctrl(",", "Comma"), ctx), { kind: "settings" });+ // Ctrl+K only means something in the chat.+ assert.equal(islandKeyAction(ctrl("k", "KeyK"), ctx), null);+ assert.deepEqual(islandKeyAction(ctrl("k", "KeyK"), { view: "prompt", inTextField: true }), { kind: "newChat" });+ // In a text field Ctrl+← → move by word.+ assert.equal(islandKeyAction(ctrl("ArrowRight"), { view: "prompt", inTextField: true }), null);+ // Anything with another modifier, or no Ctrl, is left alone.+ assert.equal(islandKeyAction(press({ key: "ArrowRight", ctrlKey: true, altKey: true }), ctx), null);+ assert.equal(islandKeyAction(press({ key: "p", code: "KeyP" }), ctx), null);+ assert.ok(ISLAND_SHORTCUTS.length >= 6);+});++// ── What the island does ──────────────────────────────────────────────────────++let did;+const host = {+ alert: (v) => did.push(`alert:${v}`),+ setView: (v) => did.push(`setView:${v}`),+ collapse: () => did.push("collapse"),+ emote: (e) => did.push(`emote:${e}`),+ setPinned: (on) => did.push(`pin:${on}`),+ takeKeyboard: () => did.push("keyboard"),++ wardrobeAnywhere: () => did.push("wardrobe"),+};+const resume = () => did.push("resume");+// The island listens on `window`, which here is the bare global object.+const listeners = [];+globalThis.addEventListener = (type, fn, capture) => listeners.push({ type, fn, capture });+registerShortcutHandlers(host, resume);++beforeEach(() => {+ did = [];+ calls.length = 0;+ State.tasks = [];+ State.focusId = null;+ State.mode = "hidden";+ State.view = "overview";+ State.isPinned = false;+ State.pendingApproval = null;+ State.stateOverride = null;+ State.chatHistory = [];+ State.settings = { ...DEFAULT_SETTINGS };+ State.loadIntegrationTasks();+});+++test("the wardrobe shortcut's own event opens the wardrobe", () => {++ emit("open-wardrobe", null);++ assert.deepEqual(did, ["resume", "wardrobe"]);++});+++test("a global shortcut arrives as an event and opens the chat", () => {+ emit("shortcut", "openChat");+ assert.deepEqual(did, ["resume", "alert:prompt"]);+});++test("island keys are read before the chat field sees them, and only while open", () => {+ const keydown = listeners.find((l) => l.type === "keydown");+ assert.equal(keydown.capture, true);+ const ev = (over) => {+ const e = { ...press(over), target: null, stopped: false, prevented: false };+ e.preventDefault = () => { e.prevented = true; };+ e.stopPropagation = () => { e.stopped = true; };+ return e;+ };+ const hidden = ev({ key: "p", code: "KeyP", ctrlKey: true });+ keydown.fn(hidden);+ assert.equal(hidden.prevented, false);++ State.mode = "expanded";+ const pin = ev({ key: "p", code: "KeyP", ctrlKey: true });+ keydown.fn(pin);+ assert.ok(pin.prevented && pin.stopped);+ assert.deepEqual(did, ["pin:true"]);++ // Typing in the chat is left alone, word jumps included.+ const word = ev({ key: "ArrowLeft", ctrlKey: true });+ word.target = { tagName: "INPUT" };+ keydown.fn(word);+ assert.equal(word.prevented, false);+ const plain = ev({ key: "k", code: "KeyK" });+ keydown.fn(plain);+ assert.equal(plain.prevented, false);+});++test("the island toggle opens with the keyboard, and closes an open island", () => {+ runGlobalShortcut(host, "toggleIsland", resume);+ assert.deepEqual(did, ["resume", "alert:overview", "keyboard"]);+ did = [];+ State.mode = "expanded";+ runGlobalShortcut(host, "toggleIsland", resume);+ assert.deepEqual(did, ["collapse"]);+});++test("go to alert: the permission first, then a question, else Mochi is annoyed", () => {+ runGlobalShortcut(host, "goToAlert", resume);+ assert.deepEqual(did, ["emote:annoyed"]);++ did = [];+ State.upsertExternalAgent("agent_gemini", "Gemini", "#fff");+ State.updateTask("agent_gemini", "question");+ runGlobalShortcut(host, "goToAlert", resume);+ assert.deepEqual(did, ["resume", "alert:question", "keyboard"]);+ assert.equal(State.focusId, "agent_gemini");++ did = [];+ State.pendingApproval = { requestId: "r1", sessionId: "s", pillId: "integration_claude", tool: "Bash", command: "ls" };+ runGlobalShortcut(host, "goToAlert", resume);+ assert.deepEqual(did, ["resume", "alert:approval", "keyboard"]);+ assert.equal(State.focusId, "integration_claude");+ // Nothing is ever decided from a shortcut.+ assert.deepEqual(sent("approval_decision"), []);+});++test("go to alert brings up the unified card: any agent's pill, a question as a question", () => {+ State.upsertExternalAgent("agent_codex", "Codex", "#fff");+ State.pendingApproval = { requestId: "r1", sessionId: "s", pillId: "agent_codex", tool: "Bash", command: "ls" };+ runGlobalShortcut(host, "goToAlert", resume);+ assert.deepEqual(did, ["resume", "alert:approval", "keyboard"]);+ assert.equal(State.focusId, "agent_codex");++ did = [];+ State.pendingApproval = {+ requestId: "r2", sessionId: "s", pillId: "integration_claude", tool: "AskUserQuestion", command: "",+ questions: [{ question: "Which?", options: [], multiSelect: false }],+ };+ runGlobalShortcut(host, "goToAlert", resume);+ assert.deepEqual(did, ["resume", "alert:question", "keyboard"]);+ assert.equal(State.focusId, "integration_claude");+ assert.deepEqual(sent("approval_decision"), []);+ assert.deepEqual(sent("approval_answer"), []);+});++test("the island toggle opens on a waiting card, and folds it rather than dropping it", () => {+ State.pendingApproval = { requestId: "r1", sessionId: "s", pillId: "integration_claude", tool: "Bash", command: "ls" };+ runGlobalShortcut(host, "toggleIsland", resume);+ assert.deepEqual(did, ["resume", "alert:approval", "keyboard"]);+ did = [];+ State.mode = "expanded";+ // The island's collapse() folds a waiting card (Island.foldApproval).+ runGlobalShortcut(host, "toggleIsland", resume);+ assert.deepEqual(did, ["collapse"]);+ assert.equal(State.pendingApproval.requestId, "r1");+});++test("the terminal shortcut is the existing Open terminal (the session's window), and folds the island", () => {+ State.tasks[0].sessionCwd = "C:\\work\\proj";+ State.mode = "expanded";+ runGlobalShortcut(host, "jumpToTerminal", resume);+ assert.deepEqual(sent("open_session"), [{ sessionId: null, path: "C:\\work\\proj" }]);+ assert.deepEqual(did, ["collapse"]);++ // A Claude Desktop session lives in the Claude app.+ did = [];+ State.upsertExternalAgent("agent_claude-desktop", "Claude Desktop", "#D97757");+ State.setFocus("agent_claude-desktop");+ runGlobalShortcut(host, "jumpToTerminal", resume);+ assert.equal(sent("open_claude_desktop").length, 1);+});++test("next and previous pill wrap around and open the overview", () => {+ const ids = State.tasks.map((t) => t.id);+ State.focusId = ids[0];+ runGlobalShortcut(host, "prevPill", resume);+ assert.equal(State.focusId, ids[ids.length - 1]);+ runGlobalShortcut(host, "nextPill", resume);+ assert.equal(State.focusId, ids[0]);+ assert.deepEqual(did, ["resume", "alert:overview", "resume", "alert:overview"]);+});++test("mute flips the sound, saves it, and Mochi reacts", () => {+ runGlobalShortcut(host, "muteToggle", resume);+ assert.equal(State.settings.soundEnabled, false);+ assert.equal(sent("save_settings").at(-1).settings.soundEnabled, false);+ runGlobalShortcut(host, "muteToggle", resume);+ assert.equal(State.settings.soundEnabled, true);+ assert.deepEqual(did, ["emote:annoyed", "emote:happy"]);+});++test("actions that aren't the island's do nothing here", () => {+ for (const id of ["wardrobeToggle", "attachFrontWindow", "desktopToggle", "nonsense"]) {+ runGlobalShortcut(host, id, resume);+ }+ assert.deepEqual(did, []);+ assert.deepEqual(calls, []);+});++test("island keys: pills by number, new chat, settings, pin", () => {+ const ids = State.tasks.map((t) => t.id);+ runIslandKey(host, { kind: "pill", number: 2 });+ assert.equal(State.focusId, ids[1]);+ runIslandKey(host, { kind: "pill", number: 9 });+ assert.equal(State.focusId, ids[1]);+ runIslandKey(host, { kind: "cycle", delta: 1 });+ assert.equal(State.focusId, ids[2 % ids.length]);++ State.chatHistory = [{ id: 1, role: "user", content: "hi" }];+ State.stateOverride = "thinking";+ runIslandKey(host, { kind: "newChat" });+ assert.equal(State.chatHistory.length, 1, "not while an answer is on its way");+ State.stateOverride = null;+ runIslandKey(host, { kind: "newChat" });+ assert.deepEqual(State.chatHistory, []);+ assert.equal(sent("chat_reset").length, 1);++ runIslandKey(host, { kind: "settings" });+ assert.equal(sent("open_settings_window").length, 1);++ runIslandKey(host, { kind: "pin" });+ State.pendingApproval = { requestId: "r1", sessionId: "s", pillId: "integration_claude", tool: "Bash", command: "ls" };+ runIslandKey(host, { kind: "pin" });+ assert.deepEqual(did, ["setView:overview", "setView:overview", "setView:prompt", "pin:true"]);+});