Skip to content

A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.

Windows 0.1.1: make approving from the island actually work

Louis Raillee436978432bc
diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml
index aa05174c..478b1f67 100644
--- a/.github/workflows/windows.yml
+++ b/.github/workflows/windows.yml
@@ -41,13 +41,23 @@ jobs:
- name: Install dependencies
run: npm ci
- - name: Check the tag matches the app version
+ # Three files carry the version and they drift silently. Publishing a
+ # "0.1.1" that installs a 0.1.0 is the kind of thing nobody notices until
+ # a bug report arrives against the wrong build.
+ - name: Check the tag and every version agree
if: startsWith(github.ref, 'refs/tags/windows-v')
shell: pwsh
run: |
- $tag = "${{ github.ref_name }}" -replace '^windows-v', ''
+ $tag = "${{ github.ref_name }}" -replace '^windows-v', ''
$conf = (Get-Content src-tauri/tauri.conf.json | ConvertFrom-Json).version
- if ($tag -ne $conf) { throw "tag says $tag but tauri.conf.json says $conf" }
+ $pkg = (Get-Content package.json | ConvertFrom-Json).version
+ $cargo = (Select-String -Path Cargo.toml -Pattern '^version\s*=\s*"(.+)"').Matches[0].Groups[1].Value
+ "tag=$tag tauri.conf=$conf package.json=$pkg Cargo.toml=$cargo"
+ $bad = @()
+ if ($tag -ne $conf) { $bad += "tauri.conf.json says $conf" }
+ if ($tag -ne $pkg) { $bad += "package.json says $pkg" }
+ if ($tag -ne $cargo) { $bad += "Cargo.toml says $cargo" }
+ if ($bad) { throw "tag says $tag but $($bad -join '; ')" }
# `npm run build` (run by tauri as beforeBuildCommand) builds coucou-hook
# first, which tauri.conf.json then bundles as a resource. `pack` then
@@ -99,6 +109,11 @@ jobs:
$v = "${{ steps.pack.outputs.version }}"
$exists = gh release view windows-latest 2>$null
if ($LASTEXITCODE -eq 0) {
+ # The tag has to follow the release, or windows-latest keeps pointing
+ # at the first commit it was ever created from and anyone building
+ # from it gets an old tree.
+ git tag -f windows-latest "${{ github.sha }}"
+ git push -f origin windows-latest
gh release edit windows-latest --title "Coucou for Windows (latest)" --notes "Always the newest Windows build — currently $v."
gh release upload windows-latest "release/Coucou-Windows-setup.exe" --clobber
} else {
diff --git a/windows/.gitignore b/windows/.gitignore
index 359c1964..0dc27bc1 100644
--- a/windows/.gitignore
+++ b/windows/.gitignore
@@ -6,3 +6,8 @@ release/
# Generated by tauri-build on every compile
src-tauri/gen/schemas/
+
+# Local secrets and overrides — never committed.
+.env
+.env.*
+!.env.example
diff --git a/windows/Cargo.lock b/windows/Cargo.lock
index 726cad74..ac0c6001 100644
--- a/windows/Cargo.lock
+++ b/windows/Cargo.lock
@@ -571,7 +571,7 @@ dependencies = [
[[package]]
name = "coucou"
-version = "0.1.0"
+version = "0.1.1"
dependencies = [
"keyring",
"reqwest 0.12.28",
@@ -587,9 +587,10 @@ dependencies = [
[[package]]
name = "coucou-hook"
-version = "0.1.0"
+version = "0.1.1"
dependencies = [
"serde_json",
+ "windows 0.61.3",
]
[[package]]
@@ -3265,6 +3266,7 @@ version = "1.0.151"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
dependencies = [
+ "indexmap 2.14.2",
"itoa",
"memchr",
"serde",
diff --git a/windows/Cargo.toml b/windows/Cargo.toml
index 873d4b31..9041a677 100644
--- a/windows/Cargo.toml
+++ b/windows/Cargo.toml
@@ -3,7 +3,7 @@ members = ["src-tauri", "hook"]
resolver = "2"
[workspace.package]
-version = "0.1.0"
+version = "0.1.1"
edition = "2021"
license = "MIT"
diff --git a/windows/hook/Cargo.toml b/windows/hook/Cargo.toml
index 434c45b2..18a01545 100644
--- a/windows/hook/Cargo.toml
+++ b/windows/hook/Cargo.toml
@@ -11,3 +11,13 @@ path = "src/main.rs"
[dependencies]
serde_json = "1"
+
+# Just enough Win32 to know our own SID and to check who is serving the pipe.
+[target.'cfg(windows)'.dependencies]
+windows = { version = "0.61", features = [
+ "Win32_Foundation",
+ "Win32_Security",
+ "Win32_Security_Authorization",
+ "Win32_System_Pipes",
+ "Win32_System_Threading",
+] }
diff --git a/windows/hook/src/main.rs b/windows/hook/src/main.rs
index 2421f09f..a3c85a1a 100644
--- a/windows/hook/src/main.rs
+++ b/windows/hook/src/main.rs
@@ -1,15 +1,17 @@
//! coucou-hook — the relay Claude Code runs on every hook event.
//!
//! Reads the hook JSON on stdin, adds a little terminal context, and hands it to
-//! Coucou over the named pipe `\\.\pipe\coucou-<user>`.
+//! Coucou over the named pipe `\\.\pipe\coucou-<sid>`.
//!
//! Hard rule (docs/CLAUDE.md): **never block Claude Code.**
-//! * Connecting is given 300 ms. If Coucou is closed, slow or crashed we exit 0
-//! with nothing on stdout and the session carries on untouched.
-//! * Only `PermissionRequest` then waits for an answer, because that is the whole
-//! point of approving from the island. If no answer arrives in time we still
-//! exit 0 with an empty stdout, so Claude Code falls back to asking in the
-//! terminal instead of us silently denying anything.
+//! * If the pipe does not exist — Coucou is closed — we exit 0 immediately with
+//! nothing on stdout, and the session carries on untouched.
+//! * Every step runs under a deadline enforced by the main thread, so a pipe that
+//! accepts the connection and then stops reading cannot wedge the session
+//! either: we abandon the worker and exit.
+//! * Only `PermissionRequest` waits for an answer, because approving from the
+//! island is the whole point. No answer means empty stdout, and Claude Code
+//! asks in the terminal exactly as if Coucou were not installed.
//!
//! Usage: `coucou-hook <EventName>` (the name is also read from the JSON).
@@ -19,45 +21,111 @@ use std::time::{Duration, Instant};
/// Budget for getting a pipe connection. Beyond this Claude Code wins, always.
const CONNECT_TIMEOUT: Duration = Duration::from_millis(300);
+/// Whole-run budget for an event nobody waits on: connect and write, no more.
+const FIRE_AND_FORGET_BUDGET: Duration = Duration::from_secs(2);
/// How long a permission prompt may stay on screen before the terminal takes over.
-const DECISION_TIMEOUT: Duration = Duration::from_secs(110);
+const DECISION_BUDGET: Duration = Duration::from_secs(110);
+/// `ERROR_PIPE_BUSY` — every instance is serving someone else right now. This is
+/// the one error worth retrying: the server exists and a slot will free up.
+const ERROR_PIPE_BUSY: i32 = 231;
+
+/// Fields that are pointless to forward and can be enormous (a whole file read,
+/// a full command output). The island never shows them.
+const DROPPED_FIELDS: &[&str] = &["tool_response", "transcript_path"];
+/// Longest string forwarded for any single field; the island truncates to far
+/// less than this anyway.
+const MAX_FIELD_LEN: usize = 2_000;
+
+mod win;
+
+/// `\\.\pipe\coucou-<sid>`. The SID keeps two accounts on the same machine from
+/// ever meeting on the same pipe; the name falls back to the user name only if
+/// the SID cannot be read at all, which should not happen.
fn pipe_path() -> String {
- let user = std::env::var("USERNAME").unwrap_or_else(|_| "user".into());
- format!(r"\\.\pipe\coucou-{user}")
+ let key = win::current_user_sid()
+ .unwrap_or_else(|| std::env::var("USERNAME").unwrap_or_else(|_| "user".into()));
+ format!(r"\\.\pipe\coucou-{key}")
}
-/// Opens the pipe, retrying while the server is busy, within CONNECT_TIMEOUT.
+/// Opens the pipe. Retries only while the server is busy: any other error means
+/// there is nothing to talk to, and waiting would only delay Claude Code.
fn connect() -> Option<std::fs::File> {
+ use std::os::windows::io::AsRawHandle;
let path = pipe_path();
let deadline = Instant::now() + CONNECT_TIMEOUT;
loop {
match std::fs::OpenOptions::new().read(true).write(true).open(&path) {
- Ok(file) => return Some(file),
- Err(_) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(15)),
- Err(_) => return None,
+ Ok(file) => {
+ let handle = windows::Win32::Foundation::HANDLE(file.as_raw_handle());
+ // Somebody else's server on our pipe name gets nothing from us.
+ return win::pipe_server_is_same_user(handle).then_some(file);
+ }
+ Err(err) => {
+ if err.raw_os_error() != Some(ERROR_PIPE_BUSY) || Instant::now() >= deadline {
+ return None;
+ }
+ std::thread::sleep(Duration::from_millis(15));
+ }
}
}
}
fn main() {
- // Any unexpected problem must still be a clean exit.
- let _ = std::panic::catch_unwind(run);
+ let Some((payload, event)) = read_event() else { std::process::exit(0) };
+
+ let waits_for_answer = event == "PermissionRequest";
+ let budget = if waits_for_answer { DECISION_BUDGET } else { FIRE_AND_FORGET_BUDGET };
+
+ // The worker owns every blocking call. If it overruns the budget we simply
+ // stop listening and exit: the process dying takes the pipe handle with it.
+ // (No catch_unwind here — the release profile is panic = "abort", so it would
+ // be dead code. `talk` is written to have nothing to panic on instead.)
+ let (tx, rx) = mpsc::channel::<Option<String>>();
+ std::thread::spawn(move || {
+ let _ = tx.send(talk(&payload, waits_for_answer));
+ });
+
+ if let Ok(Some(decision)) = rx.recv_timeout(budget) {
+ if let Some(json) = decision_json(&decision) {
+ let mut out = std::io::stdout();
+ let _ = writeln!(out, "{json}");
+ let _ = out.flush();
+ }
+ }
+ // Nothing printed: Claude Code asks in the terminal, as if we were not here.
std::process::exit(0);
}
-fn run() {
+/// The documented PermissionRequest output. Anything we do not recognise prints
+/// nothing at all rather than guessing — silence is the safe answer.
+/// See https://code.claude.com/docs/en/hooks
+fn decision_json(decision: &str) -> Option<String> {
+ let behavior = match decision.trim() {
+ // "always" still answers a plain allow; remembering it is the island's
+ // business, not Claude Code's.
+ "allow" | "always" => r#"{"behavior":"allow"}"#.to_string(),
+ "deny" => r#"{"behavior":"deny","message":"Denied from Coucou"}"#.to_string(),
+ _ => return None,
+ };
+ Some(format!(
+ r#"{{"hookSpecificOutput":{{"hookEventName":"PermissionRequest","decision":{behavior}}}}}"#
+ ))
+}
+
+/// Reads stdin and returns the payload to forward plus the event name.
+fn read_event() -> Option<(String, String)> {
let mut raw = Vec::new();
if std::io::stdin().read_to_end(&mut raw).is_err() || raw.is_empty() {
- return;
+ return None;
}
// 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 };
+ let mut payload = serde_json::from_slice::<serde_json::Value>(&raw).ok()?;
+ let map = payload.as_object_mut()?;
// The event name is passed as argv[1] by the hook command; the JSON usually
// carries it too. Trust argv when the JSON is missing it.
@@ -67,9 +135,13 @@ fn run() {
.and_then(|v| v.as_str())
.map(str::to_string)
.filter(|s| !s.is_empty())
- .unwrap_or_else(|| arg_event.clone());
+ .unwrap_or(arg_event);
map.insert("hook_event_name".into(), serde_json::Value::String(event.clone()));
+ for field in DROPPED_FIELDS {
+ map.remove(*field);
+ }
+
let cwd_missing = map
.get("cwd")
.and_then(|v| v.as_str())
@@ -99,45 +171,96 @@ fn run() {
}
}
- let Some(mut pipe) = connect() else { return };
+ truncate_strings(&mut payload);
let mut line = payload.to_string();
line.push('\n');
- if pipe.write_all(line.as_bytes()).is_err() {
- return;
+ Some((line, event))
+}
+
+/// Caps every string in the payload. A single Write can carry a whole file.
+fn truncate_strings(value: &mut serde_json::Value) {
+ match value {
+ serde_json::Value::String(s) => {
+ if s.len() > MAX_FIELD_LEN {
+ // Cut on a char boundary; a lone byte index can split UTF-8.
+ let mut end = MAX_FIELD_LEN;
+ while end > 0 && !s.is_char_boundary(end) {
+ end -= 1;
+ }
+ s.truncate(end);
+ s.push('…');
+ }
+ }
+ serde_json::Value::Array(items) => items.iter_mut().for_each(truncate_strings),
+ serde_json::Value::Object(map) => map.values_mut().for_each(truncate_strings),
+ _ => {}
+ }
+}
+
+/// Connect, send, and — for a permission request — wait for the island's word.
+fn talk(payload: &str, waits_for_answer: bool) -> Option<String> {
+ let mut pipe = connect()?;
+
+ if pipe.write_all(payload.as_bytes()).is_err() {
+ return None;
}
let _ = pipe.flush();
- if event != "PermissionRequest" {
- return; // fire and forget
+ if !waits_for_answer {
+ return None;
}
- // Wait for the island's decision on a helper thread so the timeout is real.
- let (tx, rx) = mpsc::channel::<String>();
- std::thread::spawn(move || {
- let mut buf = Vec::new();
- let mut chunk = [0u8; 1024];
- loop {
- match pipe.read(&mut chunk) {
- Ok(0) => break,
- Ok(n) => {
- buf.extend_from_slice(&chunk[..n]);
- if buf.contains(&b'\n') {
- break;
- }
+ let mut buf = Vec::new();
+ let mut chunk = [0u8; 1024];
+ loop {
+ match pipe.read(&mut chunk) {
+ Ok(0) => break,
+ Ok(n) => {
+ buf.extend_from_slice(&chunk[..n]);
+ if buf.contains(&b'\n') {
+ break;
}
- Err(_) => break,
}
+ Err(_) => break,
}
- let _ = tx.send(String::from_utf8_lossy(&buf).trim().to_string());
- });
+ }
+ let answer = String::from_utf8_lossy(&buf).trim().to_string();
+ (!answer.is_empty()).then_some(answer)
+}
- if let Ok(response) = rx.recv_timeout(DECISION_TIMEOUT) {
- if response.contains("permissionDecision") {
- let mut out = std::io::stdout();
- let _ = writeln!(out, "{response}");
- let _ = out.flush();
- }
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn decision_json_matches_the_documented_shape() {
+ assert_eq!(
+ decision_json("allow").unwrap(),
+ r#"{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":"allow"}}}"#
+ );
+ assert_eq!(
+ decision_json("deny").unwrap(),
+ r#"{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":"deny","message":"Denied from Coucou"}}}"#
+ );
+ // "always" is an island concept; Claude Code just gets an allow.
+ assert!(decision_json("always").unwrap().contains(r#""behavior":"allow""#));
+ }
+
+ #[test]
+ fn anything_unrecognised_prints_nothing() {
+ assert!(decision_json("").is_none());
+ assert!(decision_json("maybe").is_none());
+ // The shape the app used to send must not be mistaken for a decision.
+ assert!(decision_json(r#"{"permissionDecision":"allow"}"#).is_none());
+ }
+
+ #[test]
+ fn long_strings_are_cut_on_a_char_boundary() {
+ let mut v = serde_json::json!({ "tool_input": { "content": "é".repeat(4000) } });
+ truncate_strings(&mut v);
+ let s = v["tool_input"]["content"].as_str().unwrap();
+ assert!(s.len() <= MAX_FIELD_LEN + 4);
+ assert!(s.ends_with('…'));
}
- // No answer: stdout stays empty and Claude Code asks in the terminal.
}
diff --git a/windows/hook/src/win.rs b/windows/hook/src/win.rs
new file mode 100644
index 00000000..75f1aa2e
--- /dev/null
+++ b/windows/hook/src/win.rs
@@ -0,0 +1,76 @@
+//! The little bit of Win32 the relay needs: who we are, and who is on the other
+//! end of the pipe.
+//!
+//! Named pipes live in a machine-wide namespace, so `\\.\pipe\coucou-<name>` can
+//! be created by *any* account that gets there first. Two defences, both cheap:
+//! the pipe name carries our SID, and once connected we check the server process
+//! really belongs to us before sending anything.
+
+use windows::core::PWSTR;
+use windows::Win32::Foundation::{CloseHandle, HANDLE, LocalFree, HLOCAL};
+use windows::Win32::Security::Authorization::ConvertSidToStringSidW;
+use windows::Win32::Security::{GetTokenInformation, TokenUser, TOKEN_QUERY, TOKEN_USER};
+use windows::Win32::System::Pipes::GetNamedPipeServerProcessId;
+use windows::Win32::System::Threading::{
+ GetCurrentProcess, OpenProcess, OpenProcessToken, PROCESS_QUERY_LIMITED_INFORMATION,
+};
+
+/// The SID of the account this process runs as, as `S-1-5-21-…`.
+pub fn current_user_sid() -> Option<String> {
+ unsafe { token_sid(GetCurrentProcess()) }
+}
+
+/// True when the process serving `handle` runs as the same user we do.
+///
+/// A failure to answer is treated as "not ours": refusing to talk to a pipe we
+/// cannot vouch for costs one hook event, while trusting it could hand another
+/// account on this machine the contents of every tool call.
+pub fn pipe_server_is_same_user(handle: HANDLE) -> bool {
+ let Some(mine) = current_user_sid() else { return false };
+ unsafe {
+ let mut pid = 0u32;
+ if GetNamedPipeServerProcessId(handle, &mut pid).is_err() || pid == 0 {
+ return false;
+ }
+ let Ok(process) = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) else {
+ return false;
+ };
+ let theirs = token_sid(process);
+ let _ = CloseHandle(process);
+ theirs.as_deref() == Some(mine.as_str())
+ }
+}
+
+/// The user SID behind a process handle. `process` is borrowed, never closed.
+unsafe fn token_sid(process: HANDLE) -> Option<String> {
+ let mut token = HANDLE::default();
+ OpenProcessToken(process, TOKEN_QUERY, &mut token).ok()?;
+
+ // First call sizes the buffer, second fills it.
+ let mut needed = 0u32;
+ let _ = GetTokenInformation(token, TokenUser, None, 0, &mut needed);
+ if needed == 0 {
+ let _ = CloseHandle(token);
+ return None;
+ }
+ let mut buf = vec![0u8; needed as usize];
+ let ok = GetTokenInformation(
+ token,
+ TokenUser,
+ Some(buf.as_mut_ptr().cast()),
+ needed,
+ &mut needed,
+ )
+ .is_ok();
+ let _ = CloseHandle(token);
+ if !ok {
+ return None;
+ }
+
+ let user = &*(buf.as_ptr() as *const TOKEN_USER);
+ let mut text = PWSTR::null();
+ ConvertSidToStringSidW(user.User.Sid, &mut text).ok()?;
+ let sid = text.to_string().ok();
+ let _ = LocalFree(Some(HLOCAL(text.0 as *mut _)));
+ sid
+}
diff --git a/windows/package.json b/windows/package.json
index cc533b1b..22931d9b 100644
--- a/windows/package.json
+++ b/windows/package.json
@@ -1,7 +1,7 @@
{
"name": "coucou-windows",
"private": true,
- "version": "0.1.0",
+ "version": "0.1.1",
"type": "module",
"scripts": {
"dev": "vite",
diff --git a/windows/src-tauri/Cargo.toml b/windows/src-tauri/Cargo.toml
index 3f68db11..0274d9f5 100644
--- a/windows/src-tauri/Cargo.toml
+++ b/windows/src-tauri/Cargo.toml
@@ -18,14 +18,17 @@ tauri = { version = "2", features = ["tray-icon"] }
tauri-plugin-single-instance = "2"
tauri-plugin-autostart = "2"
serde = { version = "1", features = ["derive"] }
-serde_json = "1"
+serde_json = { version = "1", features = ["preserve_order"] }
tokio = { version = "1", features = ["net", "io-util", "sync", "time", "rt"] }
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
keyring = { version = "3", features = ["windows-native"] }
windows = { version = "0.61", features = [
"Win32_Foundation",
+ "Win32_Security",
+ "Win32_Security_Authorization",
"Win32_System_Ole",
"Win32_System_SystemInformation",
+ "Win32_System_Threading",
"Win32_UI_Input_KeyboardAndMouse",
"Win32_UI_WindowsAndMessaging",
] }
diff --git a/windows/src-tauri/nsis/hooks.nsh b/windows/src-tauri/nsis/hooks.nsh
new file mode 100644
index 00000000..89123584
--- /dev/null
+++ b/windows/src-tauri/nsis/hooks.nsh
@@ -0,0 +1,17 @@
+; Uninstall hooks for the NSIS installer.
+;
+; The app stages coucou-hook.exe into %LOCALAPPDATA%\Coucou\bin at launch, so the
+; installer never recorded it and the default uninstaller leaves it behind. The
+; inbox and the log live in the same place and are ours too.
+;
+; Claude Code's own settings.json is deliberately NOT touched here: it belongs to
+; the user, it may contain hooks from other tools, and rewriting somebody's
+; config from an uninstaller with no diff and no consent is exactly what the rest
+; of this app goes out of its way not to do. A relay that is gone exits 0 without
+; printing anything, so a leftover entry costs nothing beyond a dead path.
+
+!macro NSIS_HOOK_PREUNINSTALL
+ RMDir /r "$LOCALAPPDATA\Coucou\bin"
+ RMDir /r "$LOCALAPPDATA\Coucou\inbox"
+ Delete "$LOCALAPPDATA\Coucou\coucou.log"
+!macroend
diff --git a/windows/src-tauri/src/files.rs b/windows/src-tauri/src/files.rs
index 7e711344..d43e5d4d 100644
--- a/windows/src-tauri/src/files.rs
+++ b/windows/src-tauri/src/files.rs
@@ -52,6 +52,12 @@ pub fn ingest(source: &str) -> Result<DroppedFile, String> {
}
std::fs::copy(src, &dest).map_err(|e| format!("cannot copy: {e}"))?;
+ // CopyFileEx carries the source's timestamps across, so a file last edited
+ // three years ago would arrive already older than the sweep window and be
+ // deleted on the spot. The inbox ages from when *we* copied it.
+ if let Ok(file) = std::fs::File::options().write(true).open(&dest) {
+ let _ = file.set_modified(SystemTime::now());
+ }
sweep(&dir);
Ok(DroppedFile {
@@ -61,13 +67,16 @@ pub fn ingest(source: &str) -> Result<DroppedFile, String> {
})
}
+/// Drops anything copied here more than a week ago. `ingest` stamps every copy
+/// with the time it landed, so this really is the age of the copy and not the
+/// age of whatever the user happened to drag in.
fn sweep(dir: &Path) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
let now = SystemTime::now();
for entry in entries.flatten() {
let Ok(meta) = entry.metadata() else { continue };
- let Ok(modified) = meta.modified() else { continue };
- if now.duration_since(modified).map(|age| age > KEEP_FOR).unwrap_or(false) {
+ let Ok(copied) = meta.modified() else { continue };
+ if now.duration_since(copied).map(|age| age > KEEP_FOR).unwrap_or(false) {
let _ = std::fs::remove_file(entry.path());
}
}
@@ -98,6 +107,23 @@ mod tests {
// Folders are refused rather than silently ignored.
assert!(ingest(tmp.to_str().unwrap()).is_err());
+ // An ancient source must not arrive already older than the sweep window.
+ let old_source = tmp.join("ancient.txt");
+ std::fs::write(&old_source, b"old").unwrap();
+ let long_ago = SystemTime::now() - KEEP_FOR - Duration::from_secs(60 * 60);
+ std::fs::File::options()
+ .write(true)
+ .open(&old_source)
+ .unwrap()
+ .set_modified(long_ago)
+ .unwrap();
+ let aged = ingest(old_source.to_str().unwrap()).unwrap();
+ assert!(
+ Path::new(&aged.path).exists(),
+ "a file copied just now was swept as if it were a week old"
+ );
+ let _ = std::fs::remove_file(&aged.path);
+
let _ = std::fs::remove_file(&first.path);
let _ = std::fs::remove_file(&second.path);
let _ = std::fs::remove_dir_all(&tmp);
diff --git a/windows/src-tauri/src/hooks.rs b/windows/src-tauri/src/hooks.rs
index fff4ea5f..0e3e32d1 100644
--- a/windows/src-tauri/src/hooks.rs
+++ b/windows/src-tauri/src/hooks.rs
@@ -53,6 +53,9 @@ pub struct HookPreview {
pub diff: String,
pub backup: String,
pub settings_path: String,
+ /// Identifies the bytes this diff was computed from; handed back to `write`
+ /// so we only ever apply what the user actually looked at.
+ pub fingerprint: String,
}
fn home() -> PathBuf {
@@ -65,11 +68,47 @@ 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!({}),
+/// 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.
+fn read_settings_lossy() -> Value {
+ read_settings().unwrap_or_else(|_| json!({}))
}
fn hook_command(event: &str) -> String {
@@ -155,11 +194,13 @@ 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 = unsafe { GetLocalTime() };
format!(
- "{:04}{:02}{:02}-{:02}{:02}",
- t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute
+ "{:04}{:02}{:02}-{:02}{:02}{:02}",
+ t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond
)
}
@@ -168,10 +209,28 @@ fn backup_path() -> PathBuf {
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 status() -> HookStatus {
- let current = read_settings();
+ let current = read_settings_lossy();
let installed = current
.get("hooks")
.and_then(Value::as_object)
@@ -192,23 +251,38 @@ pub fn status() -> HookStatus {
}
}
-pub fn preview(install: bool) -> HookPreview {
- let current = read_settings();
+pub fn preview(install: bool) -> Result<HookPreview, String> {
+ let current = read_settings()?;
let next = if install { merged(&current) } else { without_ours(&current) };
- HookPreview {
+ Ok(HookPreview {
diff: unified_diff(&pretty(&current), &pretty(&next)),
backup: backup_path().to_string_lossy().to_string(),
settings_path: settings_path().to_string_lossy().to_string(),
- }
+ fingerprint: current_fingerprint(),
+ })
}
/// Writes the merged (or cleaned) settings after taking a dated backup.
-pub fn write(install: bool) -> Result<String, String> {
+///
+/// `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.
+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())?;
- let current = read_settings();
+ // 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}"))?;
@@ -217,13 +291,27 @@ pub fn write(install: bool) -> Result<String, String> {
let next = if install { merged(&current) } else { without_ours(&current) };
let mut text = pretty(&next);
text.push('\n');
- std::fs::write(&path, text).map_err(|e| e.to_string())?;
+
+ // 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()));
+ std::fs::write(&temp, text.as_bytes()).map_err(|e| format!("write failed: {e}"))?;
+ 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())
}
/// 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.
+///
+/// Every candidate is tried rather than just the first, because getting this
+/// wrong is silent and fatal: `resources` used to be a glob, which made NSIS
+/// mirror the source path into `_up_\target\release\`, no candidate matched, and
+/// the relay was simply never installed. It only looked healthy on a developer
+/// machine, where a leftover copy from `tauri dev` was already sitting in bin/.
pub fn ensure_hook_exe(app: &AppHandle) {
let dest = settings::hook_exe_path();
let Some(dir) = dest.parent() else { return };
@@ -241,11 +329,17 @@ pub fn ensure_hook_exe(app: &AppHandle) {
// release hook the pre-build step produces.
candidates.push(parent.join("coucou-hook.exe"));
candidates.push(parent.join("../release/coucou-hook.exe"));
+ // Belt and braces: where the old glob form used to land it.
+ candidates.push(parent.join("_up_/target/release/coucou-hook.exe"));
}
}
+ let tried: Vec<String> = candidates.iter().map(|p| p.display().to_string()).collect();
let Some(src) = candidates.into_iter().find(|p| p.exists()) else {
- eprintln!("[coucou] coucou-hook.exe not found — run `cargo build -p coucou-hook`");
+ crate::log::line(format!(
+ "coucou-hook.exe not found — Claude Code hooks cannot work. Looked in: {}",
+ tried.join(", ")
+ ));
return;
};
@@ -259,7 +353,9 @@ pub fn ensure_hook_exe(app: &AppHandle) {
// 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}");
+ if !dest.exists() {
+ crate::log::line(format!("could not install coucou-hook.exe: {err}"));
+ }
}
}
@@ -338,3 +434,132 @@ fn unified_diff(before: &str, after: &str) -> String {
}
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!({
+ "model": "claude-opus-5",
+ "theme": "dark",
+ "enabledPlugins": ["a", "b"],
+ "hooks": {
+ "PreToolUse": [
+ { "hooks": [{ "type": "command", "command": "someone-elses-tool.exe" }] }
+ ],
+ "SomeEventWeDoNotTouch": [
+ { "hooks": [{ "type": "command", "command": "keep-me.exe" }] }
+ ]
+ }
+ });
+
+ let after = merged(&existing);
+ assert_eq!(after["model"], "claude-opus-5");
+ assert_eq!(after["theme"], "dark");
+ assert_eq!(after["enabledPlugins"], serde_json::json!(["a", "b"]));
+
+ let pre = after["hooks"]["PreToolUse"].as_array().unwrap();
+ assert!(
+ pre.iter().any(|e| serde_json::to_string(e).unwrap().contains("someone-elses-tool.exe")),
+ "another tool's hook was dropped"
+ );
+ 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 a_fingerprint_notices_any_change() {
+ assert_eq!(fingerprint(b"{}"), fingerprint(b"{}"));
+ assert_ne!(fingerprint(b"{}"), fingerprint(b"{ }"));
+ assert_ne!(fingerprint(b""), fingerprint(b"{}"));
+ }
+
+ /// Everything filesystem-shaped lives in one test on purpose: it points
+ /// USERPROFILE at a temp directory, and that is process-wide.
+ #[test]
+ fn writing_backs_up_preserves_and_refuses_a_changed_file() {
+ let tmp = std::env::temp_dir().join(format!("coucou-hooks-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&tmp);
+ std::fs::create_dir_all(tmp.join(".claude")).unwrap();
+ std::env::set_var("USERPROFILE", &tmp);
+
+ let path = settings_path();
+ assert!(path.starts_with(&tmp), "the test must not touch the real home");
+
+ // A real-shaped file, written the way PowerShell 5 would: UTF-8 with BOM.
+ let original = r#"{"model":"claude-opus-5","theme":"dark","tui":{"x":1},"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"other-tool.exe"}]}]}}"#;
+ let mut bytes = vec![0xEF, 0xBB, 0xBF];
+ bytes.extend_from_slice(original.as_bytes());
+ std::fs::write(&path, &bytes).unwrap();
+
+ // Install.
+ let plan = preview(true).expect("a BOM must not stop the preview");
+ assert!(plan.diff.contains("coucou-hook"), "the diff must show what changes");
+ let backup = write(true, &plan.fingerprint).expect("install should succeed");
+
+ // The backup holds the original bytes, BOM and all.
+ assert_eq!(std::fs::read(&backup).unwrap(), bytes);
+
+ // Everything else survived, and so did the other tool's hook.
+ let after: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
+ assert_eq!(after["model"], "claude-opus-5");
+ assert_eq!(after["theme"], "dark");
+ assert_eq!(after["tui"]["x"], 1);
+ let pre = after["hooks"]["PreToolUse"].as_array().unwrap();
+ assert!(pre.iter().any(|e| serde_json::to_string(e).unwrap().contains("other-tool.exe")));
+ assert!(status().installed);
+
+ // A file that moved since the preview is refused, and left alone.
+ let stale = preview(false).unwrap();
+ std::fs::write(&path, br#"{"model":"someone-else-edited-this"}"#).unwrap();
+ let err = write(false, &stale.fingerprint).unwrap_err();
+ assert!(err.contains("changed since the preview"), "got: {err}");
+ let untouched: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
+ assert_eq!(untouched["model"], "someone-else-edited-this");
+
+ // Content we cannot parse is refused before anything is written.
+ std::fs::write(&path, b"{ broken").unwrap();
+ assert!(preview(true).is_err());
+ assert!(write(true, "whatever").is_err());
+ assert_eq!(std::fs::read(&path).unwrap(), b"{ broken");
+
+ let _ = std::fs::remove_dir_all(&tmp);
+ }
+}
diff --git a/windows/src-tauri/src/integrations.rs b/windows/src-tauri/src/integrations.rs
index 5c305b83..d666b997 100644
--- a/windows/src-tauri/src/integrations.rs
+++ b/windows/src-tauri/src/integrations.rs
@@ -8,12 +8,13 @@
// Nothing is polled until its key exists in the Credential Manager, and no
// request goes anywhere the user has not configured.
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
use std::time::Duration;
use serde::Serialize;
use serde_json::{json, Value};
-use tauri::{AppHandle, Emitter};
+use tauri::{AppHandle, Emitter, Manager};
use crate::island::WINDOW_LABEL;
use crate::log;
@@ -51,18 +52,36 @@ fn client() -> reqwest::Client {
.unwrap_or_default()
}
+/// Set from the tray's Pause item. While it is on, nothing reaches the network:
+/// pausing Coucou has to mean pausing Coucou, not just hiding the island.
+pub static PAUSED: AtomicBool = AtomicBool::new(false);
+
+pub fn set_paused(on: bool) {
+ PAUSED.store(on, Ordering::Relaxed);
+}
+
/// Spawns every poller with the macOS delays and intervals.
pub fn start(app: AppHandle) {
- spawn(app.clone(), 3, 15, poll_n8n);
- spawn(app.clone(), 5, 30, poll_vercel);
- spawn(app.clone(), 6, 30, poll_stripe);
- spawn(app.clone(), 6, 60, poll_resend);
- spawn(app.clone(), 7, 300, poll_github);
- spawn(app.clone(), 8, 300, poll_calcom);
- spawn(app, 9, 300, poll_notion);
+ spawn(app.clone(), "integration_n8n", 3, 15, poll_n8n);
+ spawn(app.clone(), "integration_vercel", 5, 30, poll_vercel);
+ spawn(app.clone(), "integration_stripe", 6, 30, poll_stripe);
+ spawn(app.clone(), "integration_resend", 6, 60, poll_resend);
+ spawn(app.clone(), "integration_github", 7, 300, poll_github);
+ spawn(app.clone(), "integration_calcom", 8, 300, poll_calcom);
+ spawn(app, "integration_notion", 9, 300, poll_notion);
+}
+
+/// True when the user has this integration switched on in settings.
+fn enabled(app: &AppHandle, id: &str) -> bool {
+ app.try_state::<crate::Shared>()
+ .map(|shared| {
+ let settings = shared.settings.lock().unwrap();
+ settings.active_integrations.iter().any(|x| x == id)
+ })
+ .unwrap_or(false)
}
-fn spawn<F, Fut>(app: AppHandle, delay_secs: u64, every_secs: u64, poll: F)
+fn spawn<F, Fut>(app: AppHandle, id: &'static str, delay_secs: u64, every_secs: u64, poll: F)
where
F: Fn(AppHandle) -> Fut + Send + 'static,
Fut: std::future::Future<Output = ()> + Send,
@@ -72,6 +91,13 @@ where
let mut ticker = tokio::time::interval(Duration::from_secs(every_secs));
loop {
ticker.tick().await;
+ // The ticker keeps its cadence; we just decline to do the work. An
+ // integration the user switched off, or a paused app, must make no
+ // network calls at all — CLAUDE.md allows talking only to services
+ // the user configured, and a disabled one is not configured.
+ if PAUSED.load(Ordering::Relaxed) || !enabled(&app, id) {
+ continue;
+ }
poll(app.clone()).await;
}
});
@@ -601,7 +627,8 @@ async fn poll_n8n(app: AppHandle) {
continue;
};
if !response.status().is_success() {
- log::line(format!("n8n list HTTP {} on {url}", response.status()));
+ // Only the status: a self-hosted base URL can carry credentials.
+ log::line(format!("n8n list HTTP {}", response.status()));
continue;
}
let Ok(json) = response.json::<Value>().await else { continue };
diff --git a/windows/src-tauri/src/island.rs b/windows/src-tauri/src/island.rs
index 5ec9d912..0a4fc878 100644
--- a/windows/src-tauri/src/island.rs
+++ b/windows/src-tauri/src/island.rs
@@ -257,16 +257,51 @@ pub fn set_activating(win: &WebviewWindow, activating: bool) {
}
}
+/// Position, size and scale of the monitor the island lives on. Any change here
+/// means the island has to be placed again.
+fn current_screen_key(app: &AppHandle) -> Option<(i32, i32, u32, u32, u64)> {
+ let pref = app
+ .try_state::<crate::Shared>()
+ .map(|s| s.settings.lock().unwrap().screen.clone())
+ .unwrap_or_else(|| "primary".into());
+ let m = target_monitor(app, &pref)?;
+ let p = m.position();
+ let size = m.size();
+ Some((p.x, p.y, size.width, size.height, m.scale_factor().to_bits()))
+}
+
/// Emits `cursor` (window-logical coordinates) at ~60 Hz while the island is
/// visible. Parked on a condvar the rest of the time.
pub fn spawn_cursor_poll(app: AppHandle, gate: Arc<PollGate>) {
std::thread::spawn(move || {
let mut was_down = false;
+ // Remembered across wakes so a display change while hidden is noticed the
+ // moment the island comes back.
+ let mut last_screen: Option<(i32, i32, u32, u32, u64)> = None;
loop {
gate.wait_until_active();
let mut last = (f64::MIN, f64::MIN);
+ let mut ticks: u32 = 0;
while gate.is_active() {
std::thread::sleep(Duration::from_millis(16));
+
+ // Monitors get plugged in, unplugged, rearranged and rescaled, and
+ // an island pinned to coordinates that no longer exist is an island
+ // nobody can reach. Checked about twice a second — the cursor poll
+ // is already running, so this costs one monitor query.
+ ticks = ticks.wrapping_add(1);
+ if ticks % 30 == 0 {
+ let now = current_screen_key(&app);
+ if now.is_some() && now != last_screen {
+ let first = last_screen.is_none();
+ last_screen = now;
+ if !first {
+ crate::log::line("display layout changed — repositioning".to_string());
+ let _ = app.emit_to(WINDOW_LABEL, "screen-changed", ());
+ }
+ }
+ }
+
let Some(win) = window(&app) else { continue };
let Ok(origin) = win.outer_position() else { continue };
let scale = win.scale_factor().unwrap_or(1.0);
diff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rs
index 209f238b..5d19db6c 100644
--- a/windows/src-tauri/src/lib.rs
+++ b/windows/src-tauri/src/lib.rs
@@ -10,6 +10,7 @@ mod pipe;
mod secrets;
mod settings;
mod tray;
+mod win_user;
use std::os::windows::process::CommandExt;
use std::process::Command;
@@ -135,16 +136,12 @@ fn open_url(url: String) {
/// and falls back to Explorer otherwise.
#[tauri::command]
fn open_in_vscode(path: Option<String>) -> bool {
- let has_code = Command::new("cmd")
- .args(["/C", "where", "code"])
- .creation_flags(CREATE_NO_WINDOW)
- .status()
- .map(|s| s.success())
- .unwrap_or(false);
-
- if has_code {
- let mut cmd = Command::new("cmd");
- cmd.arg("/C").arg("code");
+ // No `cmd /C` anywhere near this. The path is a project folder chosen by
+ // whoever is using Claude Code, and cmd would happily read `&`, `^` and `%`
+ // in a folder name as syntax. Finding the launcher ourselves and handing the
+ // path over as a separate argument keeps it a path.
+ if let Some(code) = find_on_path("code") {
+ let mut cmd = Command::new(code);
if let Some(p) = path.as_deref().filter(|p| !p.is_empty()) {
cmd.arg(p);
}
@@ -158,11 +155,35 @@ fn open_in_vscode(path: Option<String>) -> bool {
false
}
+/// Our own `where`: walks %PATH% against %PATHEXT%, no shell involved.
+/// Rust quotes arguments correctly for `.cmd`/`.bat` targets since 1.77, so
+/// spawning `code.cmd` directly is safe.
+fn find_on_path(stem: &str) -> Option<std::path::PathBuf> {
+ let exts = std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".into());
+ let dirs = std::env::var_os("PATH")?;
+ for dir in std::env::split_paths(&dirs) {
+ for ext in exts.split(';').filter(|e| !e.is_empty()) {
+ let candidate = dir.join(format!("{stem}{}", ext.to_lowercase()));
+ if candidate.is_file() {
+ return Some(candidate);
+ }
+ }
+ }
+ None
+}
+
#[tauri::command]
fn quit_app(app: AppHandle) {
app.exit(0);
}
+/// Tray → Pause. Paused means paused: the pollers stop talking to the network,
+/// not just the island stopping showing things.
+#[tauri::command]
+fn set_paused(paused: bool) {
+ integrations::set_paused(paused);
+}
+
// ── Claude Code hooks ─────────────────────────────────────────────────────────
#[tauri::command]
@@ -172,14 +193,21 @@ fn hooks_status() -> HookStatus {
/// Returns the diff the user has to look at before anything is written.
#[tauri::command]
-fn hooks_preview(install: bool) -> HookPreview {
+fn hooks_preview(install: bool) -> Result<HookPreview, String> {
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)?;
+fn hooks_apply(
+ app: AppHandle,
+ shared: State<Shared>,
+ install: bool,
+ fingerprint: String,
+) -> Result<String, String> {
+ // The fingerprint comes from the preview the user actually looked at, so a
+ // settings.json that changed in between is refused rather than overwritten.
+ let backup = hooks::write(install, &fingerprint)?;
let updated = {
let mut current = shared.settings.lock().unwrap();
current.hooks_installed = install;
@@ -195,6 +223,21 @@ fn approval_decision(app: AppHandle, request_id: String, decision: String) {
pipe::answer(&app, &request_id, &decision);
}
+/// The island has the card on screen, so the long wait for a human may begin.
+/// Until this arrives the relay only waits a few hundred milliseconds, which is
+/// what stops a paused or unresponsive island from freezing Claude Code.
+#[tauri::command]
+fn approval_ack(app: AppHandle, request_id: String) {
+ pipe::acknowledge(&app, &request_id);
+}
+
+/// Nobody can act on this request — the island is paused, or another card is
+/// already up. Claude Code falls back to asking in the terminal immediately.
+#[tauri::command]
+fn approval_decline(app: AppHandle, request_id: String) {
+ pipe::decline(&app, &request_id);
+}
+
// ── Chat, files and secrets ───────────────────────────────────────────────────
/// One chat turn. The API key and any file bytes stay on the Rust side.
@@ -351,6 +394,8 @@ pub fn run() {
hooks_preview,
hooks_apply,
approval_decision,
+ approval_ack,
+ approval_decline,
log_line,
chat_send,
chat_reset,
@@ -361,6 +406,7 @@ pub fn run() {
refresh_integration,
open_n8n,
open_settings_window,
+ set_paused,
])
.setup(move |app| {
let handle = app.handle().clone();
diff --git a/windows/src-tauri/src/pipe.rs b/windows/src-tauri/src/pipe.rs
index fd81589e..f8cd71c4 100644
--- a/windows/src-tauri/src/pipe.rs
+++ b/windows/src-tauri/src/pipe.rs
@@ -1,13 +1,21 @@
// Named-pipe server for coucou-hook.
//
-// `\\.\pipe\coucou-<user>` — one instance per connection. Every hook event is
+// `\\.\pipe\coucou-<sid>` — 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.
+// Claude Code is never blocked by us. Three things guarantee it:
+// * coucou-hook gives the connection 300 ms and exits cleanly if we are closed;
+// * we only wait for a human once the island has *confirmed* the card is on
+// screen, so a paused island or a webview that is not listening costs a few
+// hundred milliseconds, not two minutes;
+// * whatever happens we drop the connection after the decision timeout, and
+// the terminal takes over.
+//
+// What we write back is the bare word `allow` or `deny`. Turning that into the
+// documented hookSpecificOutput JSON is coucou-hook's job, so the wire format
+// Claude Code expects lives in exactly one place.
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
@@ -18,33 +26,52 @@ 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 tokio::sync::mpsc;
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);
+/// How long the island gets to say "the card is up". This is the whole of B4:
+/// without it, an island that is paused, hidden behind a crashed webview or
+/// simply not listening would leave Claude Code staring at a prompt nobody can
+/// see for nearly two minutes.
+const ACK_TIMEOUT: Duration = Duration::from_millis(800);
const MAX_PAYLOAD: usize = 1 << 20;
-/// Permission requests waiting for a click in the island.
+/// What the island can say about a permission request.
+pub enum Reply {
+ /// The card is on screen and a human can act on it.
+ Ack,
+ /// A human clicked: `allow` or `deny`.
+ Decision(String),
+ /// Nobody can act on it — paused, or another request already holds the card.
+ Decline,
+}
+
+/// Permission requests the island has been told about.
#[derive(Default)]
-pub struct Pending(pub Mutex<HashMap<String, oneshot::Sender<String>>>);
+pub struct Pending(pub Mutex<HashMap<String, mpsc::Sender<Reply>>>);
static COUNTER: AtomicU64 = AtomicU64::new(1);
+/// `\\.\pipe\coucou-<sid>` — must match coucou-hook's `pipe_path()` exactly.
pub fn pipe_name() -> String {
- let user = std::env::var("USERNAME").unwrap_or_else(|_| "user".into());
- format!(r"\\.\pipe\coucou-{user}")
+ let key = crate::win_user::current_user_sid()
+ .unwrap_or_else(|| std::env::var("USERNAME").unwrap_or_else(|_| "user".into()));
+ format!(r"\\.\pipe\coucou-{key}")
}
pub fn start(app: AppHandle) {
tauri::async_runtime::spawn(async move {
let name = pipe_name();
+ // first_pipe_instance also means we refuse to join a pipe somebody else
+ // already owns under our name, rather than serving on top of it.
let mut server = match ServerOptions::new().first_pipe_instance(true).create(&name) {
Ok(s) => s,
Err(err) => {
- eprintln!("[coucou] cannot open {name}: {err}");
+ log::line(format!("cannot open the relay pipe: {err}"));
return;
}
};
@@ -57,7 +84,7 @@ pub fn start(app: AppHandle) {
let next = match ServerOptions::new().create(&name) {
Ok(s) => s,
Err(err) => {
- eprintln!("[coucou] cannot reopen {name}: {err}");
+ log::line(format!("cannot reopen the relay pipe: {err}"));
return;
}
};
@@ -106,27 +133,18 @@ async fn handle(app: AppHandle, mut pipe: NamedPipeServer) {
}
let id = format!("{}-{}", std::process::id(), COUNTER.fetch_add(1, Ordering::Relaxed));
- let (tx, rx) = oneshot::channel::<String>();
+ let (tx, mut rx) = mpsc::channel::<Reply>(4);
{
let pending = app.state::<Pending>();
- let mut map = pending.0.lock().unwrap();
- map.insert(id.clone(), tx);
+ pending.0.lock().unwrap().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,
- };
+ let decision = wait_for_decision(&id, &mut rx).await;
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 {
@@ -136,19 +154,74 @@ async fn handle(app: AppHandle, mut pipe: NamedPipeServer) {
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"}"#,
+/// Two waits: a short one for "the card is up", then the long one for a human.
+async fn wait_for_decision(id: &str, rx: &mut mpsc::Receiver<Reply>) -> Option<String> {
+ match tokio::time::timeout(ACK_TIMEOUT, rx.recv()).await {
+ Ok(Some(Reply::Ack)) => {}
+ // A click that beats the ack is still a click.
+ Ok(Some(Reply::Decision(d))) => {
+ log::line(format!("hook id={id} answered {d}"));
+ return Some(d);
+ }
+ Ok(Some(Reply::Decline)) => {
+ log::line(format!("hook id={id} not shown — terminal takes over"));
+ return None;
+ }
+ Ok(None) => return None,
+ Err(_) => {
+ log::line(format!("hook id={id} island never acknowledged — terminal takes over"));
+ return None;
+ }
+ }
+
+ match tokio::time::timeout(DECISION_TIMEOUT, rx.recv()).await {
+ Ok(Some(Reply::Decision(d))) => {
+ log::line(format!("hook id={id} answered {d}"));
+ Some(d)
+ }
+ Ok(Some(Reply::Decline)) => {
+ log::line(format!("hook id={id} released without a decision"));
+ None
+ }
+ _ => {
+ log::line(format!("hook id={id} timed out — terminal takes over"));
+ None
+ }
+ }
+}
+
+fn send(app: &AppHandle, request_id: &str, reply: Reply, keep: bool) {
+ let sender = {
+ let pending = app.state::<Pending>();
+ let mut map = pending.0.lock().unwrap();
+ if keep { map.get(request_id).cloned() } else { map.remove(request_id) }
};
- 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());
+ let _ = tx.try_send(reply);
}
- None => log::line(format!("decision id={request_id} {decision} — no pending request")),
+ None => log::line(format!("reply for id={request_id} — no pending request")),
}
}
+
+/// The island has the card on screen; the long wait may begin.
+pub fn acknowledge(app: &AppHandle, request_id: &str) {
+ send(app, request_id, Reply::Ack, true);
+}
+
+/// Nobody can act on this one — paused, or another card already holds the view.
+pub fn decline(app: &AppHandle, request_id: &str) {
+ log::line(format!("decline id={request_id}"));
+ send(app, request_id, Reply::Decline, false);
+}
+
+/// Called by the island's Allow / Deny buttons. Only ever a bare word: turning
+/// it into Claude Code's JSON is coucou-hook's job.
+pub fn answer(app: &AppHandle, request_id: &str, decision: &str) {
+ let word = match decision {
+ "allow" | "always" => "allow",
+ _ => "deny",
+ };
+ log::line(format!("decision id={request_id} {word}"));
+ send(app, request_id, Reply::Decision(word.to_string()), false);
+}
diff --git a/windows/src-tauri/src/win_user.rs b/windows/src-tauri/src/win_user.rs
new file mode 100644
index 00000000..001b759d
--- /dev/null
+++ b/windows/src-tauri/src/win_user.rs
@@ -0,0 +1,48 @@
+// Who we are, for the relay pipe name.
+//
+// Named pipes share one machine-wide namespace, so the SID in the name is what
+// keeps two accounts on the same machine from ever meeting on `coucou-*`.
+// coucou-hook computes the same string (hook/src/win.rs) and additionally checks
+// that the process serving the pipe really is us.
+
+use windows::core::PWSTR;
+use windows::Win32::Foundation::{CloseHandle, HANDLE, HLOCAL, LocalFree};
+use windows::Win32::Security::Authorization::ConvertSidToStringSidW;
+use windows::Win32::Security::{GetTokenInformation, TokenUser, TOKEN_QUERY, TOKEN_USER};
+use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
+
+/// The SID of the account this process runs as, as `S-1-5-21-…`.
+pub fn current_user_sid() -> Option<String> {
+ unsafe {
+ let mut token = HANDLE::default();
+ OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token).ok()?;
+
+ // First call sizes the buffer, second fills it.
+ let mut needed = 0u32;
+ let _ = GetTokenInformation(token, TokenUser, None, 0, &mut needed);
+ if needed == 0 {
+ let _ = CloseHandle(token);
+ return None;
+ }
+ let mut buf = vec![0u8; needed as usize];
+ let ok = GetTokenInformation(
+ token,
+ TokenUser,
+ Some(buf.as_mut_ptr().cast()),
+ needed,
+ &mut needed,
+ )
+ .is_ok();
+ let _ = CloseHandle(token);
+ if !ok {
+ return None;
+ }
+
+ let user = &*(buf.as_ptr() as *const TOKEN_USER);
+ let mut text = PWSTR::null();
+ ConvertSidToStringSidW(user.User.Sid, &mut text).ok()?;
+ let sid = text.to_string().ok();
+ let _ = LocalFree(Some(HLOCAL(text.0 as *mut _)));
+ sid
+ }
+}
diff --git a/windows/src-tauri/tauri.conf.json b/windows/src-tauri/tauri.conf.json
index 38afee18..d292d1b1 100644
--- a/windows/src-tauri/tauri.conf.json
+++ b/windows/src-tauri/tauri.conf.json
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Coucou",
- "version": "0.1.0",
+ "version": "0.1.1",
"identifier": "fr.louisraille.coucou",
"build": {
"beforeDevCommand": "npm run dev",
@@ -12,7 +12,8 @@
"app": {
"withGlobalTauri": false,
"security": {
- "csp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self' ipc: http://ipc.localhost ws://localhost:1420 http://localhost:1420"
+ "csp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self' ipc: http://ipc.localhost",
+ "devCsp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self' ipc: http://ipc.localhost ws://localhost:1420 http://localhost:1420"
},
"windows": [
{
@@ -47,7 +48,7 @@
"icons/icon.ico"
],
- "resources": ["../target/release/coucou-hook*.exe"],
+ "resources": { "../target/release/coucou-hook.exe": "coucou-hook.exe" },
"copyright": "© Louis Raille",
"category": "DeveloperTool",
"shortDescription": "Mochi lives at the top of your screen",
@@ -55,7 +56,8 @@
"windows": {
"nsis": {
"installMode": "currentUser",
- "languages": ["English", "French"]
+ "languages": ["English", "French"],
+ "installerHooks": "nsis/hooks.nsh"
}
}
}
diff --git a/windows/src/core/bridge.ts b/windows/src/core/bridge.ts
index eb77c5dc..2967337e 100644
--- a/windows/src/core/bridge.ts
+++ b/windows/src/core/bridge.ts
@@ -63,12 +63,20 @@ export const Bridge = {
// ── 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 }),
+ hooksPreview: (install: boolean) => callOrThrow<HookPreview>("hooks_preview", { install }),
+ /**
+ * Writes ~/.claude/settings.json — only ever after an explicit click, and only
+ * when the file still matches the preview the user looked at.
+ */
+ hooksApply: (install: boolean, fingerprint: string) =>
+ callOrThrow<string>("hooks_apply", { install, fingerprint }),
- approvalDecision: (requestId: string, decision: "allow" | "deny" | "always") =>
+ approvalDecision: (requestId: string, decision: "allow" | "deny") =>
call<void>("approval_decision", { requestId, decision }),
+ /** "The card is up" — until this lands the relay only waits a moment. */
+ approvalAck: (requestId: string) => call<void>("approval_ack", { requestId }),
+ /** "Nobody can act on this" — Claude Code asks in the terminal right away. */
+ approvalDecline: (requestId: string) => call<void>("approval_decline", { requestId }),
// ── Chat, files, secrets ──────────────────────────────────────────────────
/** One chat turn. The API key and any file bytes never leave Rust. */
@@ -86,6 +94,9 @@ export const Bridge = {
refreshIntegration: (id: string) => call<void>("refresh_integration", { id }),
/** Opens the configured n8n instance in the browser. */
openN8n: () => call<void>("open_n8n"),
+
+ /** Tray → Pause. Stops the integration pollers, not just the island. */
+ setPaused: (paused: boolean) => call<void>("set_paused", { paused }),
};
export interface IntegrationUpdate {
@@ -116,6 +127,8 @@ export interface HookPreview {
diff: string;
backup: string;
settingsPath: string;
+ /** Hand back to hooksApply so only the reviewed diff is ever written. */
+ fingerprint: string;
}
/** Same as `call`, but surfaces the error so the UI can show what went wrong. */
diff --git a/windows/src/core/sound.ts b/windows/src/core/sound.ts
index 8b0fdae0..b5178554 100644
--- a/windows/src/core/sound.ts
+++ b/windows/src/core/sound.ts
@@ -20,6 +20,7 @@ class SoundEngine {
private master: GainNode | null = null;
private buffers = new Map<string, AudioBuffer>();
private loading: Promise<void> | null = null;
+ private idleTimer: number | null = null;
/** Creates the context and decodes every WAV. Safe to call more than once. */
preload(): Promise<void> {
@@ -51,9 +52,29 @@ class SoundEngine {
/** WebView2 can hand us a suspended context; call after any user input. */
resume() {
+ if (this.idleTimer != null) {
+ window.clearTimeout(this.idleTimer);
+ this.idleTimer = null;
+ }
void this.ctx?.resume();
}
+ /**
+ * Called when the island goes quiet. A running AudioContext keeps an audio
+ * thread and its render quantum alive even with nothing playing, which shows
+ * up as a steady trickle of CPU on a machine that is supposed to be idle.
+ *
+ * The delay covers the tail of whatever just played — suspending mid-sound
+ * would clip it — and `play()` resumes the context on its own.
+ */
+ idle() {
+ if (!this.ctx || this.ctx.state !== "running" || this.idleTimer != null) return;
+ this.idleTimer = window.setTimeout(() => {
+ this.idleTimer = null;
+ void this.ctx?.suspend();
+ }, 1500);
+ }
+
setVolume(v: number) {
this.volume = Math.max(0, Math.min(0.2, v));
if (this.master) this.master.gain.value = this.volume;
@@ -69,6 +90,10 @@ class SoundEngine {
const master = this.master;
const buf = this.buffers.get(name);
if (!ctx || !master || !buf) return;
+ if (this.idleTimer != null) {
+ window.clearTimeout(this.idleTimer);
+ this.idleTimer = null;
+ }
if (ctx.state === "suspended") void ctx.resume();
const src = ctx.createBufferSource();
src.buffer = buf;
diff --git a/windows/src/core/state.ts b/windows/src/core/state.ts
index d628f27e..e4988b8e 100644
--- a/windows/src/core/state.ts
+++ b/windows/src/core/state.ts
@@ -137,7 +137,6 @@ class AppState {
searchResult: SearchResult | null = null;
chatHistory: ChatMessage[] = [];
pendingApproval: ApprovalInfo | null = null;
- alwaysAllow = false;
integrations: Record<string, IntegrationInfo> = {};
diff --git a/windows/src/island/hooks.ts b/windows/src/island/hooks.ts
index 8b682335..547b1679 100644
--- a/windows/src/island/hooks.ts
+++ b/windows/src/island/hooks.ts
@@ -3,7 +3,7 @@
// Difference from macOS: no terminal filter. On Windows the hook fires from any
// terminal (Windows Terminal, VS Code, PowerShell…) and all of them are handled.
-import { onEvent } from "../core/bridge";
+import { Bridge, onEvent } from "../core/bridge";
import { Sound } from "../core/sound";
import { State } from "../core/state";
import type { Island } from "./island";
@@ -19,6 +19,8 @@ interface HookPayload {
session_id?: string;
cwd?: string;
message?: string;
+ /** UserPromptSubmit carries `prompt`; `message` belongs to Notification/Stop. */
+ prompt?: string;
tool_name?: string;
tool_input?: Record<string, unknown>;
}
@@ -71,6 +73,34 @@ function stepLabel(tool: string, input: Record<string, unknown>): string {
return label;
}
+/**
+ * What the Allow button actually authorises. Approving "Write" tells you nothing
+ * — approving `Write · C:\…\.env` tells you everything, and the difference is
+ * the whole point of approving from the island rather than blind.
+ *
+ * Ordered by how specific the field is, so an unfamiliar tool still shows
+ * whatever identifying string it carries instead of falling back to its name.
+ */
+const APPROVAL_FIELDS = [
+ "command", // Bash, PowerShell
+ "file_path", // Write, Edit, MultiEdit, NotebookEdit
+ "path", // Read, LS
+ "url", // WebFetch
+ "query", // WebSearch
+ "pattern", // Glob, Grep
+ "prompt", // Task
+] as const;
+
+function approvalTarget(tool: string, input: Record<string, unknown>): string {
+ for (const field of APPROVAL_FIELDS) {
+ const value = input[field];
+ if (typeof value === "string" && value.trim()) {
+ return `${tool} · ${value.trim()}`;
+ }
+ }
+ return tool;
+}
+
function upsert(projectName: string, cwd: string) {
const t = State.tasks.find((x) => x.id === CLAUDE_ID);
if (!t) return;
@@ -92,7 +122,13 @@ export function registerHookHandlers(island: Island) {
}
function handleHook(island: Island, payload: HookPayload) {
- if (State.paused) return;
+ if (State.paused) {
+ // Silence here used to cost Claude Code nearly two minutes: the relay waited
+ // for a decision from an island that had already decided not to look. Say so,
+ // and the terminal takes the question immediately.
+ if (payload.request_id) void Bridge.approvalDecline(payload.request_id);
+ return;
+ }
const name = payload.hook_event_name ?? "";
const cwd = payload.cwd ?? "";
@@ -118,12 +154,15 @@ function handleHook(island: Island, payload: HookPayload) {
Sound.play("work");
break;
- case "UserPromptSubmit":
+ case "UserPromptSubmit": {
upsert(projectName, cwd);
State.updateTask(CLAUDE_ID, "thinking");
- if (payload.message) State.appendStep(CLAUDE_ID, payload.message.slice(0, 60));
+ // The field is `prompt`; reading `message` meant this step was always blank.
+ const asked = payload.prompt ?? payload.message;
+ if (asked) State.appendStep(CLAUDE_ID, asked.slice(0, 60));
surface("overview", false);
break;
+ }
case "PreToolUse": {
upsert(projectName, cwd);
@@ -189,22 +228,39 @@ function handleHook(island: Island, payload: HookPayload) {
break;
case "PermissionRequest": {
+ const requestId = payload.request_id ?? "";
+ // One card, one request. A second one must never quietly replace the first
+ // — that would leave a human staring at request B while request A waits for
+ // a decision nobody can give. Hand it straight back to the terminal.
+ if (State.pendingApproval && State.pendingApproval.requestId !== requestId) {
+ if (requestId) void Bridge.approvalDecline(requestId);
+ break;
+ }
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;
State.pendingApproval = {
- requestId: payload.request_id ?? "",
+ requestId,
sessionId: payload.session_id ?? "",
tool,
- command,
+ command: approvalTarget(tool, input),
};
+ // The relay's short ack window closes in 800 ms; everything below this
+ // line is synchronous, so the card really is up by the time it lands.
+ if (requestId) void Bridge.approvalAck(requestId);
State.updateTask(CLAUDE_ID, "approval");
State.isPinned = true;
Sound.play("approval");
- if (focused) island.alert("approval");
- else State.setPillBadge(CLAUDE_ID, "approval");
+ if (focused) {
+ island.alert("approval");
+ } else {
+ // Another agent holds the view, so the card would yank it away. The badge
+ // is the signal instead — but it has to be on screen for that to mean
+ // anything, hence the reveal. We just told the relay a human can act.
+ State.setPillBadge(CLAUDE_ID, "approval");
+ island.reveal();
+ }
// 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(() => {
diff --git a/windows/src/island/island.ts b/windows/src/island/island.ts
index 5eeaf81d..4a6cc6d1 100644
--- a/windows/src/island/island.ts
+++ b/windows/src/island/island.ts
@@ -140,7 +140,6 @@ export class Island {
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;
@@ -711,16 +710,25 @@ export class Island {
if (UploadSeq.isActive) this.stepSequence();
this.updateCountdown(nowMs);
- const busy =
- this.width.animating || this.height.animating || this.radius.animating ||
- !this.botCx.settled || !this.botCy.settled || !this.botSize.settled ||
- greetingActive || this.engine.busy || State.mode !== "hidden" ||
- UploadSeq.isActive;
+ // Nothing is drawn while the island is hidden, so nothing may keep the loop
+ // alive either. This used to read `... || this.engine.busy || State.mode !==
+ // "hidden"`, and engine.busy is permanently true for any state with a
+ // looping animation — breathing, ratelimit sweat, sleeping z's, the search
+ // sweep — so a hidden island went on burning frames in exactly the states it
+ // spends most of its life in. Geometry still has to finish retracting.
+ const settling =
+ this.width.animating || this.height.animating || this.radius.animating;
+ const busy = State.mode === "hidden"
+ ? settling
+ : settling ||
+ !this.botCx.settled || !this.botCy.settled || !this.botSize.settled ||
+ greetingActive || this.engine.busy || UploadSeq.isActive;
if (busy) {
requestAnimationFrame(this.frame);
} else {
this.running = false;
+ Sound.idle();
}
};
diff --git a/windows/src/main.ts b/windows/src/main.ts
index e7d6d48e..5f1c3348 100644
--- a/windows/src/main.ts
+++ b/windows/src/main.ts
@@ -25,18 +25,25 @@ async function main() {
await onEvent<{ x: number; y: number }>("cursor", ({ x, y }) => island.onCursor(x, y));
+ /** Pause has to reach Rust too, or the pollers keep calling out. */
+ const setPaused = (on: boolean) => {
+ if (State.paused === on) return;
+ State.paused = on;
+ void Bridge.setPaused(on);
+ };
+
await onEvent<string>("tray", (what) => {
switch (what) {
case "settings":
- State.paused = false;
+ setPaused(false);
island.alert("settings");
break;
case "open":
- State.paused = false;
+ setPaused(false);
island.alert(State.defaultView());
break;
case "pause":
- State.paused = !State.paused;
+ setPaused(!State.paused);
if (State.paused) island.fsm.forceHidden();
else island.reveal();
break;
diff --git a/windows/src/settings/main.ts b/windows/src/settings/main.ts
index 7e3211d5..3ab9ab94 100644
--- a/windows/src/settings/main.ts
+++ b/windows/src/settings/main.ts
@@ -94,6 +94,12 @@ function claudeSection(status: HookStatus): HTMLElement {
text: status.installed ? "Reinstall hooks…" : "Install hooks…",
onclick: () => showPreview(true),
});
+ // Writing hook commands that point at a relay which isn't there would give
+ // every Claude Code session a broken hook and nothing to show for it.
+ if (!status.hookReady) {
+ install.disabled = true;
+ install.title = "The relay isn't installed yet.";
+ }
actions.append(install);
if (status.installed) {
actions.append(h("button", {
@@ -106,7 +112,22 @@ function claudeSection(status: HookStatus): HTMLElement {
}
async function showPreview(install: boolean) {
- const preview = await Bridge.hooksPreview(install);
+ let preview;
+ try {
+ preview = await Bridge.hooksPreview(install);
+ } catch (err) {
+ // An unreadable or invalid settings.json stops here rather than being
+ // treated as empty and written over.
+ 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(
@@ -128,7 +149,7 @@ function claudeSection(status: HookStatus): HTMLElement {
confirm.addEventListener("click", async () => {
confirm.disabled = true;
try {
- const backup = await Bridge.hooksApply(install);
+ const backup = await Bridge.hooksApply(install, preview.fingerprint);
clear(body);
body.append(h("div", {
class: "notice ok",
diff --git a/windows/src/views/views.ts b/windows/src/views/views.ts
index 21d23285..ac0ac7b6 100644
--- a/windows/src/views/views.ts
+++ b/windows/src/views/views.ts
@@ -20,7 +20,7 @@ export interface ViewActions {
/** The ↗ button: opens whatever the focused pill points at. */
openTarget(): void;
openUrl(url: string): void;
- decide(d: "allow" | "deny" | "always"): void;
+ decide(d: "allow" | "deny"): void;
toggleSound(): void;
setVolume(v: number): void;
setAutoClose(seconds: number): void;
@@ -293,26 +293,26 @@ 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"));
+ // The whole point of approving here rather than in the terminal: this line
+ // is the command, the file path or the URL being authorised, not just the
+ // name of the tool asking.
code.textContent = State.pendingApproval?.command || State.pendingApproval?.tool || "…";
- const key = String(State.alwaysAllow);
- if (key === rowKey) return;
- rowKey = key;
+ // Two buttons, built once. Rebuilding them between a mouse-down and a
+ // mouse-up would swallow the click, and there is nothing left to vary:
+ // "Always" is gone until the remembered-rules list exists to back it.
+ if (rowKey === "built") return;
+ rowKey = "built";
clear(row);
row.append(
btn("Deny", "secondary", () => actions.decide("deny"), "N"),
btn("Allow", "primary", () => actions.decide("allow"), "Y"),
);
- if (!State.alwaysAllow) {
- row.append(btn("Always", "secondary", () => actions.decide("always")));
- }
},
};
}
diff --git a/windows/vite.config.ts b/windows/vite.config.ts
index b3cfb914..1ff3b656 100644
--- a/windows/vite.config.ts
+++ b/windows/vite.config.ts
@@ -46,7 +46,7 @@ export default defineConfig({
plugins: [sharedSounds()],
clearScreen: false,
server: { port: 1420, strictPort: true, host: "127.0.0.1" },
- envPrefix: ["VITE_", "TAURI_"],
+ envPrefix: ["VITE_", "TAURI_ENV_"],
build: {
target: "chrome110",
minify: "esbuild",