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
Agents: one hardened writer and one settings section for every agent
Claudea40ec1d8f8ab
diff --git a/windows/src-tauri/src/agents.rs b/windows/src-tauri/src/agents.rsnew file mode 100644index 00000000..9451f8d3--- /dev/null+++ b/windows/src-tauri/src/agents.rs@@ -0,0 +1,523 @@+// Hook and plugin installers for every agent other than Claude Code (hooks.rs).+//+// Each agent is a list of file edits handed to config_file.rs, which applies the+// CLAUDE.md rules once for all of them: strict read, refuse unexpected types,+// diff, dated backup that must succeed, fingerprint check, atomic write. What+// lives here is only *what* changes in each agent's config, and the command+// line that starts the relay in the shell that agent uses.+//+// Formats and paths follow the Mac app (NotchBuddy/Sources/App/HookServer.swift)+// so a config shared between machines (dotfiles) looks the same everywhere.++use std::path::{Path, PathBuf};++use serde::Serialize;+use serde_json::{json, Map, Value};++use crate::config_file::{self, FileEdit, Plan};+use crate::{platform, settings};++/// Marker that identifies a Coucou entry: the relay's file name.+const MARKER: &str = "coucou-hook";++// ── The relay command line ────────────────────────────────────────────────────++/// The shell an agent runs its hook commands through on Windows. On Linux every+/// agent uses `sh` (or bash), so there is only one way to quote.+#[derive(Clone, Copy, Debug, PartialEq)]+pub enum Shell {+ /// Git Bash on Windows (Claude Code), `sh` on Linux.+ Sh,+ /// `powershell -Command` (Gemini CLI, Copilot CLI's `powershell` field).+ PowerShell,+ /// `cmd /C`, or a process started directly (Codex, Cursor, Antigravity, Muse).+ Cmd,+}++/// Where the relay is and which OS the command is for. Kept apart from the+/// real install so tests can build both the Windows and the Linux command.+pub struct Relay {+ pub exe: String,+ pub windows: bool,+}++impl Relay {+ pub fn current() -> Self {+ Self {+ exe: settings::hook_exe_path().to_string_lossy().to_string(),+ windows: cfg!(windows),+ }+ }++ /// The relay followed by `args`, as one command line for `shell`.+ pub fn command(&self, shell: Shell, args: &str) -> String {+ if !self.windows {+ return format!("{} {args}", sh_quote(&self.exe));+ }+ let exe = match shell {+ // Git Bash reads backslashes as escapes: forward slashes, quoted.+ Shell::Sh => format!("\"{}\"", self.exe.replace('\\', "/")),+ // A quoted string alone is an expression in PowerShell: `&` runs it.+ // Inside single quotes only `'` is special, and it doubles.+ Shell::PowerShell => format!("& '{}'", self.exe.replace('\'', "''")),+ // cmd /C keeps the quotes of a lone quoted program name; a plain path+ // goes unquoted so it also works if the agent turns out to use+ // PowerShell. A Windows path cannot contain `"`.+ Shell::Cmd if is_plain(&self.exe) => self.exe.clone(),+ Shell::Cmd => format!("\"{}\"", self.exe),+ };+ format!("{exe} {args}")+ }+}++/// The relay command for the running OS, for `args`.+pub fn relay_command(shell: Shell, args: &str) -> String {+ Relay::current().command(shell, args)+}++/// `s` as one single-quoted POSIX shell word: `'` becomes `'\''`, nothing else+/// is special inside single quotes.+fn sh_quote(s: &str) -> String {+ format!("'{}'", s.replace('\'', r"'\''"))+}++/// A path no Windows shell would split or interpret.+fn is_plain(path: &str) -> bool {+ path.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '\\' | ':' | '.' | '_' | '-'))+}++// ── Agents ────────────────────────────────────────────────────────────────────++type JsonChange = Box<dyn Fn(&Value) -> Result<Option<Value>, String>>;++#[derive(Clone, Copy, Debug, PartialEq)]+pub enum Agent {+ Gemini,+}++impl Agent {+ pub const ALL: &'static [Agent] = &[Agent::Gemini];++ /// The `--agent` name; the pill is `agent_<id>` (PillCatalog.swift).+ pub fn id(self) -> &'static str {+ match self {+ Agent::Gemini => "gemini",+ }+ }++ pub fn from_id(id: &str) -> Option<Agent> {+ Self::ALL.iter().copied().find(|a| a.id() == id)+ }++ /// The files this agent's install touches, under `home`.+ fn files(self, home: &Path) -> Vec<PathBuf> {+ match self {+ Agent::Gemini => vec![home.join(".gemini").join("settings.json")],+ }+ }++ /// The edits that install (or remove) Coucou for this agent.+ fn edits(self, home: &Path, relay: &Relay, install: bool) -> Vec<FileEdit<'static>> {+ let files = self.files(home);+ let path = files[0].clone();+ let label = path.display().to_string();+ let change = self.json_change(relay, install);+ vec![FileEdit { path, edit: config_file::json_edit(label, change) }]+ }++ /// The change to this agent's JSON config: the new object, or `None` to+ /// remove a file that is Coucou's alone. Command lines are built here, up+ /// front, so the change itself is pure.+ fn json_change(self, relay: &Relay, install: bool) -> JsonChange {+ let agent = self.id();+ if !install {+ return Box::new(move |v| groups_uninstall(v, agent).map(Some));+ }+ match self {+ Agent::Gemini => {+ let commands: Vec<(String, String, u64)> = GEMINI_EVENTS+ .iter()+ .map(|(event, said, timeout)| {+ let command = relay.command(Shell::PowerShell, &format!("--agent gemini {said}"));+ (event.to_string(), command, *timeout)+ })+ .collect();+ Box::new(move |v| gemini_install(v, &commands).map(Some))+ }+ }+ }++ /// True when the agent's config already routes to Coucou. Never fails: a+ /// file we cannot read just reads as "not installed".+ fn installed(self, home: &Path) -> bool {+ let files = self.files(home);+ let json = || {+ config_file::read(&files[0])+ .ok()+ .flatten()+ .and_then(|b| config_file::parse_json(Some(&b), "").ok())+ .unwrap_or_else(|| json!({}))+ };+ match self {+ Agent::Gemini => groups_have_ours(&json(), "gemini"),+ }+ }++ /// Whether the island can answer this agent's permission requests.+ fn approvals(self) -> bool {+ false+ }+}++// ── Strings shown in Settings ─────────────────────────────────────────────────++const TEXT_UNEXPECTED: &str = "has an unexpected type — Coucou has not touched it.";++impl Agent {+ pub fn name(self) -> &'static str {+ match self {+ Agent::Gemini => "Gemini CLI",+ }+ }++ /// What to do once the file is written, shown with the result.+ fn note(self) -> &'static str {+ match self {+ Agent::Gemini => "Start a new Gemini CLI session to pick the hooks up.",+ }+ }+}++// ── Public API ────────────────────────────────────────────────────────────────++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct AgentStatus {+ pub id: &'static str,+ pub name: &'static str,+ pub installed: bool,+ /// The file (or files, one per line) Coucou writes.+ pub path: String,+ pub hook_ready: bool,+ /// The island can allow or deny this agent's permission requests.+ pub approvals: bool,+ pub note: &'static str,+}++fn find(id: &str) -> Result<Agent, String> {+ Agent::from_id(id).ok_or_else(|| format!("Unknown agent \"{id}\"."))+}++pub fn list() -> Vec<AgentStatus> {+ let home = platform::home_dir();+ let hook_ready = settings::hook_exe_path().exists();+ Agent::ALL+ .iter()+ .map(|&a| AgentStatus {+ id: a.id(),+ name: a.name(),+ installed: a.installed(&home),+ path: a.files(&home).iter().map(|p| p.display().to_string()).collect::<Vec<_>>().join("\n"),+ hook_ready,+ approvals: a.approvals(),+ note: a.note(),+ })+ .collect()+}++pub fn preview(id: &str, install: bool) -> Result<Plan, String> {+ let agent = find(id)?;+ config_file::preview(&agent.edits(&platform::home_dir(), &Relay::current(), install))+}++/// Only ever called from an explicit click. Returns the backups taken, one per line.+pub fn apply(id: &str, install: bool, fingerprint: &str) -> Result<String, String> {+ let agent = find(id)?;+ apply_in(agent, &platform::home_dir(), &Relay::current(), install, fingerprint)+}++fn apply_in(agent: Agent, home: &Path, relay: &Relay, install: bool, fingerprint: &str) -> Result<String, String> {+ let backups = config_file::apply(&agent.edits(home, relay, install), fingerprint)?;+ Ok(backups.iter().map(|p| p.display().to_string()).collect::<Vec<_>>().join("\n"))+}++// ── Shared JSON helpers ───────────────────────────────────────────────────────++fn unexpected(what: &str) -> String {+ format!("{what} {TEXT_UNEXPECTED}")+}++/// `root[key]` as an object to edit: absent is empty, anything else is refused.+fn object_at(root: &Map<String, Value>, key: &str) -> Result<Map<String, Value>, String> {+ match root.get(key) {+ None => Ok(Map::new()),+ Some(Value::Object(m)) => Ok(m.clone()),+ Some(_) => Err(unexpected(&format!("\"{key}\""))),+ }+}++/// `hooks[event]` as a list to edit: absent is empty, anything else is refused.+fn list_at(hooks: &Map<String, Value>, event: &str) -> Result<Vec<Value>, String> {+ match hooks.get(event) {+ None => Ok(Vec::new()),+ Some(Value::Array(list)) => Ok(list.clone()),+ Some(_) => Err(unexpected(&format!("\"hooks\".\"{event}\""))),+ }+}++/// A command line written by Coucou for `agent`.+fn is_our_command(command: Option<&Value>, agent: &str) -> bool {+ command+ .and_then(Value::as_str)+ .is_some_and(|c| c.contains(MARKER) && c.contains(&format!("--agent {agent}")))+}++/// Claude-style groups (`{"matcher"?, "hooks": [{"command"}]}`, or a legacy+/// flat `{"command"}`) without Coucou's entries for `agent`. A group left+/// empty goes; everything else stays exactly as it was.+fn without_ours_in_groups(groups: &[Value], agent: &str) -> Vec<Value> {+ groups+ .iter()+ .filter_map(|group| {+ if is_our_command(group.get("command"), agent) {+ return None;+ }+ let Some(inner) = group.get("hooks").and_then(Value::as_array) else {+ return Some(group.clone());+ };+ let kept: Vec<Value> =+ inner.iter().filter(|h| !is_our_command(h.get("command"), agent)).cloned().collect();+ if kept.len() == inner.len() {+ return Some(group.clone());+ }+ if kept.is_empty() {+ return None;+ }+ let mut group = group.clone();+ group["hooks"] = Value::Array(kept);+ Some(group)+ })+ .collect()+}++/// `root` with one Coucou group per event, built by `group(event)`. Earlier+/// Coucou entries for `agent` are replaced; nobody else's are touched.+fn groups_install(+ root: &Value,+ agent: &str,+ events: impl IntoIterator<Item = (String, Value)>,+) -> Result<Map<String, Value>, String> {+ let mut root = root.as_object().cloned().unwrap_or_default();+ let mut hooks = object_at(&root, "hooks")?;+ for (event, group) in events {+ let mut list = without_ours_in_groups(&list_at(&hooks, &event)?, agent);+ list.push(group);+ hooks.insert(event, Value::Array(list));+ }+ root.insert("hooks".into(), Value::Object(hooks));+ Ok(root)+}++/// `root` without any Coucou group for `agent`; an event left empty goes, and+/// so does `hooks` when nothing is left in it.+fn groups_uninstall(root: &Value, agent: &str) -> Result<Value, String> {+ let mut root = root.as_object().cloned().unwrap_or_default();+ if !root.contains_key("hooks") {+ return Ok(Value::Object(root));+ }+ let hooks = object_at(&root, "hooks")?;+ let mut out = Map::new();+ for (event, value) in hooks {+ match value.as_array() {+ Some(list) => {+ let kept = without_ours_in_groups(list, agent);+ 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));+ }+ Ok(Value::Object(root))+}++fn groups_have_ours(root: &Value, agent: &str) -> bool {+ let ours = |group: &Value| {+ is_our_command(group.get("command"), agent)+ || group+ .get("hooks")+ .and_then(Value::as_array)+ .is_some_and(|inner| inner.iter().any(|h| is_our_command(h.get("command"), agent)))+ };+ root.get("hooks")+ .and_then(Value::as_object)+ .is_some_and(|hooks| hooks.values().filter_map(Value::as_array).flatten().any(ours))+}++// ── Gemini CLI — ~/.gemini/settings.json ──────────────────────────────────────+//+// Claude-style groups with a `*` matcher and timeouts in milliseconds. The+// event name the relay should report goes on the command line. On Windows,+// Gemini CLI runs hooks with `powershell -Command`. AfterModel is left out: it+// fires on every response chunk and would flood the island.++const GEMINI_EVENTS: &[(&str, &str, u64)] = &[+ ("SessionStart", "SessionStart", 10000),+ ("SessionEnd", "SessionEnd", 10000),+ ("BeforeTool", "PreToolUse", 5000),+ ("AfterTool", "PostToolUse", 5000),+ ("BeforeAgent", "UserPromptSubmit", 5000),+ ("AfterAgent", "Stop", 5000),+];++fn gemini_install(root: &Value, commands: &[(String, String, u64)]) -> Result<Value, String> {+ let events = commands.iter().map(|(event, command, timeout)| {+ (+ event.clone(),+ json!({ "matcher": "*", "hooks": [{ "type": "command", "command": command, "timeout": timeout }] }),+ )+ });+ groups_install(root, "gemini", events).map(Value::Object)+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::config_file::tests::scratch;++ fn linux() -> Relay {+ Relay { exe: "/home/me/.local/share/coucou/bin/coucou-hook".into(), windows: false }+ }++ fn windows(exe: &str) -> Relay {+ Relay { exe: exe.into(), windows: true }+ }++ const WIN: &str = r"C:\Users\me\AppData\Local\Coucou\bin\coucou-hook.exe";+ const WIN_SPACE: &str = r"C:\Users\Jane O'Neil\AppData\Local\Coucou\bin\coucou-hook.exe";++ /// Installs then uninstalls `agent` in a fresh home holding `existing` in+ /// its first file, and returns (installed file, uninstalled file).+ fn round_trip(agent: Agent, existing: Option<&str>) -> (PathBuf, Value, Option<Value>) {+ let home = scratch(&format!("agent-{}", agent.id()));+ let file = agent.files(&home)[0].clone();+ if let Some(text) = existing {+ std::fs::create_dir_all(file.parent().unwrap()).unwrap();+ std::fs::write(&file, text).unwrap();+ }+ let relay = linux();+ let plan = config_file::preview(&agent.edits(&home, &relay, true)).unwrap();+ assert!(plan.diff.contains(MARKER), "{}", plan.diff);+ apply_in(agent, &home, &relay, true, &plan.fingerprint).unwrap();+ assert!(agent.installed(&home), "{agent:?} should read as installed");+ let installed = read_json(&file);++ let plan = config_file::preview(&agent.edits(&home, &relay, false)).unwrap();+ apply_in(agent, &home, &relay, false, &plan.fingerprint).unwrap();+ assert!(!agent.installed(&home), "{agent:?} should read as removed");+ let removed = file.exists().then(|| read_json(&file));+ (home, installed, removed)+ }++ fn read_json(path: &Path) -> Value {+ serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()+ }++ #[test]+ fn the_command_is_quoted_for_the_shell_that_runs_it() {+ assert_eq!(+ linux().command(Shell::Cmd, "--agent codex"),+ "'/home/me/.local/share/coucou/bin/coucou-hook' --agent codex"+ );+ let w = windows(WIN);+ assert_eq!(+ w.command(Shell::Sh, "Stop"),+ "\"C:/Users/me/AppData/Local/Coucou/bin/coucou-hook.exe\" Stop"+ );+ assert_eq!(+ w.command(Shell::PowerShell, "--agent gemini Stop"),+ format!("& '{WIN}' --agent gemini Stop")+ );+ // A plain path is left bare, so cmd and PowerShell both run it.+ assert_eq!(w.command(Shell::Cmd, "--agent cursor"), format!("{WIN} --agent cursor"));++ let spaced = windows(WIN_SPACE);+ assert_eq!(spaced.command(Shell::Cmd, "x"), format!("\"{WIN_SPACE}\" x"));+ assert_eq!(+ spaced.command(Shell::PowerShell, "x"),+ r"& 'C:\Users\Jane O''Neil\AppData\Local\Coucou\bin\coucou-hook.exe' x"+ );+ }++ #[test]+ fn the_hook_path_is_one_shell_word_whatever_it_contains() {+ assert_eq!(sh_quote("/home/a b/x"), "'/home/a b/x'");+ assert_eq!(sh_quote(r#"/h/$(id)`x`\"y"#), r#"'/h/$(id)`x`\"y'"#);+ assert_eq!(sh_quote("/h/it's"), r"'/h/it'\''s'");+ }++ #[test]+ fn every_agent_id_is_a_valid_pill_name() {+ for agent in Agent::ALL {+ let id = agent.id();+ assert!(id.len() <= 24 && id.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'));+ assert_eq!(Agent::from_id(id), Some(*agent));+ }+ assert!(find("claude").is_err());+ }++ #[test]+ fn gemini_keeps_foreign_hooks_and_removes_only_its_own() {+ let existing = r#"{"theme":"dark","hooks":{"BeforeTool":[{"matcher":"other","hooks":[{"type":"command","command":"custom.exe"}]}]}}"#;+ let (home, installed, removed) = round_trip(Agent::Gemini, Some(existing));+ assert_eq!(installed["theme"], "dark");+ let before_tool = installed["hooks"]["BeforeTool"].as_array().unwrap();+ assert_eq!(before_tool.len(), 2);+ assert_eq!(before_tool[0]["matcher"], "other");+ assert_eq!(before_tool[1]["matcher"], "*");+ assert_eq!(before_tool[1]["hooks"][0]["timeout"], 5000);+ let cmd = before_tool[1]["hooks"][0]["command"].as_str().unwrap();+ assert!(cmd.ends_with("--agent gemini PreToolUse"), "{cmd}");+ assert!(installed["hooks"]["AfterModel"].is_null());+ assert_eq!(removed.unwrap(), serde_json::from_str::<Value>(existing).unwrap());+ let _ = std::fs::remove_dir_all(home);+ }++ #[test]+ fn installing_twice_leaves_one_entry_per_event() {+ let once = gemini_install(&json!({}), &[("BeforeTool".into(), "'x/coucou-hook' --agent gemini PreToolUse".into(), 5000)]).unwrap();+ let twice = gemini_install(&once, &[("BeforeTool".into(), "'y/coucou-hook' --agent gemini PreToolUse".into(), 5000)]).unwrap();+ assert_eq!(twice["hooks"]["BeforeTool"].as_array().unwrap().len(), 1);+ }++ #[test]+ fn unexpected_types_are_refused_for_every_json_agent() {+ for agent in Agent::ALL {+ let home = scratch(&format!("odd-{}", agent.id()));+ let file = agent.files(&home)[0].clone();+ if file.extension().is_some_and(|e| e == "json") {+ std::fs::create_dir_all(file.parent().unwrap()).unwrap();+ for odd in [r#"{"hooks":"nope"}"#, r#"{"hooks":[1]}"#, "[1,2]", "{ broken"] {+ std::fs::write(&file, odd).unwrap();+ let edits = agent.edits(&home, &linux(), true);+ assert!(config_file::preview(&edits).is_err(), "{agent:?} accepted {odd}");+ assert_eq!(std::fs::read_to_string(&file).unwrap(), odd);+ }+ }+ let _ = std::fs::remove_dir_all(home);+ }+ }++ #[test]+ fn another_tools_entry_for_an_event_with_the_wrong_shape_is_refused() {+ let odd = json!({ "hooks": { "BeforeTool": { "matcher": "x" } } });+ assert!(gemini_install(&odd, &[("BeforeTool".into(), "c".into(), 1)]).is_err());+ }+}diff --git a/windows/src-tauri/src/config_file.rs b/windows/src-tauri/src/config_file.rsnew file mode 100644index 00000000..d6ca769e--- /dev/null+++ b/windows/src-tauri/src/config_file.rs@@ -0,0 +1,628 @@+// The one careful way Coucou changes a file that belongs to somebody else:+// Claude Code's settings.json, every other agent's hook config, and the plugin+// files a few agents load.+//+// The rules (CLAUDE.md) are applied here once, for everyone:+// * read strictly — a file we cannot read or parse is an error, never "empty";+// * the change is computed from the exact bytes the user was shown, identified+// by a fingerprint, and refused if the file moved since;+// * an edit refuses values of an unexpected type instead of replacing them;+// * a dated backup of the current bytes is taken first and must succeed;+// * the new contents are written beside the target and renamed over it,+// keeping its permissions, and through a symlink to the file it points at.+//+// Nothing here decides *what* to change: callers hand in an `Edit` per file.++use std::io::ErrorKind;+use std::path::{Path, PathBuf};++use serde::Serialize;+use serde_json::{json, Value};++/// What an edit wants a file to become.+pub struct Change {+ /// The current contents as the diff shows them.+ pub before: String,+ /// The new contents, or `None` to remove the file.+ pub after: Option<String>,+}++/// Computes the change for one file from its current bytes (`None`: no file).+pub type Edit<'a> = Box<dyn Fn(Option<&[u8]>) -> Result<Change, String> + 'a>;++/// One file and what to do with it.+pub struct FileEdit<'a> {+ pub path: PathBuf,+ pub edit: Edit<'a>,+}++/// What the user looks at before anything is written.+#[derive(Serialize, Debug)]+#[serde(rename_all = "camelCase")]+pub struct Plan {+ pub diff: String,+ /// Where each existing file will be copied first, one per line; empty when+ /// there is nothing to back up.+ pub backup: String,+ /// The file (or files, one per line) that change.+ pub path: String,+ /// Identifies the exact bytes the diff was computed from; handed back to+ /// `apply` so only what the user actually looked at is ever written.+ pub fingerprint: String,+}++// ── Reading ───────────────────────────────────────────────────────────────────++/// The bytes of `path`, `None` when there is no such file. Anything else — a+/// lock, a permission problem, a directory in its place — is an error: not+/// knowing what is in a file is not the same as it being empty.+pub fn read(path: &Path) -> Result<Option<Vec<u8>>, String> {+ match std::fs::read(path) {+ Ok(bytes) => Ok(Some(bytes)),+ Err(err) if err.kind() == ErrorKind::NotFound => Ok(None),+ Err(err) => Err(format!("Can't read {}: {err}", path.display())),+ }+}++/// A JSON config as an object. A missing, empty or whitespace-only file is an+/// empty object; a UTF-8 BOM (PowerShell 5, Notepad) is stripped. Anything+/// else that is not a JSON object is refused.+pub fn parse_json(bytes: Option<&[u8]>, label: &str) -> Result<Value, String> {+ let Some(bytes) = bytes else { return Ok(json!({})) };+ let text = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes);+ if text.iter().all(u8::is_ascii_whitespace) {+ return Ok(json!({}));+ }+ match serde_json::from_slice::<Value>(text) {+ Ok(v) if v.is_object() => Ok(v),+ Ok(_) => Err(format!("{label} isn't a JSON object — Coucou won't touch it.")),+ Err(err) => Err(format!(+ "{label} isn't valid JSON ({err}). Fix or move it, then try again — Coucou won't overwrite it."+ )),+ }+}++pub fn pretty(v: &Value) -> String {+ serde_json::to_string_pretty(v).unwrap_or_default()+}++/// An `Edit` for a JSON file: `change` gets the parsed object and returns the+/// new one, or `None` to remove the file. The diff compares both pretty-printed.+pub fn json_edit<'a>(+ label: String,+ change: impl Fn(&Value) -> Result<Option<Value>, String> + 'a,+) -> Edit<'a> {+ Box::new(move |bytes| {+ let current = parse_json(bytes, &label)?;+ let after = change(¤t)?.map(|next| {+ let mut text = pretty(&next);+ text.push('\n');+ text+ });+ Ok(Change { before: pretty(¤t), after })+ })+}++/// An `Edit` for a text file Coucou generates whole (a plugin): `change` gets+/// the current text and returns the new one, or `None` to remove the file.+pub fn text_edit<'a>(+ label: String,+ change: impl Fn(Option<&str>) -> Result<Option<String>, String> + 'a,+) -> Edit<'a> {+ Box::new(move |bytes| {+ let current = match bytes {+ None => None,+ Some(b) => Some(+ std::str::from_utf8(b)+ .map_err(|_| format!("{label} isn't UTF-8 text — Coucou won't touch it."))?,+ ),+ };+ let after = change(current)?;+ Ok(Change { before: current.unwrap_or_default().to_string(), after })+ })+}++// ── Preview and apply ─────────────────────────────────────────────────────────++/// Identifies the exact bytes a preview was computed from. FNV-1a is plenty:+/// the question is only "is this still the file I showed the user?".+pub fn fingerprint(bytes: &[u8]) -> String {+ let mut hash: u64 = 0xcbf2_9ce4_8422_2325;+ for b in bytes {+ hash ^= *b as u64;+ hash = hash.wrapping_mul(0x1000_0000_01b3);+ }+ format!("{hash:016x}")+}++/// A missing file and an empty one are told apart: creating a file someone+/// else just created must be refused too.+fn fingerprint_of(bytes: Option<&[u8]>) -> String {+ match bytes {+ Some(b) => fingerprint(b),+ None => "none".into(),+ }+}++/// The diff, backups and fingerprint for a set of edits. Nothing is written.+pub fn preview(edits: &[FileEdit]) -> Result<Plan, String> {+ let mut diffs = Vec::new();+ let mut backups = Vec::new();+ let mut paths = Vec::new();+ let mut prints = Vec::new();+ for file in edits {+ let current = read(&file.path)?;+ let change = (file.edit)(current.as_deref())?;+ let after = change.after.clone().unwrap_or_default();+ let mut diff = unified_diff(&change.before, after.trim_end_matches('\n'));+ if change.after.is_none() && current.is_some() {+ diff = format!("The file is removed.\n{diff}");+ }+ if edits.len() > 1 {+ diff = format!("── {}\n{diff}", file.path.display());+ }+ diffs.push(diff);+ if current.is_some() {+ backups.push(backup_name(&file.path, &stamp(), 0).display().to_string());+ }+ paths.push(file.path.display().to_string());+ prints.push(fingerprint_of(current.as_deref()));+ }+ Ok(Plan {+ diff: diffs.join("\n"),+ backup: backups.join("\n"),+ path: paths.join("\n"),+ fingerprint: prints.join(":"),+ })+}++/// Applies the edits the user confirmed. Returns the backups taken.+///+/// Every file is read, checked against `expected` and edited before anything+/// is touched; then every existing file is backed up; only then is anything+/// written. A file that changed since the preview — another tool, another+/// window, the user's own editor — stops everything: the only thing worse than+/// not installing is silently reverting somebody else's edit.+pub fn apply(edits: &[FileEdit], expected: &str) -> Result<Vec<PathBuf>, String> {+ let wanted: Vec<&str> = expected.split(':').collect();+ if wanted.len() != edits.len() {+ return Err("The preview is out of date. Nothing was written — review the new diff.".into());+ }+ let mut planned = Vec::new();+ for (file, want) in edits.iter().zip(wanted) {+ let current = read(&file.path)?;+ if fingerprint_of(current.as_deref()) != want {+ return Err(format!(+ "{} changed since the preview. Nothing was written — review the new diff.",+ file.path.display()+ ));+ }+ let change = (file.edit)(current.as_deref())?;+ planned.push((file, current, change.after));+ }++ let mut backups = Vec::new();+ for (file, current, _) in &planned {+ if let Some(bytes) = current {+ let copy = back_up(&file.path, bytes)+ .map_err(|e| format!("Backup of {} failed, nothing was written: {e}", file.path.display()))?;+ backups.push(copy);+ }+ }++ for (file, current, after) in planned {+ match after {+ Some(text) => replace(&file.path, text.as_bytes())+ .map_err(|e| format!("Write to {} failed: {e}", file.path.display()))?,+ None if current.is_some() => std::fs::remove_file(&file.path)+ .map_err(|e| format!("Could not remove {}: {e}", file.path.display()))?,+ None => {}+ }+ }+ Ok(backups)+}++// ── Writing ───────────────────────────────────────────────────────────────────++/// Down to the second: installing then uninstalling in the same minute must not+/// quietly overwrite the first backup.+fn stamp() -> String {+ let t = crate::platform::local_time();+ format!(+ "{:04}{:02}{:02}-{:02}{:02}{:02}",+ t.year, t.month, t.day, t.hour, t.minute, t.second+ )+}++/// `settings.json.bak-20260102-030405`, then `-1`, `-2`… while that is taken.+fn backup_name(path: &Path, stamp: &str, n: u32) -> PathBuf {+ let name = path.file_name().unwrap_or_default().to_string_lossy();+ match n {+ 0 => path.with_file_name(format!("{name}.bak-{stamp}")),+ n => path.with_file_name(format!("{name}.bak-{stamp}-{n}")),+ }+}++/// Copies `bytes` — the very bytes the change was computed from — beside+/// `path`. A backup that already exists is never written over, and one that+/// could not be written whole is removed rather than left looking faithful.+fn back_up(path: &Path, bytes: &[u8]) -> std::io::Result<PathBuf> {+ let stamp = stamp();+ for n in 0..100 {+ let copy = backup_name(path, &stamp, n);+ let mut options = std::fs::OpenOptions::new();+ options.write(true).create_new(true);+ #[cfg(unix)]+ std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);+ match options.open(©) {+ Ok(mut file) => {+ let written = write_whole(&mut file, bytes).and_then(|()| keep_mode(&file, path));+ drop(file);+ if let Err(err) = written {+ let _ = std::fs::remove_file(©);+ return Err(err);+ }+ return Ok(copy);+ }+ Err(err) if err.kind() == ErrorKind::AlreadyExists => continue,+ Err(err) => return Err(err),+ }+ }+ Err(std::io::Error::new(ErrorKind::AlreadyExists, "too many backups this second"))+}++fn write_whole(file: &mut std::fs::File, bytes: &[u8]) -> std::io::Result<()> {+ use std::io::Write;+ file.write_all(bytes)?;+ file.sync_all()+}++/// Gives `file` the permissions of `original` (ours only when there is none).+/// A config can hold API keys: a rewrite or a backup must never widen access.+fn keep_mode(file: &std::fs::File, original: &Path) -> std::io::Result<()> {+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let mode = std::fs::metadata(original)+ .map(|m| m.permissions().mode() & 0o777)+ .unwrap_or(0o600);+ file.set_permissions(std::fs::Permissions::from_mode(mode))?;+ }+ #[cfg(not(unix))]+ let _ = (file, original);+ Ok(())+}++/// Writes `bytes` to `temp`, which is about to replace `original`: created+/// readable by us only, then given the original's permissions.+pub fn write_like(temp: &Path, original: &Path, bytes: &[u8]) -> std::io::Result<()> {+ let mut options = std::fs::OpenOptions::new();+ options.write(true).create(true).truncate(true);+ #[cfg(unix)]+ std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);+ let mut file = options.open(temp)?;+ write_whole(&mut file, bytes)?;+ keep_mode(&file, original)+}++/// Replaces `path` with `bytes`: written beside it and renamed over it, so a+/// crash or a full disk leaves the original intact rather than half a file.+fn replace(path: &Path, bytes: &[u8]) -> std::io::Result<()> {+ if let Some(dir) = path.parent() {+ std::fs::create_dir_all(dir)?;+ }+ // A dotfiles setup often makes a config a symlink: write to the file it+ // points at, so the link survives the rename.+ #[cfg(unix)]+ let resolved = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());+ #[cfg(unix)]+ let path = resolved.as_path();++ let name = path.file_name().unwrap_or_default().to_string_lossy();+ let temp = path.with_file_name(format!("{name}.coucou-{}", std::process::id()));+ let result = write_like(&temp, path, bytes).and_then(|()| std::fs::rename(&temp, path));+ if result.is_err() {+ let _ = std::fs::remove_file(&temp);+ }+ result+}++// ── Minimal unified diff (LCS) ────────────────────────────────────────────────++/// Config files are short, so a plain O(n·m) LCS is the simplest honest diff.+pub 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+}++#[cfg(test)]+pub mod tests {+ use super::*;++ /// A fresh directory of our own.+ pub fn scratch(name: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!("coucou-cfg-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+ }++ fn names(dir: &Path) -> Vec<String> {+ let mut names: Vec<String> = std::fs::read_dir(dir)+ .unwrap()+ .map(|e| e.unwrap().file_name().to_string_lossy().to_string())+ .collect();+ names.sort();+ names+ }++ /// Adds `"ours": true` and refuses a `hooks` that is not an object.+ fn add_ours(path: &Path) -> Vec<FileEdit<'static>> {+ vec![FileEdit {+ path: path.to_path_buf(),+ edit: json_edit("test.json".into(), |v| {+ if v.get("hooks").is_some_and(|h| !h.is_object()) {+ return Err("\"hooks\" has an unexpected type — Coucou has not touched it.".into());+ }+ let mut next = v.clone();+ next["ours"] = json!(true);+ Ok(Some(next))+ }),+ }]+ }++ fn remove_file_edit(path: &Path) -> Vec<FileEdit<'static>> {+ vec![FileEdit { path: path.to_path_buf(), edit: json_edit("test.json".into(), |_| Ok(None)) }]+ }++ #[test]+ fn unreadable_content_is_an_error_never_an_empty_object() {+ for bad in [&b"{ not json"[..], &b"[1,2,3]"[..], &b"\"a string\""[..]] {+ assert!(parse_json(Some(bad), "x").is_err());+ }+ assert_eq!(parse_json(None, "x").unwrap(), json!({}));+ assert_eq!(parse_json(Some(b" \n\t"), "x").unwrap(), json!({}));+ let mut bom = vec![0xEF, 0xBB, 0xBF];+ bom.extend_from_slice(br#"{"a":1}"#);+ assert_eq!(parse_json(Some(&bom), "x").unwrap()["a"], 1);+ }++ #[test]+ fn a_fingerprint_notices_any_change_and_tells_missing_from_empty() {+ assert_eq!(fingerprint(b"{}"), fingerprint(b"{}"));+ assert_ne!(fingerprint(b"{}"), fingerprint(b"{ }"));+ assert_ne!(fingerprint_of(None), fingerprint_of(Some(b"")));+ }++ #[test]+ fn the_backup_holds_the_original_bytes_and_the_rest_is_kept() {+ let dir = scratch("backup");+ let path = dir.join("settings.json");+ let mut original = vec![0xEF, 0xBB, 0xBF];+ original.extend_from_slice(br#"{"model":"opus","keep":{"x":[1,2]}}"#);+ std::fs::write(&path, &original).unwrap();++ let plan = preview(&add_ours(&path)).unwrap();+ assert!(plan.diff.contains("\"ours\": true"), "{}", plan.diff);+ assert!(plan.backup.contains("settings.json.bak-"));+ let backups = apply(&add_ours(&path), &plan.fingerprint).unwrap();+ assert_eq!(backups.len(), 1);+ assert_eq!(std::fs::read(&backups[0]).unwrap(), original);++ let after: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();+ assert_eq!(after["model"], "opus");+ assert_eq!(after["keep"]["x"], json!([1, 2]));+ assert_eq!(after["ours"], true);+ // Nothing but the file and its backup: no temporary left behind.+ assert_eq!(names(&dir).len(), 2);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn two_backups_in_the_same_second_never_overwrite_each_other() {+ let dir = scratch("twice");+ let path = dir.join("hooks.json");+ std::fs::write(&path, b"{}").unwrap();+ let first = apply(&add_ours(&path), &fingerprint(b"{}")).unwrap();+ let now = std::fs::read(&path).unwrap();+ let second = apply(&add_ours(&path), &fingerprint(&now)).unwrap();+ assert_ne!(first, second);+ assert_eq!(std::fs::read(&first[0]).unwrap(), b"{}");+ assert_eq!(std::fs::read(&second[0]).unwrap(), now);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_backup_that_cannot_be_taken_stops_everything() {+ let dir = scratch("nobackup");+ // A name the file system accepts, but too long for ".bak-<stamp>" on top.+ let path = dir.join(format!("{}.json", "s".repeat(240)));+ std::fs::write(&path, b"{}").unwrap();+ let err = apply(&add_ours(&path), &fingerprint(b"{}")).unwrap_err();+ assert!(err.contains("Backup"), "{err}");+ assert_eq!(std::fs::read(&path).unwrap(), b"{}");+ assert_eq!(names(&dir).len(), 1);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_file_that_changed_since_the_preview_is_refused_and_left_alone() {+ let dir = scratch("changed");+ let path = dir.join("settings.json");+ std::fs::write(&path, b"{}").unwrap();+ let plan = preview(&add_ours(&path)).unwrap();+ std::fs::write(&path, br#"{"someone":"else"}"#).unwrap();+ let err = apply(&add_ours(&path), &plan.fingerprint).unwrap_err();+ assert!(err.contains("changed since the preview"), "{err}");+ assert_eq!(std::fs::read(&path).unwrap(), br#"{"someone":"else"}"#);++ // A file created since a preview of "no file" is refused too.+ let fresh = dir.join("new.json");+ let plan = preview(&add_ours(&fresh)).unwrap();+ std::fs::write(&fresh, b"").unwrap();+ assert!(apply(&add_ours(&fresh), &plan.fingerprint).is_err());+ assert_eq!(std::fs::read(&fresh).unwrap(), b"");+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn unexpected_types_and_invalid_json_are_refused_before_anything_is_written() {+ let dir = scratch("types");+ let path = dir.join("settings.json");+ for bad in [&br#"{"hooks":"a string"}"#[..], &b"{ broken"[..]] {+ std::fs::write(&path, bad).unwrap();+ assert!(preview(&add_ours(&path)).is_err());+ assert!(apply(&add_ours(&path), &fingerprint(bad)).is_err());+ assert_eq!(std::fs::read(&path).unwrap(), bad);+ }+ assert_eq!(names(&dir), ["settings.json"]);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_new_file_is_created_with_its_folder_and_nothing_is_backed_up() {+ let dir = scratch("create");+ let path = dir.join("deep").join("er").join("hooks.json");+ let plan = preview(&add_ours(&path)).unwrap();+ assert_eq!(plan.backup, "");+ assert!(apply(&add_ours(&path), &plan.fingerprint).unwrap().is_empty());+ let after: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();+ assert_eq!(after, json!({ "ours": true }));+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn removing_a_file_backs_it_up_first() {+ let dir = scratch("remove");+ let path = dir.join("coucou.json");+ std::fs::write(&path, b"{\"a\":1}").unwrap();+ let plan = preview(&remove_file_edit(&path)).unwrap();+ assert!(plan.diff.starts_with("The file is removed."));+ let backups = apply(&remove_file_edit(&path), &plan.fingerprint).unwrap();+ assert!(!path.exists());+ assert_eq!(std::fs::read(&backups[0]).unwrap(), b"{\"a\":1}");+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn several_files_are_checked_together() {+ let dir = scratch("many");+ let (a, b) = (dir.join("a.json"), dir.join("b.json"));+ std::fs::write(&a, b"{}").unwrap();+ let edits = |a: &Path, b: &Path| {+ let mut v = add_ours(a);+ v.extend(add_ours(b));+ v+ };+ let plan = preview(&edits(&a, &b)).unwrap();+ // The second one appears in between: neither is written.+ std::fs::write(&b, b"{\"x\":1}").unwrap();+ assert!(apply(&edits(&a, &b), &plan.fingerprint).is_err());+ assert_eq!(std::fs::read(&a).unwrap(), b"{}");+ let plan = preview(&edits(&a, &b)).unwrap();+ apply(&edits(&a, &b), &plan.fingerprint).unwrap();+ for p in [&a, &b] {+ let v: Value = serde_json::from_slice(&std::fs::read(p).unwrap()).unwrap();+ assert_eq!(v["ours"], true);+ }+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[cfg(unix)]+ #[test]+ fn rewriting_keeps_permissions_and_symlinks() {+ use std::os::unix::fs::PermissionsExt;+ let dir = scratch("perm");+ let real = dir.join("dotfiles-settings.json");+ let link = dir.join("settings.json");+ std::fs::write(&real, b"{}").unwrap();+ std::fs::set_permissions(&real, std::fs::Permissions::from_mode(0o640)).unwrap();+ std::os::unix::fs::symlink(&real, &link).unwrap();++ let backups = apply(&add_ours(&link), &fingerprint(b"{}")).unwrap();+ assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink());+ let v: Value = serde_json::from_slice(&std::fs::read(&real).unwrap()).unwrap();+ assert_eq!(v["ours"], true);+ let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;+ assert_eq!(mode(&real), 0o640);+ assert_eq!(mode(&backups[0]), 0o640);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_text_file_that_is_not_utf8_is_refused() {+ let edit = text_edit("plugin.js".into(), |_| Ok(Some("x".into())));+ assert!(edit(Some(&[0xff, 0xfe, 0x00])).is_err());+ let change = edit(None).unwrap();+ assert_eq!(change.before, "");+ assert_eq!(change.after.as_deref(), Some("x"));+ }+}diff --git a/windows/src-tauri/src/hooks.rs b/windows/src-tauri/src/hooks.rsindex 03708ed9..1b44561f 100644--- a/windows/src-tauri/src/hooks.rs+++ b/windows/src-tauri/src/hooks.rs@@ -8,12 +8,17 @@// 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.+//+// Reading, the diff, the backup and the write itself live in config_file.rs,+// shared with every other agent's installer (agents.rs).use std::path::{Path, PathBuf};use serde::Serialize;use serde_json::{json, Map, Value};use tauri::{AppHandle, Manager};+use crate::agents::{self, Shell};+use crate::config_file::{self, FileEdit};use crate::{platform, settings};/// Every event the island reacts to, with the hook timeout written to settings.json.@@ -60,68 +65,20 @@ pub fn settings_path() -> PathBuf {platform::home_dir().join(".claude").join("settings.json")}-/// Reads `~/.claude/settings.json`.-///-/// The only error that means "start from nothing" is the file not being there.-/// Everything else — a lock held by another process, a permission problem, JSON-/// we cannot parse — is reported, because the alternative is treating somebody's-/// unreadable settings as an empty object and then writing that back over them.-fn read_settings() -> Result<Value, String> {- let path = settings_path();- match std::fs::read(&path) {- Ok(bytes) => parse_settings(&bytes, &path.display().to_string()),- Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(json!({})),- // A lock, a permission problem, a bad drive: all of them mean we do not- // know what is in there, and not knowing is not the same as empty.- Err(err) => Err(format!("Can't read {}: {err}", path.display())),- }-}--/// The parsing half of `read_settings`, split out so it can be tested without a-/// home directory.-fn parse_settings(bytes: &[u8], path: &str) -> Result<Value, String> {- // PowerShell writes a UTF-8 BOM with `Set-Content -Encoding utf8`, and- // serde_json refuses it. Stripping it is safe and well defined; guessing at- // anything else is not.- let text = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes);- if text.iter().all(u8::is_ascii_whitespace) {- return Ok(json!({}));- }- match serde_json::from_slice::<Value>(text) {- Ok(v) if v.is_object() => Ok(v),- Ok(_) => Err(format!("{path} isn't a JSON object — Coucou won't touch it.")),- Err(err) => Err(format!(- "{path} isn't valid JSON ({err}). Fix or move it, then try again — Coucou won't overwrite it."- )),- }-}-/// The settings as they are, or an empty object when we cannot tell. Only for/// read-only paths like `status()`, which must never fail loudly; anything that-/// writes uses `read_settings()` and surfaces the error instead.+/// writes goes through `config_file`, which surfaces the error instead.fn read_settings_lossy() -> Value {- read_settings().unwrap_or_else(|_| json!({}))+ config_file::read(&settings_path())+ .ok()+ .and_then(|bytes| config_file::parse_json(bytes.as_deref(), "settings.json").ok())+ .unwrap_or_else(|| json!({}))}-#[cfg(windows)]-fn hook_command(event: &str) -> String {- let exe = settings::hook_exe_path().to_string_lossy().replace('\\', "/");- format!("\"{exe}\" {event}")-}--/// Claude Code runs the command through `sh`, which still reads `$`, `` ` ``-/// and `\` inside double quotes. Single quotes keep the path a path, whatever-/// the home directory is called.-#[cfg(unix)]+/// On Windows Claude Code runs hook commands through Git Bash; on Linux through+/// `sh`. Either way the relay path is one quoted shell word.fn hook_command(event: &str) -> String {- format!("{} {event}", sh_quote(&settings::hook_exe_path().to_string_lossy()))-}--/// `s` as one single-quoted shell word: `'` becomes `'\''`, nothing else is-/// special inside single quotes.-#[cfg(unix)]-fn sh_quote(s: &str) -> String {- format!("'{}'", s.replace('\'', r"'\''"))+ agents::relay_command(Shell::Sh, event)}fn entry_is_ours(entry: &Value) -> bool {@@ -139,21 +96,23 @@ fn entry_is_ours(entry: &Value) -> bool {.unwrap_or(false)}-/// Settings with Coucou's hooks added; everything else is left untouched.-fn merged(existing: &Value) -> Value {+/// Settings with Coucou's hooks added; everything else is left untouched. A+/// `hooks` (or one of its events) that is not what Claude Code documents is+/// refused rather than replaced.+fn merged(existing: &Value) -> Result<Value, String> {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);+ let mut hooks = match root.get("hooks") {+ None => Map::new(),+ Some(Value::Object(h)) => h.clone(),+ Some(_) => return Err(unexpected("\"hooks\"")),+ };for (event, timeout) in HOOK_EVENTS {- let mut list = hooks- .get(*event)- .and_then(Value::as_array)- .cloned()- .unwrap_or_default();+ let mut list = match hooks.get(*event) {+ None => Vec::new(),+ Some(Value::Array(list)) => list.clone(),+ Some(_) => return Err(unexpected(&format!("\"hooks\".\"{event}\""))),+ };list.retain(|entry| !entry_is_ours(entry));list.push(json!({"hooks": [{@@ -166,14 +125,20 @@ fn merged(existing: &Value) -> Value {}root.insert("hooks".into(), Value::Object(hooks));- Value::Object(root)+ Ok(Value::Object(root))+}++fn unexpected(what: &str) -> String {+ format!("settings.json: {what} has an unexpected type — Coucou has not touched it.")}/// Settings with every Coucou entry removed, and nothing else changed.-fn without_ours(existing: &Value) -> Value {+fn without_ours(existing: &Value) -> Result<Value, String> {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 hooks = match root.get("hooks") {+ None => return Ok(Value::Object(root)),+ Some(Value::Object(h)) => h.clone(),+ Some(_) => return Err(unexpected("\"hooks\"")),};let mut out = Map::new();for (event, value) in hooks {@@ -195,299 +160,19 @@ fn without_ours(existing: &Value) -> Value {} 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()-}--/// Down to the second: installing then uninstalling in the same minute must not-/// quietly overwrite the first backup.-fn stamp() -> String {- let t = platform::local_time();- format!(- "{:04}{:02}{:02}-{:02}{:02}{:02}",- t.year, t.month, t.day, t.hour, t.minute, t.second- )-}--fn backup_path() -> PathBuf {- let p = settings_path();- p.with_file_name(format!("settings.json.bak-{}", stamp()))-}--/// Identifies the exact bytes a preview was computed from. FNV-1a is plenty:-/// the question is only "is this still the file I showed the user?".-fn fingerprint(bytes: &[u8]) -> String {- let mut hash: u64 = 0xcbf2_9ce4_8422_2325;- for b in bytes {- hash ^= *b as u64;- hash = hash.wrapping_mul(0x1000_0000_01b3);- }- format!("{hash:016x}")-}--fn current_fingerprint() -> String {- match std::fs::read(settings_path()) {- Ok(bytes) => fingerprint(&bytes),- Err(_) => fingerprint(b""),- }-}--// ── Public API ────────────────────────────────────────────────────────────────--pub fn gemini_settings_path() -> PathBuf {- platform::home_dir().join(".gemini").join("settings.json")-}--const GEMINI_EVENTS: &[(&str, &str, u64)] = &[- ("SessionStart", "SessionStart", 10000),- ("SessionEnd", "SessionEnd", 10000),- ("BeforeTool", "PreToolUse", 5000),- ("AfterTool", "PostToolUse", 5000),- ("BeforeAgent", "UserPromptSubmit", 5000),- ("AfterAgent", "Stop", 5000),-];--#[cfg(windows)]-fn gemini_hook_command(event: &str) -> String {- let exe = settings::hook_exe_path().to_string_lossy().replace('\\', "/");- format!("\"{exe}\" --agent gemini {event}")-}--#[cfg(unix)]-fn gemini_hook_command(event: &str) -> String {- format!(- "{} --agent gemini {event}",- sh_quote(&settings::hook_exe_path().to_string_lossy())- )-}--fn read_gemini_settings() -> Result<Value, String> {- let path = gemini_settings_path();- match std::fs::read(&path) {- Ok(bytes) => parse_settings(&bytes, &path.display().to_string()),- Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(json!({})),- Err(err) => Err(format!("Can't read {}: {err}", path.display())),- }-}--fn read_gemini_settings_lossy() -> Value {- read_gemini_settings().unwrap_or_else(|_| json!({}))-}--fn gemini_entry_is_ours(entry: &Value) -> bool {- if let Some(cmd) = entry.get("command").and_then(Value::as_str) {- if cmd.contains(MARKER) && cmd.contains("--agent gemini") {- return true;- }- }- if let Some(inner) = entry.get("hooks").and_then(Value::as_array) {- if inner.iter().any(|h| {- h.get("command")- .and_then(Value::as_str)- .map(|c| c.contains(MARKER) && c.contains("--agent gemini"))- .unwrap_or(false)- }) {- return true;- }- }- false-}--fn remove_gemini_nb_hook_entries(groups: &[Value]) -> Vec<Value> {- let mut out = Vec::new();- for group in groups {- if let Some(cmd) = group.get("command").and_then(Value::as_str) {- if cmd.contains(MARKER) && cmd.contains("--agent gemini") {- continue;- }- }- if let Some(inner) = group.get("hooks").and_then(Value::as_array) {- let filtered: Vec<Value> = inner- .iter()- .filter(|h| {- !h.get("command")- .and_then(Value::as_str)- .map(|c| c.contains(MARKER) && c.contains("--agent gemini"))- .unwrap_or(false)- })- .cloned()- .collect();- if !filtered.is_empty() {- let mut updated = group.as_object().cloned().unwrap_or_default();- updated.insert("hooks".into(), Value::Array(filtered));- out.push(Value::Object(updated));- }- } else {- out.push(group.clone());- }- }- out-}--fn merged_gemini(existing: &Value) -> Result<Value, String> {- let mut root = existing.as_object().cloned().unwrap_or_default();- if let Some(raw) = root.get("hooks") {- if !raw.is_object() {- return Err("~/.gemini/settings.json: \"hooks\" has an unexpected type — Coucou won't touch it.".into());- }- }- let mut hooks = root- .get("hooks")- .and_then(Value::as_object)- .cloned()- .unwrap_or_else(Map::new);-- for (gemini_event, normalized_event, timeout) in GEMINI_EVENTS {- if let Some(raw) = hooks.get(*gemini_event) {- if !raw.is_array() {- return Err(format!(- "~/.gemini/settings.json: \"hooks\"[\"{gemini_event}\"] has an unexpected type — Coucou won't touch it."- ));- }- }- let list = hooks- .get(*gemini_event)- .and_then(Value::as_array)- .cloned()- .unwrap_or_default();- let mut cleaned = remove_gemini_nb_hook_entries(&list);- cleaned.push(json!({- "matcher": "*",- "hooks": [{- "type": "command",- "command": gemini_hook_command(normalized_event),- "timeout": timeout,- }]- }));- hooks.insert((*gemini_event).to_string(), Value::Array(cleaned));- }-- root.insert("hooks".into(), Value::Object(hooks));- Ok(Value::Object(root))-}--fn without_gemini_ours(existing: &Value) -> Result<Value, String> {- let mut root = existing.as_object().cloned().unwrap_or_default();- let Some(raw_hooks) = root.get("hooks") else {- return Ok(Value::Object(root));- };- let Some(hooks) = raw_hooks.as_object() else {- return Err("~/.gemini/settings.json: \"hooks\" has an unexpected type — Coucou won't touch it.".into());- };- let mut out = Map::new();- for (event, value) in hooks {- match value.as_array() {- Some(list) => {- let kept = remove_gemini_nb_hook_entries(list);- if !kept.is_empty() {- out.insert(event.clone(), Value::Array(kept));- }- }- None => {- out.insert(event.clone(), value.clone());- }- }- }- if out.is_empty() {- root.remove("hooks");- } else {- root.insert("hooks".into(), Value::Object(out));- }Ok(Value::Object(root))}-fn gemini_backup_path() -> PathBuf {- let p = gemini_settings_path();- p.with_file_name(format!("settings.json.bak-{}", stamp()))-}--fn gemini_current_fingerprint() -> String {- match std::fs::read(gemini_settings_path()) {- Ok(bytes) => fingerprint(&bytes),- Err(_) => fingerprint(b""),- }-}--pub fn gemini_status() -> HookStatus {- let current = read_gemini_settings_lossy();- let installed = current- .get("hooks")- .and_then(Value::as_object)- .map(|hooks| {- hooks- .values()- .filter_map(Value::as_array)- .flatten()- .any(gemini_entry_is_ours)- })- .unwrap_or(false);- let hook_path = settings::hook_exe_path();- HookStatus {- installed,- settings_path: gemini_settings_path().to_string_lossy().to_string(),- hook_ready: hook_path.exists(),- hook_path: hook_path.to_string_lossy().to_string(),- }+fn edits(install: bool) -> Vec<FileEdit<'static>> {+ vec![FileEdit {+ path: settings_path(),+ edit: config_file::json_edit("settings.json".into(), move |current| {+ if install { merged(current).map(Some) } else { without_ours(current).map(Some) }+ }),+ }]}-pub fn gemini_preview(install: bool) -> Result<HookPreview, String> {- let current = read_gemini_settings()?;- let next = if install {- merged_gemini(¤t)?- } else {- without_gemini_ours(¤t)?- };- Ok(HookPreview {- diff: unified_diff(&pretty(¤t), &pretty(&next)),- backup: gemini_backup_path().to_string_lossy().to_string(),- settings_path: gemini_settings_path().to_string_lossy().to_string(),- fingerprint: gemini_current_fingerprint(),- })-}--pub fn gemini_write(install: bool, fingerprint: &str) -> Result<String, String> {- let path = gemini_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_gemini_settings()?;- if gemini_current_fingerprint() != fingerprint {- return Err(format!(- "{} changed since the preview. Nothing was written — review the new diff.",- path.display()- ));- }-- let backup = gemini_backup_path();- if path.exists() {- std::fs::copy(&path, &backup).map_err(|e| format!("backup failed: {e}"))?;- }-- let next = if install {- merged_gemini(¤t)?- } else {- without_gemini_ours(¤t)?- };- let mut text = pretty(&next);- text.push('\n');-- #[cfg(unix)]- let path = std::fs::canonicalize(&path).unwrap_or(path);-- let temp = path.with_extension(format!("json.coucou-{}", std::process::id()));- if let Err(err) = write_like(&temp, &path, text.as_bytes()) {- let _ = std::fs::remove_file(&temp);- return Err(format!("write failed: {err}"));- }- if let Err(err) = std::fs::rename(&temp, &path) {- let _ = std::fs::remove_file(&temp);- return Err(format!("write failed: {err}"));- }- Ok(backup.to_string_lossy().to_string())-}+// ── Public API ────────────────────────────────────────────────────────────────pub fn status() -> HookStatus {let current = read_settings_lossy();@@ -512,89 +197,23 @@ pub fn status() -> HookStatus {}pub fn preview(install: bool) -> Result<HookPreview, String> {- let current = read_settings()?;- let next = if install { merged(¤t) } else { without_ours(¤t) };+ let plan = config_file::preview(&edits(install))?;Ok(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(),- fingerprint: current_fingerprint(),+ diff: plan.diff,+ backup: plan.backup,+ settings_path: plan.path,+ fingerprint: plan.fingerprint,})}-/// Writes the merged (or cleaned) settings after taking a dated backup.+/// Writes the merged (or cleaned) settings after taking a dated backup, and+/// returns where the backup went ("" when there was no file to back up).///-/// `fingerprint` is the one the preview was computed from. If the file changed-/// in between — another tool, another window, the user's own editor — we stop-/// and make them look at a fresh diff, because the only thing worse than not-/// installing the hooks is silently reverting somebody else's edit.+/// `fingerprint` is the one the preview was computed from: a settings.json that+/// changed in between is refused rather than overwritten (see config_file).pub fn write(install: bool, fingerprint: &str) -> 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())?;-- // Read before the backup: an unreadable file must abort before we touch- // anything at all.- let current = read_settings()?;- if current_fingerprint() != fingerprint {- return Err(format!(- "{} changed since the preview. Nothing was written — review the new diff.",- path.display()- ));- }-- 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');-- // A dotfiles setup often makes settings.json a symlink: write to the file it- // points at, so the link survives the rename below.- #[cfg(unix)]- let path = std::fs::canonicalize(&path).unwrap_or(path);-- // Write beside the target and rename over it: a crash or a full disk leaves- // the original settings.json intact rather than half a file.- let temp = path.with_extension(format!("json.coucou-{}", std::process::id()));- if let Err(err) = write_like(&temp, &path, text.as_bytes()) {- let _ = std::fs::remove_file(&temp);- return Err(format!("write failed: {err}"));- }- if let Err(err) = std::fs::rename(&temp, &path) {- let _ = std::fs::remove_file(&temp);- return Err(format!("write failed: {err}"));- }- Ok(backup.to_string_lossy().to_string())-}--/// Writes `bytes` to `temp`, which is about to replace `original`.-///-/// On Linux a fresh file would get the umask's 0644, and settings.json can hold-/// API keys in its `env` block: the new file is created readable by us only,-/// then given the original's permissions, so the rename never widens them.-fn write_like(temp: &Path, original: &Path, bytes: &[u8]) -> std::io::Result<()> {- use std::io::Write;- let mut options = std::fs::OpenOptions::new();- options.write(true).create(true).truncate(true);- #[cfg(unix)]- std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);- let mut file = options.open(temp)?;- file.write_all(bytes)?;- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;- let mode = std::fs::metadata(original)- .map(|m| m.permissions().mode() & 0o777)- .unwrap_or(0o600);- file.set_permissions(std::fs::Permissions::from_mode(mode))?;- }- #[cfg(not(unix))]- let _ = original;- Ok(())+ let backups = config_file::apply(&edits(install), fingerprint)?;+ Ok(backups.first().map(|p| p.to_string_lossy().to_string()).unwrap_or_default())}/// Copies the relay (coucou-hook.exe / coucou-hook) into the local data dir's@@ -681,117 +300,10 @@ fn install_relay(src: &Path, dest: &Path) {}}-// ── 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-}-#[cfg(test)]mod tests {use super::*;- const WHERE: &str = "settings.json";-- #[test]- fn a_utf8_bom_is_stripped_not_treated_as_corruption() {- // PowerShell 5's `Set-Content -Encoding utf8` produces exactly this.- let mut bytes = vec![0xEF, 0xBB, 0xBF];- bytes.extend_from_slice(br#"{"model":"opus","hooks":{}}"#);- let parsed = parse_settings(&bytes, WHERE).expect("a BOM must not defeat the parser");- assert_eq!(parsed["model"], "opus");- }-- #[test]- fn unreadable_content_is_an_error_never_an_empty_object() {- // This is the whole bug: returning {} here meant `merged()` produced a- // file containing nothing but Coucou's hooks, and the write replaced- // everything the user had.- for bad in [&b"{ not json"[..], &b"[1,2,3]"[..], &b"\"a string\""[..]] {- assert!(- parse_settings(bad, WHERE).is_err(),- "content we cannot use must refuse, not come back empty"- );- }- }-- #[test]- fn empty_and_whitespace_files_start_from_nothing() {- assert_eq!(parse_settings(b"", WHERE).unwrap(), json!({}));- assert_eq!(parse_settings(b"- ", WHERE).unwrap(), json!({}));- }-#[test]fn merging_keeps_every_other_setting_and_every_foreign_hook() {let existing = serde_json::json!({@@ -808,7 +320,7 @@ mod tests {}});- let after = merged(&existing);+ let after = merged(&existing).unwrap();assert_eq!(after["model"], "claude-opus-5");assert_eq!(after["theme"], "dark");assert_eq!(after["enabledPlugins"], serde_json::json!(["a", "b"]));@@ -821,78 +333,27 @@ mod tests {assert!(pre.iter().any(entry_is_ours), "our own hook was not added");assert!(after["hooks"]["SomeEventWeDoNotTouch"].is_array());- // And removing ours puts it back exactly as it was.- let cleaned = without_ours(&after);- assert_eq!(cleaned, existing);- }-- #[test]- fn merging_gemini_creates_groups_and_preserves_others() {- let existing = serde_json::json!({- "theme": "dark",- "hooks": {- "BeforeTool": [- { "matcher": "other", "hooks": [{ "type": "command", "command": "custom.exe" }] }- ]- }- });-- let after = merged_gemini(&existing).unwrap();- assert_eq!(after["theme"], "dark");- let before_tool = after["hooks"]["BeforeTool"].as_array().unwrap();- assert_eq!(before_tool.len(), 2);- assert!(before_tool[0]["matcher"] == "other");- assert!(gemini_entry_is_ours(&before_tool[1]));+ // Installing twice adds nothing more.+ assert_eq!(merged(&after).unwrap(), after);- let cleaned = without_gemini_ours(&after).unwrap();+ // And removing ours puts it back exactly as it was.+ let cleaned = without_ours(&after).unwrap();assert_eq!(cleaned, existing);}#[test]- fn a_fingerprint_notices_any_change() {- assert_eq!(fingerprint(b"{}"), fingerprint(b"{}"));- assert_ne!(fingerprint(b"{}"), fingerprint(b"{ }"));- assert_ne!(fingerprint(b""), fingerprint(b"{}"));- }-- #[cfg(unix)]- #[test]- fn the_hook_path_is_one_shell_word_whatever_it_contains() {- assert_eq!(sh_quote("/home/a b/x"), "'/home/a b/x'");- // $, backticks, backslashes and double quotes stay literal in single quotes.- assert_eq!(sh_quote(r#"/h/$(id)`x`\"y"#), r#"'/h/$(id)`x`\"y'"#);- // A single quote closes, escapes and reopens.- assert_eq!(sh_quote("/h/it's"), r"'/h/it'\''s'");- }-- /// settings.json can carry API keys in its `env` block: rewriting it must- /// never make it readable by more people than before.- #[cfg(unix)]- #[test]- fn rewriting_settings_never_widens_its_permissions() {- use std::os::unix::fs::PermissionsExt;- let dir = std::env::temp_dir().join(format!("coucou-perm-{}", std::process::id()));- let _ = std::fs::remove_dir_all(&dir);- std::fs::create_dir_all(&dir).unwrap();- let original = dir.join("settings.json");- let temp = dir.join("settings.json.new");- let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;-- for wanted in [0o600, 0o640, 0o644] {- std::fs::write(&original, b"{}").unwrap();- std::fs::set_permissions(&original, std::fs::Permissions::from_mode(wanted)).unwrap();- let _ = std::fs::remove_file(&temp);- write_like(&temp, &original, b"{\"a\":1}").unwrap();- assert_eq!(mode(&temp), wanted, "the rewrite must keep {wanted:o}");+ fn values_of_an_unexpected_type_are_refused_not_replaced() {+ for odd in [+ json!({ "hooks": "a string" }),+ json!({ "hooks": [1, 2] }),+ json!({ "hooks": { "PreToolUse": { "not": "a list" } } }),+ ] {+ assert!(merged(&odd).is_err(), "{odd}");}-- // No original: ours only.- std::fs::remove_file(&original).unwrap();- let _ = std::fs::remove_file(&temp);- write_like(&temp, &original, b"{}").unwrap();- assert_eq!(mode(&temp), 0o600);-- let _ = std::fs::remove_dir_all(&dir);+ assert!(without_ours(&json!({ "hooks": 3 })).is_err());+ // An event we do not install stays as it is, whatever its shape.+ let kept = json!({ "hooks": { "Custom": "anything" } });+ assert_eq!(without_ours(&kept).unwrap(), kept);}/// Everything filesystem-shaped lives in one test on purpose: it pointsdiff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rsindex d0fb31bd..06ef6602 100644--- a/windows/src-tauri/src/lib.rs+++ b/windows/src-tauri/src/lib.rs@@ -1,6 +1,8 @@// Coucou for Windows — app wiring and the commands the island calls.+mod agents;mod claude;+mod config_file;mod files;mod hooks;mod integrations;@@ -49,9 +51,8 @@ pub struct BootInfo {#[tauri::command]fn boot(app: AppHandle, shared: State<Shared>) -> BootInfo {let mut settings = shared.settings.lock().unwrap().clone();- // The real state of ~/.claude/settings.json and ~/.gemini/settings.json wins over whatever we stored.+ // The real state of ~/.claude/settings.json wins over whatever we stored.settings.hooks_installed = hooks::status().installed;- settings.gemini_hooks_installed = hooks::gemini_status().installed;let screen = island::screen_info(&app, &settings.screen);BootInfo {settings,@@ -223,34 +224,27 @@ fn hooks_apply(Ok(backup)}-// ── Gemini CLI hooks ──────────────────────────────────────────────────────────+// ── Other agents' hooks and plugins ──────────────────────────────────────────#[tauri::command]-fn gemini_hooks_status() -> HookStatus {- hooks::gemini_status()+fn agent_hooks_list() -> Vec<agents::AgentStatus> {+ agents::list()}+/// The diff the user has to look at before anything is written.#[tauri::command]-fn gemini_hooks_preview(install: bool) -> Result<HookPreview, String> {- hooks::gemini_preview(install)+fn agent_hooks_preview(agent: String, install: bool) -> Result<config_file::Plan, String> {+ agents::preview(&agent, install)}+/// Only ever called from an explicit click in the settings window, with the+/// fingerprint of the preview the user looked at.#[tauri::command]-fn gemini_hooks_apply(- app: AppHandle,- shared: State<Shared>,- install: bool,- fingerprint: String,-) -> Result<String, String> {- let backup = hooks::gemini_write(install, &fingerprint)?;- let updated = {- let mut current = shared.settings.lock().unwrap();- current.gemini_hooks_installed = install;- let _ = settings::save(¤t);- current.clone()- };- let _ = app.emit("settings-changed", updated);- Ok(backup)+fn agent_hooks_apply(agent: String, install: bool, fingerprint: String) -> Result<String, String> {+ let backups = agents::apply(&agent, install, &fingerprint)?;+ let done = if install { "installed" } else { "removed" };+ log::line(format!("agent hooks {done} for {agent}"));+ Ok(backups)}#[tauri::command]@@ -440,9 +434,9 @@ pub fn run() {hooks_status,hooks_preview,hooks_apply,- gemini_hooks_status,- gemini_hooks_preview,- gemini_hooks_apply,+ agent_hooks_list,+ agent_hooks_preview,+ agent_hooks_apply,approval_decision,approval_answer,approval_ack,diff --git a/windows/src-tauri/src/settings.rs b/windows/src-tauri/src/settings.rsindex 3a4e4fe2..17f63e1c 100644--- a/windows/src-tauri/src/settings.rs+++ b/windows/src-tauri/src/settings.rs@@ -21,8 +21,6 @@ pub struct Settings {pub screen: String,pub autostart: bool,pub hooks_installed: bool,- #[serde(default)]- pub gemini_hooks_installed: bool,/// Claude model used by the chat. Changeable in the settings window.pub model: String,}@@ -47,7 +45,6 @@ impl Default for Settings {screen: "primary".into(),autostart: false,hooks_installed: false,- gemini_hooks_installed: false,model: default_model(),}}diff --git a/windows/src/core/bridge.ts b/windows/src/core/bridge.tsindex b9c6b518..6ce02053 100644--- a/windows/src/core/bridge.ts+++ b/windows/src/core/bridge.ts@@ -76,12 +76,17 @@ export const Bridge = {hooksApply: (install: boolean, fingerprint: string) =>callOrThrow<string>("hooks_apply", { install, fingerprint }),- // ── Gemini CLI hooks ───────────────────────────────────────────────────────- geminiHooksStatus: () => call<HookStatus>("gemini_hooks_status"),- geminiHooksPreview: (install: boolean) =>- callOrThrow<HookPreview>("gemini_hooks_preview", { install }),- geminiHooksApply: (install: boolean, fingerprint: string) =>- callOrThrow<string>("gemini_hooks_apply", { install, fingerprint }),+ // ── Other agents (Gemini CLI, Codex, Cursor…) ─────────────────────────────+ agentHooksList: () => call<AgentHookStatus[]>("agent_hooks_list"),+ /** Diff to show before anything is written. `install: false` previews removal. */+ agentHooksPreview: (agent: string, install: boolean) =>+ callOrThrow<AgentHookPlan>("agent_hooks_preview", { agent, install }),+ /**+ * Writes the agent's config — only ever after an explicit click, and only when+ * it still matches the preview the user looked at. Returns the backups taken.+ */+ agentHooksApply: (agent: string, install: boolean, fingerprint: string) =>+ callOrThrow<string>("agent_hooks_apply", { agent, install, fingerprint }),approvalDecision: (requestId: string, decision: "allow" | "deny") =>call<void>("approval_decision", { requestId, decision }),@@ -139,6 +144,29 @@ export interface HookStatus {hookReady: boolean;}+/** One agent other than Claude Code, as agents.rs reports it. */+export interface AgentHookStatus {+ /** The `--agent` name; its pill is `agent_<id>`. */+ id: string;+ name: string;+ installed: boolean;+ /** The file (or files, one per line) Coucou writes. */+ path: string;+ hookReady: boolean;+ /** The island can allow or deny this agent's permission requests. */+ approvals: boolean;+ /** What to do once it is written. */+ note: string;+}++export interface AgentHookPlan {+ diff: string;+ /** Where each existing file is copied first, one per line; "" when none. */+ backup: string;+ path: string;+ fingerprint: string;+}+export interface HookPreview {diff: string;backup: string;diff --git a/windows/src/core/state.ts b/windows/src/core/state.tsindex e60d5d2b..4785897a 100644--- a/windows/src/core/state.ts+++ b/windows/src/core/state.ts@@ -105,7 +105,6 @@ export interface Settings {screen: string;autostart: boolean;hooksInstalled: boolean;- geminiHooksInstalled: boolean;/** Claude model used by the chat. */model: string;}@@ -121,7 +120,6 @@ export const DEFAULT_SETTINGS: Settings = {screen: "primary",autostart: false,hooksInstalled: false,- geminiHooksInstalled: false,model: "claude-opus-5",};diff --git a/windows/src/settings/agents.ts b/windows/src/settings/agents.tsnew file mode 100644index 00000000..82f7f198--- /dev/null+++ b/windows/src/settings/agents.ts@@ -0,0 +1,137 @@+// Settings → Agents: one section for every agent other than Claude Code, all+// going through the same steps — preview the exact diff, click to confirm, and+// only then does agents.rs back the file up and write it.++import { Bridge, type AgentHookStatus } from "../core/bridge";+import { clear, h } from "../views/dom";+import { renderDiff, statusDot } from "./parts";++const TEXT = {+ title: "Agents",+ intro:+ "Show other coding agents in the island. Coucou adds its entries to each agent's own config: you see the exact change and where the backup goes before anything is written, and uninstalling removes only what Coucou added.",+ none: "Coucou could not list the agents.",+ approvals: "Sessions, and Allow / Deny from the island",+ displayOnly: "Sessions — approvals stay in the agent",+ install: "Install…",+ reinstall: "Reinstall…",+ uninstall: "Uninstall…",+ relayMissing: "The relay isn't installed yet. Restart Coucou.",+ previewInstall: (name: string) =>+ `This is exactly what changes for ${name}. Nothing else is touched.`,+ previewRemove: "This removes Coucou's entries only. Everything else stays.",+ backup: (to: string) => (to ? `Backup → ${to}` : "No existing file — nothing to back up."),+ confirmInstall: "Back up and write",+ confirmRemove: "Back up and remove",+ cancel: "Cancel",+ back: "Back",+ done: (backups: string, note: string) =>+ `Done.${backups ? ` Previous version saved as ${backups.split("\n").join(", ")}.` : ""} ${note}`,+ failed: (err: unknown) => `Could not write: ${errorText(err)}`,+};++function errorText(err: unknown): string {+ return String(err).replace(/^Error:\s*/, "");+}++export function agentsSection(list: AgentHookStatus[] | null): HTMLElement {+ const blocks = h("div", { style: "display:flex;flex-direction:column;gap:14px" });+ if (!list || list.length === 0) {+ blocks.append(h("div", { class: "hint", text: TEXT.none }));+ }+ for (const status of list ?? []) blocks.append(agentBlock(status));+ return h(+ "section",+ {},+ h("h2", {}, h("span", { text: TEXT.title })),+ h("div", { class: "hint", text: TEXT.intro }),+ blocks,+ );+}++function agentBlock(initial: AgentHookStatus): HTMLElement {+ let status = initial;+ const head = h("div", { class: "row" });+ const body = h("div", { style: "display:flex;flex-direction:column;gap:10px" });+ const block = h("div", { style: "display:flex;flex-direction:column;gap:8px" }, head, body);++ async function refresh() {+ const fresh = (await Bridge.agentHooksList())?.find((a) => a.id === status.id);+ if (fresh) status = fresh;+ draw();+ }++ function draw() {+ clear(head);+ clear(body);+ const install = h("button", {+ class: "primary",+ text: status.installed ? TEXT.reinstall : TEXT.install,+ onclick: () => void showPreview(true),+ });+ // A hook pointing at a relay that isn't there would break the agent's hooks.+ if (!status.hookReady) {+ install.disabled = true;+ install.title = TEXT.relayMissing;+ }+ head.append(+ h("div", { style: "display:flex;align-items:center;gap:8px;min-width:132px" },+ statusDot(status.installed),+ h("span", { style: "font-size:12.5px", text: status.name }),+ ),+ h("span", { class: "hint", text: status.approvals ? TEXT.approvals : TEXT.displayOnly }),+ h("span", { class: "spacer" }),+ install,+ );+ if (status.installed) {+ head.append(h("button", {+ class: "danger",+ text: TEXT.uninstall,+ onclick: () => void showPreview(false),+ }));+ }+ body.append(h("span", { class: "path", text: status.path }));+ }++ async function showPreview(install: boolean) {+ let plan;+ try {+ plan = await Bridge.agentHooksPreview(status.id, install);+ } catch (err) {+ // An unreadable or unexpected config stops here rather than being+ // treated as empty and written over.+ clear(body);+ body.append(+ h("div", { class: "notice err", text: errorText(err) }),+ h("div", { class: "row" }, h("button", { text: TEXT.back, onclick: draw })),+ );+ return;+ }+ clear(body);+ body.append(+ h("div", { class: "hint", text: install ? TEXT.previewInstall(status.name) : TEXT.previewRemove }),+ renderDiff(plan.diff),+ h("div", { class: "row" }, h("span", { class: "path", text: TEXT.backup(plan.backup) })),+ );+ const confirm = h("button", {+ class: install ? "primary" : "danger",+ text: install ? TEXT.confirmInstall : TEXT.confirmRemove,+ });+ confirm.addEventListener("click", async () => {+ confirm.disabled = true;+ try {+ const backups = await Bridge.agentHooksApply(status.id, install, plan.fingerprint);+ clear(body);+ body.append(h("div", { class: "notice ok", text: TEXT.done(backups, install ? status.note : "") }));+ window.setTimeout(() => void refresh(), 2600);+ } catch (err) {+ confirm.disabled = false;+ body.append(h("div", { class: "notice err", text: TEXT.failed(err) }));+ }+ });+ body.append(h("div", { class: "row" }, confirm, h("button", { text: TEXT.cancel, onclick: draw })));+ }++ draw();+ return block;+}diff --git a/windows/src/settings/main.ts b/windows/src/settings/main.tsindex 7f9b0690..8009de7e 100644--- a/windows/src/settings/main.ts+++ b/windows/src/settings/main.ts@@ -6,6 +6,8 @@ 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";+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")@@ -33,19 +35,6 @@ function toggle(on: boolean, onChange: (v: boolean) => void): HTMLElement {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 {@@ -144,7 +133,12 @@ function claudeSection(status: HookStatus): HTMLElement {}),renderDiff(preview.diff),h("div", { class: "row" },- h("span", { class: "path", text: `Backup → ${preview.backup}` }),+ h("span", {+ class: "path",+ text: preview.backup+ ? `Backup → ${preview.backup}`+ : "No settings.json yet — nothing to back up.",+ }),),);const confirm = h("button", {@@ -158,133 +152,10 @@ function claudeSection(status: HookStatus): HTMLElement {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;-}--// ── Gemini CLI section ────────────────────────────────────────────────────────--function geminiSection(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: "Gemini CLI" })),- body,- );-- const rebuild = async () => {- const fresh = await Bridge.geminiHooksStatus();- if (fresh) Object.assign(status, fresh);- clear(body);- draw();- const head = section.querySelector("h2")!;- clear(head);- head.append(statusDot(status.installed), h("span", { text: "Gemini CLI" }));- };-- function draw() {- body.append(- h("div", {- class: "hint",- text: status.installed- ? "Coucou is hooked into your Gemini CLI sessions (~/.gemini/settings.json). Tool calls and steps show up in the island."- : "Install the hooks in ~/.gemini/settings.json to see your Gemini CLI sessions and tool calls in the island.",- }),- 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),- });- if (!status.hookReady) {- install.disabled = true;- install.title = "The relay isn't installed yet.";- }- 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) {- let preview;- try {- preview = await Bridge.geminiHooksPreview(install);- } catch (err) {- clear(body);- body.append(- h("div", { class: "notice err", text: String(err).replace(/^Error:\s*/, "") }),- h("div", { class: "row" }, h("button", {- text: "Back",- onclick: () => { clear(body); draw(); },- })),- );- return;- }- if (!preview) return;- clear(body);- body.append(- h("div", {- class: "hint",- text: install- ? "This is exactly what will change in ~/.gemini/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.geminiHooksApply(install, preview.fingerprint);- clear(body);- body.append(h("div", {- class: "notice ok",- text: `Done. Previous settings saved as ${backup}. Open a new Gemini CLI session to pick the hooks up.`,+ // No backup when there was no settings.json to back up.+ text: backup+ ? `Done. Previous settings saved as ${backup}. Open a new Claude Code session to pick the hooks up.`+ : "Done. Open a new Claude Code session to pick the hooks up.",}));window.setTimeout(() => void rebuild(), 2600);} catch (err) {@@ -574,9 +445,7 @@ async function main() {const status = (await Bridge.hooksStatus()) ?? {installed: false, settingsPath: "", hookPath: "", hookReady: false,};- const geminiStatus = (await Bridge.geminiHooksStatus()) ?? {- installed: false, settingsPath: "", hookPath: "", hookReady: false,- };+ const agents = await Bridge.agentHooksList();const hasKey = (await Bridge.secretPresent("anthropic-api-key")) ?? false;@@ -591,7 +460,7 @@ async function main() {root.append(h("h1", {}, h("span", { text: "Coucou" }), h("span", { class: "version", text: version })),claudeSection(status),- geminiSection(geminiStatus),+ agentsSection(agents),apiSection(hasKey),integrationsSection(present),generalSection(),diff --git a/windows/src/settings/parts.ts b/windows/src/settings/parts.tsnew file mode 100644index 00000000..7704ee3e--- /dev/null+++ b/windows/src/settings/parts.ts@@ -0,0 +1,16 @@+// Small pieces every settings section draws with.++import { h } from "../views/dom";++export function statusDot(ok: boolean): HTMLElement {+ return h("i", { class: "dot", style: `background:${ok ? "#22c55e" : "#f4505e"}` });+}++export 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;+}diff --git a/windows/tests/hooks.test.mjs b/windows/tests/hooks.test.mjsindex 93eaa2fb..d99862fb 100644--- a/windows/tests/hooks.test.mjs+++ b/windows/tests/hooks.test.mjs@@ -211,7 +211,7 @@ test("a tagged agent gets its own pill next to Claude Code's", () => {assert.equal(State.tasks[0].id, CLAUDE);assert.equal(State.tasks[1].id, "agent_gemini");const agent = task("agent_gemini");- assert.equal(agent.name, "gemini");+ assert.equal(agent.name, "Gemini CLI");assert.equal(agent.source, "agent");assert.equal(agent.state, "working");assert.deepEqual(agent.steps, ["Exécute · ls"]);