Skip to content

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

Merge port/plan-usage: coucou-hook --statusline, plan pills in the header, Codex plan usage

Claude7fd25704467b
diff --cc windows/README.md
index 08ddfe94,3fa856f8..4214d943
--- a/windows/README.md
+++ b/windows/README.md
@@@ -88,6 -69,29 +88,29 @@@ in time, Coucou stays quiet and Claude
It works from any terminal — Windows Terminal, PowerShell, VS Code, Git Bash.
+ ### Plan usage
+
+ As on the Mac, the island's header can show your plan limits: a small pill
+ ("Claude 73%", green below 50 %, orange up to 80 %, red above) for the 5-hour and
+ weekly Claude limits, and another for Codex. Click one for the details and the
+ reset times. Both are off by default; turn them on in **Settings… → Plan usage**.
+
+ - **Claude** (Pro and Max plans): the numbers come from Claude Code's own status
- line. **Show in notch** first shows you the diff of the `statusLine` key in
++ line. **Show in notch** first shows you the diff of the `statusLine` change in
+ `%USERPROFILE%\.claude\settings.json`, takes a dated backup and writes only
- after your click: the status line becomes `coucou-hook --statusline`, which
++ after your click, with the same writer as the hooks: the status line becomes `coucou-hook --statusline`, which
+ passes only the limits on (300 ms at most) and runs the status line you had
+ before — kept in `statusline-previous.json` next to the relay — with the same
+ input, printing what it prints. On Windows that one runs through Git Bash, as
+ Claude Code runs it (`CLAUDE_CODE_GIT_BASH_PATH`, then the Git for Windows that
+ `git.exe` on `PATH` belongs to, then the usual install folders); it gets 10 s
+ and 64 KB of output. **Uninstall relay** puts your status line back. The
+ numbers arrive with Claude Code's replies.
+ - **Codex**: nothing is installed. When the pill shows (or is clicked, at most
+ once a minute) Coucou starts `codex app-server` and asks it
+ `account/rateLimits/read`, as Codex's `/status` does, then stops it (15 s at
+ most, never while paused). Codex must be signed in with ChatGPT.
+
## Chat and keys
**Settings… → Claude** takes your Anthropic API key. Keys live in the **Windows
@@@ -214,26 -183,14 +237,30 @@@ own window
the top edge instead of hiding in a notch.
- Permission approval works from **any** terminal; the Mac build only listens to
VS Code sessions.
-- Not in this version: sending a file by email, dragging Mochi onto a window to
- attach it as context, and jumping to a specific terminal window — "Open
- terminal" opens the working folder in VS Code when `code` is on your `PATH`.
+- "Open terminal" finds the session's window by walking up from the relay's
+ process to the terminal or editor that runs it. A session in a classic
+ console window (`cmd.exe` or PowerShell without Windows Terminal) has no such
+ ancestor — conhost owns that window — so its folder opens in VS Code instead,
+ as it does when `code` is on your `PATH` and nothing was found.
+- No global keyboard shortcuts yet: a waiting card is folded with its **⌃** or
+ `Esc` in the island, and reopened by clicking the island or Open in the tray.
+- Pills from the Mac catalog that have nothing behind them here are left out:
+ Apple Music, Ollama and LM Studio. Google AI and OpenAI can be declared but
+ show "Coming soon": the chat here only talks to Anthropic.
+- Not in this version: sending a dropped file by email and dragging Mochi onto
+ a window to attach it as context. On the Mac, email goes through Resend or
+ Apple Mail's scripting; neither has a safe equivalent that attaches a file
+ here, and the drop card would need a third button it doesn't have.
- Cal.com shows the next bookings as a list rather than the Mac's calendar.
+- The Cursor pill carries both Cursor Agent's own hooks and Claude Code running
+ in Cursor's terminal.
+- Hermes: Coucou writes the plugin but does not run the `hermes` CLI, so it is
+ turned on once by hand. Hermes runs natively on Linux; on Windows it is
+ untested.
+ - Plan usage: the user's previous status line runs through Git Bash on Windows
+ (`/bin/sh` on Linux and Mac); without Git Bash it is not run, rather than
+ guessed at with `cmd`. The Codex CLI is looked for on `PATH` and in npm's,
+ Volta's, Bun's and pnpm's folders (and nvm's on Linux).
## Linux
@@@ -277,11 -234,13 +304,16 @@@ What changes on Linux
gives no app the cursor position anywhere else.
- **Claude Code hooks** go through `~/.local/share/coucou/bin/coucou-hook` and a
Unix socket at `$XDG_RUNTIME_DIR/coucou.sock`. Both ends check that the other
- runs as the same user.
+ runs as the same user. Every other agent uses the same relay, single-quoted
+ for `sh`, and its config under `~` (see Supported agents). A config that is a
+ symlink (dotfiles) is written through to its target, with its permissions
+ kept.
- **Keys** live in the Secret Service (GNOME Keyring, KWallet).
+ - **Plan usage**: the status line relay is `~/.local/share/coucou/bin/coucou-hook
+ --statusline` and runs your previous status line with `/bin/sh -c`, like Claude
+ Code. Codex is found on `$PATH`, in `~/.local/bin`, npm's global prefix, Volta,
+ Bun, pnpm, or nvm (newest Node first), since a desktop launch often has a
+ shorter `$PATH` than your shell.
- **Files**: preferences in `~/.config/coucou/`, the log at
`~/.local/share/coucou/coucou.log`.
- What the Windows build leaves out, this one does too: sending a file by
diff --cc windows/hook/src/main.rs
index 43ff6f5b,3fa87d1b..5d9ee1de
--- a/windows/hook/src/main.rs
+++ b/windows/hook/src/main.rs
@@@ -14,11 -11,13 +14,14 @@@
//! 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.
+//! island is the whole point. No answer means no decision, and the agent asks
+//! in its terminal exactly as if Coucou were not installed.
//!
-//! Usage: `coucou-hook <EventName>` (the name is also read from the JSON), or
+//! Usage: `coucou-hook [--agent <name>] [<EventName>]` (the event name is also
- //! read from the JSON; `--agent` is absent for Claude Code).
++//! read from the JSON; `--agent` is absent for Claude Code), or
+ //! `coucou-hook --statusline` as Claude Code's status line command (plan usage,
+ //! see statusline.rs): it passes the plan limits on and runs the status line the
+ //! user had before, so that keeps working.
use std::io::{Read, Write};
use std::sync::mpsc;
@@@ -53,52 -49,13 +58,55 @@@ mod unix
#[cfg(target_os = "linux")]
use unix::connect;
+/// What the command line says: `--agent <name>` and the event name.
+struct Args {
+ agent: String,
+ event: String,
+}
+
+fn args() -> Args {
+ let mut agent = String::new();
+ let mut event = String::new();
+ let mut it = std::env::args().skip(1);
+ while let Some(arg) = it.next() {
+ if arg == "--agent" {
+ agent = it.next().unwrap_or_default();
+ } else if event.is_empty() {
+ event = arg;
+ }
+ }
+ Args { agent, event }
+}
+
+/// One event, ready to forward.
+struct Event {
+ /// The payload as one line of JSON.
+ line: String,
+ /// The canonical event name.
+ name: String,
+ /// For Claude Code's AskUserQuestion, the question as it was asked.
+ question: Option<Value>,
+}
+
fn main() {
+ if std::env::args().skip(1).any(|a| a == "--statusline") {
+ statusline::run();
+ }
- let Some((payload, event, question)) = read_event() else { std::process::exit(0) };
+ let args = args();
+ let mut raw = Vec::new();
+ let _ = std::io::stdin().read_to_end(&mut raw);
+ let env = |key: &str| std::env::var(key).ok();
+ let cwd = std::env::current_dir().map(|p| p.to_string_lossy().to_string()).unwrap_or_default();
+
+ let Some(event) = prepare(&raw, &args, &env, &cwd) else {
+ // Nothing we could forward. An agent that needs JSON still gets its
+ // "no opinion" — Copilot is fail-closed and would deny without it.
+ let name = normalize::event(&args.event);
+ print(reply::stdout(&args.agent, name, None, None));
+ std::process::exit(0);
+ };
- let waits_for_answer = event == "PermissionRequest";
+ let waits_for_answer = event.name == "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
diff --cc windows/src-tauri/src/hooks.rs
index 2f472c11,31ee2cd5..b1d61e11
--- a/windows/src-tauri/src/hooks.rs
+++ b/windows/src-tauri/src/hooks.rs
@@@ -96,23 -141,27 +98,29 @@@ fn entry_is_ours(entry: &Value) -> boo
.unwrap_or(false)
}
+ /// The status line in settings.json is Coucou's relay (old installs wrote
+ /// `coucou-hook StatusLine`, new ones `coucou-hook --statusline`; both match).
+ fn status_line_is_ours(v: &Value) -> bool {
+ v.get("command").and_then(Value::as_str).is_some_and(|c| c.contains(MARKER))
+ }
+
-/// 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": [{
@@@ -197,25 -269,197 +206,133 @@@ pub fn status() -> HookStatus
}
pub fn preview(install: bool) -> Result<HookPreview, String> {
- let plan = config_file::preview(&edits(install))?;
- Ok(HookPreview {
- preview_with(|current| if install { merged(current) } else { without_ours(current) }, pretty)
++ Ok(plan_to_preview(config_file::preview(&edits(install))?))
+ }
+
-/// The diff of what `next` makes of settings.json, shown with `view` (the whole
-/// file, or just the key that changes).
-fn preview_with(
- next: impl Fn(&Value) -> Value,
- view: fn(&Value) -> String,
-) -> Result<HookPreview, String> {
- let current = read_settings()?;
- let next = next(&current);
- Ok(HookPreview {
- diff: unified_diff(&view(&current), &view(&next)),
- backup: backup_path().to_string_lossy().to_string(),
- settings_path: settings_path().to_string_lossy().to_string(),
- fingerprint: current_fingerprint(),
- })
++fn plan_to_preview(plan: config_file::Plan) -> HookPreview {
++ HookPreview {
+ 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> {
- write_with(|current| if install { merged(current) } else { without_ours(current) }, fingerprint)
-}
-
-fn write_with(next: impl Fn(&Value) -> Value, 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 = next(&current);
- 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())
+ let backups = config_file::apply(&edits(install), fingerprint)?;
+ Ok(backups.first().map(|p| p.to_string_lossy().to_string()).unwrap_or_default())
}
+ // ── Status line (plan usage) ──────────────────────────────────────────────────
+ //
+ // Claude Code runs one `statusLine` command and hands it the plan limits. Coucou
+ // puts its relay there; a status line the user already had is kept in
+ // statusline-previous.json beside the relay, and the relay still runs it, so it
-// keeps working. Installing and removing it is separate from the hooks.
++// keeps working. Installing and removing it is separate from the hooks, and
++// goes through the same hardened writer (config_file.rs): strict read, diff,
++// fingerprint, dated backup, then the write.
+
+ /// Where the user's own status line waits while the relay stands in for it.
+ pub fn status_line_previous_path() -> PathBuf {
+ settings::hook_exe_path().with_file_name("statusline-previous.json")
+ }
+
+ fn read_status_line_previous() -> Option<Value> {
+ let bytes = std::fs::read(status_line_previous_path()).ok()?;
+ serde_json::from_slice::<Value>(&bytes).ok().filter(Value::is_object)
+ }
+
+ /// True when the `statusLine` in settings.json is Coucou's relay.
+ pub fn plan_relay_installed(settings: &Value) -> bool {
+ settings.get("statusLine").is_some_and(status_line_is_ours)
+ }
+
+ /// `statusLine` as it reads after installing or removing the relay. `None`: the
+ /// key goes. Installing swaps only `command`, so `padding`, `refreshInterval`
+ /// and the rest of the user's status line stay as they were.
+ fn status_line_after(existing: Option<&Value>, install: bool, previous: Option<&Value>) -> Option<Value> {
+ if install {
+ let mut sl = existing.filter(|v| v.is_object()).cloned().unwrap_or_else(|| json!({}));
+ let obj = sl.as_object_mut().expect("an object");
+ obj.entry("type").or_insert_with(|| json!("command"));
+ obj.insert("command".into(), json!(hook_command("--statusline")));
+ Some(sl)
+ } else if existing.is_some_and(status_line_is_ours) {
+ previous.cloned()
+ } else {
+ existing.cloned() // not ours any more (the user changed it): leave it alone
+ }
+ }
+
+ fn status_line_settings(current: &Value, install: bool, previous: Option<&Value>) -> Value {
+ let mut root = current.as_object().cloned().unwrap_or_default();
+ match status_line_after(root.get("statusLine"), install, previous) {
+ Some(sl) => root.insert("statusLine".into(), sl),
+ None => root.remove("statusLine"),
+ };
+ Value::Object(root)
+ }
+
-/// Only the `statusLine` key, which is all the diff of this change is about.
-fn status_line_view(settings: &Value) -> String {
- pretty(&json!({ "statusLine": settings.get("statusLine").cloned().unwrap_or(Value::Null) }))
++fn status_line_edits(install: bool, previous: Option<Value>) -> Vec<FileEdit<'static>> {
++ vec![FileEdit {
++ path: settings_path(),
++ edit: config_file::json_edit("settings.json".into(), move |current| {
++ Ok(Some(status_line_settings(current, install, previous.as_ref())))
++ }),
++ }]
+ }
+
+ /// The diff the user has to look at before the relay goes in or out.
+ pub fn status_line_preview(install: bool) -> Result<HookPreview, String> {
- let previous = read_status_line_previous();
- preview_with(|current| status_line_settings(current, install, previous.as_ref()), status_line_view)
++ Ok(plan_to_preview(config_file::preview(&status_line_edits(install, read_status_line_previous()))?))
+ }
+
+ /// Installs or removes the relay, after the same backup and fingerprint checks as
+ /// the hooks. Installing first saves a status line of the user's own, removing
+ /// puts it back (or removes the key if there was none).
+ pub fn status_line_write(install: bool, fingerprint: &str) -> Result<String, String> {
- let before = read_settings()?;
++ let before = config_file::read(&settings_path())
++ .and_then(|bytes| config_file::parse_json(bytes.as_deref(), "settings.json"))?;
+ let previous = read_status_line_previous();
+ let own = before.get("statusLine").filter(|v| !status_line_is_ours(v)).cloned();
- let saved = install && own.is_some() && save_status_line_previous(own.as_ref().expect("some")).is_ok();
- if install && own.is_some() && !saved {
- return Err("could not save your current status line next to the relay; nothing was changed".into());
- }
- let backup = write_with(|current| status_line_settings(current, install, previous.as_ref()), fingerprint);
- match &backup {
++ let saved = match (install, own.as_ref()) {
++ (true, Some(own)) => {
++ save_status_line_previous(own).map_err(|_| {
++ "could not save your current status line next to the relay; nothing was changed".to_string()
++ })?;
++ true
++ }
++ _ => false,
++ };
++ let result = config_file::apply(&status_line_edits(install, previous), fingerprint);
++ match &result {
+ // Back in settings.json: the saved copy has done its job.
+ Ok(_) if !install => {
+ let _ = std::fs::remove_file(status_line_previous_path());
+ }
+ // Nothing was written: do not leave a stale copy behind.
+ Err(_) if saved => {
+ let _ = std::fs::remove_file(status_line_previous_path());
+ }
+ _ => {}
+ }
- backup
++ let backups = result?;
++ Ok(backups.first().map(|p| p.to_string_lossy().to_string()).unwrap_or_default())
+ }
+
+ fn save_status_line_previous(status_line: &Value) -> std::io::Result<()> {
+ let path = status_line_previous_path();
+ if let Some(dir) = path.parent() {
+ std::fs::create_dir_all(dir)?;
+ }
- write_like(&path, &path, pretty(status_line).as_bytes())
-}
-
-/// 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(())
++ config_file::write_like(&path, &path, config_file::pretty(status_line).as_bytes())
+ }
+
/// Copies the relay (coucou-hook.exe / coucou-hook) into the local data dir's
/// bin/ on launch. In a bundled install it comes from the app resources; in
/// `tauri dev` it sits next to the app binary in the workspace target directory.
@@@ -304,6 -624,80 +421,49 @@@ fn install_relay(src: &Path, dest: &Pat
mod tests {
use super::*;
- const WHERE: &str = "settings.json";
-
+ #[test]
+ fn the_hooks_leave_the_status_line_alone() {
+ let theirs = json!({ "statusLine": { "type": "command", "command": "~/bin/my-line" } });
- assert_eq!(merged(&theirs)["statusLine"], theirs["statusLine"]);
- assert_eq!(without_ours(&theirs)["statusLine"], theirs["statusLine"]);
- assert!(merged(&json!({})).get("statusLine").is_none());
++ assert_eq!(merged(&theirs).unwrap()["statusLine"], theirs["statusLine"]);
++ assert_eq!(without_ours(&theirs).unwrap()["statusLine"], theirs["statusLine"]);
++ assert!(merged(&json!({})).unwrap().get("statusLine").is_none());
+ }
+
+ #[test]
+ fn the_relay_takes_the_status_line_and_keeps_the_users_other_fields() {
+ // None yet: ours is added.
+ let fresh = status_line_settings(&json!({ "model": "opus" }), true, None);
+ assert!(status_line_is_ours(&fresh["statusLine"]));
+ assert_eq!(fresh["statusLine"]["type"], "command");
+ assert_eq!(fresh["model"], "opus");
+
+ // Their own: only the command is swapped; padding and refresh stay.
+ let own = json!({ "statusLine": { "type": "command", "command": "~/bin/my-line", "padding": 2, "refreshInterval": 5 } });
+ let taken = status_line_settings(&own, true, None);
+ assert!(status_line_is_ours(&taken["statusLine"]));
+ assert_eq!(taken["statusLine"]["padding"], 2);
+ assert_eq!(taken["statusLine"]["refreshInterval"], 5);
+
+ // Installing again keeps ours and its extra fields.
+ let again = status_line_settings(&taken, true, None);
+ assert_eq!(again["statusLine"]["padding"], 2);
+ assert!(status_line_is_ours(&again["statusLine"]));
+ }
+
+ #[test]
+ fn removing_the_relay_restores_what_was_there_and_never_touches_anything_else() {
+ let previous = json!({ "type": "command", "command": "~/bin/my-line", "padding": 2 });
+ let ours = status_line_settings(&json!({}), true, None);
+
+ // There was one before: it comes back exactly.
+ assert_eq!(status_line_settings(&ours, false, Some(&previous))["statusLine"], previous);
+ // There was none: the key goes.
+ assert!(status_line_settings(&ours, false, None).get("statusLine").is_none());
+ // The user changed it since: not ours, so untouched.
+ let theirs = json!({ "statusLine": { "type": "command", "command": "~/bin/other" } });
+ assert_eq!(status_line_settings(&theirs, false, Some(&previous))["statusLine"], theirs["statusLine"]);
+ }
+
- #[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!({
diff --cc windows/src-tauri/src/lib.rs
index aa71d359,ef6cb424..4eab7243
--- a/windows/src-tauri/src/lib.rs
+++ b/windows/src-tauri/src/lib.rs
@@@ -1,9 -1,7 +1,10 @@@
// Coucou for Windows — app wiring and the commands the island calls.
+mod agent_hooks;
+mod agents;
mod claude;
+mod config_file;
+ mod codex_plan;
mod files;
mod hooks;
mod integrations;
@@@ -253,29 -225,45 +256,70 @@@ fn hooks_apply
Ok(backup)
}
+// ── Other agents' hooks and plugins ──────────────────────────────────────────
+
+#[tauri::command]
+fn agent_hooks_list() -> Vec<agents::AgentStatus> {
+ agents::list()
+}
+
+/// The diff the user has to look at before anything is written.
+#[tauri::command]
+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 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)
+}
+
++// ── Plan usage ────────────────────────────────────────────────────────────────
++
+ /// The diff of putting the plan usage relay into (or taking it out of) the
-/// status line: just the `statusLine` key, before and after.
++/// status line, before anything is written.
+ #[tauri::command]
+ fn status_line_preview(install: bool) -> Result<HookPreview, String> {
+ hooks::status_line_preview(install)
+ }
+
+ /// Only ever called from an explicit click in the settings window.
+ #[tauri::command]
+ fn status_line_apply(
+ app: AppHandle,
+ shared: State<Shared>,
+ install: bool,
+ fingerprint: String,
+ ) -> Result<String, String> {
+ let backup = hooks::status_line_write(install, &fingerprint)?;
+ let updated = {
+ let mut current = shared.settings.lock().unwrap();
+ current.plan_relay_installed = install;
+ // As on the Mac: taking the relay out turns the pill off with it.
+ if !install {
+ current.show_plan_in_notch = false;
+ }
+ if let Err(err) = settings::save(&current) {
+ log::line(format!("could not save settings: {err}"));
+ }
+ current.clone()
+ };
+ let _ = app.emit("settings-changed", updated);
+ Ok(backup)
+ }
+
+ /// Codex plan usage, asked of the Codex CLI (`codex app-server`) when its pill
+ /// shows. Off the main thread: it can take a few seconds.
+ #[tauri::command]
+ async fn codex_plan_usage() -> Option<serde_json::Value> {
+ tauri::async_runtime::spawn_blocking(codex_plan::read).await.ok().flatten()
+ }
+
#[tauri::command]
fn approval_decision(app: AppHandle, request_id: String, decision: String) {
pipe::answer(&app, &request_id, &decision);
@@@ -459,16 -447,13 +503,19 @@@ pub fn run()
list_monitors,
open_url,
open_in_vscode,
+ open_session,
+ open_claude_desktop,
quit_app,
hooks_status,
+ agent_hooks_status,
hooks_preview,
hooks_apply,
+ agent_hooks_list,
+ agent_hooks_preview,
+ agent_hooks_apply,
+ status_line_preview,
+ status_line_apply,
+ codex_plan_usage,
approval_decision,
approval_answer,
approval_ack,
diff --cc windows/src-tauri/src/pipe.rs
index da10762b,8c04fa2b..d5b7a99a
--- a/windows/src-tauri/src/pipe.rs
+++ b/windows/src-tauri/src/pipe.rs
@@@ -206,10 -197,11 +206,13 @@@ async fn handle(app: AppHandle, mut pip
.unwrap_or_default()
.to_string();
+ note_session_window(&pipe, &payload, &event);
+
if event != "PermissionRequest" {
- log::line(format!("hook {event}"));
+ // The status line relay calls in with every Claude Code update: not log-worthy.
+ if event != "StatusLine" {
+ log::line(format!("hook {event}"));
+ }
let _ = app.emit_to(WINDOW_LABEL, "hook", payload);
pipe.finish();
return;
diff --cc windows/src-tauri/src/platform/linux.rs
index 7333da34,4d1be471..1624ea5f
--- a/windows/src-tauri/src/platform/linux.rs
+++ b/windows/src-tauri/src/platform/linux.rs
@@@ -208,29 -208,32 +208,55 @@@ pub fn find_on_path(stem: &str) -> Opti
})
}
+// ── Session windows ("Open terminal") ─────────────────────────────────────────
+//
+// Wayland lets no app raise another app's window, and X11 would need a window
+// manager protocol client this build does not carry, so "Open terminal" opens
+// the folder in VS Code here, as before. There is no Claude desktop app for
+// Linux either.
+
+pub fn process_ancestors(_pid: u32) -> Vec<u32> {
+ Vec::new()
+}
+
+pub fn first_with_window(_pids: &[u32]) -> Option<u32> {
+ None
+}
+
+pub fn focus_process_window(_pid: u32, _folder: &str) -> bool {
+ false
+}
+
+pub fn open_claude_desktop() -> bool {
+ false
+}
+
+ /// Where the Codex CLI may be, best first: $PATH, then the usual per-user
+ /// install folders, which a desktop launch often leaves out of $PATH (npm's
+ /// global prefix, Volta, Bun, pnpm, and nvm with its newest Node first).
+ pub fn codex_candidates() -> Vec<PathBuf> {
+ let home = home_dir();
+ let mut out: Vec<PathBuf> = find_on_path("codex").into_iter().collect();
+ for dir in [".local/bin", ".npm-global/bin", ".volta/bin", ".bun/bin", ".local/share/pnpm"] {
+ out.push(home.join(dir).join("codex"));
+ }
+ out.push(PathBuf::from("/usr/local/bin/codex"));
+ out.push(PathBuf::from("/usr/bin/codex"));
+ let nvm = home.join(".nvm/versions/node");
+ if let Ok(entries) = std::fs::read_dir(&nvm) {
+ let mut versions: Vec<String> =
+ entries.filter_map(|e| e.ok()?.file_name().into_string().ok()).collect();
+ versions.sort_by(|a, b| crate::codex_plan::compare_versions(b, a));
+ out.extend(versions.iter().map(|v| nvm.join(v).join("bin/codex")));
+ }
+ out.retain(|p| {
+ std::fs::metadata(p)
+ .map(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
+ .unwrap_or(false)
+ });
+ out
+ }
+
// ── Cursor ────────────────────────────────────────────────────────────────────
/// Nothing polls the cursor here: the page reports it over the island, and the
diff --cc windows/src/core/bridge.ts
index 2228eae5,b87d6743..6396d058
--- a/windows/src/core/bridge.ts
+++ b/windows/src/core/bridge.ts
@@@ -88,17 -76,18 +88,29 @@@ export const Bridge =
hooksApply: (install: boolean, fingerprint: string) =>
callOrThrow<string>("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 }),
+ // ── Plan usage: the status line relay, installed apart from the hooks ──────
- /** Diff of the `statusLine` key only. `install: false` previews taking the relay out. */
++ /** Diff of the status line change. `install: false` previews taking the relay out. */
+ statusLinePreview: (install: boolean) => callOrThrow<HookPreview>("status_line_preview", { install }),
+ /** Same rules as hooksApply: an explicit click, and only for the diff that was shown. */
+ statusLineApply: (install: boolean, fingerprint: string) =>
+ callOrThrow<string>("status_line_apply", { install, fingerprint }),
+ /**
+ * Asks the Codex CLI (`codex app-server`) for its plan limits, as Codex's
+ * /status does. The raw `account/rateLimits/read` result, or null when Codex
+ * is missing, not signed in or slow (15 s).
+ */
+ codexPlanUsage: () => call<unknown>("codex_plan_usage"),
approvalDecision: (requestId: string, decision: "allow" | "deny") =>
call<void>("approval_decision", { requestId, decision }),
diff --cc windows/src/core/state.ts
index 4d060fd3,f79c162e..98a170be
--- a/windows/src/core/state.ts
+++ b/windows/src/core/state.ts
@@@ -2,10 -2,7 +2,11 @@@
import type { BotEmoteName, BotStateName, IslandMode, IslandViewName } from "./layout";
import type { EyeShape } from "../mochi/engine";
+import {
+ DEFAULT_MAIN_PILL, HOST_OS, availablePills, orderPills, pillDefinition, sanitizeDeclared,
+ toggleDeclared, type HostOs, type PillDefinition,
+} from "./pills";
+ import type { CodexPlanUsage, PlanUsage } from "./plan";
export type AgentSource = "claudeCode" | "n8n" | "agent";
export type PillBadge = "approval" | "finished" | "error";
diff --cc windows/src/island/hooks.ts
index f3044136,146a80d3..bb71a5d0
--- a/windows/src/island/hooks.ts
+++ b/windows/src/island/hooks.ts
@@@ -8,12 -6,11 +8,14 @@@
import { Bridge, onEvent } from "../core/bridge";
import { Sound } from "../core/sound";
import { State, type AskedQuestion } from "../core/state";
+import { pillDefinition } from "../core/pills";
+import { APPROVAL_AGENTS, agentColor, agentName, validateAgent } from "./agents";
import type { Island } from "./island";
+ import { parseClaudePlan, restorePlanUsage } from "../core/plan";
+ import { setClaudePlanUsage, storedClaudePlanUsage } from "../views/usage";
const CLAUDE_ID = "integration_claude";
+const CURSOR_ID = "agent_cursor";
/** Clears the approval card if no decision was made before the hook gave up. */
let pendingTimeout: number | null = null;
@@@ -57,12 -52,27 +59,14 @@@ interface HookPayload
tool_input?: Record<string, unknown>;
/** Optional agent tag: lowercase, digits and hyphens, ≤ 24 chars. */
coucou_agent?: string;
+ /** Hermes: where the session runs (telegram, discord…; "cli" in a terminal). */
+ platform?: string;
+ /** "cursor" when Claude Code runs in Cursor's terminal (set by the relay). */
+ term_editor?: string;
+ /** StatusLine (the plan usage relay): Claude Code's 5-hour and weekly limits. */
+ rate_limits?: unknown;
}
-/** Same rule as HookServer.validateAgent on macOS. "claude" is reserved. */
-function validateAgent(raw: string | undefined): string | null {
- if (!raw || raw.length > 24 || raw === "claude") return null;
- if (!/^[a-z0-9-]+$/.test(raw)) return null;
- return raw;
-}
-
-const FALLBACK_COLORS = ["#22C55E", "#EAB308", "#60A5FA", "#E879F9"];
-
-function agentColor(name: string): string {
- let h = 0;
- for (let i = 0; i < name.length; i++) {
- h = (Math.imul(31, h) + name.charCodeAt(i)) | 0;
- }
- return FALLBACK_COLORS[Math.abs(h) % FALLBACK_COLORS.length];
-}
-
const PROJECT_ALIASES: Record<string, string> = {
"notch-buddy": "Notch Buddy",
notchbuddy: "Notch Buddy",
diff --cc windows/src/settings/main.ts
index d8b36e51,4369c597..722e2457
--- a/windows/src/settings/main.ts
+++ b/windows/src/settings/main.ts
@@@ -3,15 -3,9 +3,15 @@@
// integrations land here too in a later stage.
import "./settings.css";
- import { Bridge, onEvent, type HookStatus } from "../core/bridge";
+ import { Bridge, onEvent, type HookPreview, type HookStatus } from "../core/bridge";
import { DEFAULT_SETTINGS, type Settings } from "../core/state";
+import {
+ MAX_DECLARED, PILL_CATEGORIES, availablePills, chooseMainPill, isComingSoon, mainPillChoices,
+ sanitizeDeclared, toggleDeclared, type PillDefinition,
+} from "../core/pills";
import { h, clear } from "../views/dom";
+import { agentsSection } from "./agents";
+import { renderDiff, statusDot } from "./parts";
/** Where secrets.rs keeps the keys on this OS. */
const KEY_STORE = navigator.userAgent.includes("Windows")
@@@ -39,6 -33,103 +39,102 @@@ function toggle(on: boolean, onChange:
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;
-}
-
+ // ── Changes to Claude Code's settings.json ────────────────────────────────────
+
+ /** One kind of change to ~/.claude/settings.json, with the words that go with it. */
+ interface Change {
+ preview: (install: boolean) => Promise<HookPreview | null>;
+ apply: (install: boolean, fingerprint: string) => Promise<string | null>;
+ installText: string;
+ removeText: string;
+ installButton: string;
+ removeButton: string;
++ /** The note once written; `backup` is "" when there was no file to back up. */
+ done: (backup: string) => string;
+ }
+
+ const HOOKS_CHANGE: Change = {
+ preview: Bridge.hooksPreview,
+ apply: Bridge.hooksApply,
+ installText: "This is exactly what will change in your settings.json. Your own hooks are left untouched.",
+ removeText: "This removes Coucou's entries only. Your own hooks are left untouched.",
+ installButton: "Back up and write",
+ removeButton: "Back up and remove",
- done: (backup) => `Done. Previous settings saved as ${backup}. Open a new Claude Code session to pick the hooks up.`,
++ done: (backup) => 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.",
+ };
+
+ const STATUS_LINE_CHANGE: Change = {
+ preview: Bridge.statusLinePreview,
+ apply: Bridge.statusLineApply,
+ installText: "This is exactly what will change: only the status line. If you already have one it keeps working, Coucou's relay runs it for you.",
+ removeText: "This puts your previous status line back, or removes the entry if there was none.",
+ installButton: "Back up and write",
+ removeButton: "Back up and remove",
- done: (backup) => `Done. Previous settings saved as ${backup}. The numbers appear after the next reply of a Claude Code session.`,
++ done: (backup) => backup
++ ? `Done. Previous settings saved as ${backup}. The numbers appear after the next reply of a Claude Code session.`
++ : "Done. The numbers appear after the next reply of a Claude Code session.",
+ };
+
+ /**
+ * Shows the diff of a change in `body` and writes it only after an explicit
+ * click, and only if settings.json still matches the diff that was shown.
+ * `back` redraws the section; `applied` runs a moment after a successful write.
+ */
+ async function reviewChange(
+ body: HTMLElement,
+ change: Change,
+ install: boolean,
+ back: () => void,
+ applied: () => void,
+ ) {
+ let preview;
+ try {
+ preview = await change.preview(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: back })),
+ );
+ return;
+ }
+ if (!preview) return;
+ clear(body);
+ body.append(
+ h("div", { class: "hint", text: install ? change.installText : change.removeText }),
+ renderDiff(preview.diff),
- h("div", { class: "row" }, h("span", { class: "path", text: `Backup → ${preview.backup}` })),
++ h("div", { class: "row" },
++ h("span", {
++ class: "path",
++ text: preview.backup
++ ? `Backup → ${preview.backup}`
++ : "No settings.json yet — nothing to back up.",
++ }),
++ ),
+ );
+ const confirm = h("button", {
+ class: install ? "primary" : "danger",
+ text: install ? change.installButton : change.removeButton,
+ });
+ confirm.addEventListener("click", async () => {
+ confirm.disabled = true;
+ try {
+ const backup = await change.apply(install, preview.fingerprint);
+ clear(body);
- body.append(h("div", { class: "notice ok", text: change.done(String(backup)) }));
++ body.append(h("div", { class: "notice ok", text: change.done(backup ?? "") }));
+ window.setTimeout(applied, 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: back })));
+ }
+
// ── Claude Code section ───────────────────────────────────────────────────────
function claudeSection(status: HookStatus): HTMLElement {
@@@ -536,9 -565,8 +659,9 @@@ async function main()
version = boot.version;
}
const status = (await Bridge.hooksStatus()) ?? {
- installed: false, settingsPath: "", hookPath: "", hookReady: false,
+ installed: false, planRelayInstalled: false, settingsPath: "", hookPath: "", hookReady: false,
};
+ const agents = await Bridge.agentHooksList();
const hasKey = (await Bridge.secretPresent("anthropic-api-key")) ?? false;
@@@ -562,9 -581,8 +685,10 @@@
root.append(
h("h1", {}, h("span", { text: "Coucou" }), h("span", { class: "version", text: version })),
claudeSection(status),
+ agentsSection(agents),
+ planSection(status),
apiSection(hasKey),
+ activePillsSection(connected),
integrationsSection(present),
generalSection(),
h("div", {
diff --cc windows/src/views/views.ts
index 2fdfe627,b1174a9b..05d0362a
--- a/windows/src/views/views.ts
+++ b/windows/src/views/views.ts
@@@ -11,7 -11,9 +11,10 @@@ import { createMiniBot, pruneMiniBots
import { buildPrompt } from "./chat";
import { buildChoose, buildUpload, buildUploading } from "./upload";
import { renderIntegrationCard, type IntegrationCardHooks } from "./integrations";
+import { pillDefinition, sessionSubtitle } from "../core/pills";
+ import {
+ PlanCard, buildPlanPill, claudePillVisible, codexPillVisible, planCardOpen, refreshCodexPlanUsage,
+ } from "./usage";
export interface ViewActions {
setView(v: IslandViewName): void;
@@@ -183,11 -223,26 +226,25 @@@ function buildOverview(actions: ViewAct
mode = null;
}
- // VS Code with a live Claude Code session keeps the ticker; every other
- // pill shows its own card, exactly like IntegrationCardView.
- const sessionActive =
- task?.id === "integration_claude" && (task.state !== "idle" || task.steps.length > 0);
+ // A workspace or agent pill with a live session keeps the ticker; every
+ // other pill shows its own card, exactly like IntegrationCardView.
+ const sessionActive = task != null && hasSessionTicker(task);
- if (task && sessionActive) {
+ const planOpen = planCardOpen();
+ if (mode === "plan" && !planOpen) {
+ mode = null;
+ cardKey = "";
+ }
+ syncPlanTimer(planOpen);
+
+ if (planOpen) {
+ if (mode !== "plan") {
+ clear(leftBody);
+ leftBody.append(plan.el);
+ mode = "plan";
+ }
+ plan.sync();
+ } else if (task && sessionActive) {
if (mode !== "ticker") {
clear(leftBody);
leftBody.append(tickerBody);