Skip to content

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.

Merge port/shortcuts: global shortcuts, in-island keys and Settings → Shortcuts

Claude642a4893e89e
diff --cc windows/Cargo.lock
index 489bfbf8,b6a09d34..1645e30d
--- a/windows/Cargo.lock
+++ b/windows/Cargo.lock
@@@ -621,11 -621,10 +621,12 @@@ dependencies =
"tauri",
"tauri-build",
"tauri-plugin-autostart",
+ "tauri-plugin-global-shortcut",
"tauri-plugin-single-instance",
"tokio",
+ "webview2-com",
"windows 0.61.3",
+ "windows-core 0.62.2",
]
[[package]]
diff --cc windows/README.md
index 865d6ecd,616fca78..1bc5870a
--- a/windows/README.md
+++ b/windows/README.md
@@@ -44,42 -44,45 +44,74 @@@ installs for the current user only —
| Click Mochi | It gets annoyed. Three times in a row and it goes dizzy |
| Rest the pointer on Mochi for two seconds | Hearts |
| 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, 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` | Opens the session's folder in VS Code ("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, and
your 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.
+
+**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">
@@@ -298,43 -191,18 +330,52 @@@ own window
the top edge instead of hiding in a notch.
- Permission approval works from **any** terminal; the Mac build only listens to
VS 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 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. There is no
- ⌘E-style shortcut.
++ 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
+ 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.
++ 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.
## Linux
@@@ -378,18 -231,19 +419,29 @@@ What changes on Linux
gives no app the cursor position anywhere else.
- **Claude Code hooks** go through `~/.local/share/coucou/bin/coucou-hook` and a
Unix 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`.
- What the Windows build leaves out, this one does too: sending a file by
diff --cc windows/src-tauri/src/lib.rs
index 413ac8ac,5f06cca6..c660bb86
--- a/windows/src-tauri/src/lib.rs
+++ b/windows/src-tauri/src/lib.rs
@@@ -19,11 -9,9 +19,12 @@@ mod openai_compat
mod pipe;
mod platform;
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;
@@@ -97,7 -84,9 +99,10 @@@ fn save_settings(app: AppHandle, shared
let collapsed = shared.gate.collapsed.load(Ordering::Relaxed);
island::apply_geometry(&app, &settings.screen, collapsed);
}
+ integrations::settings_saved(&app, &settings.active_integrations);
+ if shortcuts_changed {
+ shortcuts::apply(&app, &settings.shortcuts);
+ }
// Keep the other window in step (island ⇄ settings window).
let _ = app.emit("settings-changed", settings);
}
diff --cc windows/src-tauri/src/platform/windows.rs
index 21ed0879,6707a2d6..40442425
--- a/windows/src-tauri/src/platform/windows.rs
+++ b/windows/src-tauri/src/platform/windows.rs
@@@ -12,19 -10,16 +12,22 @@@ use ::windows::core::{BOOL, PWSTR}
use ::windows::Win32::Foundation::{CloseHandle, HANDLE, HLOCAL, HWND, LPARAM, LocalFree, POINT};
use ::windows::Win32::Security::Authorization::ConvertSidToStringSidW;
use ::windows::Win32::Security::{GetTokenInformation, TokenUser, TOKEN_QUERY, TOKEN_USER};
+use ::windows::Win32::System::Diagnostics::ToolHelp::{
+ CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W, TH32CS_SNAPPROCESS,
+};
use ::windows::Win32::System::Ole::RevokeDragDrop;
+use ::windows::Win32::System::Pipes::GetNamedPipeClientProcessId;
use ::windows::Win32::System::SystemInformation::GetLocalTime;
use ::windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
- use ::windows::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, VK_LBUTTON};
+ use ::windows::Win32::UI::Input::KeyboardAndMouse::{
+ GetAsyncKeyState, GetKeyboardLayoutList, MapVirtualKeyExW, ToUnicodeEx, HKL, MAPVK_VK_TO_VSC,
+ VK_CONTROL, VK_LBUTTON, VK_MENU, VK_SHIFT,
+ };
use ::windows::Win32::UI::WindowsAndMessaging::{
- EnumChildWindows, GetClassNameW, GetCursorPos, GetWindowLongPtrW, SetWindowLongPtrW,
- GWL_EXSTYLE, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW,
+ EnumChildWindows, EnumWindows, GetClassNameW, GetCursorPos, GetWindow, GetWindowLongPtrW,
+ GetWindowTextW, GetWindowThreadProcessId, IsIconic, IsWindowVisible, SetForegroundWindow,
+ SetWindowLongPtrW, ShowWindow, GWL_EXSTYLE, GW_OWNER, SW_RESTORE, WS_EX_NOACTIVATE,
+ WS_EX_TOOLWINDOW,
};
use super::LocalTime;
@@@ -321,129 -237,43 +324,170 @@@ 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
+ }
diff --cc windows/src-tauri/src/settings.rs
index 98d522db,003b4c28..ffc43368
--- a/windows/src-tauri/src/settings.rs
+++ b/windows/src-tauri/src/settings.rs
@@@ -26,27 -23,9 +26,30 @@@ pub struct Settings
pub 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,
}
fn default_model() -> String {
@@@ -71,14 -49,7 +74,15 @@@ impl Default for Settings
autostart: 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(),
}
}
}
@@@ -341,14 -311,7 +345,15 @@@ 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"
++ "customUrl": "https://llm.example.com",
+ "shortcuts": { "openChat": { "keys": "Ctrl+Shift+K", "enabled": false } }
}"#;
fn custom() -> Value {
@@@ -455,8 -418,8 +460,9 @@@
("soundVolume", json!("loud")),
("soundEnabled", json!(1)),
("activeIntegrations", json!("integration_n8n")),
+ ("mainPill", json!(["agent_cursor"])),
("screen", Value::Null),
+ ("shortcuts", json!("Ctrl+Alt+A")),
] {
let loaded = parse(&custom_with(key, Some(wrong)))
.unwrap_or_else(|| panic!("a file with a bad {key} was thrown away"));
@@@ -676,14 -638,7 +682,15 @@@
"autostart",
"hooksInstalled",
"model",
+ "showPlanInNotch",
+ "planRelayInstalled",
+ "showCodexPlanInNotch",
+ "chatProvider",
+ "chatModels",
+ "ollamaUrl",
+ "lmstudioUrl",
+ "customUrl",
+ "shortcuts",
]
);
let _ = std::fs::remove_dir_all(&dir);
diff --cc windows/src/core/state.ts
index 8e6897ae,d0102ece..c99a1306
--- a/windows/src/core/state.ts
+++ b/windows/src/core/state.ts
@@@ -2,13 -2,7 +2,14 @@@
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";
export type AgentSource = "claudeCode" | "n8n" | "agent";
export type PillBadge = "approval" | "finished" | "error";
@@@ -108,20 -93,8 +109,22 @@@ export interface Settings
hooksInstalled: 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;
}
export const DEFAULT_SETTINGS: Settings = {
@@@ -137,14 -109,7 +140,15 @@@
autostart: false,
hooksInstalled: false,
model: "claude-opus-5",
+ showPlanInNotch: false,
+ planRelayInstalled: false,
+ showCodexPlanInNotch: false,
+ chatProvider: "anthropic",
+ chatModels: {},
+ ollamaUrl: "",
+ lmstudioUrl: "",
+ customUrl: "",
+ shortcuts: {},
};
type Listener = () => void;
diff --cc windows/src/island/island.ts
index 8b41956f,ceafc828..cbac9486
--- a/windows/src/island/island.ts
+++ b/windows/src/island/island.ts
@@@ -7,8 -7,7 +7,8 @@@ import
EXPANDED_CORNER, EXPANDED_W, NOTCH_W, PANEL_H, PANEL_W,
ROUNDED_CORNER, VIEW_LAYOUTS, botGlowColor, botGlowOpacity, botPosition, chatPromptHeight,
islandSize,
+ QUESTION_PICKER_H,
- type IslandMode, type IslandViewName,
+ type BotEmoteName, type IslandMode, type IslandViewName,
} from "../core/layout";
import { Sound } from "../core/sound";
import { State } from "../core/state";
@@@ -389,10 -337,35 +389,36 @@@ export class Island
/** An alert stopped waiting for an answer: let the island auto-close again. */
dropPin() {
this.fsm.pinned = false;
+ // The countdown the pin held back starts now, if the mouse is elsewhere.
+ if (!this.wasInIsland) this.fsm.mouseLeft();
}
+ // ── Keyboard shortcuts (island/shortcuts.ts) ────────────────────────────────
+
+ emote(name: BotEmoteName) {
+ this.engine.triggerEmote(name);
+ this.ensureRunning();
+ }
+
+ /** Ctrl+P: keep the open island from folding away, or let it fold again. */
+ setPinned(on: boolean) {
+ State.isPinned = on;
+ this.fsm.pinned = on;
+ if (on) {
++ // The countdown bar reads the state machine's deadline, cleared with it.
+ this.fsm.cancelTimers();
- this.homeCollapseAt = null;
+ } else if (!this.wasInIsland && this.fsm.state === "home") {
+ this.fsm.mouseLeft();
- this.homeCollapseAt = performance.now() + State.settings.autoCloseInterval * 1000;
+ }
+ State.notify();
+ }
+
+ /** The island takes the keyboard, so its own shortcuts work (Mac: makeKey).
+ * It gives it back when it closes, or when the chat is left. */
+ takeKeyboard() {
+ void Bridge.focusWindow(true);
+ }
+
// ── File drop ───────────────────────────────────────────────────────────────
private onDragDrop(e: { type: string; paths?: string[] }) {
diff --cc windows/src/island/shortcuts.ts
index 00000000,e9411a04..a4d58eed
mode 000000,100644..100644
--- a/windows/src/island/shortcuts.ts
+++ b/windows/src/island/shortcuts.ts
@@@ -1,0 -1,162 +1,170 @@@
+ // 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_ID = "integration_claude";
++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;
+ }
+
+ 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();
- host.alert(State.pendingApproval ? "approval" : State.defaultView());
++ // 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");
- if (State.pendingApproval) {
++ 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(CLAUDE_ID);
- host.alert("approval");
++ 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 folder in VS Code.
- case "jumpToTerminal":
- void Bridge.openInVSCode(State.focusTask?.sessionCwd ?? null);
++ // 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));
+
+ // 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/settings/main.ts
index 8d05ae25,50874400..b7587410
--- a/windows/src/settings/main.ts
+++ b/windows/src/settings/main.ts
@@@ -3,21 -3,13 +3,25 @@@
// integrations land here too in a later stage.
import "./settings.css";
- import { Bridge, onEvent, type HookPreview, type HookStatus } from "../core/bridge";
-import { Bridge, onEvent, type HookStatus, type ShortcutsReport } from "../core/bridge";
++import { Bridge, onEvent, type HookPreview, type HookStatus, type ShortcutsReport } from "../core/bridge";
+import { CUSTOM_SERVER_KEY, providerDef, urlExposure } from "../core/providers";
+ import {
+ ISLAND_SHORTCUTS, SHORTCUTS, SHORTCUT_TEXT, activeKeys, displayKeys, duplicates, effective,
+ recordPress, type Binding,
+ } from "../core/shortcuts";
import { DEFAULT_SETTINGS, type Settings } from "../core/state";
+import {
+ MAX_DECLARED, PILL_CATEGORIES, availablePills, chooseMainPill, isComingSoon, mainPillChoices,
+ sanitizeDeclared, toggleDeclared, type PillDefinition,
+} from "../core/pills";
import { h, clear } from "../views/dom";
+import { agentsSection } from "./agents";
+import { renderDiff, statusDot } from "./parts";
+
+/** Where secrets.rs keeps the keys on this OS. */
+const KEY_STORE = navigator.userAgent.includes("Windows")
+ ? "Windows Credential Manager"
+ : "Secret Service (GNOME Keyring, KWallet)";
let settings: Settings = { ...DEFAULT_SETTINGS };
let version = "";
@@@ -926,11 -613,11 +1113,12 @@@ async function main()
version = boot.version;
}
const status = (await Bridge.hooksStatus()) ?? {
- installed: false, settingsPath: "", hookPath: "", hookReady: false,
+ installed: false, planRelayInstalled: false, settingsPath: "", hookPath: "", hookReady: false,
};
+ const agents = await Bridge.agentHooksList();
const hasKey = (await Bridge.secretPresent("anthropic-api-key")) ?? false;
+ const shortcutReport = await Bridge.shortcutsStatus();
const keys = [
"stripe-api-key", "github-token", "vercel-token",
@@@ -965,14 -630,10 +1153,15 @@@
root.append(
h("h1", {}, h("span", { text: "Coucou" }), h("span", { class: "version", text: version })),
claudeSection(status),
+ agentsSection(agents),
+ planSection(status),
apiSection(hasKey),
+ chatProvidersSection(chatKeys, keyChanged),
+ localSection(customKey),
+ activePillsSection(connected),
integrationsSection(present),
generalSection(),
+ shortcutsSection(shortcutReport),
h("div", {
class: "hint",
text: "No telemetry. Network requests only go to the services you configure yourself.",
diff --cc windows/src/settings/settings.css
index cc2517f1,c17d018c..f8b44614
--- a/windows/src/settings/settings.css
+++ b/windows/src/settings/settings.css
@@@ -266,42 -266,75 +266,115 @@@ select option
color: #fbc06a;
}
+/* Active pills — one group per catalog category, one row per pill. */
+
+.pill-group {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ padding-top: 10px;
+ border-top: 1px solid var(--hairline);
+}
+
+.pill-group > h3 {
+ font: 600 11px var(--font);
+ color: var(--dim);
+}
+
+.pill-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-height: 24px;
+}
+
+.pill-row .name {
+ font-size: 12.5px;
+}
+
+.pill-row.full .name {
+ color: var(--dim-2);
+}
+
+.pill-row .state {
+ margin-left: auto;
+ font: 400 11.5px var(--font);
+ color: var(--dim);
+}
+
+.hint.full {
+ color: var(--amber);
+}
++
+ /* Shortcuts section */
+
+ .subhead {
+ font: 600 11px var(--font);
+ color: var(--dim-2);
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ margin-top: 4px;
+ }
+
+ .shortcut-list {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ }
+
+ .row.shortcut {
+ flex-wrap: nowrap;
+ gap: 10px;
+ }
+
+ .row.shortcut.off .shortcut-name {
+ color: var(--dim-2);
+ }
+
+ .shortcut-name {
+ flex: 1 1 auto;
+ min-width: 0;
+ font-size: 12.5px;
+ }
+
+ .keycap {
+ font: 500 11.5px var(--mono);
+ min-width: 118px;
+ padding: 5px 10px;
+ border-radius: 8px;
+ background: rgba(255, 255, 255, 0.07);
+ border: 1px solid var(--hairline);
+ color: var(--ink);
+ text-align: center;
+ flex: 0 0 auto;
+ }
+
+ .keycap.recording {
+ border-color: rgba(255, 255, 255, 0.4);
+ color: var(--dim);
+ }
+
+ .keycap.static {
+ background: transparent;
+ color: var(--dim);
+ }
+
+ .tag {
+ font: 500 10.5px var(--font);
+ padding: 2px 8px;
+ border-radius: 999px;
+ background: rgba(255, 255, 255, 0.08);
+ color: var(--dim);
+ white-space: nowrap;
+ flex: 0 0 auto;
+ }
+
+ .tag.warn {
+ background: rgba(245, 165, 36, 0.13);
+ color: #fbc06a;
+ }
+
+ .tag.err {
+ background: rgba(244, 80, 94, 0.14);
+ color: #ff8d97;
+ }
diff --cc windows/tests/shortcuts.test.mjs
index 00000000,896748a9..d7e740f9
mode 000000,100644..100644
--- a/windows/tests/shortcuts.test.mjs
+++ b/windows/tests/shortcuts.test.mjs
@@@ -1,0 -1,395 +1,433 @@@
+ // 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"),
+ };
+ 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("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", tool: "Bash", command: "ls" };
++ 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("the terminal shortcut is the existing Open terminal, and folds the island", () => {
++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_in_vscode"), [{ path: "C:\\work\\proj" }]);
++ 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", tool: "Bash", command: "ls" };
++ 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"]);
+ });