A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.
Swift ai-agentsanthropicantigravityclaudeclaude-codecodexcursordynamic-islandgemini-cliiosiphonlinuxmacosmacos-appmenubar-appnotchopen-sourceswiftswiftuiwindows
feat(windows): answer with Claude Code when no Anthropic key is saved
Romain Brocheton81feebdce81f
diff --git a/windows/Cargo.lock b/windows/Cargo.lockindex 79ad9b16..9a53822f 100644--- a/windows/Cargo.lock+++ b/windows/Cargo.lock@@ -4961,6 +4961,7 @@ dependencies = ["libc","mio","pin-project-lite",+ "signal-hook-registry","socket2","tokio-macros","windows-sys 0.61.2",diff --git a/windows/README.md b/windows/README.mdindex 33efc0a7..670f0a0a 100644--- a/windows/README.md+++ b/windows/README.md@@ -249,6 +249,16 @@ side (tray, errors) embeds the same two files.Credential Manager**, never on disk and never in the interface — the island canonly ask whether a key exists. Same for every integration key.+**No key? Claude Code answers instead.** When no Anthropic key is saved and+the Claude Code CLI is installed (on PATH, or in the usual install folders),+the chat, Flow's clean-up and the notes of a call run through `claude -p`,+signed in with your own account. Coucou reads no credential: Claude Code+answers exactly as it does in a terminal. Each run loads none of your settings+(so none of your hooks), no MCP server and no skill, saves no session, and may+only search the web (the chat) and read the file you dropped. « OK Coucou »+still needs the key: its tools are Coucou's own. Saving a key switches+everything back to the API.+The chat also talks to **Google AI (Gemini)**, **OpenAI** and **OpenRouter**:add their keys in **Settings… → Chat providers**, then click the model nameabove the chat box to switch provider and model, as on the Mac. The model listdiff --git a/windows/src-tauri/Cargo.toml b/windows/src-tauri/Cargo.tomlindex a60d49af..c11d92ca 100644--- a/windows/src-tauri/Cargo.toml+++ b/windows/src-tauri/Cargo.toml@@ -20,7 +20,7 @@ tauri-plugin-autostart = "2"tauri-plugin-global-shortcut = "2"serde = { version = "1", features = ["derive"] }serde_json = { version = "1", features = ["preserve_order"] }-tokio = { version = "1", features = ["net", "io-util", "sync", "time", "rt", "macros"] }+tokio = { version = "1", features = ["net", "io-util", "sync", "time", "rt", "macros", "process"] }reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }# Phone link (phone_link/): a TLS server for the Android app, off unless the user# turns it on. Every crate here is justified in docs/ANDROID_LINK.md.diff --git a/windows/src-tauri/src/chat.rs b/windows/src-tauri/src/chat.rsindex 81d74955..e923b502 100644--- a/windows/src-tauri/src/chat.rs+++ b/windows/src-tauri/src/chat.rs@@ -13,7 +13,7 @@ use serde_json::{json, Value};use tauri::AppHandle;use crate::settings::Settings;-use crate::{claude, local_chat, openai_compat, secrets};+use crate::{claude, claude_code, local_chat, openai_compat, secrets};pub const ANTHROPIC: &str = "anthropic";@@ -248,8 +248,10 @@ pub async fn send_for_phone(pub async fn models(settings: &Settings, provider: &str) -> Result<Vec<ModelInfo>, String> {let no_key = || crate::i18n::t("No API key — add it in Settings.");if provider == ANTHROPIC {- let key = secrets::get(claude::KEY).ok_or_else(no_key)?;- return claude::models(&key).await;+ if let Some(key) = secrets::get(claude::KEY) {+ return claude::models(&key).await;+ }+ return claude_code::available().then(claude_code::models).ok_or_else(no_key);}if let Some(p) = openai_compat::provider(provider) {let key = secrets::get(p.key).ok_or_else(no_key)?;diff --git a/windows/src-tauri/src/claude.rs b/windows/src-tauri/src/claude.rsindex 7cd9a8e5..f6ed9c6a 100644--- a/windows/src-tauri/src/claude.rs+++ b/windows/src-tauri/src/claude.rs@@ -4,6 +4,10 @@// Everything happens here rather than in the island: the API key never leaves// the credential store, and file bytes never cross the IPC boundary.//+// Without a key, the chat and the one-shot answers go to the user's own Claude+// Code instead (claude_code.rs); « OK Coucou » still needs the key, its tools+// being Coucou's own.+//// COUCOU_ANTHROPIC_BASE_URL points the chat at an Anthropic-compatible gateway// instead (issue #180). Only that variable is read: Claude Code's own// ANTHROPIC_BASE_URL may name a proxy the user never meant to hand this key to.@@ -16,7 +20,7 @@ use serde_json::{json, Value};use crate::chat::{self, Chat, ChatContext, ChatReply, ModelInfo};use crate::i18n::{t, tf};-use crate::{net, secrets};+use crate::{claude_code, net, secrets};/// Credential store entry of the Anthropic API key.pub const KEY: &str = "anthropic-api-key";@@ -32,6 +36,19 @@ const MAX_INLINE_TEXT: u64 = 200_000;pub const DEFAULT_MODEL: &str = "claude-opus-5";+/// How long a chat turn through Claude Code may take: it may search the web.+const RELAY_CHAT_TIMEOUT: Duration = Duration::from_secs(180);++/// Whether Claude can answer at all: an API key, or else Claude Code.+pub fn ready() -> bool {+ secrets::present(KEY) || claude_code::available()+}++/// True when the answers come from Claude Code rather than the API.+pub fn uses_relay() -> bool {+ !secrets::present(KEY) && claude_code::available()+}+/// The Messages endpoint: Anthropic's, or the gateway in COUCOU_ANTHROPIC_BASE_URL./// Read once; the gateway's host (never the key) goes to the log once.fn endpoint() -> Result<Url, String> {@@ -143,7 +160,9 @@ pub async fn send(query: String,context: Option<ChatContext>,) -> Result<ChatReply, String> {- let key = secrets::get(KEY).ok_or_else(|| t("API key missing. Open settings."))?;+ let Some(key) = secrets::get(KEY) else {+ return send_through_claude_code(chat, model, query, context).await;+ };let endpoint = endpoint()?;let turn = chat.begin(chat::ANTHROPIC);@@ -160,10 +179,47 @@ pub async fn send(Ok(ChatReply { text })}+/// One chat turn answered by Claude Code, with web search, and reading the+/// dropped file when there is one.+async fn send_through_claude_code(+ chat: &Chat,+ model: &str,+ query: String,+ context: Option<ChatContext>,+) -> Result<ChatReply, String> {+ if !claude_code::available() {+ return Err(t("API key missing. Open settings."));+ }+ let turn = chat.begin(claude_code::PROVIDER);+ let reads_file = turn.first && matches!(context, Some(ChatContext::File { .. }));+ let inbox = crate::files::inbox_dir();+ let tools: &[&str] = if reads_file { &["WebSearch", "WebFetch", "Read"] } else { &["WebSearch", "WebFetch"] };+ let prompt = claude_code::chat_prompt(&turn.history, turn.first, context.as_ref(), &query);+ let text = claude_code::ask(&claude_code::Request {+ model,+ system: &chat::system_prompt(true),+ prompt: &prompt,+ tools,+ read_dir: reads_file.then_some(inbox.as_path()),+ timeout: RELAY_CHAT_TIMEOUT,+ })+ .await?;++ let plain = chat::plain_question(turn.first, context.as_ref(), &query);+ chat.commit(&turn, json!({ "role": "user", "content": plain }), json!({ "role": "assistant", "content": text }), &plain, &text);+ Ok(ChatReply { text })+}+/// One question, one answer, no history: the dictation clean-up and the notes/// of a call. The text of the answer, or why there is none.pub async fn complete(model: &str, system: &str, user: &str, max_tokens: u32, timeout: Duration) -> Result<String, String> {- let key = secrets::get(KEY).ok_or_else(|| t("API key missing. Open settings."))?;+ let Some(key) = secrets::get(KEY) else {+ if !claude_code::available() {+ return Err(t("API key missing. Open settings."));+ }+ let request = claude_code::Request { model, system, prompt: user, tools: &[], read_dir: None, timeout };+ return claude_code::ask(&request).await;+ };let endpoint = endpoint()?;let body = json!({"model": model,diff --git a/windows/src-tauri/src/claude_code.rs b/windows/src-tauri/src/claude_code.rsnew file mode 100644index 00000000..32f321b4--- /dev/null+++ b/windows/src-tauri/src/claude_code.rs@@ -0,0 +1,247 @@+// The Claude Code relay: with no Anthropic API key saved, the chat, Flow's+// clean-up and the notes of a call are answered by the user's own Claude Code+// (`claude -p`), signed in with their own account. Coucou reads no credential+// and makes no network call of its own: Claude Code answers exactly as it does+// in a terminal.+//+// Each run is kept apart from the user's sessions: no settings file is loaded+// (so no hooks: Coucou's own would show the relay's runs as sessions), no MCP+// server, no skill, nothing saved to resume, and it runs in an empty folder of+// Coucou's, so no CLAUDE.md is picked up. It may only use the tools it is+// given: web search for the chat, and reading the one dropped file.++use std::ffi::OsString;+use std::path::{Path, PathBuf};+use std::process::Stdio;+use std::time::Duration;++use serde_json::Value;+use tokio::io::AsyncWriteExt;++use crate::chat::{self, ChatContext, ModelInfo};+use crate::i18n::{t, tf};+use crate::{platform, settings};++/// The chat's provider id while the relay answers: its turns are plain text,+/// so they never mix with the API's content blocks.+pub const PROVIDER: &str = "claude-code";++/// The models offered in the picker without a key. Claude Code takes these ids+/// as they are, and so does the API once a key is added.+const MODELS: [(&str, &str); 3] = [+ ("claude-opus-5", "Claude Opus 5"),+ ("claude-sonnet-5", "Claude Sonnet 5"),+ ("claude-haiku-4-5", "Claude Haiku 4.5"),+];++/// What one run of `claude -p` is asked.+pub struct Request<'a> {+ pub model: &'a str,+ pub system: &'a str,+ pub prompt: &'a str,+ /// Built-in tools the run may use; none at all when empty.+ pub tools: &'a [&'a str],+ /// A folder the run may read from, besides its own.+ pub read_dir: Option<&'a Path>,+ pub timeout: Duration,+}++/// The Claude Code CLI, when it is installed.+pub fn exe() -> Option<PathBuf> {+ platform::cli_candidates("claude").into_iter().next()+}++pub fn available() -> bool {+ exe().is_some()+}++/// The models offered in the picker when Claude Code answers.+pub fn models() -> Vec<ModelInfo> {+ MODELS.iter().map(|(id, label)| ModelInfo { id: (*id).into(), label: (*label).into() }).collect()+}++/// Runs `claude -p` once and returns the text of its answer, or why there is none.+pub async fn ask(request: &Request<'_>) -> Result<String, String> {+ let exe = exe().ok_or_else(|| t("Claude Code is not installed."))?;+ let workdir = settings::local_dir().join("relay");+ std::fs::create_dir_all(&workdir).map_err(|e| e.to_string())?;++ let mut cmd = tokio::process::Command::new(&exe);+ cmd.args(args(request))+ .current_dir(&workdir)+ .env_remove("CLAUDECODE")+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .kill_on_drop(true);+ // An npm install is a `#!/usr/bin/env node` script: its own folder first on+ // PATH so it finds its Node, as codex_plan.rs does for Codex.+ if let Some(dir) = exe.parent() {+ let mut dirs = vec![dir.to_path_buf()];+ if let Some(path) = std::env::var_os("PATH") {+ dirs.extend(std::env::split_paths(&path));+ }+ if let Ok(joined) = std::env::join_paths(dirs) {+ cmd.env("PATH", joined);+ }+ }+ platform::no_console(cmd.as_std_mut());++ let mut child = cmd.spawn().map_err(|e| tf("Could not start Claude Code: {error}", &[("error", &e.to_string())]))?;+ if let Some(mut stdin) = child.stdin.take() {+ stdin.write_all(request.prompt.as_bytes()).await.map_err(|e| e.to_string())?;+ }+ let output = tokio::time::timeout(request.timeout, child.wait_with_output())+ .await+ .map_err(|_| t("Claude Code took too long to answer."))?+ .map_err(|e| e.to_string())?;+ parse(&output.stdout).map_err(|err| {+ let stderr = String::from_utf8_lossy(&output.stderr);+ match stderr.trim() {+ "" => err,+ detail => format!("{err} ({})", detail.lines().last().unwrap_or(detail)),+ }+ })+}++fn args(request: &Request<'_>) -> Vec<OsString> {+ let mut out: Vec<OsString> = [+ "-p",+ "--output-format",+ "json",+ "--model",+ request.model,+ "--system-prompt",+ request.system,+ "--tools",+ ]+ .iter()+ .map(OsString::from)+ .collect();+ out.push(request.tools.join(",").into());+ if !request.tools.is_empty() {+ out.push("--allowedTools".into());+ out.push(request.tools.join(",").into());+ }+ if let Some(dir) = request.read_dir {+ out.push("--add-dir".into());+ out.push(dir.as_os_str().to_owned());+ }+ for flag in ["--setting-sources", "", "--strict-mcp-config", "--no-session-persistence", "--disable-slash-commands"] {+ out.push(flag.into());+ }+ out+}++/// The answer's text from `claude -p --output-format json`.+fn parse(stdout: &[u8]) -> Result<String, String> {+ let json: Value = serde_json::from_slice(stdout).map_err(|_| t("Claude Code gave no answer."))?;+ let result = json.get("result").and_then(Value::as_str).unwrap_or("").trim();+ if json.get("is_error").and_then(Value::as_bool).unwrap_or(false) {+ let why = if result.is_empty() { t("Claude Code could not answer.") } else { result.to_string() };+ return Err(why);+ }+ if result.is_empty() {+ return Err(t("No response text."));+ }+ Ok(result.to_string())+}++/// One chat turn as a single prompt: the earlier plain turns, the context the+/// first question carries, then the question.+pub fn chat_prompt(history: &[Value], first: bool, context: Option<&ChatContext>, query: &str) -> String {+ let mut out = String::new();+ if !history.is_empty() {+ out.push_str("The conversation so far:\n<conversation>\n");+ for turn in history {+ let role = turn.get("role").and_then(Value::as_str).unwrap_or("user");+ let text = turn.get("content").and_then(Value::as_str).unwrap_or("");+ out.push_str(&format!("<{role}>\n{text}\n</{role}>\n"));+ }+ out.push_str("</conversation>\n\nThe user's new message:\n");+ }+ match context.filter(|_| first) {+ Some(ChatContext::File { name, path }) => {+ out.push_str(&format!("File: {name} (read it at {path})\n\n"));+ }+ Some(ChatContext::Window { app_name, title, url }) => {+ out.push_str(&chat::window_line(app_name, title, url.as_deref()));+ out.push_str("\n\n");+ }+ None => {}+ }+ out.push_str(query);+ out+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn strings(args: &[OsString]) -> Vec<String> {+ args.iter().map(|a| a.to_string_lossy().into_owned()).collect()+ }++ #[test]+ fn a_run_loads_no_settings_and_only_the_tools_it_is_given() {+ let request = Request {+ model: "claude-x",+ system: "sys",+ prompt: "hi",+ tools: &[],+ read_dir: None,+ timeout: Duration::from_secs(1),+ };+ let a = strings(&args(&request));+ assert_eq!(&a[..8], ["-p", "--output-format", "json", "--model", "claude-x", "--system-prompt", "sys", "--tools"]);+ assert_eq!(a[8], "");+ assert!(!a.contains(&"--allowedTools".to_string()));+ assert!(!a.contains(&"--add-dir".to_string()));+ let sources = a.iter().position(|x| x == "--setting-sources").unwrap();+ assert_eq!(a[sources + 1], "");+ for flag in ["--strict-mcp-config", "--no-session-persistence", "--disable-slash-commands"] {+ assert!(a.contains(&flag.to_string()), "{flag}");+ }++ let inbox = PathBuf::from("/tmp/inbox");+ let request = Request { tools: &["WebSearch", "Read"], read_dir: Some(&inbox), ..request };+ let a = strings(&args(&request));+ assert_eq!(a[8], "WebSearch,Read");+ let allowed = a.iter().position(|x| x == "--allowedTools").unwrap();+ assert_eq!(a[allowed + 1], "WebSearch,Read");+ let dir = a.iter().position(|x| x == "--add-dir").unwrap();+ assert_eq!(a[dir + 1], "/tmp/inbox");+ }++ #[test]+ fn the_answer_or_the_error_comes_from_the_result_field() {+ assert_eq!(parse(br#"{"type":"result","is_error":false,"result":" Hi "}"#).unwrap(), "Hi");+ assert_eq!(parse(br#"{"is_error":true,"result":"Not logged in"}"#).unwrap_err(), "Not logged in");+ assert_eq!(parse(br#"{"is_error":true}"#).unwrap_err(), "Claude Code could not answer.");+ assert_eq!(parse(br#"{"is_error":false,"result":" "}"#).unwrap_err(), "No response text.");+ assert_eq!(parse(b"[claude-code:unrecognized_model]").unwrap_err(), "Claude Code gave no answer.");+ }++ #[test]+ fn the_prompt_carries_the_history_then_the_context_then_the_question() {+ assert_eq!(chat_prompt(&[], true, None, "q"), "q");+ let history = vec![json!({"role":"user","content":"a"}), json!({"role":"assistant","content":"b"})];+ let p = chat_prompt(&history, false, None, "c");+ assert_eq!(+ p,+ "The conversation so far:\n<conversation>\n<user>\na\n</user>\n<assistant>\nb\n</assistant>\n</conversation>\n\nThe user's new message:\nc"+ );+ let file = ChatContext::File { name: "a.pdf".into(), path: "/inbox/a.pdf".into() };+ assert_eq!(chat_prompt(&[], true, Some(&file), "why?"), "File: a.pdf (read it at /inbox/a.pdf)\n\nwhy?");+ assert!(chat_prompt(&history, false, Some(&file), "why?").ends_with("message:\nwhy?"));+ let win = ChatContext::Window { app_name: "Code".into(), title: "main.rs".into(), url: None };+ assert_eq!(chat_prompt(&[], true, Some(&win), "q"), "Context — App: Code, Window: main.rs\n\nq");+ }++ #[test]+ fn the_picker_offers_the_same_models_as_the_settings() {+ let ids: Vec<String> = models().into_iter().map(|m| m.id).collect();+ assert_eq!(ids, ["claude-opus-5", "claude-sonnet-5", "claude-haiku-4-5"]);+ }+}diff --git a/windows/src-tauri/src/codex_plan.rs b/windows/src-tauri/src/codex_plan.rsindex d3993aec..9a8ab122 100644--- a/windows/src-tauri/src/codex_plan.rs+++ b/windows/src-tauri/src/codex_plan.rs@@ -56,7 +56,7 @@ pub fn read() -> Option<Value> {}let _busy = NotBusy;- let exe = platform::codex_candidates().into_iter().next()?;+ let exe = platform::cli_candidates("codex").into_iter().next()?;let mut cmd = Command::new(&exe);cmd.arg("app-server").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null());// An npm install is a `#!/usr/bin/env node` script (or a .cmd calling node):diff --git a/windows/src-tauri/src/flow/cleanup.rs b/windows/src-tauri/src/flow/cleanup.rsindex f8e698e3..a2304467 100644--- a/windows/src-tauri/src/flow/cleanup.rs+++ b/windows/src-tauri/src/flow/cleanup.rs@@ -1,8 +1,9 @@// The clean-up of Flow dictation: Claude removes the "um", the repeats and the// corrections said on the way ("at 3, no, at 4" → "at 4"), fixes the// punctuation and writes in the app's style. Only when it is turned on in the-// Coucou window and a Claude key is set; the text (never the audio) then goes-// to Anthropic with that key, and nowhere else. Any problem (no network, slow+// Coucou window and a Claude key is set, or else Claude Code is installed; the+// text (never the audio) then goes to Anthropic with that key or through the+// user's own Claude Code, and nowhere else. Any problem (no network, slow// answer, odd reply) and the words are pasted as they were heard. Port of// FlowCleanup.swift.@@ -14,9 +15,11 @@ use super::text;pub const MODEL: &str = "claude-haiku-4-5";/// Past this, the words are pasted as heard rather than keeping you waiting.const TIMEOUT: Duration = Duration::from_secs(4);+/// Claude Code takes a couple of seconds just to start.+const RELAY_TIMEOUT: Duration = Duration::from_secs(10);pub fn has_key() -> bool {- crate::secrets::present(crate::claude::KEY)+ crate::claude::ready()}pub async fn clean(raw: &str, style: Style, app: Option<&str>, words: &[String]) -> String {@@ -24,7 +27,8 @@ pub async fn clean(raw: &str, style: Style, app: Option<&str>, words: &[String])return raw.to_string();}let user = format!("<dictation>\n{raw}\n</dictation>");- match crate::claude::complete(MODEL, &system(style, app, words), &user, 2048, TIMEOUT).await {+ let timeout = if crate::claude::uses_relay() { RELAY_TIMEOUT } else { TIMEOUT };+ match crate::claude::complete(MODEL, &system(style, app, words), &user, 2048, timeout).await {Ok(reply) => {let cleaned = reply.replace("<dictation>", "").replace("</dictation>", "").trim().to_string();if plausible(&cleaned, raw) {diff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rsindex 5e544f80..dfe859e5 100644--- a/windows/src-tauri/src/lib.rs+++ b/windows/src-tauri/src/lib.rs@@ -4,6 +4,7 @@ mod agent_hooks;mod agents;mod chat;mod claude;+mod claude_code;mod codex_plan;mod config_file;mod desktop;@@ -577,6 +578,12 @@ fn secret_present(key: String) -> bool {secrets::present(&key)}+/// Whether Claude can answer: an API key, or else the user's own Claude Code.+#[tauri::command]+fn claude_ready() -> bool {+ claude::ready()+}+#[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.@@ -848,6 +855,7 @@ pub fn run() {chat_reset,ingest_file,secret_present,+ claude_ready,secret_set,secret_clear,refresh_integration,diff --git a/windows/src-tauri/src/phone_link/chat_backend.rs b/windows/src-tauri/src/phone_link/chat_backend.rsindex ccca521b..7f9a599a 100644--- a/windows/src-tauri/src/phone_link/chat_backend.rs+++ b/windows/src-tauri/src/phone_link/chat_backend.rs@@ -48,10 +48,13 @@ impl ChatBackend for AppChat {let id = model_id.to_string();Box::pin(async move {let Some((provider, model)) = parse_model_id(&id) else { return Err(ChatFail::Internal) };- if let Some(key) = key_name(provider) {- if secrets::get(key).is_none() {- return Err(ChatFail::NoKey);- }+ let ready = match key_name(provider) {+ Some(claude::KEY) => claude::ready(),+ Some(key) => secrets::present(key),+ None => true,+ };+ if !ready {+ return Err(ChatFail::NoKey);}let result = chat::send_for_phone(&settings, &chat, provider, model, text, |so_far| {let _ = deltas.send(so_far);diff --git a/windows/src-tauri/src/platform/linux.rs b/windows/src-tauri/src/platform/linux.rsindex 64607103..f451eefa 100644--- a/windows/src-tauri/src/platform/linux.rs+++ b/windows/src-tauri/src/platform/linux.rs@@ -268,23 +268,24 @@ 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> {+/// Where a CLI such as `codex` or `claude` may be, best first: $PATH, then the+/// usual per-user install folders, which a desktop launch often leaves out of+/// $PATH (the native installers' ~/.local/bin, npm's global prefix, Volta, Bun,+/// pnpm, and nvm with its newest Node first).+pub fn cli_candidates(name: &str) -> Vec<PathBuf> {let home = home_dir();- let mut out: Vec<PathBuf> = find_on_path("codex").into_iter().collect();+ let mut out: Vec<PathBuf> = find_on_path(name).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(home.join(dir).join(name));}- out.push(PathBuf::from("/usr/local/bin/codex"));- out.push(PathBuf::from("/usr/bin/codex"));+ out.push(PathBuf::from("/usr/local/bin").join(name));+ out.push(PathBuf::from("/usr/bin").join(name));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.extend(versions.iter().map(|v| nvm.join(v).join("bin").join(name)));}out.retain(|p| {std::fs::metadata(p)diff --git a/windows/src-tauri/src/platform/windows.rs b/windows/src-tauri/src/platform/windows.rsindex aec1aa33..e850ae55 100644--- a/windows/src-tauri/src/platform/windows.rs+++ b/windows/src-tauri/src/platform/windows.rs@@ -141,22 +141,23 @@ pub fn find_on_path(stem: &str) -> Option<PathBuf> {None}-/// Where the Codex CLI may be, best first: %PATH% (codex.exe or npm's-/// codex.cmd), then npm's global folder and the Volta / Bun / pnpm ones.-/// Rust quotes the one fixed argument safely for a `.cmd` (see find_on_path).-pub fn codex_candidates() -> Vec<PathBuf> {- let mut out: Vec<PathBuf> = find_on_path("codex").into_iter().collect();+/// Where a CLI such as `codex` or `claude` may be, best first: %PATH% (the+/// .exe or npm's .cmd), then npm's global folder, the Volta / Bun / pnpm ones+/// and the native installers' %USERPROFILE%\.local\bin. Rust quotes arguments+/// safely for a `.cmd` (see find_on_path).+pub fn cli_candidates(name: &str) -> Vec<PathBuf> {+ let mut out: Vec<PathBuf> = find_on_path(name).into_iter().collect();let var = |k: &str| std::env::var_os(k).map(PathBuf::from).filter(|p| p.is_absolute());if let Some(appdata) = var("APPDATA") {- out.push(appdata.join("npm").join("codex.cmd"));+ out.push(appdata.join("npm").join(format!("{name}.cmd")));}if let Some(local) = var("LOCALAPPDATA") {- out.push(local.join("Volta").join("bin").join("codex.exe"));- out.push(local.join("pnpm").join("codex.cmd"));+ out.push(local.join("Volta").join("bin").join(format!("{name}.exe")));+ out.push(local.join("pnpm").join(format!("{name}.cmd")));}if let Some(home) = var("USERPROFILE") {- out.push(home.join(".bun").join("bin").join("codex.exe"));- out.push(home.join(".local").join("bin").join("codex.exe"));+ out.push(home.join(".bun").join("bin").join(format!("{name}.exe")));+ out.push(home.join(".local").join("bin").join(format!("{name}.exe")));}out.retain(|p| p.is_file());outdiff --git a/windows/src/core/bridge.ts b/windows/src/core/bridge.tsindex ce2f2c4a..52f63162 100644--- a/windows/src/core/bridge.ts+++ b/windows/src/core/bridge.ts@@ -380,6 +380,11 @@ export const Bridge = {ingestFile: (path: string) => callOrThrow<DroppedFile>("ingest_file", { path }),/** Only ever tells you whether a key exists — never its value. */secretPresent: (key: string) => call<boolean>("secret_present", { key }),+ /** Whether Claude can answer: the API key, or else the user's own Claude Code. */+ claudeReady: () => call<boolean>("claude_ready"),+ /** Whether a provider can answer with this key: Claude Code stands in for a missing Anthropic one. */+ keyReady: (key: string) =>+ key === "anthropic-api-key" ? call<boolean>("claude_ready") : call<boolean>("secret_present", { key }),secretSet: (key: string, value: string) => callOrThrow<void>("secret_set", { key, value }),secretClear: (key: string) => callOrThrow<void>("secret_clear", { key }),diff --git a/windows/src/i18n/extra.json b/windows/src/i18n/extra.jsonindex 06e3c499..e43bb4fa 100644--- a/windows/src/i18n/extra.json+++ b/windows/src/i18n/extra.json@@ -6091,6 +6091,84 @@"id": "Matikan pil lain untuk memberi tempat bagi WhatsApp (maksimal {max}).","de": "Schalte eine andere Pill aus, um Platz für WhatsApp zu schaffen (höchstens {max}).","tr": "WhatsApp’a yer açmak için başka bir hapı kapat (en fazla {max})."+ },+ "No key: your Claude Code answers instead, with your account.": {+ "zh-Hans": "没有密钥:改由你的 Claude Code 用你的账户回答。",+ "hi": "कोई कुंजी नहीं: इसके बजाय आपका Claude Code आपके खाते से जवाब देता है।",+ "es": "Sin clave: responde tu Claude Code, con tu cuenta.",+ "ar": "لا يوجد مفتاح: يجيب Claude Code الخاص بك بدلاً من ذلك، بحسابك.",+ "fr": "Pas de clé : ton Claude Code répond à la place, avec ton compte.",+ "bn": "কোনো কী নেই: এর বদলে আপনার Claude Code আপনার অ্যাকাউন্ট দিয়ে উত্তর দেয়।",+ "pt-BR": "Sem chave: seu Claude Code responde no lugar, com sua conta.",+ "ru": "Ключа нет: вместо него отвечает ваш Claude Code с вашей учётной записью.",+ "id": "Tidak ada kunci: Claude Code Anda yang menjawab, dengan akun Anda.",+ "de": "Kein Schlüssel: Stattdessen antwortet dein Claude Code mit deinem Konto.",+ "tr": "Anahtar yok: bunun yerine Claude Code'unuz hesabınızla yanıtlıyor."+ },+ "Claude Code is not installed.": {+ "zh-Hans": "未安装 Claude Code。",+ "hi": "Claude Code इंस्टॉल नहीं है।",+ "es": "Claude Code no está instalado.",+ "ar": "Claude Code غير مثبّت.",+ "fr": "Claude Code n'est pas installé.",+ "bn": "Claude Code ইনস্টল করা নেই।",+ "pt-BR": "O Claude Code não está instalado.",+ "ru": "Claude Code не установлен.",+ "id": "Claude Code belum terpasang.",+ "de": "Claude Code ist nicht installiert.",+ "tr": "Claude Code yüklü değil."+ },+ "Could not start Claude Code: {error}": {+ "zh-Hans": "无法启动 Claude Code:{error}",+ "hi": "Claude Code शुरू नहीं हो सका: {error}",+ "es": "No se pudo iniciar Claude Code: {error}",+ "ar": "تعذّر تشغيل Claude Code: {error}",+ "fr": "Impossible de lancer Claude Code : {error}",+ "bn": "Claude Code চালু করা যায়নি: {error}",+ "pt-BR": "Não foi possível iniciar o Claude Code: {error}",+ "ru": "Не удалось запустить Claude Code: {error}",+ "id": "Tidak dapat memulai Claude Code: {error}",+ "de": "Claude Code konnte nicht gestartet werden: {error}",+ "tr": "Claude Code başlatılamadı: {error}"+ },+ "Claude Code took too long to answer.": {+ "zh-Hans": "Claude Code 回答太慢。",+ "hi": "Claude Code ने जवाब देने में बहुत देर की।",+ "es": "Claude Code tardó demasiado en responder.",+ "ar": "استغرق Claude Code وقتاً طويلاً للرد.",+ "fr": "Claude Code a mis trop de temps à répondre.",+ "bn": "Claude Code উত্তর দিতে খুব বেশি সময় নিয়েছে।",+ "pt-BR": "O Claude Code demorou demais para responder.",+ "ru": "Claude Code слишком долго не отвечал.",+ "id": "Claude Code terlalu lama menjawab.",+ "de": "Claude Code hat zu lange für die Antwort gebraucht.",+ "tr": "Claude Code yanıt vermekte çok gecikti."+ },+ "Claude Code gave no answer.": {+ "zh-Hans": "Claude Code 没有给出回答。",+ "hi": "Claude Code ने कोई जवाब नहीं दिया।",+ "es": "Claude Code no dio ninguna respuesta.",+ "ar": "لم يقدّم Claude Code أي إجابة.",+ "fr": "Claude Code n'a donné aucune réponse.",+ "bn": "Claude Code কোনো উত্তর দেয়নি।",+ "pt-BR": "O Claude Code não deu resposta.",+ "ru": "Claude Code не дал ответа.",+ "id": "Claude Code tidak memberi jawaban.",+ "de": "Claude Code hat keine Antwort gegeben.",+ "tr": "Claude Code yanıt vermedi."+ },+ "Claude Code could not answer.": {+ "zh-Hans": "Claude Code 无法回答。",+ "hi": "Claude Code जवाब नहीं दे सका।",+ "es": "Claude Code no pudo responder.",+ "ar": "لم يتمكن Claude Code من الإجابة.",+ "fr": "Claude Code n'a pas pu répondre.",+ "bn": "Claude Code উত্তর দিতে পারেনি।",+ "pt-BR": "O Claude Code não conseguiu responder.",+ "ru": "Claude Code не смог ответить.",+ "id": "Claude Code tidak dapat menjawab.",+ "de": "Claude Code konnte nicht antworten.",+ "tr": "Claude Code yanıt veremedi."}}}diff --git a/windows/src/island/integrations.ts b/windows/src/island/integrations.tsindex 712f6cad..d6fc9de0 100644--- a/windows/src/island/integrations.ts+++ b/windows/src/island/integrations.ts@@ -57,7 +57,7 @@ export async function refreshConfigured() {let configured: boolean;switch (def.connect.kind) {case "key":- configured = (await Bridge.secretPresent(def.connect.key)) ?? false;+ configured = (await Bridge.keyReady(def.connect.key)) ?? false;break;case "hooks":// Without an answer from Rust (a plain browser), the Claude Code pilldiff --git a/windows/src/settings/main.ts b/windows/src/settings/main.tsindex 7d086b82..5d043f36 100644--- a/windows/src/settings/main.ts+++ b/windows/src/settings/main.ts@@ -337,9 +337,15 @@ const MODELS: [string, string][] = [["claude-haiku-4-5", "Claude Haiku 4.5"],];-function apiSection(hasKey: boolean): HTMLElement {- const dot = statusDot(hasKey);- const state = h("span", { class: "hint", text: hasKey ? t("Key saved in the {store}.", { store: KEY_STORE }) : t("No key yet — the chat needs one.") });+/** The state line under Claude: the key, else Claude Code standing in for it, else what is missing. */+function apiState(hasKey: boolean, relay: boolean): string {+ if (hasKey) return t("Key saved in the {store}.", { store: KEY_STORE });+ return relay ? t("No key: your Claude Code answers instead, with your account.") : t("No key yet — the chat needs one.");+}++function apiSection(hasKey: boolean, relay: boolean): HTMLElement {+ const dot = statusDot(hasKey || relay);+ const state = h("span", { class: "hint", text: apiState(hasKey, relay) });const field = h("input", {type: "password",@@ -355,10 +361,9 @@ function apiSection(hasKey: boolean): HTMLElement {async function refresh() {const present = (await Bridge.secretPresent("anthropic-api-key")) ?? false;- dot.style.background = present ? "#22c55e" : "#f4505e";- state.textContent = present- ? t("Key saved in the {store}.", { store: KEY_STORE })- : t("No key yet — the chat needs one.");+ const ready = (await Bridge.claudeReady()) ?? false;+ dot.style.background = ready ? "#22c55e" : "#f4505e";+ state.textContent = apiState(present, ready && !present);field.placeholder = present ? `•••••••••••• ${t("(stored)")}` : "sk-ant-...";clearBtn.style.display = present ? "" : "none";}@@ -1362,6 +1367,7 @@ async function render() {const agents = await Bridge.agentHooksList();const hasKey = (await Bridge.secretPresent("anthropic-api-key")) ?? false;+ const claudeRelay = !hasKey && ((await Bridge.claudeReady()) ?? false);const shortcutReport = await Bridge.shortcutsStatus();const keys = [@@ -1376,7 +1382,7 @@ async function render() {const connected: Record<string, boolean> = { ...((await Bridge.agentHooksStatus()) ?? {}) };for (const def of availablePills()) {if (def.connect.kind === "key") {- connected[def.id] = present[def.connect.key] ?? (await Bridge.secretPresent(def.connect.key)) ?? false;+ connected[def.id] = present[def.connect.key] ?? (await Bridge.keyReady(def.connect.key)) ?? false;}}/** A chat provider's key was saved or removed: its pill's row says so at once. */@@ -1401,7 +1407,7 @@ async function render() {general: () => [generalSection()],pills: () => [activePillsSection(connected)],agents: () => [claudeSection(status), agentsSection(agents), planSection(status)],- chat: () => [apiSection(hasKey), chatProvidersSection(chatKeys, keyChanged), localSection(customKey)],+ chat: () => [apiSection(hasKey, claudeRelay), chatProvidersSection(chatKeys, keyChanged), localSection(customKey)],integrations: () => [integrationsSection(present), ...whatsappSections()],phone: () => [phoneSection(settings.phoneLink ?? false, toggle, settings)],shortcuts: () => [shortcutsSection(shortcutReport)],diff --git a/windows/src/settings/phone.ts b/windows/src/settings/phone.tsindex f94a4070..d197be6e 100644--- a/windows/src/settings/phone.ts+++ b/windows/src/settings/phone.ts@@ -461,7 +461,7 @@ function chatBlock(makeToggle: Toggle, settings: Settings): HTMLElement {body.replaceChildren();if (!status.enabled) return;const hasKey: Record<string, boolean> = {};- for (const p of usableProvidersCandidates()) hasKey[p.id] = (await Bridge.secretPresent(p.key!)) ?? false;+ for (const p of usableProvidersCandidates()) hasKey[p.id] = (await Bridge.keyReady(p.key!)) ?? false;const providers = usableProviders(settings, hasKey);body.append(h("div", { class: "hint", text: t("Models the phone may use") }));if (providers.length === 0) body.append(h("div", { class: "hint", text: t("No provider is ready: add an API key or connect a local model first.") }));diff --git a/windows/src/views/chat.ts b/windows/src/views/chat.tsindex f11fea16..27a7101b 100644--- a/windows/src/views/chat.ts+++ b/windows/src/views/chat.ts@@ -152,7 +152,7 @@ function buildPicker(onChange: () => void): Picker {return;}// Nothing is asked of a provider that has no key yet.- if (p.key && !(await Bridge.secretPresent(p.key))) {+ if (p.key && !(await Bridge.keyReady(p.key))) {if (ticket === request) status(t(STRINGS.noKey), true);return;}diff --git a/windows/tests/chat.test.mjs b/windows/tests/chat.test.mjsindex ff03d4a7..35e7eb98 100644--- a/windows/tests/chat.test.mjs+++ b/windows/tests/chat.test.mjs@@ -51,17 +51,30 @@ test("the model button shows the active provider's model", () => {test("a provider without a key is never asked for its models", async () => {answers.secret_present = false;+ answers.claude_ready = false;$(".model-btn").fire("click");await flush();assert.ok($(".chat-body").classList.contains("picking"));assert.deepEqual(chips(), ["Anthropic", "Google", "OpenAI", "OpenRouter"]);- assert.deepEqual(sent("secret_present"), [{ key: "anthropic-api-key" }]);+ assert.equal(sent("claude_ready").length, 1);assert.deepEqual(sent("chat_models"), []);assert.match($(".picker-status").textContent, /No API key/);});+test("without a key, Claude Code standing in still lists Claude's models", async () => {+ answers.secret_present = false;+ answers.claude_ready = true;+ answers.chat_models = [{ id: "claude-opus-5", label: "Claude Opus 5" }];+ $(".model-btn").fire("click");+ await flush();+ assert.deepEqual(sent("secret_present"), []);+ assert.deepEqual(sent("chat_models"), [{ provider: "anthropic" }]);+ assert.deepEqual(models(), ["Claude Opus 5"]);+});+test("with a key, the models are listed and picking one saves it", async () => {answers.secret_present = true;+ answers.claude_ready = true;answers.chat_models = [{ id: "claude-opus-5", label: "Claude Opus 5" },{ id: "claude-sonnet-5", label: "Claude Sonnet 5" },