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.

Chat: one conversation for every provider, full Claude answers, first name

Claudeb2ad2130fdfb
diff --git a/windows/src-tauri/src/chat.rs b/windows/src-tauri/src/chat.rs
new file mode 100644
index 00000000..9f1be2b7
--- /dev/null
+++ b/windows/src-tauri/src/chat.rs
@@ -0,0 +1,289 @@
+// The chat, whoever answers it: the conversation, the system prompt, and which
+// provider a turn goes to. Each provider's own wire format lives in its module
+// (claude.rs for Anthropic).
+//
+// API keys never leave the credential store and file bytes never cross the IPC
+// boundary: the island sends the question and gets the answer's text back.
+
+use std::sync::Mutex;
+
+use serde::{Deserialize, Serialize};
+use serde_json::{json, Value};
+use tauri::AppHandle;
+
+use crate::settings::Settings;
+use crate::{claude, secrets};
+
+pub const ANTHROPIC: &str = "anthropic";
+
+#[derive(Debug, Clone, Deserialize)]
+#[serde(tag = "kind", rename_all = "camelCase")]
+pub enum ChatContext {
+ File { name: String, path: String },
+ Window { app_name: String, title: String, url: Option<String> },
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ChatReply {
+ pub text: String,
+}
+
+/// A model a provider offers, for the picker in the chat view.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ModelInfo {
+ pub id: String,
+ pub label: String,
+}
+
+// ── Conversation ──────────────────────────────────────────────────────────────
+
+/// The conversation is kept twice: in the wire format of the provider that
+/// answered last (Claude's carries web search blocks no other provider would
+/// understand), and as plain text turns. Switching provider mid-conversation
+/// rebuilds the history from the plain turns, so nothing in one provider's
+/// format is ever sent to another.
+#[derive(Default)]
+pub struct Chat {
+ inner: Mutex<Conversation>,
+}
+
+#[derive(Default)]
+struct Conversation {
+ /// Bumped by every reset, so an answer that lands after "New chat" is dropped.
+ epoch: u64,
+ /// The provider `native` belongs to.
+ owner: Option<String>,
+ native: Vec<Value>,
+ /// `{"role", "content": text}` turns, the same whoever answered.
+ plain: Vec<Value>,
+}
+
+/// What a provider needs to build one turn.
+pub struct Turn {
+ epoch: u64,
+ provider: String,
+ /// No earlier turn: the file or window context rides along with this one.
+ pub first: bool,
+ /// The earlier turns, in this provider's format.
+ pub history: Vec<Value>,
+}
+
+impl Chat {
+ pub fn reset(&self) {
+ let mut c = self.inner.lock().unwrap();
+ let epoch = c.epoch + 1;
+ *c = Conversation { epoch, ..Default::default() };
+ }
+
+ /// Starts a turn with `provider`, converting the history if another
+ /// provider answered the previous turns.
+ pub fn begin(&self, provider: &str) -> Turn {
+ let mut c = self.inner.lock().unwrap();
+ if c.owner.as_deref() != Some(provider) {
+ c.native = c.plain.clone();
+ c.owner = Some(provider.to_string());
+ }
+ Turn {
+ epoch: c.epoch,
+ provider: provider.to_string(),
+ first: c.plain.is_empty(),
+ history: c.native.clone(),
+ }
+ }
+
+ /// Records a finished turn: the user message and the answer in the
+ /// provider's format, and their plain text. Only a successful turn is
+ /// recorded, so the history always matches what the model saw.
+ pub fn commit(&self, turn: &Turn, user: Value, assistant: Value, user_text: &str, answer: &str) {
+ let mut c = self.inner.lock().unwrap();
+ if c.epoch != turn.epoch || c.owner.as_deref() != Some(turn.provider.as_str()) {
+ return;
+ }
+ c.native.push(user);
+ c.native.push(assistant);
+ c.plain.push(json!({ "role": "user", "content": user_text }));
+ c.plain.push(json!({ "role": "assistant", "content": answer }));
+ }
+}
+
+// ── System prompt ─────────────────────────────────────────────────────────────
+
+/// Mochi's instructions. Greets the user by their first name when the account
+/// has one worth using (identity.rs), and only claims web search where the
+/// provider runs it (Claude).
+pub fn system_prompt(web_search: bool) -> String {
+ system_prompt_for(crate::identity::first_name(), web_search)
+}
+
+fn system_prompt_for(first_name: Option<&str>, web_search: bool) -> String {
+ let opening = match first_name {
+ Some(name) => format!("You are Mochi, {name}'s personal AI assistant living at the top of their screen."),
+ None => "You are Mochi, a personal AI assistant living at the top of the user's screen.".to_string(),
+ };
+ let abilities = if web_search {
+ "You have web search access and can help with absolutely anything — research, coding, finding places, recommendations, tasks, questions."
+ } else {
+ "You can help with absolutely anything — research, coding, recommendations, tasks, questions. You have no web access: say so when something needs current information."
+ };
+ format!(
+ "{opening} {abilities} \
+Respond in the user's language. Be thorough and complete — use as much detail as the task requires. \
+Use light Markdown when it helps: short paragraphs, bullet lists, **bold**, `inline code` and fenced code blocks. Avoid tables and big headings: the chat window is small."
+ )
+}
+
+/// The window context line, as ClaudeService.chat() writes it.
+pub fn window_line(app_name: &str, title: &str, url: Option<&str>) -> String {
+ let mut text = format!("Context — App: {app_name}, Window: {title}");
+ if let Some(url) = url {
+ text.push_str(&format!(", URL: {url}"));
+ }
+ text
+}
+
+/// The plain-text record of what the user asked, context included.
+pub fn plain_question(first: bool, context: Option<&ChatContext>, query: &str) -> String {
+ match context.filter(|_| first) {
+ Some(ChatContext::File { name, .. }) => format!("File: {name}\n\n{query}"),
+ Some(ChatContext::Window { app_name, title, url }) => {
+ format!("{}\n\n{query}", window_line(app_name, title, url.as_deref()))
+ }
+ None => query.to_string(),
+ }
+}
+
+// ── Which provider ────────────────────────────────────────────────────────────
+
+/// The model chosen for `provider`, or its default.
+pub fn model_for(settings: &Settings, _provider: &str) -> String {
+ let m = settings.model.trim();
+ if m.is_empty() { claude::DEFAULT_MODEL.to_string() } else { m.to_string() }
+}
+
+/// One chat turn with the provider chosen in the settings.
+pub async fn send(
+ app: &AppHandle,
+ chat: &Chat,
+ settings: &Settings,
+ query: String,
+ context: Option<ChatContext>,
+) -> Result<ChatReply, String> {
+ let _ = app;
+ let model = model_for(settings, ANTHROPIC);
+ claude::send(chat, &model, query, context).await
+}
+
+/// The models `provider` offers. Asked only when the user opens the picker on
+/// that provider, and only once it has a key (or, for a local server, an
+/// address): nothing is sent anywhere before that.
+pub async fn models(settings: &Settings, provider: &str) -> Result<Vec<ModelInfo>, String> {
+ const NO_KEY: &str = "No API key — add it in Settings.";
+ let _ = settings;
+ if provider == ANTHROPIC {
+ let key = secrets::get(claude::KEY).ok_or(NO_KEY)?;
+ return claude::models(&key).await;
+ }
+ Err(format!("Unknown chat provider: {provider}"))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn turn_texts(history: &[Value]) -> Vec<(String, Value)> {
+ history
+ .iter()
+ .map(|m| (m["role"].as_str().unwrap().to_string(), m["content"].clone()))
+ .collect()
+ }
+
+ #[test]
+ fn a_turn_is_recorded_only_once_it_succeeds() {
+ let chat = Chat::default();
+ let t = chat.begin("anthropic");
+ assert!(t.first);
+ assert!(t.history.is_empty());
+ // A failed turn records nothing: the next one is still the first.
+ let t = chat.begin("anthropic");
+ assert!(t.first);
+ chat.commit(&t, json!({"role":"user","content":[{"type":"text","text":"hi"}]}), json!({"role":"assistant","content":[{"type":"text","text":"hello"}]}), "hi", "hello");
+ let t = chat.begin("anthropic");
+ assert!(!t.first);
+ assert_eq!(t.history.len(), 2);
+ assert!(t.history[0]["content"].is_array());
+ }
+
+ #[test]
+ fn switching_provider_never_sends_claude_blocks_to_another_one() {
+ let chat = Chat::default();
+ let t = chat.begin("anthropic");
+ let blocks = json!([
+ {"type":"server_tool_use","id":"srvtoolu_1","name":"web_search","input":{"query":"x"}},
+ {"type":"web_search_tool_result","tool_use_id":"srvtoolu_1","content":[]},
+ {"type":"text","text":"Found it."}
+ ]);
+ chat.commit(&t, json!({"role":"user","content":[{"type":"text","text":"look"}]}), json!({"role":"assistant","content":blocks}), "look", "Found it.");
+
+ let t = chat.begin("openai");
+ assert!(!t.first);
+ assert_eq!(
+ turn_texts(&t.history),
+ vec![("user".into(), json!("look")), ("assistant".into(), json!("Found it."))]
+ );
+ let raw = serde_json::to_string(&t.history).unwrap();
+ assert!(!raw.contains("web_search"), "{raw}");
+
+ // And back: Claude gets the plain turns too, including OpenAI's answer.
+ chat.commit(&t, json!({"role":"user","content":"more"}), json!({"role":"assistant","content":"Sure."}), "more", "Sure.");
+ let t = chat.begin("anthropic");
+ assert_eq!(t.history.len(), 4);
+ assert_eq!(t.history[3], json!({"role":"assistant","content":"Sure."}));
+ assert!(!serde_json::to_string(&t.history).unwrap().contains("web_search"));
+ }
+
+ #[test]
+ fn an_answer_that_lands_after_a_reset_or_a_switch_is_dropped() {
+ let chat = Chat::default();
+ let t = chat.begin("openai");
+ chat.reset();
+ chat.commit(&t, json!({"role":"user","content":"q"}), json!({"role":"assistant","content":"a"}), "q", "a");
+ assert!(chat.begin("openai").first);
+
+ let t = chat.begin("openai");
+ let _other = chat.begin("google");
+ chat.commit(&t, json!({"role":"user","content":"q"}), json!({"role":"assistant","content":"a"}), "q", "a");
+ assert!(chat.begin("google").first);
+ }
+
+ #[test]
+ fn the_prompt_greets_by_first_name_and_claims_web_search_only_for_claude() {
+ let p = system_prompt_for(Some("Louis"), true);
+ assert!(p.starts_with("You are Mochi, Louis's personal AI assistant living at the top of their screen."));
+ assert!(p.contains("web search access"));
+ assert!(p.contains("light Markdown"));
+ let p = system_prompt_for(None, false);
+ assert!(p.starts_with("You are Mochi, a personal AI assistant living at the top of the user's screen."));
+ assert!(!p.contains("web search"));
+ assert!(p.contains("no web access"));
+ }
+
+ #[test]
+ fn context_goes_with_the_first_question_only() {
+ let file = ChatContext::File { name: "a.txt".into(), path: "/x/a.txt".into() };
+ assert_eq!(plain_question(true, Some(&file), "why?"), "File: a.txt\n\nwhy?");
+ assert_eq!(plain_question(false, Some(&file), "why?"), "why?");
+ let win = ChatContext::Window { app_name: "Code".into(), title: "main.rs".into(), url: None };
+ assert_eq!(plain_question(true, Some(&win), "q"), "Context — App: Code, Window: main.rs\n\nq");
+ assert_eq!(window_line("Edge", "Docs", Some("https://x.dev")), "Context — App: Edge, Window: Docs, URL: https://x.dev");
+ }
+
+ #[test]
+ fn the_model_comes_from_the_settings_or_the_default() {
+ let mut s = Settings::default();
+ assert_eq!(model_for(&s, "anthropic"), claude::DEFAULT_MODEL);
+ s.model = "claude-haiku-4-5".into();
+ assert_eq!(model_for(&s, "anthropic"), "claude-haiku-4-5");
+ }
+}
diff --git a/windows/src-tauri/src/claude.rs b/windows/src-tauri/src/claude.rs
index 060a57c6..2080347a 100644
--- a/windows/src-tauri/src/claude.rs
+++ b/windows/src-tauri/src/claude.rs
@@ -2,16 +2,25 @@
// chat with web search, and files sent as document/image/text blocks.
//
// Everything happens here rather than in the island: the API key never leaves
-// the Credential Manager, and file bytes never cross the IPC boundary.
+// the credential store, and file bytes never cross the IPC boundary.
+//
+// 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.
-use std::sync::Mutex;
+use std::sync::OnceLock;
+use std::time::Duration;
-use serde::{Deserialize, Serialize};
+use reqwest::Url;
use serde_json::{json, Value};
-use crate::secrets;
+use crate::chat::{self, Chat, ChatContext, ChatReply, ModelInfo};
+use crate::{net, secrets};
-const ENDPOINT: &str = "https://api.anthropic.com/v1/messages";
+/// Credential store entry of the Anthropic API key.
+pub const KEY: &str = "anthropic-api-key";
+const DEFAULT_ENDPOINT: &str = "https://api.anthropic.com/v1/messages";
+const BASE_URL_VAR: &str = "COUCOU_ANTHROPIC_BASE_URL";
const ANTHROPIC_VERSION: &str = "2023-06-01";
/// Server-side fallback: on a policy decline the API retries the same request on
/// a fallback model inside the same call, so the island never shows a dead end.
@@ -22,69 +31,45 @@ const MAX_INLINE_TEXT: u64 = 200_000;
pub const DEFAULT_MODEL: &str = "claude-opus-5";
-const SYSTEM_PROMPT: &str = "You are Mochi, a personal AI assistant living at the top of the user's screen. \
-You have web search access and can help with absolutely anything — research, coding, finding places, recommendations, tasks, questions. \
-Respond in the user's language. Be thorough and complete — use as much detail as the task requires. \
-No markdown formatting (no **, no ##, no bullet dashes). Use plain text with line breaks.";
-
-#[derive(Default)]
-pub struct Chat {
- /// Full multi-turn history, including tool_use / tool_result blocks.
- messages: Mutex<Vec<Value>>,
-}
-
-impl Chat {
- pub fn reset(&self) {
- self.messages.lock().unwrap().clear();
- }
-
- fn is_empty(&self) -> bool {
- self.messages.lock().unwrap().is_empty()
- }
-
- fn push(&self, message: Value) {
- self.messages.lock().unwrap().push(message);
- }
-
- fn pop(&self) {
- self.messages.lock().unwrap().pop();
- }
-
- fn snapshot(&self) -> Vec<Value> {
- self.messages.lock().unwrap().clone()
- }
-}
-
-#[derive(Debug, Clone, Deserialize)]
-#[serde(tag = "kind", rename_all = "camelCase")]
-pub enum ChatContext {
- File { name: String, path: String },
- Window { app_name: String, title: String, url: Option<String> },
+/// 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> {
+ static ENDPOINT: OnceLock<Result<Url, String>> = OnceLock::new();
+ ENDPOINT
+ .get_or_init(|| {
+ let raw = std::env::var(BASE_URL_VAR).ok().filter(|v| !v.trim().is_empty());
+ let resolved = match raw {
+ None => Ok(Url::parse(DEFAULT_ENDPOINT).expect("valid default endpoint")),
+ Some(raw) => net::anthropic_endpoint(&raw),
+ };
+ match &resolved {
+ Ok(url) if url.as_str() != DEFAULT_ENDPOINT => crate::log::line(format!(
+ "chat: Claude requests go to {} ({BASE_URL_VAR})",
+ net::host_for_log(url)
+ )),
+ Err(err) => crate::log::line(format!("chat: {err}")),
+ _ => {}
+ }
+ resolved
+ })
+ .clone()
}
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ChatReply {
- pub text: String,
+/// The model list endpoint next to the Messages one.
+fn models_endpoint(messages: &Url) -> Url {
+ let mut url = messages.clone();
+ let path = url.path().trim_end_matches("/messages").to_string();
+ url.set_path(&format!("{path}/models"));
+ url.set_query(Some("limit=100"));
+ url
}
-/// One chat turn. Returns the assistant's text, or a message the island shows
-/// in the note view.
-pub async fn send(
- chat: &Chat,
- model: &str,
- query: String,
- context: Option<ChatContext>,
-) -> Result<ChatReply, String> {
- let key = secrets::get("anthropic-api-key")
- .ok_or_else(|| "API key missing. Open settings.".to_string())?;
-
+/// The user's content blocks for one turn. File / window context rides along
+/// with the first message only, exactly like ClaudeService.chat().
+fn user_content(first: bool, context: Option<&ChatContext>, query: &str) -> Vec<Value> {
let mut content: Vec<Value> = Vec::new();
-
- // File / window context rides along with the first message only, exactly
- // like ClaudeService.chat().
- if chat.is_empty() {
- match &context {
+ if first {
+ match context {
Some(ChatContext::File { name, path }) => {
if let Some(block) = file_block(path) {
content.push(block);
@@ -92,79 +77,90 @@ pub async fn send(
content.push(json!({ "type": "text", "text": format!("File: {name}") }));
}
Some(ChatContext::Window { app_name, title, url }) => {
- let mut text = format!("Context — App: {app_name}, Window: {title}");
- if let Some(url) = url {
- text.push_str(&format!(", URL: {url}"));
- }
- content.push(json!({ "type": "text", "text": text }));
+ let line = chat::window_line(app_name, title, url.as_deref());
+ content.push(json!({ "type": "text", "text": line }));
}
None => {}
}
}
content.push(json!({ "type": "text", "text": query }));
+ content
+}
- chat.push(json!({ "role": "user", "content": content }));
-
- let body = json!({
+fn request_body(model: &str, system: &str, history: &[Value], user: &Value) -> Value {
+ let mut messages = history.to_vec();
+ messages.push(user.clone());
+ json!({
"model": model,
"max_tokens": MAX_TOKENS,
- "system": SYSTEM_PROMPT,
+ "system": system,
"tools": [{ "type": "web_search_20260209", "name": "web_search", "max_uses": 5 }],
"fallbacks": "default",
- "messages": chat.snapshot(),
- });
-
- let response = match call(&key, &body).await {
- Ok(v) => v,
- Err(err) => {
- chat.pop(); // keep the history consistent with what the model saw
- return Err(err);
- }
- };
+ "messages": messages,
+ })
+}
+/// The assistant's full text from a Messages API content array — the same as
+/// claudeResponseText() on the Mac (#67). Web search answers interleave text
+/// with tool blocks, and citations split a sentence across adjacent text
+/// blocks: every text block is kept, joined as is, and only the whole trimmed.
+pub fn response_text(content: &[Value]) -> Option<String> {
+ let text: String = content
+ .iter()
+ .filter(|b| b.get("type").and_then(Value::as_str) == Some("text"))
+ .filter_map(|b| b.get("text").and_then(Value::as_str))
+ .collect();
+ let text = text.trim();
+ (!text.is_empty()).then(|| text.to_string())
+}
+
+/// The content blocks to keep in the history and the text to show, or why there are none.
+fn interpret(response: &Value) -> Result<(Vec<Value>, String), String> {
// A policy decline comes back as HTTP 200 with stop_reason "refusal".
if response.get("stop_reason").and_then(Value::as_str) == Some("refusal") {
- chat.pop();
let why = response
- .get("stop_details")
- .and_then(|d| d.get("explanation"))
+ .pointer("/stop_details/explanation")
.and_then(Value::as_str)
.unwrap_or("Claude declined this one.");
return Err(why.to_string());
}
+ let blocks = response
+ .get("content")
+ .and_then(Value::as_array)
+ .cloned()
+ .ok_or("Unexpected API response.")?;
+ let text = response_text(&blocks).ok_or("No response text.")?;
+ Ok((blocks, text))
+}
- let Some(blocks) = response.get("content").and_then(Value::as_array).cloned() else {
- chat.pop();
- return Err("Unexpected API response.".into());
- };
+/// One chat turn. Returns the assistant's text, or a message the island shows
+/// in the note view.
+pub async fn send(
+ chat: &Chat,
+ model: &str,
+ query: String,
+ context: Option<ChatContext>,
+) -> Result<ChatReply, String> {
+ let key = secrets::get(KEY).ok_or_else(|| "API key missing. Open settings.".to_string())?;
+ let endpoint = endpoint()?;
- // Store the whole content — tool_use / tool_result blocks included — so the
- // next turn has the right context.
- chat.push(json!({ "role": "assistant", "content": blocks.clone() }));
+ let turn = chat.begin(chat::ANTHROPIC);
+ let user = json!({ "role": "user", "content": user_content(turn.first, context.as_ref(), &query) });
+ let body = request_body(model, &chat::system_prompt(true), &turn.history, &user);
- let text = blocks
- .iter()
- .filter(|b| b.get("type").and_then(Value::as_str) == Some("text"))
- .filter_map(|b| b.get("text").and_then(Value::as_str))
- .collect::<Vec<_>>()
- .join("\n")
- .trim()
- .to_string();
+ let response = call(&endpoint, &key, &body).await?;
+ let (blocks, text) = interpret(&response)?;
- if text.is_empty() {
- return Err("No response text.".into());
- }
+ // Store the whole content — tool_use / tool_result blocks included — so the
+ // next turn has the right context.
+ let plain = chat::plain_question(turn.first, context.as_ref(), &query);
+ chat.commit(&turn, user, json!({ "role": "assistant", "content": blocks }), &plain, &text);
Ok(ChatReply { text })
}
-async fn call(key: &str, body: &Value) -> Result<Value, String> {
- let client = reqwest::Client::builder()
- .timeout(std::time::Duration::from_secs(90))
- .build()
- .map_err(|e| e.to_string())?;
-
- let response = client
- .post(ENDPOINT)
+async fn call(endpoint: &Url, key: &str, body: &Value) -> Result<Value, String> {
+ let response = net::client(endpoint, Duration::from_secs(90))?
+ .post(endpoint.clone())
.header("x-api-key", key)
.header("anthropic-version", ANTHROPIC_VERSION)
.header("anthropic-beta", FALLBACK_BETA)
@@ -175,21 +171,46 @@ async fn call(key: &str, body: &Value) -> Result<Value, String> {
.map_err(|e| format!("Network error: {e}"))?;
let status = response.status();
- let text = response.text().await.map_err(|e| e.to_string())?;
if !status.is_success() {
// Surface the API's own message, which is what makes a bad key obvious.
- let detail = serde_json::from_str::<Value>(&text)
- .ok()
- .and_then(|v| {
- v.get("error")
- .and_then(|e| e.get("message"))
- .and_then(Value::as_str)
- .map(str::to_string)
- })
- .unwrap_or_else(|| text.chars().take(200).collect());
- return Err(format!("Claude API {status}: {detail}"));
+ let body = net::read_capped(response, net::MAX_ERROR_BODY).await.unwrap_or_default();
+ return Err(format!("Claude API {status}: {}", net::error_detail(&body)));
+ }
+ let bytes = net::read_capped(response, net::MAX_BODY).await?;
+ serde_json::from_slice(&bytes).map_err(|e| format!("Bad API response: {e}"))
+}
+
+/// The models on the user's Anthropic account, newest first, as the API lists them.
+pub async fn models(key: &str) -> Result<Vec<ModelInfo>, String> {
+ let url = models_endpoint(&endpoint()?);
+ let response = net::client(&url, Duration::from_secs(10))?
+ .get(url.clone())
+ .header("x-api-key", key)
+ .header("anthropic-version", ANTHROPIC_VERSION)
+ .send()
+ .await
+ .map_err(|e| format!("Network error: {e}"))?;
+ let status = response.status();
+ if !status.is_success() {
+ let body = net::read_capped(response, net::MAX_ERROR_BODY).await.unwrap_or_default();
+ return Err(format!("Claude API {status}: {}", net::error_detail(&body)));
}
- serde_json::from_str(&text).map_err(|e| format!("Bad API response: {e}"))
+ let bytes = net::read_capped(response, net::MAX_BODY).await?;
+ let json: Value = serde_json::from_slice(&bytes).map_err(|_| "Unexpected API response.".to_string())?;
+ Ok(parse_models(&json))
+}
+
+fn parse_models(json: &Value) -> Vec<ModelInfo> {
+ json.get("data")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ .filter_map(|m| {
+ let id = m.get("id")?.as_str()?.to_string();
+ let label = m.get("display_name").and_then(Value::as_str).unwrap_or(&id).to_string();
+ Some(ModelInfo { id, label })
+ })
+ .collect()
}
/// PDF → document block, image → image block, text/code → inline text.
@@ -227,7 +248,7 @@ fn file_block(path: &str) -> Option<Value> {
}
/// Small standalone base64 encoder — not worth another dependency.
-/// Also used for Stripe's basic auth.
+/// Also used for Stripe's basic auth and the images sent to other providers.
pub(crate) fn base64_for(bytes: &[u8]) -> String {
base64(bytes)
}
@@ -248,7 +269,7 @@ fn base64(bytes: &[u8]) -> String {
#[cfg(test)]
mod tests {
- use super::base64;
+ use super::*;
#[test]
fn base64_matches_rfc4648_vectors() {
@@ -260,4 +281,93 @@ mod tests {
assert_eq!(base64(b"fooba"), "Zm9vYmE=");
assert_eq!(base64(b"foobar"), "Zm9vYmFy");
}
+
+ fn texts(parts: &[&str]) -> Vec<Value> {
+ parts.iter().map(|t| json!({ "type": "text", "text": t })).collect()
+ }
+
+ #[test]
+ fn every_text_block_is_kept_in_order_without_added_separators() {
+ assert_eq!(response_text(&texts(&["Simple answer."])).as_deref(), Some("Simple answer."));
+ let content = vec![
+ json!({"type":"text","text":"I'll look that up.\n"}),
+ json!({"type":"server_tool_use","id":"srvtoolu_01","name":"web_search","input":{"query":"test"}}),
+ json!({"type":"web_search_tool_result","tool_use_id":"srvtoolu_01","content":[]}),
+ json!({"type":"text","text":"The answer is 42."}),
+ ];
+ assert_eq!(response_text(&content).as_deref(), Some("I'll look that up.\nThe answer is 42."));
+ // An empty leading block does not hide the answer.
+ let content = vec![
+ json!({"type":"text","text":""}),
+ json!({"type":"web_search_tool_result","tool_use_id":"b","content":[]}),
+ json!({"type":"text","text":"Here is the actual answer."}),
+ ];
+ assert_eq!(response_text(&content).as_deref(), Some("Here is the actual answer."));
+ // Citations split a sentence across blocks: no newline is inserted.
+ assert_eq!(
+ response_text(&texts(&["Paris is the ", "capital", " of France."])).as_deref(),
+ Some("Paris is the capital of France.")
+ );
+ // Search result text never leaks into the answer.
+ let content = vec![
+ json!({"type":"text","text":"Answer."}),
+ json!({"type":"web_search_tool_result","tool_use_id":"a","content":[{"type":"web_search_result","title":"Page","text":"Leak"}]}),
+ ];
+ assert_eq!(response_text(&content).as_deref(), Some("Answer."));
+ assert_eq!(response_text(&[json!({"type":"server_tool_use","id":"x"})]), None);
+ assert_eq!(response_text(&texts(&["", " \n"])), None);
+ }
+
+ #[test]
+ fn a_refusal_or_an_empty_answer_is_an_error() {
+ let refusal = json!({"stop_reason":"refusal","stop_details":{"explanation":"Not this."},"content":[]});
+ assert_eq!(interpret(&refusal).unwrap_err(), "Not this.");
+ assert_eq!(interpret(&json!({"stop_reason":"refusal"})).unwrap_err(), "Claude declined this one.");
+ assert_eq!(interpret(&json!({"id":"x"})).unwrap_err(), "Unexpected API response.");
+ assert_eq!(interpret(&json!({"content":[]})).unwrap_err(), "No response text.");
+ let (blocks, text) = interpret(&json!({"content":[{"type":"text","text":" Hi "}]})).unwrap();
+ assert_eq!(text, "Hi");
+ assert_eq!(blocks.len(), 1);
+ }
+
+ #[test]
+ fn the_request_carries_history_web_search_and_the_new_turn_last() {
+ let history = vec![json!({"role":"user","content":"a"}), json!({"role":"assistant","content":"b"})];
+ let user = json!({"role":"user","content":[{"type":"text","text":"c"}]});
+ let body = request_body("claude-x", "sys", &history, &user);
+ assert_eq!(body["model"], "claude-x");
+ assert_eq!(body["system"], "sys");
+ assert_eq!(body["max_tokens"], MAX_TOKENS);
+ assert_eq!(body["tools"][0]["name"], "web_search");
+ assert_eq!(body["messages"].as_array().unwrap().len(), 3);
+ assert_eq!(body["messages"][2], user);
+ }
+
+ #[test]
+ fn context_is_sent_with_the_first_turn_only() {
+ let ctx = ChatContext::Window { app_name: "Edge".into(), title: "Docs".into(), url: Some("https://x.dev".into()) };
+ let first = user_content(true, Some(&ctx), "q");
+ assert_eq!(first.len(), 2);
+ assert_eq!(first[0]["text"], "Context — App: Edge, Window: Docs, URL: https://x.dev");
+ assert_eq!(user_content(false, Some(&ctx), "q"), vec![json!({"type":"text","text":"q"})]);
+ // A file that cannot be read still names itself.
+ let ctx = ChatContext::File { name: "gone.pdf".into(), path: "/no/such/gone.pdf".into() };
+ assert_eq!(user_content(true, Some(&ctx), "q")[0]["text"], "File: gone.pdf");
+ }
+
+ #[test]
+ fn the_model_list_sits_next_to_the_messages_endpoint() {
+ let url = Url::parse(DEFAULT_ENDPOINT).unwrap();
+ assert_eq!(models_endpoint(&url).as_str(), "https://api.anthropic.com/v1/models?limit=100");
+ let url = net::anthropic_endpoint("https://gw.example.com/anthropic").unwrap();
+ assert_eq!(models_endpoint(&url).as_str(), "https://gw.example.com/anthropic/v1/models?limit=100");
+ let list = json!({"data":[{"id":"claude-opus-5","display_name":"Claude Opus 5"},{"id":"claude-x"},{"nope":1}]});
+ assert_eq!(
+ parse_models(&list),
+ vec![
+ ModelInfo { id: "claude-opus-5".into(), label: "Claude Opus 5".into() },
+ ModelInfo { id: "claude-x".into(), label: "claude-x".into() },
+ ]
+ );
+ }
}
diff --git a/windows/src-tauri/src/identity.rs b/windows/src-tauri/src/identity.rs
new file mode 100644
index 00000000..9fdac341
--- /dev/null
+++ b/windows/src-tauri/src/identity.rs
@@ -0,0 +1,67 @@
+// The user's first name, for Mochi's system prompt — the same rules as
+// UserIdentity.swift on the Mac. The full name comes from the OS account
+// (platform::user_full_name); this file only decides whether it is something
+// you would greet someone by.
+
+use std::sync::OnceLock;
+
+const MAX_FULL_NAME_CHARS: usize = 32;
+
+/// Resolved once: the account name cannot change while the app runs.
+pub fn first_name() -> Option<&'static str> {
+ static NAME: OnceLock<Option<String>> = OnceLock::new();
+ NAME.get_or_init(|| crate::platform::user_full_name().as_deref().and_then(first_name_from))
+ .as_deref()
+}
+
+/// "Théodore Riant" gives "Théodore"; a login handle such as "theodoreriant"
+/// or "t.riant2" gives nothing, because "Hey theodoreriant!" reads worse than
+/// a greeting with no name at all.
+pub fn first_name_from(full_name: &str) -> Option<String> {
+ let full = full_name.trim();
+ if full.is_empty() || full.chars().count() > MAX_FULL_NAME_CHARS || looks_like_login_handle(full) {
+ return None;
+ }
+ let first = full.split(' ').find(|p| !p.is_empty())?;
+ first.chars().all(is_name_part).then(|| first.to_string())
+}
+
+/// Where no full name is set the OS hands back the account name, so a single
+/// lowercase word, or one carrying digits or separators, is taken as a handle.
+fn looks_like_login_handle(name: &str) -> bool {
+ if name.contains(' ') {
+ return false;
+ }
+ name.to_lowercase() == name || name.chars().any(|c| c.is_numeric() || "._-@".contains(c))
+}
+
+fn is_name_part(c: char) -> bool {
+ c.is_alphabetic() || c == '\'' || c == '-'
+}
+
+#[cfg(test)]
+mod tests {
+ use super::first_name_from;
+
+ #[test]
+ fn a_real_full_name_gives_its_first_word() {
+ assert_eq!(first_name_from("Théodore Riant").as_deref(), Some("Théodore"));
+ assert_eq!(first_name_from(" Louis Raille ").as_deref(), Some("Louis"));
+ assert_eq!(first_name_from("Jean-Luc Picard").as_deref(), Some("Jean-Luc"));
+ assert_eq!(first_name_from("O'Brien Miles").as_deref(), Some("O'Brien"));
+ assert_eq!(first_name_from("Louis").as_deref(), Some("Louis"));
+ assert_eq!(first_name_from("Zoë").as_deref(), Some("Zoë"));
+ }
+
+ #[test]
+ fn login_handles_and_odd_names_give_nothing() {
+ for name in ["", " ", "theodoreriant", "t.riant2", "Louis2", "louis_r", "me@example", "Admin_01"] {
+ assert_eq!(first_name_from(name), None, "{name}");
+ }
+ // A first word that is not a name.
+ assert_eq!(first_name_from("R2-D2 Unit"), None);
+ assert_eq!(first_name_from("Dr. Who"), None);
+ // Too long to be a person's name.
+ assert_eq!(first_name_from(&format!("Louis {}", "a".repeat(40))), None);
+ }
+}
diff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rs
index d9ec3353..eec354d0 100644
--- a/windows/src-tauri/src/lib.rs
+++ b/windows/src-tauri/src/lib.rs
@@ -1,11 +1,14 @@
// Coucou for Windows — app wiring and the commands the island calls.
+mod chat;
mod claude;
mod files;
mod hooks;
+mod identity;
mod integrations;
mod island;
mod log;
+mod net;
mod pipe;
mod platform;
mod secrets;
@@ -20,7 +23,7 @@ use serde::Serialize;
use tauri::{AppHandle, Emitter, Manager, State, WebviewUrl, WebviewWindowBuilder};
use tauri_plugin_autostart::{ManagerExt, MacosLauncher};
-use claude::{Chat, ChatContext, ChatReply};
+use chat::{Chat, ChatContext, ChatReply, ModelInfo};
use files::DroppedFile;
use hooks::{HookPreview, HookStatus};
use island::{PollGate, ScreenInfo};
@@ -238,13 +241,21 @@ fn approval_decline(app: AppHandle, request_id: String) {
/// One chat turn. The API key and any file bytes stay on the Rust side.
#[tauri::command]
async fn chat_send(
+ app: AppHandle,
shared: State<'_, Shared>,
chat: State<'_, Chat>,
query: String,
context: Option<ChatContext>,
) -> Result<ChatReply, String> {
- let model = shared.settings.lock().unwrap().model.clone();
- claude::send(&chat, &model, query, context).await
+ let settings = shared.settings.lock().unwrap().clone();
+ chat::send(&app, &chat, &settings, query, context).await
+}
+
+/// The models a provider offers. Only asked with the provider's key.
+#[tauri::command]
+async fn chat_models(shared: State<'_, Shared>, provider: String) -> Result<Vec<ModelInfo>, String> {
+ let settings = shared.settings.lock().unwrap().clone();
+ chat::models(&settings, &provider).await
}
#[tauri::command]
@@ -394,6 +405,7 @@ pub fn run() {
approval_decline,
log_line,
chat_send,
+ chat_models,
chat_reset,
ingest_file,
secret_present,
diff --git a/windows/src-tauri/src/net.rs b/windows/src-tauri/src/net.rs
new file mode 100644
index 00000000..ef31c7fd
--- /dev/null
+++ b/windows/src-tauri/src/net.rs
@@ -0,0 +1,283 @@
+// Network helpers shared by the chat providers: address checks, bounded reads
+// and HTTP clients.
+//
+// Every answer a server sends is read with a ceiling, so a misbehaving or
+// hostile server (a local model address can point anywhere) cannot make the
+// app hold an unbounded amount of memory.
+
+use std::net::{IpAddr, Ipv4Addr};
+use std::time::Duration;
+
+use reqwest::Url;
+
+/// Ceiling for a JSON answer: a chat reply or a model list.
+pub const MAX_BODY: usize = 8 * 1024 * 1024;
+/// Ceiling for an error body: only its message is shown.
+pub const MAX_ERROR_BODY: usize = 64 * 1024;
+
+/// True for an address that is this machine: `localhost`, 127.0.0.0/8, ::1,
+/// and the unspecified addresses (0.0.0.0, ::), which connect to this machine.
+pub fn is_loopback_host(host: &str) -> bool {
+ let host = host.trim_start_matches('[').trim_end_matches(']').to_ascii_lowercase();
+ if host == "localhost" || host.ends_with(".localhost") {
+ return true;
+ }
+ match host.parse::<IpAddr>() {
+ Ok(IpAddr::V4(ip)) => ip.is_loopback() || ip.is_unspecified(),
+ Ok(IpAddr::V6(ip)) => {
+ ip.is_loopback()
+ || ip.is_unspecified()
+ || ip.to_ipv4_mapped().is_some_and(|v4| v4.is_loopback())
+ }
+ Err(_) => false,
+ }
+}
+
+pub fn is_loopback_url(url: &Url) -> bool {
+ url.host_str().is_some_and(is_loopback_host)
+}
+
+/// The address of a model server as the user typed or pasted it, cleaned up:
+/// a missing scheme becomes `http://`, trailing slashes and the documentation
+/// sub-paths people paste (`/api`, `/v1`) go, and the loopback names become
+/// 127.0.0.1 — on Windows `localhost` may resolve to ::1 first while Ollama
+/// only listens on IPv4. Only http and https, and no `user:password@`.
+pub fn normalise_server_url(raw: &str) -> Result<Url, String> {
+ let raw = raw.trim();
+ if raw.is_empty() {
+ return Err("Enter the server address first.".into());
+ }
+ let with_scheme = if raw.contains("://") { raw.to_string() } else { format!("http://{raw}") };
+ let mut url = Url::parse(&with_scheme).map_err(|_| format!("Not a valid address: {raw}"))?;
+ if !matches!(url.scheme(), "http" | "https") {
+ return Err("The address must start with http:// or https://.".into());
+ }
+ if !url.username().is_empty() || url.password().is_some() {
+ return Err("Leave the user name and password out of the address.".into());
+ }
+ if url.host_str().is_none_or(str::is_empty) {
+ return Err(format!("Not a valid address: {raw}"));
+ }
+ if is_loopback_url(&url) {
+ let _ = url.set_ip_host(IpAddr::V4(Ipv4Addr::LOCALHOST));
+ }
+ let mut path = url.path().trim_end_matches('/').to_string();
+ for suffix in ["/api", "/v1"] {
+ if let Some(rest) = path.strip_suffix(suffix) {
+ path = rest.trim_end_matches('/').to_string();
+ }
+ }
+ url.set_path(&path);
+ url.set_query(None);
+ url.set_fragment(None);
+ Ok(url)
+}
+
+/// `base` + `tail`, with exactly one slash between them.
+pub fn join(base: &Url, tail: &str) -> String {
+ format!("{}/{}", base.as_str().trim_end_matches('/'), tail.trim_start_matches('/'))
+}
+
+/// The Messages endpoint for an Anthropic-compatible gateway given in
+/// COUCOU_ANTHROPIC_BASE_URL. A base URL (`https://gw.example.com`,
+/// `…/v1`) gets `/v1/messages` added; a full endpoint is kept. The key goes
+/// wherever this points, so it must be https — plain http only to this machine.
+pub fn anthropic_endpoint(raw: &str) -> Result<Url, String> {
+ const VAR: &str = "COUCOU_ANTHROPIC_BASE_URL";
+ let mut url = Url::parse(raw.trim()).map_err(|_| format!("{VAR} is not a valid URL."))?;
+ match url.scheme() {
+ "https" => {}
+ "http" if is_loopback_url(&url) => {}
+ "http" => return Err(format!("{VAR} must use https:// (plain http only to this computer).")),
+ _ => return Err(format!("{VAR} must start with https://.")),
+ }
+ if !url.username().is_empty() || url.password().is_some() || url.host_str().is_none() {
+ return Err(format!("{VAR} must not carry a user name or password."));
+ }
+ let path = url.path().trim_end_matches('/').to_string();
+ let path = if path.ends_with("/v1/messages") {
+ path
+ } else if path.ends_with("/v1") {
+ format!("{path}/messages")
+ } else {
+ format!("{path}/v1/messages")
+ };
+ url.set_path(&path);
+ url.set_fragment(None);
+ Ok(url)
+}
+
+/// A client for `url`: requests to this machine skip any system proxy, which
+/// would otherwise see (and usually fail) a loopback address.
+pub fn client(url: &Url, timeout: Duration) -> Result<reqwest::Client, String> {
+ let mut builder = reqwest::Client::builder()
+ .connect_timeout(Duration::from_secs(10).min(timeout))
+ .timeout(timeout);
+ if is_loopback_url(url) {
+ builder = builder.no_proxy();
+ }
+ builder.build().map_err(|e| e.to_string())
+}
+
+/// The body of `response`, refused past `limit` bytes.
+pub async fn read_capped(mut response: reqwest::Response, limit: usize) -> Result<Vec<u8>, String> {
+ if response.content_length().is_some_and(|n| n > limit as u64) {
+ return Err("The server's answer is too large.".into());
+ }
+ let mut body = Vec::new();
+ while let Some(chunk) = response.chunk().await.map_err(|e| format!("Network error: {e}"))? {
+ if body.len() + chunk.len() > limit {
+ return Err("The server's answer is too large.".into());
+ }
+ body.extend_from_slice(&chunk);
+ }
+ Ok(body)
+}
+
+/// The text of an error body, cut down for a message: `error.message`
+/// (OpenAI, Anthropic), a bare `error` string (Ollama), or the first characters.
+pub fn error_detail(body: &[u8]) -> String {
+ let text = String::from_utf8_lossy(body);
+ if let Ok(v) = serde_json::from_str::<serde_json::Value>(&text) {
+ if let Some(m) = v.pointer("/error/message").and_then(|m| m.as_str()) {
+ return m.to_string();
+ }
+ if let Some(m) = v.get("error").and_then(|m| m.as_str()) {
+ return m.to_string();
+ }
+ if let Some(m) = v.get("message").and_then(|m| m.as_str()) {
+ return m.to_string();
+ }
+ // Gemini answers some errors as a one-element array.
+ if let Some(m) = v.pointer("/0/error/message").and_then(|m| m.as_str()) {
+ return m.to_string();
+ }
+ }
+ text.trim().chars().take(200).collect()
+}
+
+/// Only the host of an address, for the log: never a path, a query or a key.
+pub fn host_for_log(url: &Url) -> String {
+ match (url.host_str(), url.port()) {
+ (Some(h), Some(p)) => format!("{h}:{p}"),
+ (Some(h), None) => h.to_string(),
+ _ => "?".into(),
+ }
+}
+
+#[cfg(test)]
+pub(crate) mod tests {
+ use super::*;
+
+ #[test]
+ fn loopback_hosts_are_recognised_and_others_are_not() {
+ for host in ["localhost", "LOCALHOST", "app.localhost", "127.0.0.1", "127.8.9.1", "::1", "[::1]", "0.0.0.0", "[::]", "::ffff:127.0.0.1"] {
+ assert!(is_loopback_host(host), "{host}");
+ }
+ for host in ["example.com", "192.168.1.10", "10.0.0.2", "localhost.example.com", "[2001:db8::1]", "128.0.0.1", ""] {
+ assert!(!is_loopback_host(host), "{host}");
+ }
+ }
+
+ #[test]
+ fn a_pasted_server_address_is_cleaned_up() {
+ let n = |s: &str| normalise_server_url(s).map(|u| u.to_string());
+ assert_eq!(n(" http://localhost:11434/ ").unwrap(), "http://127.0.0.1:11434/");
+ assert_eq!(n("http://localhost:11434/v1").unwrap(), "http://127.0.0.1:11434/");
+ assert_eq!(n("http://127.0.0.1:1234/v1/").unwrap(), "http://127.0.0.1:1234/");
+ assert_eq!(n("localhost:11434/api").unwrap(), "http://127.0.0.1:11434/");
+ assert_eq!(n("0.0.0.0:11434").unwrap(), "http://127.0.0.1:11434/");
+ assert_eq!(n("http://[::1]:8000").unwrap(), "http://127.0.0.1:8000/");
+ assert_eq!(n("https://llm.example.com/proxy/v1?x=1#y").unwrap(), "https://llm.example.com/proxy");
+ assert_eq!(n("gpu-box.lan:8000").unwrap(), "http://gpu-box.lan:8000/");
+ }
+
+ #[test]
+ fn a_server_address_that_is_not_http_is_refused() {
+ assert!(normalise_server_url("").is_err());
+ assert!(normalise_server_url(" ").is_err());
+ assert!(normalise_server_url("file:///etc/passwd").is_err());
+ assert!(normalise_server_url("javascript://alert(1)").is_err());
+ assert!(normalise_server_url("http://user:[email protected]").is_err());
+ assert!(normalise_server_url("http://").is_err());
+ }
+
+ #[test]
+ fn join_puts_one_slash_between_base_and_path() {
+ let base = normalise_server_url("http://127.0.0.1:11434").unwrap();
+ assert_eq!(join(&base, "/v1/models"), "http://127.0.0.1:11434/v1/models");
+ let base = Url::parse("https://api.openai.com/v1").unwrap();
+ assert_eq!(join(&base, "chat/completions"), "https://api.openai.com/v1/chat/completions");
+ }
+
+ #[test]
+ fn the_anthropic_gateway_is_taken_as_a_base_url_and_must_be_https() {
+ let e = |s: &str| anthropic_endpoint(s).map(|u| u.to_string());
+ assert_eq!(e("https://gw.example.com").unwrap(), "https://gw.example.com/v1/messages");
+ assert_eq!(e("https://gw.example.com/").unwrap(), "https://gw.example.com/v1/messages");
+ assert_eq!(e("https://gw.example.com/anthropic").unwrap(), "https://gw.example.com/anthropic/v1/messages");
+ assert_eq!(e("https://gw.example.com/v1").unwrap(), "https://gw.example.com/v1/messages");
+ assert_eq!(e("https://gw.example.com/v1/messages/").unwrap(), "https://gw.example.com/v1/messages");
+ assert_eq!(e(" http://localhost:4000 ").unwrap(), "http://localhost:4000/v1/messages");
+ assert_eq!(e("http://127.0.0.1:4000/v1").unwrap(), "http://127.0.0.1:4000/v1/messages");
+ assert!(e("http://gw.example.com").is_err());
+ assert!(e("ftp://gw.example.com").is_err());
+ assert!(e("https://me:[email protected]").is_err());
+ assert!(e("not a url").is_err());
+ }
+
+ #[test]
+ fn error_details_come_from_the_usual_places() {
+ assert_eq!(error_detail(br#"{"error":{"message":"bad key"}}"#), "bad key");
+ assert_eq!(error_detail(br#"{"error":"model 'x' not found"}"#), "model 'x' not found");
+ assert_eq!(error_detail(br#"[{"error":{"message":"quota"}}]"#), "quota");
+ assert_eq!(error_detail(b" plain text "), "plain text");
+ assert_eq!(error_detail("x".repeat(500).as_bytes()).len(), 200);
+ }
+
+ #[test]
+ fn only_the_host_goes_to_the_log() {
+ let url = Url::parse("https://gw.example.com:8443/secret/path?key=abc").unwrap();
+ assert_eq!(host_for_log(&url), "gw.example.com:8443");
+ let url = Url::parse("https://gw.example.com/v1/messages").unwrap();
+ assert_eq!(host_for_log(&url), "gw.example.com");
+ }
+
+ /// One-shot HTTP server on a free port answering the next request with `body`.
+ pub(crate) fn serve_once(status: &str, headers: &str, body: Vec<u8>) -> String {
+ use std::io::{Read, Write};
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ let head = format!("HTTP/1.1 {status}\r\n{headers}Connection: close\r\n\r\n");
+ std::thread::spawn(move || {
+ let (mut conn, _) = listener.accept().unwrap();
+ let mut buf = [0u8; 8192];
+ let _ = conn.read(&mut buf);
+ let _ = conn.write_all(head.as_bytes());
+ let _ = conn.write_all(&body);
+ });
+ url
+ }
+
+ fn block_on<T>(f: impl std::future::Future<Output = T>) -> T {
+ tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(f)
+ }
+
+ #[test]
+ fn a_body_past_the_ceiling_is_refused_with_or_without_a_length() {
+ let get = |url: String| async move {
+ let url = Url::parse(&url).unwrap();
+ let response = client(&url, Duration::from_secs(5)).unwrap().get(url).send().await.unwrap();
+ read_capped(response, 1000).await
+ };
+ // Declared length too large.
+ let url = serve_once("200 OK", "Content-Length: 5000\r\n", vec![b'x'; 5000]);
+ assert!(block_on(get(url)).is_err());
+ // No length (read to the end of the connection): stopped while reading.
+ let url = serve_once("200 OK", "", vec![b'x'; 5000]);
+ assert!(block_on(get(url)).is_err());
+ // Under the ceiling: read whole.
+ let url = serve_once("200 OK", "Content-Length: 3\r\n", b"abc".to_vec());
+ assert_eq!(block_on(get(url)).unwrap(), b"abc");
+ }
+}
diff --git a/windows/src-tauri/src/platform/linux.rs b/windows/src-tauri/src/platform/linux.rs
index e748a336..c2feb283 100644
--- a/windows/src-tauri/src/platform/linux.rs
+++ b/windows/src-tauri/src/platform/linux.rs
@@ -119,6 +119,25 @@ pub fn relay_socket_path() -> Option<PathBuf> {
is_private_dir(&dir).then(|| dir.join("coucou.sock"))
}
+// ── Who we are ────────────────────────────────────────────────────────────────
+
+/// The account's full name: the first field of the passwd GECOS entry
+/// ("Louis Raille,,,"), or nothing when it is unset.
+pub fn user_full_name() -> Option<String> {
+ unsafe {
+ let mut pwd: libc::passwd = std::mem::zeroed();
+ let mut result: *mut libc::passwd = std::ptr::null_mut();
+ let mut buf = vec![0 as libc::c_char; 16 * 1024];
+ let rc = libc::getpwuid_r(libc::getuid(), &mut pwd, buf.as_mut_ptr(), buf.len(), &mut result);
+ if rc != 0 || result.is_null() || pwd.pw_gecos.is_null() {
+ return None;
+ }
+ let gecos = std::ffi::CStr::from_ptr(pwd.pw_gecos).to_string_lossy().into_owned();
+ let name = gecos.split(',').next().unwrap_or("").trim().to_string();
+ (!name.is_empty()).then_some(name)
+ }
+}
+
// ── Processes ─────────────────────────────────────────────────────────────────
/// Nothing to hide: a spawned process only gets a terminal if it asks for one.
diff --git a/windows/src-tauri/src/platform/windows.rs b/windows/src-tauri/src/platform/windows.rs
index 6e1200a8..1b2f62e7 100644
--- a/windows/src-tauri/src/platform/windows.rs
+++ b/windows/src-tauri/src/platform/windows.rs
@@ -145,6 +145,66 @@ pub fn current_user_sid() -> Option<String> {
}
}
+// The display name only feeds Mochi's greeting (identity.rs). The calls are
+// declared here by hand, with their documented C signatures, so they need no
+// extra `windows` crate features.
+#[link(name = "secur32")]
+extern "system" {
+ fn GetUserNameExW(name_format: i32, name_buffer: *mut u16, size: *mut u32) -> u8;
+}
+
+#[link(name = "netapi32")]
+extern "system" {
+ fn NetUserGetInfo(server: *const u16, user: *const u16, level: u32, buffer: *mut *mut u8) -> u32;
+ fn NetApiBufferFree(buffer: *mut core::ffi::c_void) -> u32;
+}
+
+/// EXTENDED_NAME_FORMAT::NameDisplay.
+const NAME_DISPLAY: i32 = 3;
+
+/// The account's display name ("Louis Raille"): the directory's for a domain
+/// or Entra account, else the local account's "Full name", else nothing.
+pub fn user_full_name() -> Option<String> {
+ directory_display_name().or_else(local_full_name).filter(|n| !n.trim().is_empty())
+}
+
+fn directory_display_name() -> Option<String> {
+ let mut buf = [0u16; 256];
+ let mut size = buf.len() as u32;
+ // On success `size` is the length copied, without the terminating null.
+ let ok = unsafe { GetUserNameExW(NAME_DISPLAY, buf.as_mut_ptr(), &mut size) } != 0;
+ if !ok || size as usize > buf.len() {
+ return None;
+ }
+ String::from_utf16(&buf[..size as usize]).ok()
+}
+
+fn local_full_name() -> Option<String> {
+ let user = std::env::var("USERNAME").ok().filter(|u| !u.is_empty())?;
+ let wide: Vec<u16> = user.encode_utf16().chain(std::iter::once(0)).collect();
+ let mut info: *mut u8 = std::ptr::null_mut();
+ // Level 10 is USER_INFO_10 { name, comment, usr_comment, full_name }, four
+ // wide-string pointers; any user may read it about themselves.
+ let status = unsafe { NetUserGetInfo(std::ptr::null(), wide.as_ptr(), 10, &mut info) };
+ if status != 0 || info.is_null() {
+ return None;
+ }
+ unsafe {
+ let full = *(info as *const *const u16).add(3);
+ let text = if full.is_null() {
+ None
+ } else {
+ let mut len = 0usize;
+ while len < 256 && *full.add(len) != 0 {
+ len += 1;
+ }
+ String::from_utf16(std::slice::from_raw_parts(full, len)).ok()
+ };
+ NetApiBufferFree(info.cast());
+ text
+ }
+}
+
// ── Cursor ────────────────────────────────────────────────────────────────────
/// The 60 Hz poll reads the cursor and flips click-through from it.