Skip to content

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

Windows and Linux: chat on your own subscription, as on the Mac

Claude2e7088a791ff
diff --git a/NotchBuddy/Resources/Localizable.xcstrings b/NotchBuddy/Resources/Localizable.xcstrings
index 49ee689d..d75b5eb9 100644
--- a/NotchBuddy/Resources/Localizable.xcstrings
+++ b/NotchBuddy/Resources/Localizable.xcstrings
@@ -75095,95 +75095,6 @@
}
}
},
- "chat.relay.no-key" : {
- "extractionState" : "manual",
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "No key: your Claude Code answers instead, with your account."
- }
- },
- "fr" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Pas de clé : ton Claude Code répond à la place, avec ton compte."
- }
- },
- "es" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Sin clave: responde tu Claude Code, con tu cuenta."
- }
- },
- "pt-BR" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Sem chave: o seu Claude Code responde no lugar, com a sua conta."
- }
- },
- "ru" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Нет ключа: вместо него отвечает ваш Claude Code с вашей учётной записью."
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "没有密钥:改由你的 Claude Code 用你的账户回答。"
- }
- },
- "hi" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "कोई कुंजी नहीं: इसके बजाय आपका Claude Code आपके खाते से जवाब देता है।"
- }
- },
- "ar" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "لا يوجد مفتاح: يجيب Claude Code الخاص بك بدلاً من ذلك، بحسابك."
- }
- },
- "bn" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "কোনো কী নেই: এর বদলে আপনার Claude Code আপনার অ্যাকাউন্ট দিয়ে উত্তর দেয়।"
- }
- },
- "id" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Tanpa kunci: Claude Code-mu yang menjawab, dengan akunmu."
- }
- },
- "de" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Kein Schlüssel: Dein Claude Code antwortet stattdessen, mit deinem Konto."
- }
- },
- "tr" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Anahtar yok: Bunun yerine Claude Code’un kendi hesabınla yanıtlar."
- }
- },
- "th" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "ไม่มีคีย์: Claude Code ของคุณจะตอบแทน ด้วยบัญชีของคุณ"
- }
- },
- "zh-Hant" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "沒有金鑰:改由你的 Claude Code 用你的帳戶回答。"
- }
- }
- }
- },
"chat.subscriptions.title" : {
"extractionState" : "manual",
"localizations" : {
diff --git a/windows/scripts/gen-strings.mjs b/windows/scripts/gen-strings.mjs
index ce6fb5a7..c9c611fe 100644
--- a/windows/scripts/gen-strings.mjs
+++ b/windows/scripts/gen-strings.mjs
@@ -33,6 +33,9 @@ export const LANGUAGES = ["en", "zh-Hans", "hi", "es", "ar", "fr", "bn", "pt-BR"
const RENAMES = {
"Auto-close · %llds": ["seconds"],
"Chat with %@": ["name"],
+ "chat.subscriptions.default-model": ["tool"],
+ "chat.subscriptions.found": ["tool"],
+ "chat.subscriptions.missing": ["tool"],
"Claude is reading %@…": ["name"],
"Connected · %@": ["detail"],
"Key configured · %@": ["model"],
diff --git a/windows/src-tauri/src/chat.rs b/windows/src-tauri/src/chat.rs
index e923b502..a681e05e 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, claude_code, local_chat, openai_compat, secrets};
+use crate::{claude, cli_relay, local_chat, openai_compat, secrets};
pub const ANTHROPIC: &str = "anthropic";
@@ -207,6 +207,9 @@ pub async fn send(
let context = context.map(checked_context).transpose()?;
let provider = settings.chat_provider.as_str();
let model = model_for(settings, provider);
+ if cli_relay::uses_subscription(settings, provider) {
+ return cli_relay::send(chat, provider, &model, query, context).await;
+ }
if provider == ANTHROPIC || provider.is_empty() {
return claude::send(chat, &model, query, context).await;
}
@@ -230,6 +233,9 @@ pub async fn send_for_phone(
query: String,
on_delta: impl FnMut(String),
) -> Result<ChatReply, String> {
+ if cli_relay::uses_subscription(settings, provider) {
+ return cli_relay::send(chat, provider, model, query, None).await;
+ }
if provider == ANTHROPIC {
return claude::send(chat, model, query, None).await;
}
@@ -247,11 +253,12 @@ pub async fn send_for_phone(
/// address): nothing is sent anywhere before that.
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 cli_relay::uses_subscription(settings, provider) {
+ return Ok(cli_relay::models(provider));
+ }
if provider == ANTHROPIC {
- 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);
+ let key = secrets::get(claude::KEY).ok_or_else(no_key)?;
+ return claude::models(&key).await;
}
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.rs
index 701fe3a6..50e74f91 100644
--- a/windows/src-tauri/src/claude.rs
+++ b/windows/src-tauri/src/claude.rs
@@ -36,9 +36,6 @@ 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()
@@ -160,8 +157,10 @@ pub async fn send(
query: String,
context: Option<ChatContext>,
) -> Result<ChatReply, String> {
+ // No key: Settings → Chat → Your AI subscriptions lets Claude Code answer
+ // instead (cli_relay.rs); chat.rs sends the turn there before it gets here.
let Some(key) = secrets::get(KEY) else {
- return send_through_claude_code(chat, model, query, context).await;
+ return Err(t("API key missing. Open settings."));
};
let endpoint = endpoint()?;
@@ -179,40 +178,6 @@ 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();
- // Reading a dropped file, the run gets no web at all: a file written to
- // steer the model could otherwise send what it reads (or the other files
- // in the inbox) to a website through a fetch or a search.
- let tools: &[&str] = if reads_file { &["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> {
diff --git a/windows/src-tauri/src/claude_code.rs b/windows/src-tauri/src/claude_code.rs
index 32f321b4..b28fb2ac 100644
--- a/windows/src-tauri/src/claude_code.rs
+++ b/windows/src-tauri/src/claude_code.rs
@@ -22,10 +22,6 @@ 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] = [
diff --git a/windows/src-tauri/src/cli_relay.rs b/windows/src-tauri/src/cli_relay.rs
new file mode 100644
index 00000000..328d6804
--- /dev/null
+++ b/windows/src-tauri/src/cli_relay.rs
@@ -0,0 +1,692 @@
+// The chat on the user's own subscription (Settings → Chat → Your AI
+// subscriptions, as on the Mac: CLIRelay.swift). With the switch on, the chat
+// is answered by the provider's official terminal tool, signed in with the
+// user's own account: Claude Code (claude_code.rs), Antigravity CLI or Gemini
+// CLI, Codex CLI, Cursor CLI and GitHub Copilot CLI. Coucou reads no
+// credential and makes no network call of its own.
+//
+// Each run is kept apart from the user's sessions and can only answer: plan,
+// ask or read-only modes, no shell, no edits, no user hooks, MCP servers,
+// extensions or plugins where the tool lets us turn them off, nothing saved to
+// resume, in an empty folder of Coucou's. Web search for the chat only: a
+// dropped file is read with no web at all (a file written to steer the model
+// could otherwise send what it reads to a website). Claude Code reads the file
+// itself; the other tools get a text file's contents in the prompt.
+
+use std::ffi::OsString;
+use std::path::{Path, PathBuf};
+use std::process::Stdio;
+use std::time::Duration;
+
+use serde::Serialize;
+use serde_json::{json, Value};
+use tokio::io::AsyncWriteExt;
+
+use crate::chat::{self, Chat, ChatContext, ChatReply, ModelInfo};
+use crate::i18n::tf;
+use crate::settings::Settings;
+use crate::{claude_code, platform, secrets, settings};
+
+/// How long a chat turn may take: it may search the web.
+const CHAT_TIMEOUT: Duration = Duration::from_secs(180);
+/// A dropped text file's contents go in the prompt up to this size.
+const MAX_INLINE_TEXT: u64 = 200_000;
+
+/// The Gemini CLI policy that keeps a run off the web while it reads a file.
+const NO_WEB_POLICY: &str = "[[rule]]\ntoolName = [\"google_web_search\", \"web_fetch\"]\ndecision = \"deny\"\npriority = 900\ndenyMessage = \"No web while Coucou reads a file.\"\n";
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Cli {
+ Claude,
+ Antigravity,
+ Gemini,
+ Codex,
+ Cursor,
+ Copilot,
+}
+
+impl Cli {
+ pub fn name(self) -> &'static str {
+ match self {
+ Cli::Claude => "Claude Code",
+ Cli::Antigravity => "Antigravity CLI",
+ Cli::Gemini => "Gemini CLI",
+ Cli::Codex => "Codex CLI",
+ Cli::Cursor => "Cursor CLI",
+ Cli::Copilot => "Copilot CLI",
+ }
+ }
+
+ /// Its executable names, the official one first.
+ fn binaries(self) -> &'static [&'static str] {
+ match self {
+ Cli::Claude => &["claude"],
+ Cli::Antigravity => &["agy"],
+ Cli::Gemini => &["gemini"],
+ Cli::Codex => &["codex"],
+ Cli::Cursor => &["cursor-agent", "agent"],
+ Cli::Copilot => &["copilot"],
+ }
+ }
+
+ /// What to type once in a terminal to sign in.
+ pub fn sign_in(self) -> &'static str {
+ match self {
+ Cli::Claude => "claude",
+ Cli::Antigravity => "agy",
+ Cli::Gemini => "gemini",
+ Cli::Codex => "codex login",
+ Cli::Cursor => "cursor-agent login",
+ Cli::Copilot => "copilot",
+ }
+ }
+
+ pub fn install_url(self) -> &'static str {
+ match self {
+ Cli::Claude => "https://code.claude.com/docs/en/setup",
+ Cli::Antigravity => "https://antigravity.google/docs/cli",
+ Cli::Gemini => "https://geminicli.com",
+ Cli::Codex => "https://developers.openai.com/codex/cli",
+ Cli::Cursor => "https://cursor.com/cli",
+ Cli::Copilot => "https://docs.github.com/copilot/how-tos/copilot-cli",
+ }
+ }
+
+ /// The tool, when it is installed.
+ pub fn exe(self) -> Option<PathBuf> {
+ self.binaries().iter().find_map(|name| platform::cli_candidates(name).into_iter().next())
+ }
+}
+
+/// The providers listed under "Your AI subscriptions", in order.
+pub const PROVIDERS: [&str; 5] = ["anthropic", "google", "openai", "cursor", "copilot"];
+
+/// The tools that answer for `provider`, the preferred one first. Empty: API only.
+pub fn clis_for(provider: &str) -> &'static [Cli] {
+ match provider {
+ "anthropic" => &[Cli::Claude],
+ "google" => &[Cli::Antigravity, Cli::Gemini],
+ "openai" => &[Cli::Codex],
+ "cursor" => &[Cli::Cursor],
+ "copilot" => &[Cli::Copilot],
+ _ => &[],
+ }
+}
+
+/// Cursor and Copilot have no API here: they answer only through the subscription.
+pub fn subscription_only(provider: &str) -> bool {
+ matches!(provider, "cursor" | "copilot")
+}
+
+fn key_for(provider: &str) -> Option<&'static str> {
+ match provider {
+ "anthropic" => Some(crate::claude::KEY),
+ "google" => Some("google-api-key"),
+ "openai" => Some("openai-api-key"),
+ _ => None,
+ }
+}
+
+/// The installed tool that answers for `provider`, if any.
+pub fn installed(provider: &str) -> Option<(Cli, PathBuf)> {
+ clis_for(provider).iter().find_map(|cli| cli.exe().map(|path| (*cli, path)))
+}
+
+/// Whether the chat with `provider` goes through the user's subscription.
+pub fn uses_subscription(settings: &Settings, provider: &str) -> bool {
+ if clis_for(provider).is_empty() {
+ return false;
+ }
+ if let Some(on) = settings.chat_subscriptions.get(provider) {
+ return *on;
+ }
+ // Never chosen: on when there is no key to use instead (what 0.5.5 did for
+ // Claude), and for Cursor and Copilot once their tool is installed.
+ if subscription_only(provider) {
+ return installed(provider).is_some();
+ }
+ key_for(provider).is_some_and(|key| !secrets::present(key))
+}
+
+/// One row of Settings → Chat → Your AI subscriptions.
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Status {
+ pub provider: &'static str,
+ /// The tool that answers (or would, once installed).
+ pub tool: &'static str,
+ pub installed: bool,
+ pub on: bool,
+ pub sign_in: &'static str,
+ pub install_url: &'static str,
+ pub subscription_only: bool,
+}
+
+pub fn status(settings: &Settings) -> Vec<Status> {
+ PROVIDERS
+ .iter()
+ .map(|provider| {
+ let found = installed(provider).map(|(cli, _)| cli);
+ let cli = found.unwrap_or(clis_for(provider)[0]);
+ Status {
+ provider,
+ tool: cli.name(),
+ installed: found.is_some(),
+ on: uses_subscription(settings, provider),
+ sign_in: cli.sign_in(),
+ install_url: cli.install_url(),
+ subscription_only: subscription_only(provider),
+ }
+ })
+ .collect()
+}
+
+/// The models offered in the picker: Claude Code's, else the tool's own choice.
+pub fn models(provider: &str) -> Vec<ModelInfo> {
+ if provider == "anthropic" {
+ return claude_code::models();
+ }
+ let tool = installed(provider).map(|(cli, _)| cli).unwrap_or(clis_for(provider)[0]);
+ vec![ModelInfo { id: String::new(), label: tf("The model chosen in {tool}", &[("tool", tool.name())]) }]
+}
+
+// ── One run ───────────────────────────────────────────────────────────────────
+
+pub struct Request<'a> {
+ /// None: the tool's own default model.
+ pub model: Option<&'a str>,
+ pub system: &'a str,
+ pub prompt: &'a str,
+ pub web: bool,
+ pub no_web_policy: Option<&'a Path>,
+}
+
+/// The prompt as the tool receives it: the system prompt on top.
+fn full_prompt(r: &Request<'_>) -> String {
+ format!("<instructions>\n{}\n</instructions>\n\n{}", r.system, r.prompt)
+}
+
+/// The command line of one run (everything but Claude Code, see claude_code.rs).
+/// `prompt_arg`: the prompt goes in the arguments; else on stdin (npm's `.cmd`
+/// shims on Windows can't take a multi-line argument).
+fn args(cli: Cli, r: &Request<'_>, prompt_arg: bool) -> Vec<OsString> {
+ let model = r.model.filter(|m| !m.is_empty());
+ let prompt = full_prompt(r);
+ let mut out: Vec<String> = Vec::new();
+ match cli {
+ Cli::Claude => unreachable!("Claude Code runs through claude_code.rs"),
+ Cli::Gemini => {
+ // Plan mode: read-only tools and Google search, nothing that writes or runs.
+ if prompt_arg {
+ out.extend(["-p".into(), prompt]);
+ }
+ out.extend(
+ ["--output-format", "json", "--approval-mode", "plan", "--skip-trust", "--extensions", "none",
+ "--allowed-mcp-server-names", "coucou-none"]
+ .map(String::from),
+ );
+ if let (false, Some(policy)) = (r.web, r.no_web_policy) {
+ out.extend(["--policy".into(), policy.to_string_lossy().into_owned()]);
+ }
+ }
+ Cli::Antigravity => {
+ out.extend(["-p".into(), prompt]);
+ out.extend(["--output-format", "json", "--mode", "plan", "--disable-slash-commands"].map(String::from));
+ }
+ Cli::Codex => {
+ // Read-only sandbox and no shell at all; it searches only for the chat.
+ if r.web {
+ out.push("--search".into());
+ }
+ out.extend(
+ ["exec", "--json", "--skip-git-repo-check", "--ephemeral", "--ignore-user-config", "--ignore-rules",
+ "--sandbox", "read-only", "--color", "never"]
+ .map(String::from),
+ );
+ for feature in ["shell_tool", "unified_exec", "apps", "plugins", "hooks"] {
+ out.extend(["--disable".into(), feature.into()]);
+ }
+ }
+ Cli::Cursor => {
+ // Print mode, ask mode: answers and reads, never edits or runs (no --force).
+ out.push("-p".into());
+ if prompt_arg {
+ out.push(prompt);
+ }
+ out.extend(["--output-format", "json", "--mode", "ask", "--trust"].map(String::from));
+ }
+ Cli::Copilot => {
+ if prompt_arg {
+ out.extend(["-p".into(), prompt]);
+ }
+ out.extend(
+ ["--silent", "--no-custom-instructions", "--disable-builtin-mcps", "--no-ask-user", "--no-auto-update",
+ "--no-color"]
+ .map(String::from),
+ );
+ if r.web {
+ out.extend(["--available-tools", "web_fetch", "--allow-all-urls"].map(String::from));
+ } else {
+ out.extend(["--available-tools", "view"].map(String::from));
+ }
+ }
+ }
+ if let Some(model) = model {
+ out.extend(["--model".into(), model.to_string()]);
+ }
+ if cli == Cli::Codex {
+ out.push("-".into());
+ }
+ out.into_iter().map(OsString::from).collect()
+}
+
+/// Whether the prompt goes in on stdin: Codex always; Gemini, Cursor and
+/// Copilot when they are npm's `.cmd` shims; Antigravity never.
+fn prompt_on_stdin(cli: Cli, exe: &Path) -> bool {
+ let shim = exe
+ .extension()
+ .and_then(|e| e.to_str())
+ .is_some_and(|e| e.eq_ignore_ascii_case("cmd") || e.eq_ignore_ascii_case("bat"));
+ match cli {
+ Cli::Codex | Cli::Claude => true,
+ Cli::Antigravity => false,
+ Cli::Gemini | Cli::Cursor | Cli::Copilot => shim,
+ }
+}
+
+/// Runs the tool once and returns the text of its answer.
+async fn ask(cli: Cli, exe: &Path, r: &Request<'_>) -> Result<String, String> {
+ let workdir = settings::local_dir().join("relay");
+ std::fs::create_dir_all(&workdir).map_err(|e| e.to_string())?;
+ let stdin_prompt = prompt_on_stdin(cli, exe);
+
+ let mut cmd = tokio::process::Command::new(exe);
+ cmd.args(args(cli, r, !stdin_prompt))
+ .current_dir(&workdir)
+ .env_remove("CLAUDECODE")
+ .env("NO_COLOR", "1")
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .kill_on_drop(true);
+ // An npm install is a node script: its own folder first on PATH so it finds its Node.
+ 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 {tool}: {error}", &[("tool", cli.name()), ("error", &e.to_string())]))?;
+ if let Some(mut stdin) = child.stdin.take() {
+ if stdin_prompt {
+ stdin.write_all(full_prompt(r).as_bytes()).await.map_err(|e| e.to_string())?;
+ }
+ drop(stdin);
+ }
+ let output = tokio::time::timeout(CHAT_TIMEOUT, child.wait_with_output())
+ .await
+ .map_err(|_| tf("{tool} took too long to answer.", &[("tool", cli.name())]))?
+ .map_err(|e| e.to_string())?;
+ parse(cli, &output.stdout, &output.stderr, output.status.success())
+}
+
+// ── Output formats ────────────────────────────────────────────────────────────
+
+/// The answer's text, or why there is none.
+fn parse(cli: Cli, stdout: &[u8], stderr: &[u8], success: bool) -> Result<String, String> {
+ let detail = last_line(stderr);
+ let result = match cli {
+ Cli::Claude | Cli::Cursor => parse_result_object(cli, stdout),
+ Cli::Gemini | Cli::Antigravity => parse_response_object(cli, stdout, stderr),
+ Cli::Codex => parse_codex_events(cli, stdout),
+ Cli::Copilot => {
+ let text = String::from_utf8_lossy(stdout).trim().to_string();
+ if success && !text.is_empty() { Ok(text) } else { Err(Failure::NoAnswer) }
+ }
+ };
+ match result {
+ Ok(text) => Ok(text),
+ Err(failure) => {
+ let said = match &failure {
+ Failure::Said(why) => why.clone(),
+ Failure::NoAnswer => detail.clone(),
+ };
+ if needs_sign_in(&said) {
+ return Err(tf(
+ "{tool} is not signed in. Sign in once in a terminal: {command}",
+ &[("tool", cli.name()), ("command", cli.sign_in())],
+ ));
+ }
+ match failure {
+ Failure::Said(why) => Err(why),
+ Failure::NoAnswer if detail.is_empty() => Err(tf("{tool} gave no answer.", &[("tool", cli.name())])),
+ Failure::NoAnswer => Err(format!("{} ({detail})", tf("{tool} gave no answer.", &[("tool", cli.name())]))),
+ }
+ }
+ }
+}
+
+enum Failure {
+ NoAnswer,
+ Said(String),
+}
+
+/// Claude Code and Cursor: `{"result": …, "is_error": …}`.
+fn parse_result_object(cli: Cli, stdout: &[u8]) -> Result<String, Failure> {
+ let json = last_json_object(stdout).ok_or(Failure::NoAnswer)?;
+ let text = json.get("result").and_then(Value::as_str).unwrap_or("").trim().to_string();
+ if json.get("is_error").and_then(Value::as_bool).unwrap_or(false) {
+ return Err(Failure::Said(if text.is_empty() {
+ tf("{tool} could not answer.", &[("tool", cli.name())])
+ } else {
+ text
+ }));
+ }
+ if text.is_empty() { Err(Failure::NoAnswer) } else { Ok(text) }
+}
+
+/// Gemini CLI and Antigravity CLI: `{"response": …, "error": {…}}`, the error on stderr too.
+fn parse_response_object(_cli: Cli, stdout: &[u8], stderr: &[u8]) -> Result<String, Failure> {
+ let out = last_json_object(stdout);
+ if let Some(text) = out.as_ref().and_then(|j| j.get("response")).and_then(Value::as_str) {
+ if !text.trim().is_empty() {
+ return Ok(text.trim().to_string());
+ }
+ }
+ for json in [out, last_json_object(stderr)].into_iter().flatten() {
+ let error = &json["error"];
+ let message = error["message"].as_str().or_else(|| error.as_str()).unwrap_or("");
+ if !message.is_empty() {
+ return Err(Failure::Said(message.to_string()));
+ }
+ }
+ Err(Failure::NoAnswer)
+}
+
+/// `codex exec --json`: one event per line; the answer is the last finished agent message.
+fn parse_codex_events(_cli: Cli, stdout: &[u8]) -> Result<String, Failure> {
+ let mut answer = None;
+ let mut failure = None;
+ for line in String::from_utf8_lossy(stdout).lines() {
+ let Ok(event) = serde_json::from_str::<Value>(line) else { continue };
+ match event["type"].as_str() {
+ Some("item.completed") if event["item"]["type"] == "agent_message" => {
+ if let Some(text) = event["item"]["text"].as_str().filter(|t| !t.is_empty()) {
+ answer = Some(text.trim().to_string());
+ }
+ }
+ Some("turn.failed") => failure = event["error"]["message"].as_str().map(String::from),
+ Some("error") => failure = event["message"].as_str().map(String::from),
+ _ => {}
+ }
+ }
+ match (answer, failure) {
+ (Some(text), _) => Ok(text),
+ (None, Some(why)) => Err(Failure::Said(why)),
+ (None, None) => Err(Failure::NoAnswer),
+ }
+}
+
+/// The last JSON object in a tool's output (some print a line or two before it).
+fn last_json_object(bytes: &[u8]) -> Option<Value> {
+ let text = String::from_utf8_lossy(bytes);
+ if let Ok(v @ Value::Object(_)) = serde_json::from_str::<Value>(text.trim()) {
+ return Some(v);
+ }
+ let start = text.rfind("\n{")?;
+ match serde_json::from_str::<Value>(text[start + 1..].trim()) {
+ Ok(v @ Value::Object(_)) => Some(v),
+ _ => None,
+ }
+}
+
+/// The last line a tool wrote on stderr, without terminal colours.
+fn last_line(bytes: &[u8]) -> String {
+ let text = String::from_utf8_lossy(bytes);
+ let mut clean = String::with_capacity(text.len());
+ let mut chars = text.chars().peekable();
+ while let Some(c) = chars.next() {
+ if c == '\u{1b}' && chars.peek() == Some(&'[') {
+ chars.next();
+ for c in chars.by_ref() {
+ if c.is_ascii_alphabetic() {
+ break;
+ }
+ }
+ } else {
+ clean.push(c);
+ }
+ }
+ clean.lines().map(str::trim).filter(|l| !l.is_empty()).last().unwrap_or("").to_string()
+}
+
+fn needs_sign_in(text: &str) -> bool {
+ let t = text.to_lowercase();
+ ["log in", "login", "logged in", "authenticat", "unauthorized", "401", "sign in", "signed in", "auth method",
+ "invalid api key"]
+ .iter()
+ .any(|needle| t.contains(needle))
+}
+
+// ── The chat ──────────────────────────────────────────────────────────────────
+
+/// One chat turn with `provider` answered through the user's subscription.
+pub async fn send(
+ chat: &Chat,
+ provider: &str,
+ model: &str,
+ query: String,
+ context: Option<ChatContext>,
+) -> Result<ChatReply, String> {
+ let Some((cli, exe)) = installed(provider) else {
+ let tool = clis_for(provider).first().map(|c| c.name()).unwrap_or(provider);
+ return Err(tf(
+ "{tool} is not installed. Install it from Settings → Chat, sign in once in a terminal, then ask again.",
+ &[("tool", tool)],
+ ));
+ };
+ let turn = chat.begin(&format!("subscription:{provider}"));
+ let reads_file = turn.first && matches!(context, Some(ChatContext::File { .. }));
+ let system = chat::system_prompt(!reads_file);
+ let text = if cli == Cli::Claude {
+ // Reading a dropped file, Claude Code reads it itself and gets no web at all.
+ let inbox = crate::files::inbox_dir();
+ let tools: &[&str] = if reads_file { &["Read"] } else { &["WebSearch", "WebFetch"] };
+ let prompt = claude_code::chat_prompt(&turn.history, turn.first, context.as_ref(), &query);
+ claude_code::ask(&claude_code::Request {
+ model,
+ system: &system,
+ prompt: &prompt,
+ tools,
+ read_dir: reads_file.then_some(inbox.as_path()),
+ timeout: CHAT_TIMEOUT,
+ })
+ .await?
+ } else {
+ let prompt = chat_prompt(&turn.history, turn.first, context.as_ref(), &query);
+ let policy = (cli == Cli::Gemini && reads_file).then(|| {
+ let path = settings::local_dir().join("relay").join("gemini-no-web.toml");
+ let _ = std::fs::create_dir_all(settings::local_dir().join("relay"));
+ let _ = std::fs::write(&path, NO_WEB_POLICY);
+ path
+ });
+ let request = Request { model: None, system: &system, prompt: &prompt, web: !reads_file, no_web_policy: policy.as_deref() };
+ ask(cli, &exe, &request).await?
+ };
+ // The record keeps the file's name, never its contents: later turns search the web.
+ 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 chat turn as a single prompt for the tools other than Claude Code: the
+/// earlier plain turns, then a text file's contents or the window, then the question.
+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 }) => match inline_text(Path::new(path)) {
+ Some(body) => out.push_str(&format!("File: {name}\nFile contents:\n{body}\n\n")),
+ None => out.push_str(&format!("File: {name} (its contents can't be read here)\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
+}
+
+/// A text file's contents, up to MAX_INLINE_TEXT; nothing for anything else.
+fn inline_text(path: &Path) -> Option<String> {
+ if std::fs::metadata(path).ok()?.len() > MAX_INLINE_TEXT {
+ return None;
+ }
+ let text = String::from_utf8(std::fs::read(path).ok()?).ok()?;
+ (!text.contains('\0')).then_some(text)
+}
+
+/// Settings → Chat: the switch of `provider` moved.
+pub fn set(settings: &mut Settings, provider: &str, on: bool) {
+ if clis_for(provider).is_empty() {
+ return;
+ }
+ settings.chat_subscriptions.insert(provider.to_string(), on);
+ // The chat can't stay on a provider that no longer answers.
+ if !on && subscription_only(provider) && settings.chat_provider == provider {
+ settings.chat_provider = chat::ANTHROPIC.into();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn strings(args: &[OsString]) -> Vec<String> {
+ args.iter().map(|a| a.to_string_lossy().into_owned()).collect()
+ }
+
+ fn after(args: &[String], flag: &str) -> Option<String> {
+ args.iter().position(|a| a == flag).and_then(|i| args.get(i + 1).cloned())
+ }
+
+ fn request(web: bool) -> Request<'static> {
+ Request { model: None, system: "SYS", prompt: "Hello?", web, no_web_policy: None }
+ }
+
+ #[test]
+ fn each_tool_only_answers() {
+ let gemini = strings(&args(Cli::Gemini, &request(true), true));
+ assert!(after(&gemini, "-p").unwrap().starts_with("<instructions>\nSYS\n</instructions>"));
+ assert_eq!(after(&gemini, "--approval-mode").as_deref(), Some("plan"));
+ assert_eq!(after(&gemini, "--extensions").as_deref(), Some("none"));
+ let policy = PathBuf::from("/tmp/no-web.toml");
+ let file = Request { no_web_policy: Some(&policy), ..request(false) };
+ assert_eq!(after(&strings(&args(Cli::Gemini, &file, true)), "--policy").as_deref(), Some("/tmp/no-web.toml"));
+ // Through npm's .cmd shim the prompt goes on stdin.
+ assert!(!strings(&args(Cli::Gemini, &request(true), false)).contains(&"-p".to_string()));
+
+ let agy = strings(&args(Cli::Antigravity, &request(true), true));
+ assert_eq!(after(&agy, "--mode").as_deref(), Some("plan"));
+
+ let codex = strings(&args(Cli::Codex, &request(true), false));
+ assert_eq!(&codex[..2], ["--search", "exec"]);
+ assert_eq!(codex.last().map(String::as_str), Some("-"));
+ assert_eq!(after(&codex, "--sandbox").as_deref(), Some("read-only"));
+ assert!(codex.contains(&"shell_tool".to_string()) && codex.contains(&"--ephemeral".to_string()));
+ assert!(!strings(&args(Cli::Codex, &request(false), false)).contains(&"--search".to_string()));
+
+ let cursor = strings(&args(Cli::Cursor, &request(true), true));
+ assert_eq!(after(&cursor, "--mode").as_deref(), Some("ask"));
+ assert!(!cursor.contains(&"--force".to_string()) && !cursor.contains(&"--yolo".to_string()));
+
+ let copilot = strings(&args(Cli::Copilot, &request(true), true));
+ assert_eq!(after(&copilot, "--available-tools").as_deref(), Some("web_fetch"));
+ assert!(!copilot.contains(&"--allow-all-tools".to_string()));
+ let copilot_file = strings(&args(Cli::Copilot, &request(false), true));
+ assert_eq!(after(&copilot_file, "--available-tools").as_deref(), Some("view"));
+ assert!(!copilot_file.contains(&"--allow-all-urls".to_string()));
+
+ let model = Request { model: Some("m1"), ..request(true) };
+ assert_eq!(after(&strings(&args(Cli::Cursor, &model, true)), "--model").as_deref(), Some("m1"));
+ let empty = Request { model: Some(""), ..request(true) };
+ assert!(!strings(&args(Cli::Cursor, &empty, true)).contains(&"--model".to_string()));
+ }
+
+ #[test]
+ fn the_prompt_goes_on_stdin_through_a_cmd_shim() {
+ assert!(prompt_on_stdin(Cli::Codex, Path::new("codex")));
+ assert!(!prompt_on_stdin(Cli::Antigravity, Path::new("agy.exe")));
+ assert!(prompt_on_stdin(Cli::Gemini, Path::new(r"C:\npm\gemini.cmd")));
+ assert!(!prompt_on_stdin(Cli::Gemini, Path::new("/usr/local/bin/gemini")));
+ assert!(prompt_on_stdin(Cli::Copilot, Path::new("copilot.CMD")));
+ }
+
+ #[test]
+ fn answers_come_from_each_format() {
+ assert_eq!(parse(Cli::Cursor, b"warming up\n{\"result\":\"Yo\",\"is_error\":false}", b"", true).unwrap(), "Yo");
+ assert_eq!(parse(Cli::Gemini, br#"{"response":"Bonjour","stats":{}}"#, b"", true).unwrap(), "Bonjour");
+ assert_eq!(parse(Cli::Antigravity, br#"{"status":"SUCCESS","response":"Hey"}"#, b"", true).unwrap(), "Hey");
+ let events = b"{\"type\":\"thread.started\"}\n{\"type\":\"item.completed\",\"item\":{\"type\":\"reasoning\",\"text\":\"x\"}}\n{\"type\":\"item.completed\",\"item\":{\"type\":\"agent_message\",\"text\":\"Final\"}}\n";
+ assert_eq!(parse(Cli::Codex, events, b"", true).unwrap(), "Final");
+ assert_eq!(parse(Cli::Copilot, b" The answer\n", b"", true).unwrap(), "The answer");
+ }
+
+ #[test]
+ fn failures_say_why_and_how_to_sign_in() {
+ let quota = br#"{"error":{"type":"Error","message":"Quota exceeded"}}"#;
+ assert_eq!(parse(Cli::Gemini, b"", quota, false).unwrap_err(), "Quota exceeded");
+ let auth = br#"{"error":{"message":"Please set an Auth method in your settings.json"}}"#;
+ assert!(parse(Cli::Gemini, b"", auth, false).unwrap_err().ends_with("gemini"));
+ let codex = br#"{"type":"error","message":"unexpected status 401 Unauthorized"}"#;
+ assert!(parse(Cli::Codex, codex, b"", false).unwrap_err().ends_with("codex login"));
+ let crash = b"\x1b[31mboom: model not found\x1b[0m\n";
+ assert_eq!(parse(Cli::Copilot, b"", crash, false).unwrap_err(), "Copilot CLI gave no answer. (boom: model not found)");
+ assert_eq!(parse(Cli::Cursor, br#"{"is_error":true,"result":"Usage limit"}"#, b"", false).unwrap_err(), "Usage limit");
+ }
+
+ #[test]
+ fn a_file_goes_in_the_prompt_but_not_in_the_history() {
+ let dir = std::env::temp_dir().join(format!("coucou-cli-relay-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("notes.txt");
+ std::fs::write(&path, "secret plan").unwrap();
+ let file = ChatContext::File { name: "notes.txt".into(), path: path.to_string_lossy().into_owned() };
+ let p = chat_prompt(&[], true, Some(&file), "Sum it up");
+ assert!(p.starts_with("File: notes.txt\nFile contents:\nsecret plan\n\n") && p.ends_with("Sum it up"));
+ assert!(!chat::plain_question(true, Some(&file), "Sum it up").contains("secret plan"));
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn the_switch_defaults_and_choices() {
+ let mut s = Settings::default();
+ // Ollama has no subscription; a choice sticks; turning Cursor off leaves its chat.
+ assert!(!uses_subscription(&s, "ollama"));
+ set(&mut s, "google", true);
+ assert!(uses_subscription(&s, "google"));
+ set(&mut s, "google", false);
+ assert!(!uses_subscription(&s, "google"));
+ s.chat_provider = "cursor".into();
+ set(&mut s, "cursor", false);
+ assert_eq!(s.chat_provider, "anthropic");
+ assert_eq!(status(&s).len(), PROVIDERS.len());
+ }
+}
diff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rs
index ac7f3f8d..765772de 100644
--- a/windows/src-tauri/src/lib.rs
+++ b/windows/src-tauri/src/lib.rs
@@ -5,6 +5,7 @@ mod agents;
mod chat;
mod claude;
mod claude_code;
+mod cli_relay;
mod codex_plan;
mod config_file;
mod desktop;
@@ -583,6 +584,30 @@ fn claude_ready() -> bool {
claude::ready()
}
+/// Settings → Chat → Your AI subscriptions: each provider's switch and
+/// whether its terminal tool is installed (looked up again on every call).
+#[tauri::command]
+fn subscription_status(shared: State<Shared>) -> Vec<cli_relay::Status> {
+ let settings = shared.settings.lock().unwrap().clone();
+ cli_relay::status(&settings)
+}
+
+/// A switch under "Your AI subscriptions" moved: saved, and both windows told.
+#[tauri::command]
+fn subscription_set(app: AppHandle, shared: State<Shared>, provider: String, on: bool) -> Vec<cli_relay::Status> {
+ let settings = {
+ let mut current = shared.settings.lock().unwrap();
+ cli_relay::set(&mut current, &provider, on);
+ current.clone()
+ };
+ if let Err(err) = settings::save(&settings) {
+ log::line(format!("could not save settings: {err}"));
+ }
+ let status = cli_relay::status(&settings);
+ let _ = app.emit("settings-changed", settings);
+ status
+}
+
#[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.
@@ -866,6 +891,8 @@ pub fn run() {
ingest_file,
secret_present,
claude_ready,
+ subscription_status,
+ subscription_set,
secret_set,
secret_clear,
refresh_integration,
diff --git a/windows/src-tauri/src/settings.rs b/windows/src-tauri/src/settings.rs
index b9656236..e3048fbe 100644
--- a/windows/src-tauri/src/settings.rs
+++ b/windows/src-tauri/src/settings.rs
@@ -45,6 +45,10 @@ pub struct Settings {
/// The model picked for each provider other than Anthropic (whose model is
/// `model`), by provider id.
pub chat_models: BTreeMap<String, String>,
+ /// Settings → Chat → Your AI subscriptions: the switch of each provider
+ /// that can answer through its own terminal tool (cli_relay.rs). A
+ /// provider not in it was never switched: see cli_relay::uses_subscription.
+ pub chat_subscriptions: BTreeMap<String, bool>,
/// Addresses of the model servers once connected; empty means not connected.
pub ollama_url: String,
pub lmstudio_url: String,
@@ -148,6 +152,7 @@ impl Default for Settings {
show_codex_plan_in_notch: false,
chat_provider: crate::chat::ANTHROPIC.into(),
chat_models: BTreeMap::new(),
+ chat_subscriptions: BTreeMap::new(),
ollama_url: String::new(),
lmstudio_url: String::new(),
custom_url: String::new(),
@@ -446,6 +451,7 @@ mod tests {
"showCodexPlanInNotch": true,
"chatProvider": "ollama",
"chatModels": { "ollama": "llama3.2", "openai": "gpt-x" },
+ "chatSubscriptions": { "google": true, "anthropic": false },
"ollamaUrl": "http://127.0.0.1:11434",
"lmstudioUrl": "http://127.0.0.1:1234",
"customUrl": "https://llm.example.com",
@@ -964,6 +970,7 @@ mod tests {
"showCodexPlanInNotch",
"chatProvider",
"chatModels",
+ "chatSubscriptions",
"ollamaUrl",
"lmstudioUrl",
"customUrl",
diff --git a/windows/src/core/bridge.ts b/windows/src/core/bridge.ts
index 52f63162..c8868a08 100644
--- a/windows/src/core/bridge.ts
+++ b/windows/src/core/bridge.ts
@@ -382,6 +382,11 @@ export const Bridge = {
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"),
+ /** Settings → Chat → Your AI subscriptions: each switch and whether its tool is installed. */
+ subscriptionStatus: () => call<SubscriptionStatus[]>("subscription_status"),
+ /** Moves a switch; returns the rows as they are now. */
+ subscriptionSet: (provider: string, on: boolean) =>
+ call<SubscriptionStatus[]>("subscription_set", { provider, on }),
/** 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 }),
@@ -546,6 +551,19 @@ export interface ModelInfo {
label: string;
}
+/** One row of Settings → Chat → Your AI subscriptions (cli_relay.rs `Status`). */
+export interface SubscriptionStatus {
+ provider: string;
+ /** The terminal tool that answers, or would once installed. */
+ tool: string;
+ installed: boolean;
+ on: boolean;
+ /** What to type once in a terminal to sign in. */
+ signIn: string;
+ installUrl: string;
+ subscriptionOnly: boolean;
+}
+
export interface LocalServer {
/** The address as it is stored. */
url: string;
diff --git a/windows/src/core/providers.ts b/windows/src/core/providers.ts
index 54a57829..29b6d64d 100644
--- a/windows/src/core/providers.ts
+++ b/windows/src/core/providers.ts
@@ -7,7 +7,8 @@ import { N_ } from "../i18n/i18n";
export type ProviderId =
| "anthropic" | "openai" | "google" | "openrouter"
- | "ollama" | "lmstudio" | "custom";
+ | "ollama" | "lmstudio" | "custom"
+ | "cursor" | "copilot";
export interface ProviderDef {
id: ProviderId;
@@ -31,8 +32,14 @@ export const PROVIDERS: readonly ProviderDef[] = [
{ id: "ollama", name: "Ollama", accent: "#FACC15", key: null, urlField: "ollamaUrl", defaultModel: "", prefer: null },
{ id: "lmstudio", name: "LM Studio", accent: "#A3E635", key: null, urlField: "lmstudioUrl", defaultModel: "", prefer: null },
{ id: "custom", name: N_("Custom server"), accent: "#C0C4CC", key: null, urlField: "customUrl", defaultModel: "", prefer: null },
+ // Only through the user's own subscription (cli_relay.rs): no key, no address.
+ { id: "cursor", name: "Cursor", accent: "#A1A1AA", key: null, urlField: null, defaultModel: "", prefer: null },
+ { id: "copilot", name: "GitHub Copilot", accent: "#8B5CF6", key: null, urlField: null, defaultModel: "", prefer: null },
];
+/** Answered only through the user's subscription, switched on in Settings → Chat. */
+export const SUBSCRIPTION_ONLY: readonly ProviderId[] = ["cursor", "copilot"];
+
/** Credential store entry of the custom server's optional key. */
export const CUSTOM_SERVER_KEY = "openai-compatible-key";
@@ -55,13 +62,17 @@ export function withModel(settings: Settings, provider: ProviderId, model: strin
/**
* The chips of the picker: every cloud provider (one without a key says so
- * when picked), and a model server once it is connected — or while it is the
- * active one, so the picker never hides where the chat goes.
+ * when picked), a model server once it is connected, and Cursor or Copilot
+ * once their subscription is on (`subscribed`: the providers whose switch is
+ * on, from Rust) — or while it is the active one, so the picker never hides
+ * where the chat goes.
*/
-export function visibleProviders(settings: Settings): ProviderDef[] {
- return PROVIDERS.filter(
- (p) => !p.urlField || settings[p.urlField] !== "" || settings.chatProvider === p.id,
- );
+export function visibleProviders(settings: Settings, subscribed: ReadonlySet<string> = new Set()): ProviderDef[] {
+ return PROVIDERS.filter((p) => {
+ if (settings.chatProvider === p.id) return true;
+ if (SUBSCRIPTION_ONLY.includes(p.id)) return subscribed.has(p.id) || settings.chatSubscriptions?.[p.id] === true;
+ return !p.urlField || settings[p.urlField] !== "";
+ });
}
/** The model to keep once the list arrives: the saved one if offered, else a sensible one. */
diff --git a/windows/src/core/state.ts b/windows/src/core/state.ts
index a99718d6..bab28737 100644
--- a/windows/src/core/state.ts
+++ b/windows/src/core/state.ts
@@ -126,6 +126,8 @@ export interface Settings {
chatProvider: ProviderId;
/** The model picked for each provider other than Anthropic, by provider id. */
chatModels: Record<string, string>;
+ /** Settings → Chat → Your AI subscriptions: each provider's switch (cli_relay.rs). */
+ chatSubscriptions: Record<string, boolean>;
/** Model server addresses once connected; empty means not connected. */
ollamaUrl: string;
lmstudioUrl: string;
@@ -186,6 +188,7 @@ export const DEFAULT_SETTINGS: Settings = {
showCodexPlanInNotch: false,
chatProvider: "anthropic",
chatModels: {},
+ chatSubscriptions: {},
ollamaUrl: "",
lmstudioUrl: "",
customUrl: "",
diff --git a/windows/src/core/subscriptions.ts b/windows/src/core/subscriptions.ts
new file mode 100644
index 00000000..bc96b964
--- /dev/null
+++ b/windows/src/core/subscriptions.ts
@@ -0,0 +1,34 @@
+// The chat on the user's own subscription, as the island sees it: which
+// providers answer through their terminal tool (cli_relay.rs), asked of Rust
+// and kept until the next ask.
+
+import { Bridge, type SubscriptionStatus } from "./bridge";
+import type { Settings } from "./state";
+
+let rows: SubscriptionStatus[] = [];
+
+/** Asks Rust again (it looks for the tools on every call). */
+export async function loadSubscriptions(): Promise<SubscriptionStatus[]> {
+ rows = (await Bridge.subscriptionStatus()) ?? rows;
+ return rows;
+}
+
+export function setSubscriptions(next: SubscriptionStatus[] | null | undefined) {
+ if (next) rows = next;
+}
+
+export function subscription(provider: string): SubscriptionStatus | undefined {
+ return rows.find((r) => r.provider === provider);
+}
+
+/** The providers whose switch is on. */
+export function subscribedProviders(): Set<string> {
+ return new Set(rows.filter((r) => r.on).map((r) => r.provider));
+}
+
+/** The model chip: the tool's name when it answers (with Claude's model for Claude Code). */
+export function chipLabel(settings: Settings, model: string): string {
+ const sub = subscription(settings.chatProvider);
+ if (!sub?.on) return model;
+ return settings.chatProvider === "anthropic" && model ? `${model} · ${sub.tool}` : sub.tool;
+}
diff --git a/windows/src/i18n/extra.json b/windows/src/i18n/extra.json
index 592fb332..bb388dd4 100644
--- a/windows/src/i18n/extra.json
+++ b/windows/src/i18n/extra.json
@@ -6156,6 +6156,110 @@
"id": "Claude Code tidak dapat menjawab.",
"de": "Claude Code konnte nicht antworten.",
"tr": "Claude Code yanıt veremedi."
+ },
+ "Not signed in yet? Run this once in a terminal: {command}": {
+ "zh-Hans": "还没登录?在终端里运行一次:{command}",
+ "hi": "अभी तक साइन इन नहीं किया? किसी टर्मिनल में एक बार चलाएँ: {command}",
+ "es": "¿Aún no has iniciado sesión? Ejecuta una vez en una terminal: {command}",
+ "ar": "لم تسجّل الدخول بعد؟ شغّل مرة واحدة في طرفية: {command}",
+ "fr": "Pas encore connecté ? Lance une fois dans un terminal : {command}",
+ "bn": "এখনও সাইন ইন করেননি? একটি টার্মিনালে একবার চালান: {command}",
+ "pt-BR": "Ainda não entrou? Rode uma vez em um terminal: {command}",
+ "ru": "Ещё не вошли? Выполните один раз в терминале: {command}",
+ "id": "Belum masuk? Jalankan sekali di terminal: {command}",
+ "de": "Noch nicht angemeldet? Einmal in einem Terminal ausführen: {command}",
+ "tr": "Henüz oturum açmadınız mı? Bir terminalde bir kez çalıştırın: {command}"
+ },
+ "{tool} is not installed. Install it from Settings → Chat, sign in once in a terminal, then ask again.": {
+ "zh-Hans": "{tool} 未安装。请在 设置 → 聊天 中安装,在终端登录一次,然后再问一次。",
+ "hi": "{tool} इंस्टॉल नहीं है। सेटिंग्स → चैट से इसे इंस्टॉल करें, किसी टर्मिनल में एक बार साइन इन करें, फिर दोबारा पूछें।",
+ "es": "{tool} no está instalado. Instálalo desde Ajustes → Chat, inicia sesión una vez en una terminal y vuelve a preguntar.",
+ "ar": "{tool} غير مثبّت. ثبّته من الإعدادات ← الدردشة، وسجّل الدخول مرة واحدة في طرفية، ثم اسأل مجددًا.",
+ "fr": "{tool} n'est pas installé. Installe-le depuis Réglages → Chat, connecte-toi une fois dans un terminal, puis redemande.",
+ "bn": "{tool} ইনস্টল করা নেই। সেটিংস → চ্যাট থেকে এটি ইনস্টল করুন, একটি টার্মিনালে একবার সাইন ইন করুন, তারপর আবার জিজ্ঞেস করুন।",
+ "pt-BR": "O {tool} não está instalado. Instale em Ajustes → Chat, entre uma vez em um terminal e pergunte de novo.",
+ "ru": "{tool} не установлен. Установите его в Настройки → Чат, один раз войдите в терминале и спросите снова.",
+ "id": "{tool} belum terpasang. Pasang dari Pengaturan → Chat, masuk sekali di terminal, lalu tanya lagi.",
+ "de": "{tool} ist nicht installiert. Installiere es über Einstellungen → Chat, melde dich einmal in einem Terminal an und frag dann erneut.",
+ "tr": "{tool} yüklü değil. Ayarlar → Sohbet'ten yükleyin, bir terminalde bir kez oturum açın, sonra tekrar sorun."
+ },
+ "Could not start {tool}: {error}": {
+ "zh-Hans": "无法启动 {tool}:{error}",
+ "hi": "{tool} शुरू नहीं हो सका: {error}",
+ "es": "No se pudo iniciar {tool}: {error}",
+ "ar": "تعذّر تشغيل {tool}: {error}",
+ "fr": "Impossible de lancer {tool} : {error}",
+ "bn": "{tool} চালু করা যায়নি: {error}",
+ "pt-BR": "Não foi possível iniciar o {tool}: {error}",
+ "ru": "Не удалось запустить {tool}: {error}",
+ "id": "Tidak dapat memulai {tool}: {error}",
+ "de": "{tool} konnte nicht gestartet werden: {error}",
+ "tr": "{tool} başlatılamadı: {error}"
+ },
+ "{tool} took too long to answer.": {
+ "zh-Hans": "{tool} 回答时间过长。",
+ "hi": "{tool} ने जवाब देने में बहुत समय लिया।",
+ "es": "{tool} tardó demasiado en responder.",
+ "ar": "استغرق {tool} وقتًا طويلًا للرد.",
+ "fr": "{tool} a mis trop de temps à répondre.",
+ "bn": "{tool} উত্তর দিতে অনেক সময় নিয়েছে।",
+ "pt-BR": "O {tool} demorou demais para responder.",
+ "ru": "{tool} слишком долго отвечал.",
+ "id": "{tool} terlalu lama menjawab.",
+ "de": "{tool} hat zu lange für eine Antwort gebraucht.",
+ "tr": "{tool} yanıt vermekte çok uzun sürdü."
+ },
+ "{tool} is not signed in. Sign in once in a terminal: {command}": {
+ "zh-Hans": "{tool} 尚未登录。请在终端登录一次:{command}",
+ "hi": "{tool} में साइन इन नहीं है। किसी टर्मिनल में एक बार साइन इन करें: {command}",
+ "es": "{tool} no ha iniciado sesión. Inicia sesión una vez en una terminal: {command}",
+ "ar": "لم يتم تسجيل الدخول إلى {tool}. سجّل الدخول مرة واحدة في طرفية: {command}",
+ "fr": "{tool} n'est pas connecté. Connecte-toi une fois dans un terminal : {command}",
+ "bn": "{tool}-এ সাইন ইন করা নেই। একটি টার্মিনালে একবার সাইন ইন করুন: {command}",
+ "pt-BR": "O {tool} não está conectado. Entre uma vez em um terminal: {command}",
+ "ru": "Вход в {tool} не выполнен. Войдите один раз в терминале: {command}",
+ "id": "{tool} belum masuk. Masuk sekali di terminal: {command}",
+ "de": "{tool} ist nicht angemeldet. Melde dich einmal in einem Terminal an: {command}",
+ "tr": "{tool} oturumu açık değil. Bir terminalde bir kez oturum açın: {command}"
+ },
+ "{tool} gave no answer.": {
+ "zh-Hans": "{tool} 没有回答。",
+ "hi": "{tool} ने कोई जवाब नहीं दिया।",
+ "es": "{tool} no respondió.",
+ "ar": "لم يُجب {tool}.",
+ "fr": "{tool} n'a pas répondu.",
+ "bn": "{tool} কোনো উত্তর দেয়নি।",
+ "pt-BR": "O {tool} não respondeu.",
+ "ru": "{tool} не ответил.",
+ "id": "{tool} tidak menjawab.",
+ "de": "{tool} hat nicht geantwortet.",
+ "tr": "{tool} yanıt vermedi."
+ },
+ "{tool} could not answer.": {
+ "zh-Hans": "{tool} 无法回答。",
+ "hi": "{tool} जवाब नहीं दे सका।",
+ "es": "{tool} no pudo responder.",
+ "ar": "لم يتمكن {tool} من الإجابة.",
+ "fr": "{tool} n'a pas pu répondre.",
+ "bn": "{tool} উত্তর দিতে পারেনি।",
+ "pt-BR": "O {tool} não conseguiu responder.",
+ "ru": "{tool} не смог ответить.",
+ "id": "{tool} tidak dapat menjawab.",
+ "de": "{tool} konnte nicht antworten.",
+ "tr": "{tool} yanıt veremedi."
+ },
+ "No key: the chat can go through your Claude subscription above.": {
+ "zh-Hans": "没有密钥:聊天可以使用上方你的 Claude 订阅。",
+ "hi": "कोई कुंजी नहीं: चैट ऊपर दी गई आपकी Claude सदस्यता से चल सकती है।",
+ "es": "Sin clave: el chat puede usar tu suscripción de Claude de arriba.",
+ "ar": "لا يوجد مفتاح: يمكن للدردشة استخدام اشتراكك في Claude أعلاه.",
+ "fr": "Pas de clé : le chat peut passer par ton abonnement Claude ci-dessus.",
+ "bn": "কোনো কী নেই: চ্যাট উপরের আপনার Claude সাবস্ক্রিপশন দিয়ে চলতে পারে।",
+ "pt-BR": "Sem chave: o chat pode usar sua assinatura do Claude acima.",
+ "ru": "Нет ключа: чат может работать через вашу подписку Claude выше.",
+ "id": "Tanpa kunci: chat bisa memakai langganan Claude-mu di atas.",
+ "de": "Kein Schlüssel: Der Chat kann über dein Claude-Abo oben laufen.",
+ "tr": "Anahtar yok: sohbet yukarıdaki Claude aboneliğinizi kullanabilir."
}
}
}
diff --git a/windows/src/i18n/strings.json b/windows/src/i18n/strings.json
index f8ac50a0..fc9c2cfe 100644
--- a/windows/src/i18n/strings.json
+++ b/windows/src/i18n/strings.json
@@ -1120,6 +1120,19 @@
"de": "Chat",
"tr": "Sohbet"
},
+ "Chat on the plan you already pay for. Coucou asks your AI's official terminal tool, signed in with your own account: it never sees your password or your key.": {
+ "zh-Hans": "用你已经付费的套餐聊天。Coucou 会调用你的 AI 的官方终端工具,并使用你自己的账户登录:它永远看不到你的密码或密钥。",
+ "hi": "उस प्लान से चैट करें जिसका आप पहले से भुगतान करते हैं। Coucou आपकी AI के आधिकारिक टर्मिनल टूल से पूछता है, जो आपके अपने खाते से साइन इन है: वह आपका पासवर्ड या कुंजी कभी नहीं देखता।",
+ "es": "Chatea con el plan que ya pagas. Coucou usa la herramienta oficial de terminal de tu IA, con tu propia cuenta: nunca ve tu contraseña ni tu clave.",
+ "ar": "تحدّث باستخدام الخطة التي تدفع ثمنها بالفعل. يستعين Coucou بأداة الطرفية الرسمية للذكاء الاصطناعي الخاص بك، المسجّلة بحسابك أنت: لا يرى أبدًا كلمة مرورك أو مفتاحك.",
+ "fr": "Discute avec l'abonnement que tu paies déjà. Coucou passe par l'outil terminal officiel de ton IA, connecté à ton propre compte : il ne voit jamais ton mot de passe ni ta clé.",
+ "bn": "যে প্ল্যানের জন্য আপনি আগেই টাকা দেন, সেটি দিয়েই চ্যাট করুন। Coucou আপনার AI-এর অফিশিয়াল টার্মিনাল টুলকে জিজ্ঞেস করে, যা আপনার নিজের অ্যাকাউন্টে সাইন ইন করা: এটি কখনো আপনার পাসওয়ার্ড বা কী দেখে না।",
+ "pt-BR": "Converse usando o plano que você já paga. O Coucou usa a ferramenta oficial de terminal da sua IA, conectada à sua própria conta: ele nunca vê sua senha nem sua chave.",
+ "ru": "Общайтесь в рамках подписки, за которую вы уже платите. Coucou обращается к официальному терминальному инструменту вашего ИИ, вошедшему в вашу учётную запись: он никогда не видит ваш пароль или ключ.",
+ "id": "Chat dengan paket yang sudah kamu bayar. Coucou memakai alat terminal resmi AI-mu, masuk dengan akunmu sendiri: Coucou tidak pernah melihat kata sandi atau kuncimu.",
+ "de": "Chatte mit dem Abo, das du schon bezahlst. Coucou fragt das offizielle Terminal-Tool deiner KI, angemeldet mit deinem eigenen Konto: Es sieht nie dein Passwort oder deinen Schlüssel.",
+ "tr": "Zaten ödediğiniz planla sohbet edin. Coucou, yapay zekânızın kendi hesabınızla oturum açmış resmi terminal aracına sorar: şifrenizi veya anahtarınızı asla görmez."
+ },
"Chat with {name}": {
"zh-Hans": "与 {name} 聊天",
"hi": "{name} के साथ चैट",
@@ -3356,6 +3369,19 @@
"de": "Hooks installieren",
"tr": "Hook'ları kur"
},
+ "Install it": {
+ "zh-Hans": "去安装",
+ "hi": "इंस्टॉल करें",
+ "es": "Instalarlo",
+ "ar": "تثبيته",
+ "fr": "L'installer",
+ "bn": "ইনস্টল করুন",
+ "pt-BR": "Instalar",
+ "ru": "Установить",
+ "id": "Pasang",
+ "de": "Installieren",
+ "tr": "Yükle"
+ },
"Install plugin": {
"zh-Hans": "安装插件",
"hi": "प्लगइन इंस्टॉल करें",
@@ -4487,19 +4513,6 @@
"de": "Keine Fehlerdetails verfügbar.",
"tr": "Hata ayrıntısı yok."
},
- "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: o seu Claude Code responde no lugar, com a sua conta.",
- "ru": "Нет ключа: вместо него отвечает ваш Claude Code с вашей учётной записью.",
- "id": "Tanpa kunci: Claude Code-mu yang menjawab, dengan akunmu.",
- "de": "Kein Schlüssel: Dein Claude Code antwortet stattdessen, mit deinem Konto.",
- "tr": "Anahtar yok: Bunun yerine Claude Code’un kendi hesabınla yanıtlar."
- },
"No messages": {
"zh-Hans": "没有邮件",
"hi": "कोई संदेश नहीं",
@@ -4786,6 +4799,19 @@
"de": "Nicht angefordert",
"tr": "İstenmedi"
},
+ "Not signed in yet? Run this once in Terminal: {0}": {
+ "zh-Hans": "还没登录?在终端里运行一次:{0}",
+ "hi": "अभी तक साइन इन नहीं किया? टर्मिनल में एक बार चलाएँ: {0}",
+ "es": "¿Aún no has iniciado sesión? Ejecuta una vez en la Terminal: {0}",
+ "ar": "لم تسجّل الدخول بعد؟ شغّل مرة واحدة في Terminal: {0}",
+ "fr": "Pas encore connecté ? Lance une fois dans le Terminal : {0}",
+ "bn": "এখনও সাইন ইন করেননি? টার্মিনালে একবার চালান: {0}",
+ "pt-BR": "Ainda não entrou? Rode uma vez no Terminal: {0}",
+ "ru": "Ещё не вошли? Выполните один раз в Терминале: {0}",
+ "id": "Belum masuk? Jalankan sekali di Terminal: {0}",
+ "de": "Noch nicht angemeldet? Einmal im Terminal ausführen: {0}",
+ "tr": "Henüz oturum açmadınız mı? Terminal'de bir kez çalıştırın: {0}"
+ },
"Notch": {
"zh-Hans": "刘海",
"hi": "नॉच",
@@ -4903,6 +4929,19 @@
"de": "OK, bleibt unverändert",
"tr": "Tamam, olduğu gibi bırakıyorum"
},
+ "Off: the chat uses your API key below.": {
+ "zh-Hans": "已关闭:聊天使用下方的 API 密钥。",
+ "hi": "बंद: चैट नीचे दी गई आपकी API कुंजी का इस्तेमाल करती है।",
+ "es": "Desactivado: el chat usa tu clave API de abajo.",
+ "ar": "متوقف: تستخدم الدردشة مفتاح API أدناه.",
+ "fr": "Désactivé : le chat utilise ta clé API ci-dessous.",
+ "bn": "বন্ধ: চ্যাট নিচের আপনার API কী ব্যবহার করে।",
+ "pt-BR": "Desligado: o chat usa sua chave de API abaixo.",
+ "ru": "Выключено: чат использует ваш API-ключ ниже.",
+ "id": "Mati: chat memakai kunci API-mu di bawah.",
+ "de": "Aus: Der Chat nutzt deinen API-Schlüssel unten.",
+ "tr": "Kapalı: sohbet aşağıdaki API anahtarınızı kullanır."
+ },
"Ollama disconnected.": {
"zh-Hans": "Ollama 已断开连接。",
"hi": "Ollama डिस्कनेक्ट हो गया।",
@@ -7516,6 +7555,19 @@
"de": "Die Tasten für die Notch und ihre Aktionen.",
"tr": "Çentiği ve işlemlerini açan tuşlar."
},
+ "The model chosen in {tool}": {
+ "zh-Hans": "在 {tool} 中选择的模型",
+ "hi": "{tool} में चुना गया मॉडल",
+ "es": "El modelo elegido en {tool}",
+ "ar": "النموذج المختار في {tool}",
+ "fr": "Le modèle choisi dans {tool}",
+ "bn": "{tool}-এ বেছে নেওয়া মডেল",
+ "pt-BR": "O modelo escolhido no {tool}",
+ "ru": "Модель, выбранная в {tool}",
+ "id": "Model yang dipilih di {tool}",
+ "de": "Das in {tool} gewählte Modell",
+ "tr": "{tool} içinde seçilen model"
+ },
"The most accurate, offline, 25 languages. Downloaded once (about 650 MB).": {
"zh-Hans": "最准确,离线可用,支持 25 种语言。只需下载一次(约 650 MB)。",
"hi": "सबसे सटीक, ऑफ़लाइन, 25 भाषाएँ। एक बार डाउनलोड (लगभग 650 MB)।",
@@ -7958,6 +8010,19 @@
"de": "{name} wird hochgeladen",
"tr": "{name} yükleniyor"
},
+ "Use my subscription": {
+ "zh-Hans": "使用我的订阅",
+ "hi": "मेरी सदस्यता इस्तेमाल करें",
+ "es": "Usar mi suscripción",
+ "ar": "استخدام اشتراكي",
+ "fr": "Utiliser mon abonnement",
+ "bn": "আমার সাবস্ক্রিপশন ব্যবহার করুন",
+ "pt-BR": "Usar minha assinatura",
+ "ru": "Использовать мою подписку",
+ "id": "Pakai langgananku",
+ "de": "Mein Abo verwenden",
+ "tr": "Aboneliğimi kullan"
+ },
"Used by the chat. The list comes from your Anthropic account.": {
"zh-Hans": "由聊天使用。列表来自你的 Anthropic 账户。",
"hi": "चैट द्वारा उपयोग किया जाता है। सूची आपके Anthropic खाते से आती है।",
@@ -8647,6 +8712,19 @@
"de": "Du sprichst",
"tr": "Konuştuğun dil"
},
+ "Your AI subscriptions": {
+ "zh-Hans": "你的 AI 订阅",
+ "hi": "आपकी AI सदस्यताएँ",
+ "es": "Tus suscripciones de IA",
+ "ar": "اشتراكاتك في الذكاء الاصطناعي",
+ "fr": "Tes abonnements IA",
+ "bn": "আপনার AI সাবস্ক্রিপশন",
+ "pt-BR": "Suas assinaturas de IA",
+ "ru": "Ваши подписки на ИИ",
+ "id": "Langganan AI-mu",
+ "de": "Deine KI-Abos",
+ "tr": "Yapay zekâ abonelikleriniz"
+ },
"Your Coucou so far": {
"zh-Hans": "你的 Coucou 至今",
"hi": "अब तक आपका Coucou",
@@ -8751,6 +8829,19 @@
"de": "Deine Diktate erscheinen hier. Halte in einer beliebigen App {0} gedrückt und sprich.",
"tr": "Diktelerin burada görünür. Herhangi bir uygulamada {0} tuşunu basılı tut ve konuş."
},
+ "Your plan · {0}": {
+ "zh-Hans": "你的套餐 · {0}",
+ "hi": "आपका प्लान · {0}",
+ "es": "Tu plan · {0}",
+ "ar": "خطتك · {0}",
+ "fr": "Ton abonnement · {0}",
+ "bn": "আপনার প্ল্যান · {0}",
+ "pt-BR": "Seu plano · {0}",
+ "ru": "Ваша подписка · {0}",
+ "id": "Paketmu · {0}",
+ "de": "Dein Abo · {0}",
+ "tr": "Planınız · {0}"
+ },
"Your voice is turned into text by your Mac's speech recognition, on-device when your Mac supports it; Coucou sends it nowhere. After pasting, the clipboard gets back what it held.": {
"zh-Hans": "你的声音由 Mac 的语音识别转成文字,Mac 支持时在设备上完成;Coucou 不会把它发送到任何地方。粘贴之后,剪贴板会恢复原来的内容。",
"hi": "आपकी आवाज़ को आपके Mac की वाक् पहचान टेक्स्ट में बदलती है, जब आपका Mac समर्थन करे तो डिवाइस पर ही; Coucou इसे कहीं नहीं भेजता। चिपकाने के बाद क्लिपबोर्ड में पहले वाली चीज़ वापस आ जाती है।",
@@ -9154,6 +9245,19 @@
"de": "{0} Std. %02lld",
"tr": "{0} sa %02lld"
},
+ "{0} is not installed. Install it from Settings → Chat, sign in once in Terminal, then ask again.": {
+ "zh-Hans": "{0} 未安装。请在 设置 → 聊天 中安装,在终端登录一次,然后再问一次。",
+ "hi": "{0} इंस्टॉल नहीं है। सेटिंग्स → चैट से इसे इंस्टॉल करें, टर्मिनल में एक बार साइन इन करें, फिर दोबारा पूछें।",
+ "es": "{0} no está instalado. Instálalo desde Ajustes → Chat, inicia sesión una vez en la Terminal y vuelve a preguntar.",
+ "ar": "{0} غير مثبّت. ثبّته من الإعدادات ← الدردشة، وسجّل الدخول مرة واحدة في Terminal، ثم اسأل مجددًا.",
+ "fr": "{0} n'est pas installé. Installe-le depuis Réglages → Chat, connecte-toi une fois dans le Terminal, puis redemande.",
+ "bn": "{0} ইনস্টল করা নেই। সেটিংস → চ্যাট থেকে এটি ইনস্টল করুন, টার্মিনালে একবার সাইন ইন করুন, তারপর আবার জিজ্ঞেস করুন।",
+ "pt-BR": "O {0} não está instalado. Instale em Ajustes → Chat, entre uma vez no Terminal e pergunte de novo.",
+ "ru": "{0} не установлен. Установите его в Настройки → Чат, один раз войдите в Терминале и спросите снова.",
+ "id": "{0} belum terpasang. Pasang dari Pengaturan → Chat, masuk sekali di Terminal, lalu tanya lagi.",
+ "de": "{0} ist nicht installiert. Installiere es über Einstellungen → Chat, melde dich einmal im Terminal an und frag dann erneut.",
+ "tr": "{0} yüklü değil. Ayarlar → Sohbet'ten yükleyin, Terminal'de bir kez oturum açın, sonra tekrar sorun."
+ },
"{0} min": {
"zh-Hans": "{0} 分钟",
"hi": "{0} मिनट",
@@ -9271,6 +9375,32 @@
"de": "vor {n} Min.",
"tr": "{n} dk önce"
},
+ "{tool} found ✓": {
+ "zh-Hans": "已找到 {tool} ✓",
+ "hi": "{tool} मिला ✓",
+ "es": "{tool} encontrado ✓",
+ "ar": "تم العثور على {tool} ✓",
+ "fr": "{tool} trouvé ✓",
+ "bn": "{tool} পাওয়া গেছে ✓",
+ "pt-BR": "{tool} encontrado ✓",
+ "ru": "{tool} найден ✓",
+ "id": "{tool} ditemukan ✓",
+ "de": "{tool} gefunden ✓",
+ "tr": "{tool} bulundu ✓"
+ },
+ "{tool} not found.": {
+ "zh-Hans": "未找到 {tool}。",
+ "hi": "{tool} नहीं मिला।",
+ "es": "No se encontró {tool}.",
+ "ar": "لم يتم العثور على {tool}.",
+ "fr": "{tool} introuvable.",
+ "bn": "{tool} পাওয়া যায়নি।",
+ "pt-BR": "{tool} não encontrado.",
+ "ru": "{tool} не найден.",
+ "id": "{tool} tidak ditemukan.",
+ "de": "{tool} nicht gefunden.",
+ "tr": "{tool} bulunamadı."
+ },
"« OK Coucou », Mochi's voice and the dictation key.": {
"zh-Hans": "“OK Coucou”、Mochi 的声音和听写按键。",
"hi": "“OK Coucou”, मोची की आवाज़ और डिक्टेशन कुंजी।",
diff --git a/windows/src/settings/main.ts b/windows/src/settings/main.ts
index 5d043f36..04d9609f 100644
--- a/windows/src/settings/main.ts
+++ b/windows/src/settings/main.ts
@@ -4,7 +4,7 @@
// island's settings are drawn here, one Notch page at a time.
import "./settings.css";
-import { Bridge, onEvent, type HookPreview, type HookStatus, type ShortcutsReport } from "../core/bridge";
+import { Bridge, onEvent, type HookPreview, type HookStatus, type ShortcutsReport, type SubscriptionStatus } from "../core/bridge";
import { CUSTOM_SERVER_KEY, providerDef, urlExposure } from "../core/providers";
import {
ISLAND_SHORTCUTS, SHORTCUTS, SHORTCUT_TEXT, activeKeys, displayKeys, duplicates, effective,
@@ -329,6 +329,68 @@ function planSection(status: HookStatus): HTMLElement {
return section;
}
+// ── Your AI subscriptions ─────────────────────────────────────────────────────
+
+/** The plan people know, by provider. */
+const SUBSCRIPTION_NAMES: Record<string, string> = {
+ anthropic: "Claude", google: "Google Gemini", openai: "ChatGPT", cursor: "Cursor", copilot: "GitHub Copilot",
+};
+
+/**
+ * One switch per provider (cli_relay.rs): on, the chat goes through its
+ * official terminal tool, signed in with the user's own account; off, through
+ * its API key. Says whether the tool is installed and how to sign in.
+ */
+function subscriptionsSection(): HTMLElement {
+ const list = h("div", { style: "display:flex;flex-direction:column;gap:12px" });
+ const draw = (rows: SubscriptionStatus[]) => {
+ clear(list);
+ for (const row of rows) {
+ const p = providerDef(row.provider);
+ const sw = toggle(row.on, (on) => {
+ void Bridge.subscriptionSet(row.provider, on).then((next) => {
+ if (next) draw(next);
+ });
+ });
+ const lines: HTMLElement[] = [];
+ if (row.installed) {
+ lines.push(h("div", { class: "hint", style: "color:#22c55e", text: t("{tool} found ✓", { tool: row.tool }) }));
+ lines.push(h("div", {
+ class: "hint",
+ text: t("Not signed in yet? Run this once in a terminal: {command}", { command: row.signIn }),
+ }));
+ } else {
+ lines.push(h("div", { class: "row" },
+ h("span", { class: "hint", text: t("{tool} not found.", { tool: row.tool }) }),
+ h("button", { text: t("Install it"), onclick: () => void Bridge.openUrl(row.installUrl) }),
+ ));
+ }
+ if (!row.subscriptionOnly && !row.on) {
+ lines.push(h("div", { class: "hint", text: t("Off: the chat uses your API key below.") }));
+ }
+ list.append(h("div", {},
+ h("div", { class: "row" },
+ h("i", { class: "dot", style: `background:${p.accent}` }),
+ h("label", { text: SUBSCRIPTION_NAMES[row.provider] ?? p.name }),
+ sw,
+ ),
+ ...lines,
+ ));
+ }
+ };
+ void Bridge.subscriptionStatus().then((rows) => draw(rows ?? []));
+ return h(
+ "section",
+ {},
+ h("h2", { text: t("Your AI subscriptions") }),
+ h("div", {
+ class: "hint",
+ text: t("Chat on the plan you already pay for. Coucou asks your AI's official terminal tool, signed in with your own account: it never sees your password or your key."),
+ }),
+ list,
+ );
+}
+
// ── Claude API section ────────────────────────────────────────────────────────
const MODELS: [string, string][] = [
@@ -337,10 +399,12 @@ const MODELS: [string, string][] = [
["claude-haiku-4-5", "Claude Haiku 4.5"],
];
-/** The state line under Claude: the key, else Claude Code standing in for it, else what is missing. */
+/** The state line under Claude: the key, else Claude Code (switched on above), 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.");
+ return relay
+ ? t("No key: the chat can go through your Claude subscription above.")
+ : t("No key yet — the chat needs one.");
}
function apiSection(hasKey: boolean, relay: boolean): HTMLElement {
@@ -1407,7 +1471,7 @@ async function render() {
general: () => [generalSection()],
pills: () => [activePillsSection(connected)],
agents: () => [claudeSection(status), agentsSection(agents), planSection(status)],
- chat: () => [apiSection(hasKey, claudeRelay), chatProvidersSection(chatKeys, keyChanged), localSection(customKey)],
+ chat: () => [subscriptionsSection(), 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/views/chat.ts b/windows/src/views/chat.ts
index 134fa9c9..cc9b950d 100644
--- a/windows/src/views/chat.ts
+++ b/windows/src/views/chat.ts
@@ -14,6 +14,7 @@ import {
activeModel, pickModel, providerDef, visibleProviders, withModel, type ProviderDef,
} from "../core/providers";
import { Sound } from "../core/sound";
+import { chipLabel, loadSubscriptions, subscribedProviders, subscription } from "../core/subscriptions";
import { State, type ChatMessage } from "../core/state";
import type { ViewHost } from "./views";
import { N_, t, tl } from "../i18n/i18n";
@@ -85,7 +86,7 @@ function buildPicker(onChange: () => void): Picker {
function drawChips() {
clear(chips);
- for (const p of visibleProviders(State.settings)) {
+ for (const p of visibleProviders(State.settings, subscribedProviders())) {
const on = p.id === State.settings.chatProvider;
const chip = h(
"button",
@@ -123,7 +124,9 @@ function buildPicker(onChange: () => void): Picker {
function drawModels(p: ProviderDef, models: ModelInfo[]) {
clear(list);
- const current = activeModel(State.settings);
+ // Through a subscription, a tool other than Claude Code uses its own model ("").
+ const ownModel = subscription(p.id)?.on && p.id !== "anthropic";
+ const current = ownModel ? "" : activeModel(State.settings);
for (const m of models) {
const on = m.id === current;
const row = h(
@@ -133,6 +136,7 @@ function buildPicker(onChange: () => void): Picker {
on ? svg(ICONS.check, 11, { stroke: 2.2 }) : null,
);
row.addEventListener("click", () => {
+ if (!m.id) return close();
State.settings = withModel(State.settings, p.id, m.id);
saveSettings();
Sound.play("blip");
@@ -146,13 +150,15 @@ function buildPicker(onChange: () => void): Picker {
async function loadModels() {
const p = providerDef(State.settings.chatProvider);
const ticket = ++request;
- const cached = p.urlField ? undefined : cache.get(p.id);
+ const subscribed = subscription(p.id)?.on ?? false;
+ const cacheKey = `${p.id}:${subscribed}`;
+ const cached = p.urlField ? undefined : cache.get(cacheKey);
if (cached) {
drawModels(p, cached);
return;
}
- // Nothing is asked of a provider that has no key yet.
- if (p.key && !(await Bridge.keyReady(p.key))) {
+ // Nothing is asked of a provider that has no key yet (its subscription needs none).
+ if (!subscribed && p.key && !(await Bridge.keyReady(p.key))) {
if (ticket === request) status(t(STRINGS.noKey), true);
return;
}
@@ -161,8 +167,8 @@ function buildPicker(onChange: () => void): Picker {
try {
const models = await Bridge.chatModels(p.id);
if (ticket !== request) return;
- if (!p.urlField) cache.set(p.id, models);
- const keep = pickModel(p, models.map((m) => m.id), activeModel(State.settings));
+ if (!p.urlField) cache.set(cacheKey, models);
+ const keep = subscribed && p.id !== "anthropic" ? null : pickModel(p, models.map((m) => m.id), activeModel(State.settings));
if (keep && keep !== activeModel(State.settings)) {
State.settings = withModel(State.settings, p.id, keep);
saveSettings();
@@ -179,7 +185,13 @@ function buildPicker(onChange: () => void): Picker {
el.classList.add("on");
drawChips();
onChange();
- void loadModels();
+ // Which subscriptions are on may have changed in Settings: ask, then list.
+ void loadSubscriptions().then(() => {
+ if (!isOpen) return;
+ drawChips();
+ onChange();
+ void loadModels();
+ });
}
function close() {
@@ -230,6 +242,7 @@ export function buildPrompt(onHeightChange: () => void): ViewHost {
drawModelButton();
});
body.append(chipRow, log, picker.el, modelRow, bar);
+ void loadSubscriptions().then(() => drawModelButton());
const el = h("div", { class: "view" }, h("div", { class: "card wash chat-card" }, body));
(el.querySelector(".card") as HTMLElement).style.setProperty("--wash", "rgba(99,102,241,0.5)");
@@ -242,7 +255,7 @@ export function buildPrompt(onHeightChange: () => void): ViewHost {
function drawModelButton() {
const p = providerDef(State.settings.chatProvider);
modelDot.style.background = p.accent;
- modelName.textContent = activeModel(State.settings) || t(STRINGS.noModel);
+ modelName.textContent = chipLabel(State.settings, activeModel(State.settings)) || t(STRINGS.noModel);
modelBtn.classList.toggle("open", picker.isOpen);
modelBtn.disabled = sending;
}
diff --git a/windows/tests/providers.test.mjs b/windows/tests/providers.test.mjs
index 1b2b9471..f82ebb09 100644
--- a/windows/tests/providers.test.mjs
+++ b/windows/tests/providers.test.mjs
@@ -11,7 +11,12 @@ import { DEFAULT_SETTINGS } from "../src/core/state.ts";
const settings = (over = {}) => ({ ...DEFAULT_SETTINGS, ...over });
test("the ids and key names match the Rust side and the Mac", () => {
- assert.deepEqual(PROVIDERS.map((p) => p.id), ["anthropic", "google", "openai", "openrouter", "ollama", "lmstudio", "custom"]);
+ assert.deepEqual(PROVIDERS.map((p) => p.id), [
+ "anthropic", "google", "openai", "openrouter", "ollama", "lmstudio", "custom", "cursor", "copilot",
+ ]);
+ // Cursor and Copilot answer only through the subscription: no key, no address.
+ assert.equal(providerDef("cursor").key, null);
+ assert.equal(providerDef("copilot").urlField, null);
assert.equal(providerDef("google").key, "google-api-key");
assert.equal(providerDef("openai").key, "openai-api-key");
assert.equal(providerDef("openrouter").key, "openrouter-api-key");
@@ -41,6 +46,13 @@ test("model servers show in the picker once connected, or while in use", () => {
assert.deepEqual(ids(settings({ chatProvider: "custom" })), ["anthropic", "google", "openai", "openrouter", "custom"]);
});
+test("Cursor and Copilot show once their subscription is on, or while in use", () => {
+ const ids = (s, on) => visibleProviders(s, on).map((p) => p.id);
+ assert.deepEqual(ids(settings(), new Set(["cursor"])), ["anthropic", "google", "openai", "openrouter", "cursor"]);
+ assert.deepEqual(ids(settings({ chatSubscriptions: { copilot: true } })), ["anthropic", "google", "openai", "openrouter", "copilot"]);
+ assert.deepEqual(ids(settings({ chatProvider: "copilot" })), ["anthropic", "google", "openai", "openrouter", "copilot"]);
+});
+
test("the saved model is kept when offered, else a sensible one is picked", () => {
const google = providerDef("google");
assert.equal(pickModel(google, ["gemini-2.5-pro", "gemini-2.0-flash"], "gemini-2.5-pro"), "gemini-2.5-pro");
diff --git a/windows/tests/subscriptions.test.mjs b/windows/tests/subscriptions.test.mjs
new file mode 100644
index 00000000..1bfaccb5
--- /dev/null
+++ b/windows/tests/subscriptions.test.mjs
@@ -0,0 +1,19 @@
+// The model chip through a subscription (src/core/subscriptions.ts).
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { chipLabel, setSubscriptions, subscribedProviders } from "../src/core/subscriptions.ts";
+import { DEFAULT_SETTINGS } from "../src/core/state.ts";
+
+const row = (provider, tool, on) => ({
+ provider, tool, on, installed: true, signIn: "x", installUrl: "https://x", subscriptionOnly: false,
+});
+
+test("the chip names the tool that answers", () => {
+ setSubscriptions([row("anthropic", "Claude Code", true), row("google", "Antigravity CLI", true), row("openai", "Codex CLI", false)]);
+ assert.equal(chipLabel({ ...DEFAULT_SETTINGS, chatProvider: "anthropic" }, "claude-opus-5"), "claude-opus-5 · Claude Code");
+ assert.equal(chipLabel({ ...DEFAULT_SETTINGS, chatProvider: "google" }, "gemini-2.0-flash"), "Antigravity CLI");
+ // Off: the API model, as before.
+ assert.equal(chipLabel({ ...DEFAULT_SETTINGS, chatProvider: "openai" }, "gpt-4o"), "gpt-4o");
+ assert.deepEqual([...subscribedProviders()], ["anthropic", "google"]);
+});