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.

Fixes from an independent review of the catch-up

Claude5bddaec4ab7a
diff --git a/windows/hook/src/main.rs b/windows/hook/src/main.rs
index 7510eb23..0768a807 100644
--- a/windows/hook/src/main.rs
+++ b/windows/hook/src/main.rs
@@ -117,7 +117,9 @@ fn main() {
std::process::exit(0);
};
- let waits_for_answer = event.name == "PermissionRequest";
+ // Only an agent whose decisions the island can give waits for one; any other
+ // would be held for nothing, its decision being thrown away (reply.rs).
+ let waits_for_answer = event.name == "PermissionRequest" && reply::takes_decisions(&args.agent);
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 --git a/windows/src-tauri/src/chat.rs b/windows/src-tauri/src/chat.rs
index d5c939cf..834e2ef8 100644
--- a/windows/src-tauri/src/chat.rs
+++ b/windows/src-tauri/src/chat.rs
@@ -172,6 +172,30 @@ pub fn model_for(settings: &Settings, provider: &str) -> String {
.unwrap_or_default()
}
+/// A file rides along only if it is one of Coucou's own copies of a dropped
+/// file (files.rs puts them in the inbox). The page names the path, so without
+/// this any file the user can read could be sent to a chat provider.
+fn checked_context(context: ChatContext) -> Result<ChatContext, String> {
+ match context {
+ ChatContext::File { name, path } => {
+ let inbox = crate::files::inbox_dir();
+ if !is_inside(&inbox, std::path::Path::new(&path)) {
+ return Err(crate::i18n::t("Only a file dropped on the island can be sent with a question."));
+ }
+ Ok(ChatContext::File { name, path })
+ }
+ other => Ok(other),
+ }
+}
+
+/// True when `path` is a regular file directly inside `dir`, both resolved
+/// (no `..`, no symlink pointing out of it).
+fn is_inside(dir: &std::path::Path, path: &std::path::Path) -> bool {
+ let (Ok(dir), Ok(file)) = (dir.canonicalize(), path.canonicalize()) else { return false };
+ file.parent() == Some(dir.as_path())
+ && std::fs::symlink_metadata(&file).map(|m| m.is_file()).unwrap_or(false)
+}
+
/// One chat turn with the provider chosen in the settings.
pub async fn send(
app: &AppHandle,
@@ -180,6 +204,7 @@ pub async fn send(
query: String,
context: Option<ChatContext>,
) -> Result<ChatReply, String> {
+ let context = context.map(checked_context).transpose()?;
let provider = settings.chat_provider.as_str();
let model = model_for(settings, provider);
if provider == ANTHROPIC || provider.is_empty() {
@@ -317,4 +342,26 @@ mod tests {
assert_eq!(model_for(&s, "ollama"), "llama3.2");
assert_eq!(model_for(&s, "anthropic"), "claude-haiku-4-5");
}
+
+ #[test]
+ fn only_files_in_the_inbox_ride_along() {
+ let base = std::env::temp_dir().join(format!("coucou-chat-ctx-{}", std::process::id()));
+ let inbox = base.join("inbox");
+ std::fs::create_dir_all(inbox.join("sub")).unwrap();
+ std::fs::write(inbox.join("a.txt"), b"a").unwrap();
+ std::fs::write(base.join("secret.txt"), b"s").unwrap();
+ std::fs::write(inbox.join("sub").join("b.txt"), b"b").unwrap();
+ assert!(is_inside(&inbox, &inbox.join("a.txt")));
+ assert!(!is_inside(&inbox, &base.join("secret.txt")));
+ assert!(!is_inside(&inbox, &inbox.join("..").join("secret.txt")));
+ assert!(!is_inside(&inbox, &inbox.join("sub").join("b.txt")));
+ assert!(!is_inside(&inbox, &inbox.join("missing.txt")));
+ assert!(!is_inside(&inbox, &inbox));
+ #[cfg(unix)]
+ {
+ std::os::unix::fs::symlink(base.join("secret.txt"), inbox.join("link.txt")).unwrap();
+ assert!(!is_inside(&inbox, &inbox.join("link.txt")));
+ }
+ let _ = std::fs::remove_dir_all(&base);
+ }
}
diff --git a/windows/src-tauri/src/codex_plan.rs b/windows/src-tauri/src/codex_plan.rs
index 734ce7bf..d3993aec 100644
--- a/windows/src-tauri/src/codex_plan.rs
+++ b/windows/src-tauri/src/codex_plan.rs
@@ -87,6 +87,15 @@ pub fn read() -> Option<Value> {
drop(stdin);
answer
})();
+ // An npm install runs `codex.cmd`: killing cmd.exe alone would leave the
+ // node app-server under it running. End the whole tree there.
+ #[cfg(windows)]
+ {
+ let mut kill = Command::new("taskkill");
+ kill.args(["/T", "/F", "/PID", &child.id().to_string()]);
+ platform::no_console(&mut kill);
+ let _ = kill.status();
+ }
let _ = child.kill();
let _ = child.wait();
answer.map(|result| limits_only(&result))
diff --git a/windows/src-tauri/src/config_file.rs b/windows/src-tauri/src/config_file.rs
index 3dc5114d..3579c2d2 100644
--- a/windows/src-tauri/src/config_file.rs
+++ b/windows/src-tauri/src/config_file.rs
@@ -228,7 +228,7 @@ pub fn apply(edits: &[FileEdit], expected: &str) -> Result<Vec<PathBuf>, String>
.map_err(|e| {
tf("Write to {path} failed: {error}", &[("path", &file.path.display().to_string()), ("error", &e.to_string())])
})?,
- None if current.is_some() => std::fs::remove_file(&file.path)
+ None if current.is_some() => std::fs::remove_file(resolve_link(&file.path))
.map_err(|e| {
tf("Could not remove {path}: {error}", &[("path", &file.path.display().to_string()), ("error", &e.to_string())])
})?,
@@ -321,6 +321,16 @@ pub fn write_like(temp: &Path, original: &Path, bytes: &[u8]) -> std::io::Result
keep_mode(&file, original)
}
+/// The file a symlinked config points at (on Windows too), else `path` itself.
+fn resolve_link(path: &Path) -> std::path::PathBuf {
+ let is_link = std::fs::symlink_metadata(path).map(|m| m.file_type().is_symlink()).unwrap_or(false);
+ if is_link {
+ std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
+ } else {
+ path.to_path_buf()
+ }
+}
+
/// Replaces `path` with `bytes`: written beside it and renamed over it, so a
/// crash or a full disk leaves the original intact rather than half a file.
fn replace(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
@@ -329,9 +339,7 @@ fn replace(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
}
// A dotfiles setup often makes a config a symlink: write to the file it
// points at, so the link survives the rename.
- #[cfg(unix)]
- let resolved = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
- #[cfg(unix)]
+ let resolved = resolve_link(path);
let path = resolved.as_path();
let name = path.file_name().unwrap_or_default().to_string_lossy();
diff --git a/windows/src-tauri/src/hooks.rs b/windows/src-tauri/src/hooks.rs
index 098c5a8c..36aa761a 100644
--- a/windows/src-tauri/src/hooks.rs
+++ b/windows/src-tauri/src/hooks.rs
@@ -269,20 +269,25 @@ fn status_line_after(existing: Option<&Value>, install: bool, previous: Option<&
}
}
-fn status_line_settings(current: &Value, install: bool, previous: Option<&Value>) -> Value {
+fn status_line_settings(current: &Value, install: bool, previous: Option<&Value>) -> Result<Value, String> {
let mut root = current.as_object().cloned().unwrap_or_default();
+ // A statusLine that is not an object is something we do not understand:
+ // refuse rather than replace it.
+ if install && root.get("statusLine").is_some_and(|v| !v.is_object()) {
+ return Err(unexpected("\"statusLine\""));
+ }
match status_line_after(root.get("statusLine"), install, previous) {
Some(sl) => root.insert("statusLine".into(), sl),
None => root.remove("statusLine"),
};
- Value::Object(root)
+ Ok(Value::Object(root))
}
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())))
+ Ok(Some(status_line_settings(current, install, previous.as_ref())?))
}),
}]
}
@@ -432,20 +437,20 @@ mod tests {
#[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);
+ let fresh = status_line_settings(&json!({ "model": "opus" }), true, None).unwrap();
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);
+ let taken = status_line_settings(&own, true, None).unwrap();
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);
+ let again = status_line_settings(&taken, true, None).unwrap();
assert_eq!(again["statusLine"]["padding"], 2);
assert!(status_line_is_ours(&again["statusLine"]));
}
@@ -453,15 +458,17 @@ mod tests {
#[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);
+ let ours = status_line_settings(&json!({}), true, None).unwrap();
// There was one before: it comes back exactly.
- assert_eq!(status_line_settings(&ours, false, Some(&previous))["statusLine"], previous);
+ assert_eq!(status_line_settings(&ours, false, Some(&previous)).unwrap()["statusLine"], previous);
// There was none: the key goes.
- assert!(status_line_settings(&ours, false, None).get("statusLine").is_none());
+ assert!(status_line_settings(&ours, false, None).unwrap().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"]);
+ assert_eq!(status_line_settings(&theirs, false, Some(&previous)).unwrap()["statusLine"], theirs["statusLine"]);
+ // A statusLine we do not understand is refused, never replaced.
+ assert!(status_line_settings(&json!({ "statusLine": "echo hi" }), true, None).is_err());
}
#[test]
diff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rs
index c7fcd57b..3667b5e8 100644
--- a/windows/src-tauri/src/lib.rs
+++ b/windows/src-tauri/src/lib.rs
@@ -451,6 +451,13 @@ async fn local_connect(provider: String, url: String) -> Result<local_chat::Conn
local_chat::connect(&provider, &url).await
}
+/// Stores the custom server's key for the address typed next to it; it is only
+/// ever sent to that address.
+#[tauri::command]
+fn local_set_key(url: String, key: String) -> Result<(), String> {
+ local_chat::set_custom_key(&url, &key)
+}
+
#[tauri::command]
fn chat_reset(chat: State<Chat>) {
chat.reset();
@@ -470,6 +477,10 @@ fn secret_present(key: String) -> bool {
#[tauri::command]
fn secret_set(app: AppHandle, key: String, value: String) -> Result<(), String> {
+ // Bound to its server's address: only local_set_key may store it.
+ if key == local_chat::CUSTOM_KEY {
+ return Err("use local_set_key".into());
+ }
let before = (key == "github-token").then(|| secrets::get(&key));
secrets::set(&key, &value)?;
if let Some(before) = before {
@@ -668,6 +679,7 @@ pub fn run() {
chat_send,
chat_models,
local_connect,
+ local_set_key,
chat_reset,
ingest_file,
secret_present,
diff --git a/windows/src-tauri/src/local_chat.rs b/windows/src-tauri/src/local_chat.rs
index e2be452d..95d624c7 100644
--- a/windows/src-tauri/src/local_chat.rs
+++ b/windows/src-tauri/src/local_chat.rs
@@ -39,6 +39,46 @@ const NO_KEY: &str = "ollama";
/// Models that embed or rank rather than chat are left out of the list.
const NOT_CHAT: &[&str] = &["embed", "bge-", "all-minilm", "clip", "rerank"];
+// ── The custom server's key ───────────────────────────────────────────────────
+//
+// The key is stored together with the one address it was entered for, and is
+// only ever sent there. The address in the settings, or the one given to
+// "Connect", can be changed from the page; the key cannot follow it. And a key
+// never goes over plain http to another machine.
+
+#[derive(Serialize, serde::Deserialize)]
+struct BoundKey {
+ url: String,
+ key: String,
+}
+
+fn may_carry_key(url: &Url) -> bool {
+ url.scheme() == "https" || net::is_loopback_url(url)
+}
+
+/// Settings → Local models: stores the key for the address typed next to it.
+pub fn set_custom_key(typed_url: &str, key: &str) -> Result<(), String> {
+ let url = net::normalise_server_url(typed_url)?;
+ if !may_carry_key(&url) {
+ return Err(t("A key is only sent over https, or to a server on this computer."));
+ }
+ let bound = BoundKey { url: url.as_str().trim_end_matches('/').to_string(), key: key.trim().to_string() };
+ let value = serde_json::to_string(&bound).map_err(|e| e.to_string())?;
+ secrets::set(CUSTOM_KEY, &value)
+}
+
+/// The key, if it was entered for exactly this address.
+fn custom_key_for(url: &Url) -> Option<String> {
+ let stored = secrets::get(CUSTOM_KEY)?;
+ key_for(&stored, url)
+}
+
+fn key_for(stored: &str, url: &Url) -> Option<String> {
+ let bound: BoundKey = serde_json::from_str(stored).ok()?;
+ (may_carry_key(url) && bound.url == url.as_str().trim_end_matches('/') && !bound.key.is_empty())
+ .then_some(bound.key)
+}
+
/// A model server as the settings describe it.
pub struct Server {
pub id: &'static str,
@@ -53,7 +93,10 @@ pub fn server(settings: &Settings, id: &str) -> Option<Server> {
let (id, name, url, key) = match id {
"ollama" => ("ollama", "Ollama", &settings.ollama_url, None),
"lmstudio" => ("lmstudio", "LM Studio", &settings.lmstudio_url, None),
- "custom" => ("custom", crate::i18n::n_("OpenAI-compatible server"), &settings.custom_url, secrets::get(CUSTOM_KEY)),
+ "custom" => {
+ let key = net::normalise_server_url(&settings.custom_url).ok().and_then(|u| custom_key_for(&u));
+ ("custom", crate::i18n::n_("OpenAI-compatible server"), &settings.custom_url, key)
+ }
_ => return None,
};
Some(Server { id, name, url: url.clone(), key })
@@ -104,7 +147,7 @@ pub struct Connected {
pub async fn connect(id: &str, typed: &str) -> Result<Connected, String> {
let raw = if typed.trim().is_empty() { usual_address(id).unwrap_or_default() } else { typed.to_string() };
let url = net::normalise_server_url(&raw)?;
- let key = if id == "custom" { secrets::get(CUSTOM_KEY) } else { None };
+ let key = if id == "custom" { custom_key_for(&url) } else { None };
let models = list(&url, key.as_deref()).await?;
Ok(Connected {
url: url.as_str().trim_end_matches('/').to_string(),
@@ -500,4 +543,18 @@ mod tests {
assert_eq!(file_note("blob.bin", bin.to_str().unwrap()), "File: blob.bin");
let _ = std::fs::remove_dir_all(dir);
}
+
+ #[test]
+ fn the_custom_key_only_goes_to_the_address_it_was_entered_for() {
+ let url = |u: &str| net::normalise_server_url(u).unwrap();
+ let stored = serde_json::to_string(&BoundKey { url: "https://llm.example.com".into(), key: "sk-1".into() }).unwrap();
+ assert_eq!(key_for(&stored, &url("https://llm.example.com")).as_deref(), Some("sk-1"));
+ assert_eq!(key_for(&stored, &url("https://attacker.example")), None);
+ assert_eq!(key_for(&stored, &url("http://llm.example.com")), None);
+ // A plain string (the page can write one through secret_set) binds nothing.
+ assert_eq!(key_for("sk-raw", &url("https://llm.example.com")), None);
+ let local = serde_json::to_string(&BoundKey { url: "http://127.0.0.1:8080".into(), key: "k".into() }).unwrap();
+ assert_eq!(key_for(&local, &url("http://127.0.0.1:8080")).as_deref(), Some("k"));
+ assert!(!may_carry_key(&url("http://192.168.1.20:8080")));
+ }
}
diff --git a/windows/src/core/bridge.ts b/windows/src/core/bridge.ts
index fd75ce00..1bbf25fc 100644
--- a/windows/src/core/bridge.ts
+++ b/windows/src/core/bridge.ts
@@ -140,6 +140,9 @@ export const Bridge = {
*/
chatModels: (provider: string) => callOrThrow<ModelInfo[]>("chat_models", { provider }),
/** Settings → Local models → Connect: does the server answer, and with which models? */
+ /** The custom server's key, bound to the address it is entered for. */
+ localSetKey: (url: string, key: string) => call<void>("local_set_key", { url, key }),
+
localConnect: (provider: "ollama" | "lmstudio" | "custom", url: string) =>
callOrThrow<LocalServer>("local_connect", { provider, url }),
/** Copies a dropped file into the inbox. */
diff --git a/windows/src/i18n/extra.json b/windows/src/i18n/extra.json
index 64803e52..b339dfc0 100644
--- a/windows/src/i18n/extra.json
+++ b/windows/src/i18n/extra.json
@@ -3294,6 +3294,28 @@
"pt-BR": "⚠ falhou",
"ru": "⚠ ошибка",
"id": "⚠ gagal"
+ },
+ "A key is only sent over https, or to a server on this computer.": {
+ "zh-Hans": "密钥只会通过 https 发送,或发送到本机上的服务器。",
+ "hi": "कुंजी केवल https पर, या इसी कंप्यूटर के सर्वर को भेजी जाती है।",
+ "es": "La clave solo se envía por https o a un servidor de este ordenador.",
+ "ar": "لا يُرسَل المفتاح إلا عبر https، أو إلى خادم على هذا الحاسوب.",
+ "fr": "La clé n'est envoyée qu'en https, ou à un serveur sur cet ordinateur.",
+ "bn": "কী কেবল https-এর মাধ্যমে, অথবা এই কম্পিউটারের কোনো সার্ভারে পাঠানো হয়।",
+ "pt-BR": "A chave só é enviada por https ou para um servidor neste computador.",
+ "ru": "Ключ отправляется только по https или на сервер на этом компьютере.",
+ "id": "Kunci hanya dikirim lewat https, atau ke server di komputer ini."
+ },
+ "Only a file dropped on the island can be sent with a question.": {
+ "zh-Hans": "只有拖放到岛上的文件才能随问题一起发送。",
+ "hi": "सवाल के साथ केवल वही फ़ाइल भेजी जा सकती है जो island पर छोड़ी गई हो।",
+ "es": "Solo se puede enviar con una pregunta un archivo soltado en la isla.",
+ "ar": "لا يمكن إرسال ملف مع سؤال إلا إذا أُفلِت على الجزيرة.",
+ "fr": "Seul un fichier déposé sur l'île peut être envoyé avec une question.",
+ "bn": "প্রশ্নের সঙ্গে কেবল আইল্যান্ডে ছাড়া ফাইলই পাঠানো যায়।",
+ "pt-BR": "Só um arquivo solto na ilha pode ser enviado com uma pergunta.",
+ "ru": "С вопросом можно отправить только файл, перетащенный на остров.",
+ "id": "Hanya file yang dijatuhkan ke pulau yang bisa dikirim bersama pertanyaan."
}
}
}
diff --git a/windows/src/settings/main.ts b/windows/src/settings/main.ts
index 8aa14810..4282bac4 100644
--- a/windows/src/settings/main.ts
+++ b/windows/src/settings/main.ts
@@ -697,7 +697,8 @@ function localSection(customKey: boolean): HTMLElement {
status.append(h("div", { class: "hint", text: CHAT_STRINGS.connecting }));
try {
if (id === "custom" && key.value.trim()) {
- await Bridge.secretSet(CUSTOM_SERVER_KEY, key.value.trim());
+ // Stored with this address: the key is only ever sent there.
+ await Bridge.localSetKey(input.value || def.usual, key.value.trim());
key.value = "";
customKey = true;
}
diff --git a/windows/src/views/dom.ts b/windows/src/views/dom.ts
index 38d56f44..b5b9465c 100644
--- a/windows/src/views/dom.ts
+++ b/windows/src/views/dom.ts
@@ -87,7 +87,6 @@ export function h<K extends keyof HTMLElementTagNameMap>(
}
if (k === "class") el.className = String(v);
else if (k === "text") el.textContent = String(v);
- else if (k === "html") el.innerHTML = String(v);
else if (k.startsWith("on") && typeof v === "function") {
el.addEventListener(k.slice(2).toLowerCase(), v as EventListener);
} else if (k === "style") el.setAttribute("style", String(v));