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
Windows: Claude Code hooks and approving from the island
Louis Railled68e00baf429
diff --git a/windows/Cargo.lock b/windows/Cargo.lockindex 07562e65..48ca1f62 100644--- a/windows/Cargo.lock+++ b/windows/Cargo.lock@@ -562,6 +562,7 @@ dependencies = ["tauri-build","tauri-plugin-autostart","tauri-plugin-single-instance",+ "tokio","windows 0.61.3",]diff --git a/windows/hook/src/main.rs b/windows/hook/src/main.rsindex d689f657..2421f09f 100644--- a/windows/hook/src/main.rs+++ b/windows/hook/src/main.rs@@ -51,6 +51,10 @@ fn run() {if std::io::stdin().read_to_end(&mut raw).is_err() || raw.is_empty() {return;}+ // Some shells hand us a UTF-8 BOM; serde_json would choke on it.+ if raw.starts_with(&[0xEF, 0xBB, 0xBF]) {+ raw.drain(..3);+ }let Ok(mut payload) = serde_json::from_slice::<serde_json::Value>(&raw) else { return };let Some(map) = payload.as_object_mut() else { return };diff --git a/windows/package.json b/windows/package.jsonindex 2018d6ca..27572ff4 100644--- a/windows/package.json+++ b/windows/package.json@@ -8,7 +8,9 @@"build": "tsc --noEmit && vite build","preview": "vite preview","icons": "node scripts/gen-icons.mjs",- "tauri": "tauri"+ "tauri": "tauri",+ "predev": "cargo build --release -p coucou-hook",+ "prebuild": "cargo build --release -p coucou-hook"},"devDependencies": {"@tauri-apps/cli": "^2",diff --git a/windows/settings.html b/windows/settings.htmlnew file mode 100644index 00000000..2f6d9ddf--- /dev/null+++ b/windows/settings.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>Settings — Coucou</title>+ </head>+ <body class="settings-window" style="background: #0b0c0e; color: #f5f6f8">+ <div id="settings-root"><p style="padding: 24px">Loading…</p></div>+ <script type="module" src="/src/settings/main.ts"></script>+ </body>+</html>diff --git a/windows/src-tauri/Cargo.toml b/windows/src-tauri/Cargo.tomlindex 3ba67a7e..577c5608 100644--- a/windows/src-tauri/Cargo.toml+++ b/windows/src-tauri/Cargo.toml@@ -19,7 +19,9 @@ tauri-plugin-single-instance = "2"tauri-plugin-autostart = "2"serde = { version = "1", features = ["derive"] }serde_json = "1"+tokio = { version = "1", features = ["net", "io-util", "sync", "time", "rt"] }windows = { version = "0.61", features = ["Win32_Foundation",+ "Win32_System_SystemInformation","Win32_UI_WindowsAndMessaging",] }diff --git a/windows/src-tauri/capabilities/default.json b/windows/src-tauri/capabilities/default.jsonindex 4ad5a962..38b8f5df 100644--- a/windows/src-tauri/capabilities/default.json+++ b/windows/src-tauri/capabilities/default.json@@ -1,7 +1,7 @@{"$schema": "../gen/schemas/desktop-schema.json","identifier": "default",- "description": "What the island window is allowed to do. Everything that touches the OS goes through Coucou's own commands.",- "windows": ["island"],+ "description": "What Coucou's windows are allowed to do. Everything that touches the OS goes through Coucou's own commands.",+ "windows": ["island", "settings"],"permissions": ["core:default", "autostart:default"]}diff --git a/windows/src-tauri/src/hooks.rs b/windows/src-tauri/src/hooks.rsnew file mode 100644index 00000000..fff4ea5f--- /dev/null+++ b/windows/src-tauri/src/hooks.rs@@ -0,0 +1,340 @@+// Claude Code hook installation.+//+// The rule from CLAUDE.md is strict and is followed to the letter:+// read %USERPROFILE%\.claude\settings.json, take a dated backup, merge without+// touching anybody else's hooks, show the diff, and write only after an explicit+// click. Uninstall removes Coucou's entries and nothing else.+//+// The command is only the quoted exe path in forward slashes plus the event name:+// on Windows Claude Code runs hook commands through Git Bash, and anything with+// PowerShell or cmd in it breaks.++use std::path::{Path, PathBuf};++use serde::Serialize;+use serde_json::{json, Map, Value};+use tauri::{AppHandle, Manager};+use windows::Win32::System::SystemInformation::GetLocalTime;++use crate::settings;++/// Every event the island reacts to, with the hook timeout written to settings.json.+/// PermissionRequest waits for a human, so it gets the decision timeout + 10 s.+pub const HOOK_EVENTS: &[(&str, u64)] = &[+ ("SessionStart", 10),+ ("SessionEnd", 10),+ ("UserPromptSubmit", 10),+ ("PreToolUse", 10),+ ("PostToolUse", 10),+ ("PostToolUseFailure", 10),+ ("PermissionRequest", 120),+ ("Notification", 10),+ ("Stop", 10),+ ("StopFailure", 10),+ ("SubagentStart", 10),+ ("SubagentStop", 10),+];++/// Marker that identifies a Coucou entry inside settings.json.+const MARKER: &str = "coucou-hook";++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct HookStatus {+ pub installed: bool,+ pub settings_path: String,+ pub hook_path: String,+ pub hook_ready: bool,+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct HookPreview {+ pub diff: String,+ pub backup: String,+ pub settings_path: String,+}++fn home() -> PathBuf {+ std::env::var_os("USERPROFILE")+ .map(PathBuf::from)+ .unwrap_or_else(|| PathBuf::from("."))+}++pub fn settings_path() -> PathBuf {+ home().join(".claude").join("settings.json")+}++fn read_settings() -> Value {+ match std::fs::read(settings_path()) {+ Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|_| json!({})),+ Err(_) => json!({}),+ }+}++fn hook_command(event: &str) -> String {+ let exe = settings::hook_exe_path().to_string_lossy().replace('\\', "/");+ format!("\"{exe}\" {event}")+}++fn entry_is_ours(entry: &Value) -> bool {+ entry+ .get("hooks")+ .and_then(Value::as_array)+ .map(|hooks| {+ hooks.iter().any(|h| {+ h.get("command")+ .and_then(Value::as_str)+ .map(|c| c.contains(MARKER))+ .unwrap_or(false)+ })+ })+ .unwrap_or(false)+}++/// Settings with Coucou's hooks added; everything else is left untouched.+fn merged(existing: &Value) -> Value {+ let mut root = existing.as_object().cloned().unwrap_or_default();+ let mut hooks = root+ .get("hooks")+ .and_then(Value::as_object)+ .cloned()+ .unwrap_or_else(Map::new);++ for (event, timeout) in HOOK_EVENTS {+ let mut list = hooks+ .get(*event)+ .and_then(Value::as_array)+ .cloned()+ .unwrap_or_default();+ list.retain(|entry| !entry_is_ours(entry));+ list.push(json!({+ "hooks": [{+ "type": "command",+ "command": hook_command(event),+ "timeout": timeout,+ }]+ }));+ hooks.insert((*event).to_string(), Value::Array(list));+ }++ root.insert("hooks".into(), Value::Object(hooks));+ Value::Object(root)+}++/// Settings with every Coucou entry removed, and nothing else changed.+fn without_ours(existing: &Value) -> Value {+ let mut root = existing.as_object().cloned().unwrap_or_default();+ let Some(hooks) = root.get("hooks").and_then(Value::as_object).cloned() else {+ return Value::Object(root);+ };+ let mut out = Map::new();+ for (event, value) in hooks {+ match value.as_array() {+ Some(list) => {+ let kept: Vec<Value> =+ list.iter().filter(|e| !entry_is_ours(e)).cloned().collect();+ if !kept.is_empty() {+ out.insert(event, Value::Array(kept));+ }+ }+ None => {+ out.insert(event, value);+ }+ }+ }+ if out.is_empty() {+ root.remove("hooks");+ } else {+ root.insert("hooks".into(), Value::Object(out));+ }+ Value::Object(root)+}++fn pretty(v: &Value) -> String {+ serde_json::to_string_pretty(v).unwrap_or_default()+}++fn stamp() -> String {+ let t = unsafe { GetLocalTime() };+ format!(+ "{:04}{:02}{:02}-{:02}{:02}",+ t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute+ )+}++fn backup_path() -> PathBuf {+ let p = settings_path();+ p.with_file_name(format!("settings.json.bak-{}", stamp()))+}++// ── Public API ────────────────────────────────────────────────────────────────++pub fn status() -> HookStatus {+ let current = read_settings();+ let installed = current+ .get("hooks")+ .and_then(Value::as_object)+ .map(|hooks| {+ hooks+ .values()+ .filter_map(Value::as_array)+ .flatten()+ .any(entry_is_ours)+ })+ .unwrap_or(false);+ let hook_path = settings::hook_exe_path();+ HookStatus {+ installed,+ settings_path: settings_path().to_string_lossy().to_string(),+ hook_ready: hook_path.exists(),+ hook_path: hook_path.to_string_lossy().to_string(),+ }+}++pub fn preview(install: bool) -> HookPreview {+ let current = read_settings();+ let next = if install { merged(¤t) } else { without_ours(¤t) };+ HookPreview {+ diff: unified_diff(&pretty(¤t), &pretty(&next)),+ backup: backup_path().to_string_lossy().to_string(),+ settings_path: settings_path().to_string_lossy().to_string(),+ }+}++/// Writes the merged (or cleaned) settings after taking a dated backup.+pub fn write(install: bool) -> Result<String, String> {+ let path = settings_path();+ let dir = path.parent().unwrap_or(Path::new("."));+ std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;++ let current = read_settings();+ let backup = backup_path();+ if path.exists() {+ std::fs::copy(&path, &backup).map_err(|e| format!("backup failed: {e}"))?;+ }++ let next = if install { merged(¤t) } else { without_ours(¤t) };+ let mut text = pretty(&next);+ text.push('\n');+ std::fs::write(&path, text).map_err(|e| e.to_string())?;+ Ok(backup.to_string_lossy().to_string())+}++/// Copies coucou-hook.exe into %LOCALAPPDATA%\Coucou\bin on launch.+/// In a bundled install it comes from the app resources; in `tauri dev` it sits+/// next to coucou.exe in the workspace target directory.+pub fn ensure_hook_exe(app: &AppHandle) {+ let dest = settings::hook_exe_path();+ let Some(dir) = dest.parent() else { return };+ if std::fs::create_dir_all(dir).is_err() {+ return;+ }++ let mut candidates: Vec<PathBuf> = Vec::new();+ if let Ok(p) = app.path().resolve("coucou-hook.exe", tauri::path::BaseDirectory::Resource) {+ candidates.push(p);+ }+ if let Ok(exe) = std::env::current_exe() {+ if let Some(parent) = exe.parent() {+ // Installed build, then `tauri dev` (target/debug) next to the+ // release hook the pre-build step produces.+ candidates.push(parent.join("coucou-hook.exe"));+ candidates.push(parent.join("../release/coucou-hook.exe"));+ }+ }++ let Some(src) = candidates.into_iter().find(|p| p.exists()) else {+ eprintln!("[coucou] coucou-hook.exe not found — run `cargo build -p coucou-hook`");+ return;+ };++ let same = match (std::fs::metadata(&src), std::fs::metadata(&dest)) {+ (Ok(a), Ok(b)) => a.len() == b.len() && a.modified().ok() == b.modified().ok(),+ _ => false,+ };+ if same {+ return;+ }+ // A hook may be running right now and hold the file open; keeping the old+ // copy is fine, it is the same relay.+ if let Err(err) = std::fs::copy(&src, &dest) {+ eprintln!("[coucou] could not refresh coucou-hook.exe: {err}");+ }+}++// ── Minimal unified diff (LCS) ────────────────────────────────────────────────++/// settings.json is short, so a plain O(n·m) LCS is the simplest honest diff.+fn unified_diff(before: &str, after: &str) -> String {+ let a: Vec<&str> = before.lines().collect();+ let b: Vec<&str> = after.lines().collect();+ let (n, m) = (a.len(), b.len());++ let mut lcs = vec![vec![0usize; m + 1]; n + 1];+ for i in (0..n).rev() {+ for j in (0..m).rev() {+ lcs[i][j] = if a[i] == b[j] {+ lcs[i + 1][j + 1] + 1+ } else {+ lcs[i + 1][j].max(lcs[i][j + 1])+ };+ }+ }++ let mut out: Vec<String> = Vec::new();+ let (mut i, mut j) = (0usize, 0usize);+ while i < n && j < m {+ if a[i] == b[j] {+ out.push(format!(" {}", a[i]));+ i += 1;+ j += 1;+ } else if lcs[i + 1][j] >= lcs[i][j + 1] {+ out.push(format!("- {}", a[i]));+ i += 1;+ } else {+ out.push(format!("+ {}", b[j]));+ j += 1;+ }+ }+ while i < n {+ out.push(format!("- {}", a[i]));+ i += 1;+ }+ while j < m {+ out.push(format!("+ {}", b[j]));+ j += 1;+ }++ // Keep three lines of context around each change so the panel stays readable.+ let changed: Vec<usize> = out+ .iter()+ .enumerate()+ .filter(|(_, l)| l.starts_with('+') || l.starts_with('-'))+ .map(|(i, _)| i)+ .collect();+ if changed.is_empty() {+ return "No change.".into();+ }+ let mut keep = vec![false; out.len()];+ for idx in changed {+ let lo = idx.saturating_sub(3);+ let hi = (idx + 4).min(out.len());+ for k in lo..hi {+ keep[k] = true;+ }+ }+ let mut result = String::new();+ let mut gap = false;+ for (idx, line) in out.iter().enumerate() {+ if keep[idx] {+ result.push_str(line);+ result.push('\n');+ gap = false;+ } else if !gap {+ result.push_str(" …\n");+ gap = true;+ }+ }+ result+}diff --git a/windows/src-tauri/src/island.rs b/windows/src-tauri/src/island.rsindex eb0f56be..5b38b183 100644--- a/windows/src-tauri/src/island.rs+++ b/windows/src-tauri/src/island.rs@@ -5,7 +5,7 @@// centre of the main display inside a borderless, transparent, always-on-top// window that never takes focus.-use std::sync::atomic::AtomicBool;+use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Condvar, Mutex};use std::time::Duration;@@ -27,6 +27,10 @@ pub const STRIP_H: f64 = 6.0;pub const WINDOW_LABEL: &str = "island";+/// Margin around the island that still counts as "on the island", in logical px.+/// Wider than the macOS 6 pt because a click must never be swallowed.+const HIT_MARGIN: f64 = 14.0;+#[derive(Serialize, Clone)]pub struct CursorPayload {pub x: f64,@@ -42,11 +46,25 @@ pub struct ScreenInfo {pub scale: f64,}+/// The island shape in window-logical coordinates, pushed by the front end.+/// The poll thread owns the click-through decision so it lands in the same 16 ms+/// tick as the cursor read — an IPC round trip here loses clicks.+#[derive(Clone, Copy, Default)]+pub struct IslandRect {+ pub x: f64,+ pub y: f64,+ pub w: f64,+ pub h: f64,+}+/// Wakes / parks the cursor poll thread so a hidden island costs literally nothing.pub struct PollGate {active: Mutex<bool>,cv: Condvar,pub collapsed: AtomicBool,+ pub rect: Mutex<IslandRect>,+ /// Mirrors the window flag so we only call into Win32 when it changes.+ ignoring: AtomicBool,}impl PollGate {@@ -55,9 +73,20 @@ impl PollGate {active: Mutex::new(false),cv: Condvar::new(),collapsed: AtomicBool::new(true),+ rect: Mutex::new(IslandRect::default()),+ ignoring: AtomicBool::new(false),}}+ pub fn set_rect(&self, rect: IslandRect) {+ *self.rect.lock().unwrap() = rect;+ }++ /// Forces the next poll tick to re-apply the flag (after a window resize).+ pub fn forget_ignore_state(&self) {+ self.ignoring.store(false, Ordering::Relaxed);+ }+pub fn set_active(&self, on: bool) {let mut guard = self.active.lock().unwrap();*guard = on;@@ -203,6 +232,21 @@ pub fn spawn_cursor_poll(app: AppHandle, gate: Arc<PollGate>) {continue;}last = (x, y);++ // Click-through: the window only takes the mouse over the island+ // shape. A small entry margin means the flag is already off by the+ // time a moving cursor reaches a button.+ let r = *gate.rect.lock().unwrap();+ let inside = r.w > 0.0+ && x >= r.x - HIT_MARGIN+ && x <= r.x + r.w + HIT_MARGIN+ && y >= r.y - HIT_MARGIN+ && y <= r.y + r.h + HIT_MARGIN;+ if gate.ignoring.load(Ordering::Relaxed) == inside {+ gate.ignoring.store(!inside, Ordering::Relaxed);+ let _ = win.set_ignore_cursor_events(!inside);+ }+let _ = win.emit("cursor", CursorPayload { x, y });}}diff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rsindex 222a1651..aba3d047 100644--- a/windows/src-tauri/src/lib.rs+++ b/windows/src-tauri/src/lib.rs@@ -1,6 +1,9 @@// Coucou for Windows — app wiring and the commands the island calls.+mod hooks;mod island;+mod log;+mod pipe;mod settings;mod tray;@@ -10,10 +13,12 @@ use std::sync::atomic::Ordering;use std::sync::{Arc, Mutex};use serde::Serialize;-use tauri::{AppHandle, Emitter, State};+use tauri::{AppHandle, Emitter, Manager, State, WebviewUrl, WebviewWindowBuilder};use tauri_plugin_autostart::{ManagerExt, MacosLauncher};+use hooks::{HookPreview, HookStatus};use island::{PollGate, ScreenInfo};+use pipe::Pending;use settings::Settings;/// Keeps spawned helpers from flashing a console window.@@ -35,7 +40,9 @@ pub struct BootInfo {#[tauri::command]fn boot(app: AppHandle, shared: State<Shared>) -> BootInfo {- let settings = shared.settings.lock().unwrap().clone();+ let mut settings = shared.settings.lock().unwrap().clone();+ // The real state of ~/.claude/settings.json wins over whatever we stored.+ settings.hooks_installed = hooks::status().installed;let screen = island::screen_info(&app, &settings.screen);BootInfo {settings,@@ -68,6 +75,8 @@ fn save_settings(app: AppHandle, shared: State<Shared>, settings: Settings) {let collapsed = shared.gate.collapsed.load(Ordering::Relaxed);island::apply_geometry(&app, &settings.screen, collapsed);}+ // Keep the other window in step (island ⇄ settings window).+ let _ = app.emit("settings-changed", settings);}/// Hidden island → shrink the window to the invisible wake strip and park the@@ -77,15 +86,16 @@ fn set_collapsed(app: AppHandle, shared: State<Shared>, collapsed: bool) {let pref = shared.settings.lock().unwrap().screen.clone();shared.gate.collapsed.store(collapsed, Ordering::Relaxed);island::apply_geometry(&app, &pref, collapsed);- if collapsed {- island::set_ignore_cursor(&app, false);- }+ // The wake strip must always take the mouse, and a resize invalidates the flag.+ island::set_ignore_cursor(&app, false);+ shared.gate.forget_ignore_state();shared.gate.set_active(!collapsed);}+/// The front end pushes the island shape; Rust decides click-through from it.#[tauri::command]-fn set_ignore_cursor(app: AppHandle, ignore: bool) {- island::set_ignore_cursor(&app, ignore);+fn set_island_rect(shared: State<Shared>, x: f64, y: f64, width: f64, height: f64) {+ shared.gate.set_rect(island::IslandRect { x, y, w: width, h: height });}#[tauri::command]@@ -147,6 +157,70 @@ fn quit_app(app: AppHandle) {app.exit(0);}+// ── Claude Code hooks ─────────────────────────────────────────────────────────++#[tauri::command]+fn hooks_status() -> HookStatus {+ hooks::status()+}++/// Returns the diff the user has to look at before anything is written.+#[tauri::command]+fn hooks_preview(install: bool) -> HookPreview {+ hooks::preview(install)+}++/// Only ever called from an explicit click in the settings window.+#[tauri::command]+fn hooks_apply(app: AppHandle, shared: State<Shared>, install: bool) -> Result<String, String> {+ let backup = hooks::write(install)?;+ let updated = {+ let mut current = shared.settings.lock().unwrap();+ current.hooks_installed = install;+ let _ = settings::save(¤t);+ current.clone()+ };+ let _ = app.emit("settings-changed", updated);+ Ok(backup)+}++#[tauri::command]+fn approval_decision(app: AppHandle, request_id: String, decision: String) {+ pipe::answer(&app, &request_id, &decision);+}++/// Lets the island write to the same log as the Rust side.+#[tauri::command]+fn log_line(message: String) {+ log::line(format!("ui {message}"));+}++// ── Settings window ───────────────────────────────────────────────────────────++pub fn show_settings_window(app: &AppHandle) {+ if let Some(win) = app.get_webview_window("settings") {+ let _ = win.unminimize();+ let _ = win.show();+ let _ = win.set_focus();+ return;+ }+ if let Err(err) = WebviewWindowBuilder::new(app, "settings", WebviewUrl::App("settings.html".into()))+ .title("Settings — Coucou")+ .inner_size(560.0, 680.0)+ .min_inner_size(460.0, 480.0)+ .resizable(true)+ .center()+ .build()+ {+ log::line(format!("settings window failed: {err}"));+ }+}++#[tauri::command]+fn open_settings_window(app: AppHandle) {+ show_settings_window(&app);+}+pub fn run() {let loaded = settings::load();let gate = Arc::new(PollGate::new());@@ -160,16 +234,23 @@ pub fn run() {settings: Mutex::new(loaded.clone()),gate: gate.clone(),})+ .manage(Pending::default()).invoke_handler(tauri::generate_handler![boot,save_settings,set_collapsed,- set_ignore_cursor,+ set_island_rect,focus_window,reposition,open_url,open_in_vscode,quit_app,+ hooks_status,+ hooks_preview,+ hooks_apply,+ approval_decision,+ log_line,+ open_settings_window,]).setup(move |app| {let handle = app.handle().clone();@@ -183,6 +264,10 @@ pub fn run() {gate.collapsed.store(false, Ordering::Relaxed);gate.set_active(true);island::spawn_cursor_poll(handle.clone(), gate.clone());++ log::line(format!("--- Coucou {} started ---", env!("CARGO_PKG_VERSION")));+ hooks::ensure_hook_exe(&handle);+ pipe::start(handle.clone());Ok(())}).run(tauri::generate_context!())diff --git a/windows/src-tauri/src/log.rs b/windows/src-tauri/src/log.rsnew file mode 100644index 00000000..13425a56--- /dev/null+++ b/windows/src-tauri/src/log.rs@@ -0,0 +1,28 @@+// Small append-only log at %LOCALAPPDATA%\Coucou\coucou.log — the Windows+// equivalent of nbLog() in HookServer.swift. Nothing leaves the machine.++use std::io::Write;++use windows::Win32::System::SystemInformation::GetLocalTime;++use crate::settings;++pub fn line(message: impl AsRef<str>) {+ let t = unsafe { GetLocalTime() };+ let stamp = format!(+ "{:04}-{:02}-{:02} {:02}:{:02}:{:02}",+ t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond+ );+ let dir = settings::local_dir();+ if std::fs::create_dir_all(&dir).is_err() {+ return;+ }+ let path = dir.join("coucou.log");+ // Keep it from growing forever: start fresh past ~1 MB.+ if std::fs::metadata(&path).map(|m| m.len() > 1_000_000).unwrap_or(false) {+ let _ = std::fs::remove_file(&path);+ }+ if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {+ let _ = writeln!(file, "{stamp} {}", message.as_ref());+ }+}diff --git a/windows/src-tauri/src/pipe.rs b/windows/src-tauri/src/pipe.rsnew file mode 100644index 00000000..fd81589e--- /dev/null+++ b/windows/src-tauri/src/pipe.rs@@ -0,0 +1,154 @@+// Named-pipe server for coucou-hook.+//+// `\\.\pipe\coucou-<user>` — one instance per connection. Every hook event is+// forwarded to the island as a `hook` event. `PermissionRequest` is the only one+// that keeps its connection open: it waits for the island's decision and writes+// it back on the same pipe, which is how approving from the island works.+//+// Claude Code is never blocked by us: coucou-hook gives the connection 300 ms and+// exits cleanly if Coucou is closed, and we drop the connection after the+// decision timeout so the terminal takes over.++use std::collections::HashMap;+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::Mutex;+use std::time::Duration;++use serde_json::{json, Value};+use tauri::{AppHandle, Emitter, Manager};+use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tokio::net::windows::named_pipe::{NamedPipeServer, ServerOptions};+use tokio::sync::oneshot;++use crate::island::WINDOW_LABEL;+use crate::log;++/// Slightly under coucou-hook's own 110 s wait, so we always answer first.+const DECISION_TIMEOUT: Duration = Duration::from_secs(108);+const MAX_PAYLOAD: usize = 1 << 20;++/// Permission requests waiting for a click in the island.+#[derive(Default)]+pub struct Pending(pub Mutex<HashMap<String, oneshot::Sender<String>>>);++static COUNTER: AtomicU64 = AtomicU64::new(1);++pub fn pipe_name() -> String {+ let user = std::env::var("USERNAME").unwrap_or_else(|_| "user".into());+ format!(r"\\.\pipe\coucou-{user}")+}++pub fn start(app: AppHandle) {+ tauri::async_runtime::spawn(async move {+ let name = pipe_name();+ let mut server = match ServerOptions::new().first_pipe_instance(true).create(&name) {+ Ok(s) => s,+ Err(err) => {+ eprintln!("[coucou] cannot open {name}: {err}");+ return;+ }+ };+ loop {+ if server.connect().await.is_err() {+ tokio::time::sleep(Duration::from_millis(200)).await;+ continue;+ }+ // Hand the connected instance to a task and listen on a fresh one.+ let next = match ServerOptions::new().create(&name) {+ Ok(s) => s,+ Err(err) => {+ eprintln!("[coucou] cannot reopen {name}: {err}");+ return;+ }+ };+ let connected = std::mem::replace(&mut server, next);+ let app = app.clone();+ tauri::async_runtime::spawn(async move { handle(app, connected).await });+ }+ });+}++async fn handle(app: AppHandle, mut pipe: NamedPipeServer) {+ let mut buf = Vec::new();+ let mut chunk = [0u8; 4096];+ loop {+ match pipe.read(&mut chunk).await {+ Ok(0) => break,+ Ok(n) => {+ buf.extend_from_slice(&chunk[..n]);+ if buf.contains(&b'\n') || buf.len() > MAX_PAYLOAD {+ break;+ }+ }+ Err(_) => return,+ }+ }+ let line = match buf.iter().position(|b| *b == b'\n') {+ Some(i) => &buf[..i],+ None => &buf[..],+ };+ let Ok(mut payload) = serde_json::from_slice::<Value>(line) else { return };+ if !payload.is_object() {+ return;+ }++ let event = payload+ .get("hook_event_name")+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string();++ if event != "PermissionRequest" {+ log::line(format!("hook {event}"));+ let _ = app.emit_to(WINDOW_LABEL, "hook", payload);+ let _ = pipe.disconnect();+ return;+ }++ let id = format!("{}-{}", std::process::id(), COUNTER.fetch_add(1, Ordering::Relaxed));+ let (tx, rx) = oneshot::channel::<String>();+ {+ let pending = app.state::<Pending>();+ let mut map = pending.0.lock().unwrap();+ map.insert(id.clone(), tx);+ }+ payload["request_id"] = json!(id);+ log::line(format!("hook PermissionRequest id={id}"));+ let _ = app.emit_to(WINDOW_LABEL, "hook", payload);++ let decision = match tokio::time::timeout(DECISION_TIMEOUT, rx).await {+ Ok(Ok(d)) => Some(d),+ _ => None,+ };+ app.state::<Pending>().0.lock().unwrap().remove(&id);++ match &decision {+ Some(d) => log::line(format!("hook id={id} answered {d}")),+ None => log::line(format!("hook id={id} timed out — terminal takes over")),+ }++ // No decision: say nothing at all. coucou-hook then writes nothing to stdout+ // and Claude Code asks in the terminal, exactly as if Coucou were closed.+ if let Some(d) = decision {+ let _ = pipe.write_all(format!("{d}\n").as_bytes()).await;+ let _ = pipe.flush().await;+ }+ let _ = pipe.disconnect();+}++/// Called by the island's Allow / Deny / Always buttons.+pub fn answer(app: &AppHandle, request_id: &str, decision: &str) {+ let json = match decision {+ "allow" => r#"{"permissionDecision":"allow"}"#,+ "always" => r#"{"permissionDecision":"allow","alwaysAllow":true}"#,+ _ => r#"{"permissionDecision":"deny"}"#,+ };+ let sender = app.state::<Pending>().0.lock().unwrap().remove(request_id);+ match sender {+ Some(tx) => {+ log::line(format!("decision id={request_id} {decision}"));+ let _ = tx.send(json.to_string());+ }+ None => log::line(format!("decision id={request_id} {decision} — no pending request")),+ }+}diff --git a/windows/src-tauri/src/tray.rs b/windows/src-tauri/src/tray.rsindex dca65128..f6aa0c8f 100644--- a/windows/src-tauri/src/tray.rs+++ b/windows/src-tauri/src/tray.rs@@ -21,6 +21,7 @@ pub fn build(app: &AppHandle) -> tauri::Result<()> {.menu(&menu).on_menu_event(|app: &AppHandle, event| match event.id.as_ref() {"quit" => app.exit(0),+ "settings" => crate::show_settings_window(app),id => {let _ = app.emit_to(WINDOW_LABEL, "tray", id.to_string());}diff --git a/windows/src-tauri/tauri.conf.json b/windows/src-tauri/tauri.conf.jsonindex caabb3be..76cb07d8 100644--- a/windows/src-tauri/tauri.conf.json+++ b/windows/src-tauri/tauri.conf.json@@ -47,6 +47,7 @@"icons/[email protected]","icons/icon.ico"],+ "resources": ["../target/release/coucou-hook*.exe"],"copyright": "© Louis Raille","category": "DeveloperTool","shortDescription": "Mochi lives at the top of your screen",diff --git a/windows/src/core/bridge.ts b/windows/src/core/bridge.tsindex 3d8f1cb5..f7851935 100644--- a/windows/src/core/bridge.ts+++ b/windows/src/core/bridge.ts@@ -35,11 +35,12 @@ export const Bridge = {/** Shrink the window down to the invisible wake strip (hidden) or back to full. */setCollapsed: (collapsed: boolean) => call<void>("set_collapsed", { collapsed }),- /** Island shape in window coordinates, so Rust can do the click-through test. */- setIslandRect: (x: number, y: number, width: number, height: number, radius: number) =>- call<void>("set_island_rect", { x, y, width, height, radius }),-- setIgnoreCursor: (ignore: boolean) => call<void>("set_ignore_cursor", { ignore }),+ /**+ * Pushes the island shape in window coordinates. Rust flips click-through from+ * its own cursor poll, so the flag is never a frame behind a click.+ */+ setIslandRect: (x: number, y: number, width: number, height: number) =>+ call<void>("set_island_rect", { x, y, width, height }),/** Give the window keyboard focus (chat field) and take it away again. */focusWindow: (focused: boolean) => call<void>("focus_window", { focused }),@@ -53,15 +54,41 @@ export const Bridge = {quit: () => call<void>("quit_app"),- // ── Claude Code hooks (stage 2) ───────────────────────────────────────────- hooksStatus: () => call<{ installed: boolean; settingsPath: string }>("hooks_status"),- hooksPreview: () => call<{ diff: string; backup: string }>("hooks_preview"),- hooksInstall: () => call<void>("hooks_install"),- hooksUninstall: () => call<void>("hooks_uninstall"),+ openSettingsWindow: () => call<void>("open_settings_window"),++ /** Writes to %LOCALAPPDATA%\Coucou\coucou.log, next to the Rust lines. */+ log: (message: string) => call<void>("log_line", { message }),++ // ── Claude Code hooks ─────────────────────────────────────────────────────+ hooksStatus: () => call<HookStatus>("hooks_status"),+ /** Diff to show before anything is written. `install: false` previews removal. */+ hooksPreview: (install: boolean) => call<HookPreview>("hooks_preview", { install }),+ /** Writes ~/.claude/settings.json — only ever after an explicit click. */+ hooksApply: (install: boolean) => callOrThrow<string>("hooks_apply", { install }),+approvalDecision: (requestId: string, decision: "allow" | "deny" | "always") =>call<void>("approval_decision", { requestId, decision }),};+export interface HookStatus {+ installed: boolean;+ settingsPath: string;+ hookPath: string;+ hookReady: boolean;+}++export interface HookPreview {+ diff: string;+ backup: string;+ settingsPath: string;+}++/** Same as `call`, but surfaces the error so the UI can show what went wrong. */+async function callOrThrow<T>(cmd: string, args?: Record<string, unknown>): Promise<T> {+ if (!IS_TAURI) throw new Error("not running inside Coucou");+ return invoke<T>(cmd, args);+}+export type BridgeEvent =| { name: "cursor"; payload: { x: number; y: number } }| { name: "tray"; payload: string }diff --git a/windows/src/island/fsm.ts b/windows/src/island/fsm.tsindex b55d67d5..e26e46a1 100644--- a/windows/src/island/fsm.ts+++ b/windows/src/island/fsm.ts@@ -16,6 +16,8 @@ export class IslandStateMachine {greetAutoCollapseDelay = 0.6;/** coucou → petit while the mouse hovers the greeting. */greetHoverCollapseDelay = 10;+ /** An alert waiting for an answer stays open, even when the mouse leaves. */+ pinned = false;private petitHide: number | null = null;private homeCollapse: number | null = null;@@ -106,6 +108,7 @@ export class IslandStateMachine {private scheduleHomeCollapse() {this.clear("homeCollapse");+ if (this.pinned) return;this.homeCollapse = window.setTimeout(() => {this.homeCollapse = null;if (this.state === "home") this.transition("petit");diff --git a/windows/src/island/hooks.ts b/windows/src/island/hooks.tsindex d59ab063..8b682335 100644--- a/windows/src/island/hooks.ts+++ b/windows/src/island/hooks.ts@@ -10,6 +10,9 @@ import type { Island } from "./island";const CLAUDE_ID = "integration_claude";+/** Clears the approval card if no decision was made before the hook gave up. */+let pendingTimeout: number | null = null;+interface HookPayload {hook_event_name?: string;request_id?: string;@@ -187,6 +190,7 @@ function handleHook(island: Island, payload: HookPayload) {case "PermissionRequest": {upsert(projectName, cwd);+ if (pendingTimeout != null) window.clearTimeout(pendingTimeout);const tool = payload.tool_name ?? "Tool";const input = payload.tool_input ?? {};const command = typeof input.command === "string" ? input.command : tool;@@ -201,6 +205,19 @@ function handleHook(island: Island, payload: HookPayload) {Sound.play("approval");if (focused) island.alert("approval");else State.setPillBadge(CLAUDE_ID, "approval");+ // Coucou answers within 108 s or not at all; after that the terminal has+ // taken over and the card would be lying.+ pendingTimeout = window.setTimeout(() => {+ pendingTimeout = null;+ if (!State.pendingApproval) return;+ State.pendingApproval = null;+ State.isPinned = false;+ island.dropPin();+ State.updateTask(CLAUDE_ID, "working");+ State.setPillBadge(CLAUDE_ID, null);+ if (State.view === "approval") island.setView(State.defaultView());+ State.notify();+ }, 110_000);break;}diff --git a/windows/src/island/island.ts b/windows/src/island/island.tsindex 7e9119d7..785c7982 100644--- a/windows/src/island/island.ts+++ b/windows/src/island/island.ts@@ -18,7 +18,8 @@ import { h } from "../views/dom";import { IslandStateMachine } from "./fsm";const BOT_OVERHANG = 40;-const HIT_MARGIN = 6;+/** Same margin as the Rust hit test (src-tauri/src/island.rs). */+const HIT_MARGIN = 14;const modeOrder = (m: IslandMode) => (m === "hidden" ? 0 : m === "compact" ? 1 : 2);@@ -58,9 +59,9 @@ export class Island {// Rust starts the window at full size so the launch greeting has room.private collapsed = false;private collapseTimer: number | null = null;- // Tauri windows start with cursor events enabled; keep the mirror honest.- private ignoringCursor = false;private wasInIsland = false;+ /** Last shape handed to Rust for the click-through test. */+ private pushedRect = { x: -1, y: -1, w: -1, h: -1 };private homeCollapseAt: number | null = null;// Bot hover → love (IslandWindowController.botHoverIn)@@ -104,12 +105,14 @@ export class Island {},decide: (d) => {const req = State.pendingApproval;+ void Bridge.log(`decide ${d} req=${req?.requestId ?? "none"}`);if (!req) return;Sound.play(d === "deny" ? "blip" : "approve");void Bridge.approvalDecision(req.requestId, d);if (d === "always") State.alwaysAllow = true;State.pendingApproval = null;State.isPinned = false;+ this.fsm.pinned = false;State.updateTask("integration_claude", "working");State.setPillBadge("integration_claude", null);this.setView(State.defaultView());@@ -132,7 +135,7 @@ export class Island {void Bridge.saveSettings(State.settings);State.notify();},- openSettingsWindow: () => this.setView("settings"),+ openSettingsWindow: () => void Bridge.openSettingsWindow(),blip: () => Sound.play("blip"),};@@ -247,12 +250,14 @@ export class Island {collapse() {State.isPinned = false;+ this.fsm.pinned = false;if (this.fsm.state === "home") this.fsm.mouseLeft();this.setMode("compact");}- /** Alert from the hook server: open on this view and pin it. */+ /** Alert from the hook server: open on this view. Pinned alerts never auto-close. */alert(view: IslandViewName) {+ this.fsm.pinned = State.isPinned;this.fsm.forceHome();this.expand(view);}@@ -261,6 +266,11 @@ export class Island {this.fsm.reveal();}+ /** An alert stopped waiting for an answer: let the island auto-close again. */+ dropPin() {+ this.fsm.pinned = false;+ }+// ── Geometry ────────────────────────────────────────────────────────────────private targetSize(): { w: number; h: number; r: number } {@@ -296,6 +306,13 @@ export class Island {this.miniGrid.style.left = `${w - 40 - 14}px`;this.miniGrid.style.top = `${hh / 2 - 14}px`;this.greetingCanvas.style.left = `${(w - EXPANDED_W) / 2}px`;++ const rect = { x: (PANEL_W - w) / 2, y: 0, w, h: hh };+ const p = this.pushedRect;+ if (Math.abs(p.x - rect.x) > 0.5 || Math.abs(p.w - rect.w) > 0.5 || Math.abs(p.h - rect.h) > 0.5) {+ this.pushedRect = rect;+ void Bridge.setIslandRect(rect.x, rect.y, rect.w, rect.h);+ }}/** Island rect in window coordinates (origin top-left of the 720×320 window). */@@ -319,9 +336,7 @@ export class Island {this.collapseTimer = null;if (State.mode !== "hidden") return;this.collapsed = true;- this.ignoringCursor = false;void Bridge.setCollapsed(true);- void Bridge.setIgnoreCursor(false);}, 420);} else if (this.collapsed) {// Grow the window back before the island animates open.@@ -374,11 +389,6 @@ export class Island {x >= rect.x - HIT_MARGIN && x <= rect.x + rect.w + HIT_MARGIN &&y >= rect.y - HIT_MARGIN && y <= rect.y + rect.h + HIT_MARGIN;- if (this.ignoringCursor === inIsland) {- this.ignoringCursor = !inIsland;- void Bridge.setIgnoreCursor(!inIsland);- }-if (inIsland && !this.wasInIsland) {if (this.fsm.state === "coucou") this.greeting.hover();this.fsm.mouseEntered();diff --git a/windows/src/main.ts b/windows/src/main.tsindex addfdb5d..e9fe95e6 100644--- a/windows/src/main.ts+++ b/windows/src/main.ts@@ -3,7 +3,7 @@import "./style.css";import { Bridge, IS_TAURI, onEvent } from "./core/bridge";import { Sound } from "./core/sound";-import { State } from "./core/state";+import { State, type Settings } from "./core/state";import { Island } from "./island/island";import { registerHookHandlers } from "./island/hooks";@@ -44,6 +44,12 @@ async function main() {await onEvent<null>("screen-changed", () => void Bridge.reposition());+ // The settings window writes preferences; apply them here without a restart.+ await onEvent<Settings>("settings-changed", (s) => {+ State.settings = { ...State.settings, ...s };+ island.applySettings();+ });+registerHookHandlers(island);island.launch();diff --git a/windows/src/settings/main.ts b/windows/src/settings/main.tsnew file mode 100644index 00000000..23bacb0d--- /dev/null+++ b/windows/src/settings/main.ts@@ -0,0 +1,240 @@+// Settings window — the place where anything that writes to disk is confirmed.+// Stage 2 covers the Claude Code hooks and the general preferences; API keys and+// integrations land here too in a later stage.++import "./settings.css";+import { Bridge, onEvent, type HookStatus } from "../core/bridge";+import { DEFAULT_SETTINGS, type Settings } from "../core/state";+import { h, clear } from "../views/dom";++let settings: Settings = { ...DEFAULT_SETTINGS };+let version = "";++const root = document.getElementById("settings-root")!;++async function save() {+ await Bridge.saveSettings(settings);+}++// ── Reusable bits ─────────────────────────────────────────────────────────────++function toggle(on: boolean, onChange: (v: boolean) => void): HTMLElement {+ const el = h("button", { class: on ? "switch on" : "switch", "aria-pressed": on });+ el.addEventListener("click", () => {+ const next = !el.classList.contains("on");+ el.classList.toggle("on", next);+ onChange(next);+ });+ return el;+}++function statusDot(ok: boolean): HTMLElement {+ return h("i", { class: "dot", style: `background:${ok ? "#22c55e" : "#f4505e"}` });+}++function renderDiff(text: string): HTMLElement {+ const box = h("div", { class: "diff" });+ for (const line of text.split("\n")) {+ const cls = line.startsWith("+") ? "add" : line.startsWith("-") ? "del" : "ctx";+ box.append(h("div", { class: cls, text: line }));+ }+ return box;+}++// ── Claude Code section ───────────────────────────────────────────────────────++function claudeSection(status: HookStatus): HTMLElement {+ const body = h("div", { style: "display:flex;flex-direction:column;gap:12px" });+ const section = h(+ "section",+ {},+ h("h2", {}, statusDot(status.installed), h("span", { text: "Claude Code" })),+ body,+ );++ const rebuild = async () => {+ const fresh = await Bridge.hooksStatus();+ if (fresh) Object.assign(status, fresh);+ clear(body);+ draw();+ const head = section.querySelector("h2")!;+ clear(head);+ head.append(statusDot(status.installed), h("span", { text: "Claude Code" }));+ };++ function draw() {+ body.append(+ h("div", {+ class: "hint",+ text: status.installed+ ? "Coucou is hooked into your Claude Code sessions. Tool calls, questions and permission requests show up in the island, and you can answer them there."+ : "Install the hooks to see your Claude Code sessions in the island and approve permissions without leaving what you are doing.",+ }),+ h("div", { class: "row" },+ h("label", { text: "settings.json" }),+ h("span", { class: "path", text: status.settingsPath }),+ ),+ h("div", { class: "row" },+ h("label", { text: "Relay" }),+ h("span", { class: "path", text: status.hookPath }),+ statusDot(status.hookReady),+ ),+ );++ if (!status.hookReady) {+ body.append(h("div", {+ class: "notice warn",+ text: "coucou-hook.exe is not in place yet. Restart Coucou; if it still fails, build it with `cargo build -p coucou-hook`.",+ }));+ }++ const actions = h("div", { class: "row" });+ const install = h("button", {+ class: "primary",+ text: status.installed ? "Reinstall hooks…" : "Install hooks…",+ onclick: () => showPreview(true),+ });+ actions.append(install);+ if (status.installed) {+ actions.append(h("button", {+ class: "danger",+ text: "Uninstall hooks…",+ onclick: () => showPreview(false),+ }));+ }+ body.append(actions);+ }++ async function showPreview(install: boolean) {+ const preview = await Bridge.hooksPreview(install);+ if (!preview) return;+ clear(body);+ body.append(+ h("div", {+ class: "hint",+ text: install+ ? "This is exactly what will change in your settings.json. Your own hooks are left untouched."+ : "This removes Coucou's entries only. Your own hooks are left untouched.",+ }),+ renderDiff(preview.diff),+ h("div", { class: "row" },+ h("span", { class: "path", text: `Backup → ${preview.backup}` }),+ ),+ );+ const confirm = h("button", {+ class: install ? "primary" : "danger",+ text: install ? "Back up and write" : "Back up and remove",+ });+ confirm.addEventListener("click", async () => {+ confirm.disabled = true;+ try {+ const backup = await Bridge.hooksApply(install);+ clear(body);+ body.append(h("div", {+ class: "notice ok",+ text: `Done. Previous settings saved as ${backup}. Open a new Claude Code session to pick the hooks up.`,+ }));+ window.setTimeout(() => void rebuild(), 2600);+ } catch (err) {+ confirm.disabled = false;+ body.append(h("div", { class: "notice err", text: `Could not write: ${String(err)}` }));+ }+ });+ body.append(h("div", { class: "row" }, confirm, h("button", {+ text: "Cancel",+ onclick: () => { clear(body); draw(); },+ })));+ }++ draw();+ return section;+}++// ── General section ───────────────────────────────────────────────────────────++function generalSection(): HTMLElement {+ const volume = h("input", {+ type: "range", min: "0", max: "0.2", step: "0.005",+ value: String(settings.soundVolume),+ }) as HTMLInputElement;+ volume.addEventListener("input", () => {+ settings.soundVolume = Number(volume.value);+ void save();+ });++ const autoClose = h("input", {+ type: "number", min: "5", max: "120", step: "1",+ value: String(Math.round(settings.autoCloseInterval)),+ style: "width:72px",+ }) as HTMLInputElement;+ autoClose.addEventListener("change", () => {+ settings.autoCloseInterval = Math.max(5, Math.min(120, Number(autoClose.value) || 15));+ autoClose.value = String(settings.autoCloseInterval);+ void save();+ });++ const screen = h("select", {}) as HTMLSelectElement;+ screen.append(+ h("option", { value: "primary", text: "Main display" }),+ h("option", { value: "cursor", text: "Display under the cursor" }),+ );+ screen.value = settings.screen;+ screen.addEventListener("change", () => {+ settings.screen = screen.value as Settings["screen"];+ void save();+ });++ return h(+ "section",+ {},+ h("h2", {}, h("span", { text: "General" })),+ h("div", { class: "row" },+ h("label", { text: "Sound" }),+ toggle(settings.soundEnabled, (v) => { settings.soundEnabled = v; void save(); }),+ volume,+ ),+ h("div", { class: "row" },+ h("label", { text: "Auto-close" }),+ autoClose,+ h("span", { class: "hint", text: "seconds after you leave the island" }),+ ),+ h("div", { class: "row" },+ h("label", { text: "Island lives on" }),+ screen,+ ),+ h("div", { class: "row" },+ h("label", { text: "Launch at startup" }),+ toggle(settings.autostart, (v) => { settings.autostart = v; void save(); }),+ ),+ );+}++// ── Boot ──────────────────────────────────────────────────────────────────────++async function main() {+ const boot = await Bridge.boot();+ if (boot) {+ settings = { ...settings, ...boot.settings };+ version = boot.version;+ }+ const status = (await Bridge.hooksStatus()) ?? {+ installed: false, settingsPath: "", hookPath: "", hookReady: false,+ };++ clear(root);+ root.append(+ h("h1", {}, h("span", { text: "Coucou" }), h("span", { class: "version", text: version })),+ claudeSection(status),+ generalSection(),+ h("div", {+ class: "hint",+ text: "No telemetry. Network requests only go to the services you configure yourself.",+ }),+ );++ void onEvent<Settings>("settings-changed", (s) => {+ settings = { ...settings, ...s };+ });+}++void main();diff --git a/windows/src/settings/settings.css b/windows/src/settings/settings.cssnew file mode 100644index 00000000..0f5e95d3--- /dev/null+++ b/windows/src/settings/settings.css@@ -0,0 +1,244 @@+/* Settings window — same palette as the island, laid out as a normal window. */++:root {+ --font: system-ui, "Segoe UI Variable Text", "Segoe UI", sans-serif;+ --mono: "Cascadia Mono", "Consolas", ui-monospace, monospace;+ --ink: #f5f6f8;+ --dim: #9398a1;+ --dim-2: #6b7079;+ --bg: #0b0c0e;+ --card: #141518;+ --hairline: rgba(255, 255, 255, 0.07);+ --green: #22c55e;+ --red: #f4505e;+ --amber: #f5a524;+}++* {+ box-sizing: border-box;+ margin: 0;+ padding: 0;+}++body.settings-window {+ background: var(--bg);+ color: var(--ink);+ font: 400 13px/1.45 var(--font);+ -webkit-font-smoothing: antialiased;+ min-height: 100vh;+}++#settings-root {+ padding: 22px 24px 32px;+ display: flex;+ flex-direction: column;+ gap: 18px;+ max-width: 720px;+ margin: 0 auto;+}++h1 {+ font: 600 17px var(--font);+ letter-spacing: -0.01em;+}++h1 .version {+ font: 400 12px var(--font);+ color: var(--dim-2);+ margin-left: 8px;+}++section {+ background: var(--card);+ border: 1px solid var(--hairline);+ border-radius: 14px;+ padding: 16px 18px;+ display: flex;+ flex-direction: column;+ gap: 12px;+}++section > h2 {+ font: 600 13px var(--font);+ display: flex;+ align-items: center;+ gap: 8px;+}++.hint {+ font: 400 12px var(--font);+ color: var(--dim);+}++.row {+ display: flex;+ align-items: center;+ gap: 12px;+ flex-wrap: wrap;+}++.row > label {+ min-width: 132px;+ color: var(--dim);+ font-size: 12.5px;+}++.spacer {+ flex: 1 1 auto;+}++.dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ display: inline-block;+ flex: 0 0 auto;+}++button {+ font: 500 12.5px var(--font);+ padding: 7px 14px;+ border: 0;+ border-radius: 999px;+ background: rgba(255, 255, 255, 0.09);+ color: var(--ink);+ cursor: pointer;+ transition: background 0.14s, transform 0.08s;+}++button:hover:not(:disabled) {+ background: rgba(255, 255, 255, 0.15);+}++button:active:not(:disabled) {+ transform: scale(0.96);+}++button.primary {+ background: var(--ink);+ color: #0b0c0e;+}++button.primary:hover:not(:disabled) {+ background: #fff;+}++button.danger {+ background: rgba(244, 80, 94, 0.16);+ color: #ff8d97;+}++button:disabled {+ opacity: 0.45;+ cursor: default;+}++code,+.path {+ font: 400 11.5px var(--mono);+ color: var(--dim);+ word-break: break-all;+ user-select: text;+}++.switch {+ position: relative;+ width: 36px;+ height: 20px;+ border-radius: 10px;+ background: rgba(255, 255, 255, 0.15);+ flex: 0 0 36px;+ padding: 0;+}++.switch.on {+ background: var(--green);+}++.switch::after {+ content: "";+ position: absolute;+ top: 2px;+ left: 2px;+ width: 16px;+ height: 16px;+ border-radius: 50%;+ background: #fff;+ transition: transform 0.18s;+}++.switch.on::after {+ transform: translateX(16px);+}++input[type="range"] {+ -webkit-appearance: none;+ appearance: none;+ height: 4px;+ border-radius: 2px;+ background: rgba(255, 255, 255, 0.2);+ width: 140px;+}++input[type="range"]::-webkit-slider-thumb {+ -webkit-appearance: none;+ width: 13px;+ height: 13px;+ border-radius: 50%;+ background: #fff;+}++input[type="number"],+select {+ font: 400 12.5px var(--font);+ background: rgba(255, 255, 255, 0.07);+ border: 1px solid var(--hairline);+ border-radius: 8px;+ color: var(--ink);+ padding: 5px 8px;+}++.diff {+ font: 400 11.5px/1.5 var(--mono);+ background: #08090b;+ border: 1px solid var(--hairline);+ border-radius: 10px;+ padding: 10px 12px;+ max-height: 260px;+ overflow: auto;+ white-space: pre;+ user-select: text;+}++.diff .add {+ color: #86efac;+}++.diff .del {+ color: #ff8d97;+}++.diff .ctx {+ color: var(--dim-2);+}++.notice {+ font: 400 12px var(--font);+ border-radius: 10px;+ padding: 8px 12px;+}++.notice.ok {+ background: rgba(34, 197, 94, 0.12);+ color: #86efac;+}++.notice.err {+ background: rgba(244, 80, 94, 0.14);+ color: #ff8d97;+}++.notice.warn {+ background: rgba(245, 165, 36, 0.13);+ color: #fbc06a;+}diff --git a/windows/src/views/views.ts b/windows/src/views/views.tsindex 5f1a4750..44af2bb3 100644--- a/windows/src/views/views.ts+++ b/windows/src/views/views.ts@@ -225,12 +225,18 @@ function buildApproval(actions: ViewActions): ViewHost {const code = h("div", { class: "code" });const row = h("div", { class: "actions" });const el = h("div", { class: "view" }, card("amber", stack(116, 16, who, code, row)));+ // The buttons are only rebuilt when they actually change: replacing them between+ // a mouse-down and a mouse-up would swallow the click.+ let rowKey = "";return {el,sync() {clear(who);who.append(agentWho(State.focusTask, "needs permission"));code.textContent = State.pendingApproval?.command || State.pendingApproval?.tool || "…";+ const key = String(State.alwaysAllow);+ if (key === rowKey) return;+ rowKey = key;clear(row);row.append(btn("Deny", "secondary", () => actions.decide("deny"), "N"),@@ -269,7 +275,10 @@ function buildError(actions: ViewActions): ViewHost {const who = h("div");const title = h("div", { class: "title", text: "Workflow stopped." });const detail = h("div", { class: "detail" });- const row = h("div", { class: "actions" });+ const row = h("div", { class: "actions" },+ btn("Retry", "primary", () => actions.setView(State.defaultView())),+ btn("Open in n8n", "secondary", () => actions.openUrl("")),+ );const el = h("div", { class: "view" }, card("red", stack(116, 16, who, title, detail, row)));return {el,@@ -279,11 +288,6 @@ function buildError(actions: ViewActions): ViewHost {who.append(agentWho(task, task?.source === "n8n" ? "n8n" : "Claude Code"));title.textContent = task?.source === "n8n" ? "Workflow stopped." : "Session stopped on an error.";detail.textContent = task?.steps.at(-1) ?? "No detail available.";- clear(row);- row.append(- btn("Retry", "primary", () => actions.setView(State.defaultView())),- btn("Open in n8n", "secondary", () => actions.openUrl("")),- );},};}@@ -293,7 +297,10 @@ function buildError(actions: ViewActions): ViewHost {function buildFinished(actions: ViewActions): ViewHost {const who = h("div");const title = h("div", { class: "title" });- const row = h("div", { class: "actions" });+ const row = h("div", { class: "actions" },+ btn("Open terminal", "primary", () => actions.openTerminal()),+ btn("OK", "secondary", () => actions.collapse()),+ );const el = h("div", { class: "view" }, card("green", stack(116, 16, who, title, row)));return {el,@@ -301,11 +308,6 @@ function buildFinished(actions: ViewActions): ViewHost {clear(who);who.append(agentWho(State.focusTask, "Claude Code finished"));title.textContent = State.focusTask?.steps.at(-1) ?? "Session finished";- clear(row);- row.append(- btn("Open terminal", "primary", () => actions.openTerminal()),- btn("OK", "secondary", () => actions.collapse()),- );},};}diff --git a/windows/vite.config.ts b/windows/vite.config.tsindex 76cf6e5b..b3cfb914 100644--- a/windows/vite.config.ts+++ b/windows/vite.config.ts@@ -52,5 +52,11 @@ export default defineConfig({minify: "esbuild",sourcemap: false,emptyOutDir: true,+ rollupOptions: {+ input: {+ island: resolve(__dirname, "index.html"),+ settings: resolve(__dirname, "settings.html"),+ },+ },},});