A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.
Swift ai-agentsanthropicantigravityclaudeclaude-codecodexcursordynamic-islandgemini-cliiosiphonlinuxmacosmacos-appmenubar-appnotchopen-sourceswiftswiftuiwindows
Windows: integrations and the settings window
Louis Raille41e274535d05
diff --git a/windows/src-tauri/src/claude.rs b/windows/src-tauri/src/claude.rsindex 93b48f8e..060a57c6 100644--- a/windows/src-tauri/src/claude.rs+++ b/windows/src-tauri/src/claude.rs@@ -227,6 +227,11 @@ fn file_block(path: &str) -> Option<Value> {}/// Small standalone base64 encoder — not worth another dependency.+/// Also used for Stripe's basic auth.+pub(crate) fn base64_for(bytes: &[u8]) -> String {+ base64(bytes)+}+fn base64(bytes: &[u8]) -> String {const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);diff --git a/windows/src-tauri/src/integrations.rs b/windows/src-tauri/src/integrations.rsnew file mode 100644index 00000000..5c305b83--- /dev/null+++ b/windows/src-tauri/src/integrations.rs@@ -0,0 +1,738 @@+// Integration pollers — the Rust side of StripePoller / GithubPoller /+// VercelPoller / N8nPoller / ResendPoller / NotionPoller / CalcomPoller.+//+// Same endpoints, same first-run delays and intervals as the Swift pollers. Each+// one emits an `integration` event; the island owns the badge, the sound and the+// 60 s auto-clear, exactly as the Swift handlers do.+//+// Nothing is polled until its key exists in the Credential Manager, and no+// request goes anywhere the user has not configured.++use std::sync::Mutex;+use std::time::Duration;++use serde::Serialize;+use serde_json::{json, Value};+use tauri::{AppHandle, Emitter};++use crate::island::WINDOW_LABEL;+use crate::log;+use crate::secrets;++const TIMEOUT: Duration = Duration::from_secs(10);++/// What the island receives. `event` is only set when something actually changed,+/// which is what drives the pill badge and the sound.+#[derive(Serialize, Clone)]+#[serde(rename_all = "camelCase")]+pub struct IntegrationUpdate {+ pub id: &'static str,+ pub data: Value,+ pub error: Option<String>,+ pub event: Option<IntegrationEvent>,+}++#[derive(Serialize, Clone)]+#[serde(rename_all = "camelCase")]+pub struct IntegrationEvent {+ pub success: bool,+ pub label: String,+ pub detail: Option<String>,+}++fn emit(app: &AppHandle, update: IntegrationUpdate) {+ let _ = app.emit_to(WINDOW_LABEL, "integration", update);+}++fn client() -> reqwest::Client {+ reqwest::Client::builder()+ .timeout(TIMEOUT)+ .build()+ .unwrap_or_default()+}++/// Spawns every poller with the macOS delays and intervals.+pub fn start(app: AppHandle) {+ spawn(app.clone(), 3, 15, poll_n8n);+ spawn(app.clone(), 5, 30, poll_vercel);+ spawn(app.clone(), 6, 30, poll_stripe);+ spawn(app.clone(), 6, 60, poll_resend);+ spawn(app.clone(), 7, 300, poll_github);+ spawn(app.clone(), 8, 300, poll_calcom);+ spawn(app, 9, 300, poll_notion);+}++fn spawn<F, Fut>(app: AppHandle, delay_secs: u64, every_secs: u64, poll: F)+where+ F: Fn(AppHandle) -> Fut + Send + 'static,+ Fut: std::future::Future<Output = ()> + Send,+{+ tauri::async_runtime::spawn(async move {+ tokio::time::sleep(Duration::from_secs(delay_secs)).await;+ let mut ticker = tokio::time::interval(Duration::from_secs(every_secs));+ loop {+ ticker.tick().await;+ poll(app.clone()).await;+ }+ });+}++/// One-shot refresh from the Refresh buttons in the island.+pub async fn poll_once(app: AppHandle, id: &str) {+ match id {+ "integration_stripe" => poll_stripe(app).await,+ "integration_github" => poll_github(app).await,+ "integration_vercel" => poll_vercel(app).await,+ "integration_n8n" => poll_n8n(app).await,+ "integration_resend" => poll_resend(app).await,+ "integration_notion" => poll_notion(app).await,+ "integration_calcom" => poll_calcom(app).await,+ _ => {}+ }+}++/// Remembers the newest id per integration so an event fires once, not on every poll.+struct Seen(Mutex<std::collections::HashMap<&'static str, String>>);++static SEEN: std::sync::LazyLock<Seen> =+ std::sync::LazyLock::new(|| Seen(Mutex::new(std::collections::HashMap::new())));++/// Returns true the first time a given id is seen (and false on the very first+/// load, which only fills the card).+fn is_new(key: &'static str, id: &str) -> bool {+ let mut map = SEEN.0.lock().unwrap();+ match map.insert(key, id.to_string()) {+ Some(previous) => previous != id,+ None => false, // first poll: populate silently, like the Swift pollers+ }+}++fn status_error(code: u16, unauthorised_hint: &str) -> String {+ match code {+ 401 => "Invalid API key (401)".into(),+ 403 => unauthorised_hint.into(),+ _ => format!("API error {code}"),+ }+}++// ── Stripe ────────────────────────────────────────────────────────────────────++async fn poll_stripe(app: AppHandle) {+ let Some(key) = secrets::get("stripe-api-key") else { return };+ let auth = format!("Basic {}", crate::claude::base64_for(format!("{key}:").as_bytes()));+ let http = client();++ let balance = http+ .get("https://api.stripe.com/v1/balance")+ .header("Authorization", &auth)+ .send()+ .await;++ let (amount, currency) = match balance {+ Ok(r) if r.status().is_success() => {+ let json: Value = r.json().await.unwrap_or(json!({}));+ let mut buckets: Vec<Value> = Vec::new();+ for k in ["available", "pending"] {+ if let Some(arr) = json.get(k).and_then(Value::as_array) {+ buckets.extend(arr.iter().cloned());+ }+ }+ let currency = buckets+ .first()+ .and_then(|b| b.get("currency"))+ .and_then(Value::as_str)+ .unwrap_or("eur")+ .to_string();+ let amount: i64 = buckets+ .iter()+ .filter_map(|b| b.get("amount").and_then(Value::as_i64))+ .sum();+ (amount, currency)+ }+ Ok(r) => {+ let code = r.status().as_u16();+ emit(&app, IntegrationUpdate {+ id: "integration_stripe",+ data: json!({}),+ error: Some(status_error(code, "Use a secret key (sk_live_… not pk_live_…)")),+ event: None,+ });+ return;+ }+ Err(e) => {+ emit(&app, IntegrationUpdate {+ id: "integration_stripe",+ data: json!({}),+ error: Some(format!("No connection: {e}")),+ event: None,+ });+ return;+ }+ };++ let charges = http+ .get("https://api.stripe.com/v1/charges?limit=3")+ .header("Authorization", &auth)+ .send()+ .await;+ let Ok(response) = charges else { return };+ if !response.status().is_success() {+ return;+ }+ let json: Value = response.json().await.unwrap_or(json!({}));+ let payments: Vec<Value> = json+ .get("data")+ .and_then(Value::as_array)+ .map(|list| {+ list.iter()+ .filter_map(|c| {+ let description = c+ .get("description")+ .and_then(Value::as_str)+ .or_else(|| {+ c.get("billing_details")+ .and_then(|b| b.get("name"))+ .and_then(Value::as_str)+ })+ .map(str::to_string);+ Some(json!({+ "id": c.get("id")?.as_str()?,+ "amount": c.get("amount")?.as_i64()?,+ "currency": c.get("currency")?.as_str()?,+ "description": description,+ "createdAt": c.get("created").and_then(Value::as_i64).unwrap_or(0) * 1000,+ "status": c.get("status").and_then(Value::as_str).unwrap_or("succeeded"),+ }))+ })+ .collect()+ })+ .unwrap_or_default();++ let newest = payments+ .first()+ .and_then(|p| p.get("id"))+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_string();+ let event = if !newest.is_empty() && is_new("stripe", &newest) {+ let label = payments[0]+ .get("description")+ .and_then(Value::as_str)+ .map(str::to_string)+ .unwrap_or_else(|| {+ let cents = payments[0].get("amount").and_then(Value::as_i64).unwrap_or(0);+ format!("{:.2}", cents as f64 / 100.0)+ });+ Some(IntegrationEvent { success: true, label, detail: None })+ } else {+ None+ };++ emit(&app, IntegrationUpdate {+ id: "integration_stripe",+ data: json!({ "balance": amount, "currency": currency, "payments": payments }),+ error: None,+ event,+ });+}++// ── GitHub ────────────────────────────────────────────────────────────────────++async fn poll_github(app: AppHandle) {+ let Some(token) = secrets::get("github-token") else { return };+ let http = client();++ let user = http+ .get("https://api.github.com/user")+ .header("Authorization", format!("Bearer {token}"))+ .header("Accept", "application/vnd.github+json")+ .header("User-Agent", "Coucou")+ .send()+ .await;+ let Ok(response) = user else { return };+ if !response.status().is_success() {+ emit(&app, IntegrationUpdate {+ id: "integration_github",+ data: json!({}),+ error: Some(status_error(response.status().as_u16(), "Token lacks the needed scope")),+ event: None,+ });+ return;+ }+ let json: Value = response.json().await.unwrap_or(json!({}));+ let public = json.get("public_repos").and_then(Value::as_i64).unwrap_or(0);+ let private = json+ .get("owned_private_repos")+ .or_else(|| json.get("total_private_repos"))+ .and_then(Value::as_i64)+ .unwrap_or(0);++ let repos = http+ .get("https://api.github.com/user/repos?per_page=100&affiliation=owner&sort=pushed")+ .header("Authorization", format!("Bearer {token}"))+ .header("Accept", "application/vnd.github+json")+ .header("User-Agent", "Coucou")+ .send()+ .await;+ let stars: i64 = match repos {+ Ok(r) if r.status().is_success() => r+ .json::<Value>()+ .await+ .ok()+ .and_then(|v| v.as_array().cloned())+ .map(|list| {+ list.iter()+ .filter_map(|r| r.get("stargazers_count").and_then(Value::as_i64))+ .sum()+ })+ .unwrap_or(0),+ _ => 0,+ };++ emit(&app, IntegrationUpdate {+ id: "integration_github",+ data: json!({ "totalRepos": public + private, "totalStars": stars }),+ error: None,+ event: None,+ });+}++// ── Vercel ────────────────────────────────────────────────────────────────────++async fn poll_vercel(app: AppHandle) {+ let Some(token) = secrets::get("vercel-token") else { return };+ let response = client()+ .get("https://api.vercel.com/v6/deployments?limit=5")+ .header("Authorization", format!("Bearer {token}"))+ .header("Accept", "application/json")+ .send()+ .await;+ let Ok(response) = response else { return };+ if !response.status().is_success() {+ emit(&app, IntegrationUpdate {+ id: "integration_vercel",+ data: json!({}),+ error: Some(status_error(response.status().as_u16(), "Token lacks access")),+ event: None,+ });+ return;+ }+ let json: Value = response.json().await.unwrap_or(json!({}));+ let terminal = ["READY", "ERROR", "CANCELED"];+ let deployments: Vec<Value> = json+ .get("deployments")+ .and_then(Value::as_array)+ .map(|list| {+ list.iter()+ .filter_map(|d| {+ let state = d.get("state")?.as_str()?;+ if !terminal.contains(&state) {+ return None;+ }+ let meta = d.get("meta");+ let pick = |keys: [&str; 3]| {+ meta.and_then(|m| keys.iter().find_map(|k| m.get(*k).and_then(Value::as_str)))+ .map(str::to_string)+ };+ Some(json!({+ "id": d.get("uid")?.as_str()?,+ "projectName": d.get("name")?.as_str()?,+ "url": d.get("url").and_then(Value::as_str).unwrap_or(""),+ "state": state,+ "createdAt": d.get("createdAt").and_then(Value::as_f64).unwrap_or(0.0),+ "commitMessage": pick(["githubCommitMessage", "gitlabCommitMessage", "bitbucketCommitMessage"]),+ "branch": pick(["githubCommitRef", "gitlabCommitRef", "bitbucketBranch"]),+ }))+ })+ .collect()+ })+ .unwrap_or_default();++ let event = deployments.first().and_then(|latest| {+ let id = latest.get("id")?.as_str()?;+ if !is_new("vercel", id) {+ return None;+ }+ let success = latest.get("state")?.as_str()? == "READY";+ Some(IntegrationEvent {+ success,+ label: latest.get("projectName")?.as_str()?.to_string(),+ detail: None,+ })+ });++ emit(&app, IntegrationUpdate {+ id: "integration_vercel",+ data: json!({ "deployments": deployments }),+ error: None,+ event,+ });+}++// ── Resend ────────────────────────────────────────────────────────────────────++async fn poll_resend(app: AppHandle) {+ let Some(key) = secrets::get("resend-api-key") else { return };+ let response = client()+ .get("https://api.resend.com/emails?limit=100")+ .header("Authorization", format!("Bearer {key}"))+ .header("Accept", "application/json")+ .send()+ .await;+ let Ok(response) = response else { return };+ if !response.status().is_success() {+ emit(&app, IntegrationUpdate {+ id: "integration_resend",+ data: json!({}),+ error: Some(status_error(response.status().as_u16(), "Key lacks access")),+ event: None,+ });+ return;+ }+ let json: Value = response.json().await.unwrap_or(json!({}));+ let total = json+ .get("total")+ .or_else(|| json.get("count"))+ .and_then(Value::as_i64);+ let emails: Vec<Value> = json+ .get("data")+ .and_then(Value::as_array)+ .map(|list| {+ list.iter()+ .take(5)+ .filter_map(|e| {+ let to = match e.get("to") {+ Some(Value::Array(a)) => a.clone(),+ Some(Value::String(s)) => vec![Value::String(s.clone())],+ _ => vec![],+ };+ Some(json!({+ "id": e.get("id")?.as_str()?,+ "to": to,+ "subject": e.get("subject").and_then(Value::as_str).unwrap_or(""),+ "createdAt": e.get("created_at").and_then(Value::as_str).unwrap_or(""),+ "lastEvent": e.get("last_event").and_then(Value::as_str).unwrap_or(""),+ }))+ })+ .collect()+ })+ .unwrap_or_default();++ emit(&app, IntegrationUpdate {+ id: "integration_resend",+ data: json!({ "emails": emails, "total": total }),+ error: None,+ event: None,+ });+}++// ── Notion ────────────────────────────────────────────────────────────────────++async fn poll_notion(app: AppHandle) {+ let Some(token) = secrets::get("notion-api-key") else { return };+ let response = client()+ .post("https://api.notion.com/v1/search")+ .header("Authorization", format!("Bearer {token}"))+ .header("Notion-Version", "2022-06-28")+ .header("Content-Type", "application/json")+ .json(&json!({+ "sort": { "direction": "descending", "timestamp": "last_edited_time" },+ "page_size": 3+ }))+ .send()+ .await;+ let Ok(response) = response else { return };+ if !response.status().is_success() {+ emit(&app, IntegrationUpdate {+ id: "integration_notion",+ data: json!({}),+ error: Some(status_error(response.status().as_u16(), "Integration lacks access")),+ event: None,+ });+ return;+ }+ let json: Value = response.json().await.unwrap_or(json!({}));+ let pages: Vec<Value> = json+ .get("results")+ .and_then(Value::as_array)+ .map(|list| list.iter().filter_map(parse_notion_page).collect())+ .unwrap_or_default();++ emit(&app, IntegrationUpdate {+ id: "integration_notion",+ data: json!({ "pages": pages }),+ error: None,+ event: None,+ });+}++fn parse_notion_page(obj: &Value) -> Option<Value> {+ let id = obj.get("id")?.as_str()?;+ let is_database = obj.get("object").and_then(Value::as_str) == Some("database");++ let mut title = "Untitled".to_string();+ if is_database {+ if let Some(text) = obj+ .get("title")+ .and_then(Value::as_array)+ .and_then(|a| a.first())+ .and_then(|t| t.get("plain_text"))+ .and_then(Value::as_str)+ {+ if !text.is_empty() {+ title = text.to_string();+ }+ }+ } else if let Some(props) = obj.get("properties").and_then(Value::as_object) {+ for prop in props.values() {+ if prop.get("type").and_then(Value::as_str) != Some("title") {+ continue;+ }+ if let Some(text) = prop+ .get("title")+ .and_then(Value::as_array)+ .and_then(|a| a.first())+ .and_then(|t| t.get("plain_text"))+ .and_then(Value::as_str)+ {+ if !text.is_empty() {+ title = text.to_string();+ break;+ }+ }+ }+ }++ let emoji = obj+ .get("icon")+ .filter(|i| i.get("type").and_then(Value::as_str) == Some("emoji"))+ .and_then(|i| i.get("emoji"))+ .and_then(Value::as_str);++ Some(json!({+ "id": id,+ "title": title,+ "emoji": emoji,+ "lastEditedAt": obj.get("last_edited_time").and_then(Value::as_str)?,+ "url": obj.get("url").and_then(Value::as_str).unwrap_or("https://notion.so"),+ }))+}++// ── Cal.com ───────────────────────────────────────────────────────────────────++async fn poll_calcom(app: AppHandle) {+ let Some(key) = secrets::get("calcom-api-key") else { return };+ let response = client()+ .get("https://api.cal.com/v2/bookings?status=upcoming")+ .header("Authorization", format!("Bearer {key}"))+ .header("cal-api-version", "2024-08-13")+ .send()+ .await;+ let Ok(response) = response else { return };+ if !response.status().is_success() {+ emit(&app, IntegrationUpdate {+ id: "integration_calcom",+ data: json!({}),+ error: Some(status_error(response.status().as_u16(), "Key lacks access")),+ event: None,+ });+ return;+ }+ let json: Value = response.json().await.unwrap_or(json!({}));+ let bookings: Vec<Value> = json+ .get("data")+ .and_then(Value::as_array)+ .map(|list| {+ list.iter()+ .filter_map(|b| {+ let start = b+ .get("start")+ .or_else(|| b.get("startTime"))+ .and_then(Value::as_str)?;+ let attendee = b.get("attendees").and_then(Value::as_array).and_then(|a| a.first());+ let notes = b+ .get("responses")+ .and_then(|r| r.get("notes"))+ .and_then(|n| n.get("value"))+ .and_then(Value::as_str)+ .or_else(|| b.get("description").and_then(Value::as_str))+ .filter(|s| !s.is_empty());+ Some(json!({+ "id": b.get("id").map(|v| v.to_string()).unwrap_or_default(),+ "title": b.get("title").and_then(Value::as_str).unwrap_or("Meeting"),+ "start": start,+ "status": b.get("status").and_then(Value::as_str).unwrap_or("accepted"),+ "attendeeName": attendee.and_then(|a| a.get("name")).and_then(Value::as_str),+ "attendeeEmail": attendee.and_then(|a| a.get("email")).and_then(Value::as_str),+ "attendeeNotes": notes,+ }))+ })+ .collect()+ })+ .unwrap_or_default();++ emit(&app, IntegrationUpdate {+ id: "integration_calcom",+ data: json!({ "bookings": bookings }),+ error: None,+ event: None,+ });+}++// ── n8n ───────────────────────────────────────────────────────────────────────++async fn poll_n8n(app: AppHandle) {+ let (Some(key), Some(raw_base)) = (secrets::get("n8n-api-key"), secrets::get("n8n-url")) else {+ return;+ };+ let base = raw_base.trim_end_matches('/').to_string();+ let http = client();++ // Same two shapes as the Swift poller: the public API first, then /rest.+ let list_urls = [+ format!("{base}/api/v1/executions?limit=1&includeData=false"),+ format!("{base}/rest/executions?limit=1&includeData=false"),+ ];++ let mut items: Option<Vec<Value>> = None;+ for url in &list_urls {+ let Ok(response) = http.get(url).header("X-N8N-API-KEY", &key).header("Accept", "application/json").send().await+ else {+ continue;+ };+ if !response.status().is_success() {+ log::line(format!("n8n list HTTP {} on {url}", response.status()));+ continue;+ }+ let Ok(json) = response.json::<Value>().await else { continue };+ items = match &json {+ Value::Object(o) => o.get("data").and_then(Value::as_array).cloned(),+ Value::Array(a) => Some(a.clone()),+ _ => None,+ };+ if items.is_some() {+ break;+ }+ }++ let Some(first) = items.and_then(|list| list.into_iter().next()) else { return };+ let id = match first.get("id") {+ Some(Value::String(s)) => s.clone(),+ Some(Value::Number(n)) => n.to_string(),+ _ => return,+ };++ let status = first.get("status").and_then(Value::as_str).unwrap_or("");+ if !["success", "error", "crashed", "canceled", "failed"].contains(&status) {+ return;+ }+ if !is_new("n8n", &id) {+ return;+ }+ let success = status == "success";++ let detail_urls = [+ format!("{base}/api/v1/executions/{id}?includeData=true"),+ format!("{base}/api/v1/executions/{id}"),+ format!("{base}/rest/executions/{id}?includeData=true"),+ format!("{base}/rest/executions/{id}"),+ ];+ let mut name = "Workflow".to_string();+ let mut detail = None;+ for url in &detail_urls {+ let Ok(response) = http.get(url).header("X-N8N-API-KEY", &key).header("Accept", "application/json").send().await+ else {+ continue;+ };+ if !response.status().is_success() {+ continue;+ }+ let Ok(json) = response.json::<Value>().await else { continue };+ name = json+ .get("workflowData")+ .and_then(|w| w.get("name"))+ .and_then(Value::as_str)+ .or_else(|| json.get("name").and_then(Value::as_str))+ .unwrap_or("Workflow")+ .to_string();+ detail = n8n_detail(&json, success);+ break;+ }++ log::line(format!("n8n execution {id} {status} · {name}"));+ emit(&app, IntegrationUpdate {+ id: "integration_n8n",+ data: json!({ "workflow": name, "status": status }),+ error: None,+ event: Some(IntegrationEvent { success, label: name, detail }),+ });+}++fn n8n_detail(json: &Value, success: bool) -> Option<String> {+ let result = json.get("data")?.get("resultData")?;+ if !success {+ if let Some(error) = result.get("error") {+ let message = error.get("message").and_then(Value::as_str).unwrap_or("");+ if let Some(node) = error.get("node").and_then(|n| n.get("name")).and_then(Value::as_str) {+ if !node.is_empty() {+ return Some(format!("{node}\n{message}"));+ }+ }+ return Some(message.to_string());+ }+ let runs = result.get("runData")?.as_object()?;+ for (node, value) in runs {+ if let Some(message) = value+ .as_array()+ .and_then(|a| a.first())+ .and_then(|r| r.get("error"))+ .and_then(|e| e.get("message"))+ .and_then(Value::as_str)+ {+ return Some(format!("{node}\n{message}"));+ }+ }+ return None;+ }++ let last_node = result.get("lastNodeExecuted")?.as_str()?;+ let items = result+ .get("runData")?+ .get(last_node)?+ .as_array()?+ .first()?+ .get("data")?+ .get("main")?+ .as_array()?+ .first()?+ .as_array()?;+ let count = items.len();+ let header = format!("→ {last_node} · {count} item{}", if count == 1 { "" } else { "s" });++ let fields = items+ .first()+ .and_then(|i| i.get("json"))+ .and_then(Value::as_object)+ .map(|obj| {+ obj.iter()+ .take(4)+ .map(|(k, v)| format!("{k}: {}", fmt_value(v)))+ .collect::<Vec<_>>()+ .join("\n")+ })+ .filter(|s| !s.is_empty());++ Some(match fields {+ Some(f) => format!("{header}\n{f}"),+ None => header,+ })+}++fn fmt_value(v: &Value) -> String {+ match v {+ Value::String(s) => s.chars().take(50).collect(),+ Value::Array(a) => format!("[{}]", a.len()),+ Value::Object(_) => "{…}".into(),+ other => other.to_string(),+ }+}diff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rsindex 5112170c..209f238b 100644--- a/windows/src-tauri/src/lib.rs+++ b/windows/src-tauri/src/lib.rs@@ -3,6 +3,7 @@mod claude;mod files;mod hooks;+mod integrations;mod island;mod log;mod pipe;@@ -235,6 +236,20 @@ fn secret_clear(key: String) -> Result<(), String> {secrets::clear(&key)}+/// Opens the configured n8n instance — the URL lives in the Credential Manager.+#[tauri::command]+fn open_n8n() {+ if let Some(url) = secrets::get("n8n-url") {+ open_url(url);+ }+}++/// Refresh buttons in the integration cards.+#[tauri::command]+async fn refresh_integration(app: AppHandle, id: String) {+ integrations::poll_once(app, &id).await;+}+/// Lets the island write to the same log as the Rust side.#[tauri::command]fn log_line(message: String) {@@ -243,25 +258,65 @@ fn log_line(message: String) {// ── Settings window ───────────────────────────────────────────────────────────-pub fn show_settings_window(app: &AppHandle) {- if let Some(win) = app.get_webview_window("settings") {- let _ = win.unminimize();- let _ = win.show();- let _ = win.set_focus();- return;+/// WebView2 allows exactly one browser environment per app, and its options are+/// fixed by whichever webview is created first. Every window must therefore ask+/// for the *same* arguments as the island (see `additionalBrowserArgs` in+/// tauri.conf.json) — a mismatch makes the second window come up blank, with no+/// error anywhere.+const BROWSER_ARGS: &str = "--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection --autoplay-policy=no-user-gesture-required";++/// In a dev build the pages are served by Vite, so the second window needs the+/// absolute dev URL; a bundled build resolves it inside the app bundle.+fn settings_page_url(app: &AppHandle) -> WebviewUrl {+ #[cfg(dev)]+ if let Some(mut base) = app.config().build.dev_url.clone() {+ base.set_path("/settings.html");+ return WebviewUrl::External(base);}- if let Err(err) = WebviewWindowBuilder::new(app, "settings", WebviewUrl::App("settings.html".into()))+ let _ = app;+ WebviewUrl::App("settings.html".into())+}++/// The settings window is created hidden at launch and only ever shown and+/// hidden afterwards. A WebView2 window created later — on the main thread or+/// not — silently comes up blank in this app, so the window that works is the+/// one that exists before the island's webview does.+fn create_settings_window(app: &AppHandle) {+ let url = settings_page_url(app);+ match WebviewWindowBuilder::new(app, "settings", url)+ .additional_browser_args(BROWSER_ARGS).title("Settings — Coucou").inner_size(560.0, 680.0).min_inner_size(460.0, 480.0).resizable(true)+ .visible(false).center().build(){- log::line(format!("settings window failed: {err}"));+ Ok(win) => {+ // Closing it must only hide it, or it could never be reopened.+ let hidden = win.clone();+ win.on_window_event(move |event| {+ if let tauri::WindowEvent::CloseRequested { api, .. } = event {+ api.prevent_close();+ let _ = hidden.hide();+ }+ });+ }+ Err(err) => log::line(format!("settings window failed: {err}")),}}+pub fn show_settings_window(app: &AppHandle) {+ let Some(win) = app.get_webview_window("settings") else {+ log::line("settings window missing");+ return;+ };+ let _ = win.unminimize();+ let _ = win.show();+ let _ = win.set_focus();+}+#[tauri::command]fn open_settings_window(app: AppHandle) {show_settings_window(&app);@@ -303,11 +358,15 @@ pub fn run() {secret_present,secret_set,secret_clear,+ refresh_integration,+ open_n8n,open_settings_window,]).setup(move |app| {let handle = app.handle().clone();tray::build(&handle)?;+ // Before the island: see create_settings_window.+ create_settings_window(&handle);if let Some(win) = island::window(&handle) {island::make_non_activating(&win);@@ -321,6 +380,7 @@ pub fn run() {log::line(format!("--- Coucou {} started ---", env!("CARGO_PKG_VERSION")));hooks::ensure_hook_exe(&handle);pipe::start(handle.clone());+ integrations::start(handle.clone());Ok(())}).run(tauri::generate_context!())diff --git a/windows/src/core/bridge.ts b/windows/src/core/bridge.tsindex ab990608..eb77c5dc 100644--- a/windows/src/core/bridge.ts+++ b/windows/src/core/bridge.ts@@ -81,8 +81,20 @@ export const Bridge = {secretPresent: (key: string) => call<boolean>("secret_present", { key }),secretSet: (key: string, value: string) => callOrThrow<void>("secret_set", { key, value }),secretClear: (key: string) => callOrThrow<void>("secret_clear", { key }),++ // ── Integrations ──────────────────────────────────────────────────────────+ refreshIntegration: (id: string) => call<void>("refresh_integration", { id }),+ /** Opens the configured n8n instance in the browser. */+ openN8n: () => call<void>("open_n8n"),};+export interface IntegrationUpdate {+ id: string;+ data: Record<string, unknown>;+ error: string | null;+ event: { success: boolean; label: string; detail: string | null } | null;+}+export type ChatContext =| { kind: "file"; name: string; path: string }| { kind: "window"; appName: string; title: string; url?: string };diff --git a/windows/src/core/state.ts b/windows/src/core/state.tsindex 32c8c05b..99e50e48 100644--- a/windows/src/core/state.ts+++ b/windows/src/core/state.ts@@ -73,6 +73,14 @@ export const TOGGLEABLE_INTEGRATION_IDS = ["integration_notion", "integration_calcom", "integration_stripe",];+/** What an integration poller last reported. */+export interface IntegrationInfo {+ data: Record<string, unknown>;+ error: string | null;+ loaded: boolean;+ configured: boolean;+}+export interface Settings {soundEnabled: boolean;soundVolume: number;@@ -132,6 +140,8 @@ class AppState {pendingApproval: ApprovalInfo | null = null;alwaysAllow = false;+ integrations: Record<string, IntegrationInfo> = {};+lastActivity = performance.now();settings: Settings = { ...DEFAULT_SETTINGS };diff --git a/windows/src/island/integrations.ts b/windows/src/island/integrations.tsnew file mode 100644index 00000000..862ffb14--- /dev/null+++ b/windows/src/island/integrations.ts@@ -0,0 +1,88 @@+// Integration events → island state. Port of the `handle…` methods in the Swift+// pollers: a genuinely new item flips the pill to finished/error, badges it when+// the pill isn't focused, plays a sound, and clears itself after 60 s.++import { onEvent, Bridge, type IntegrationUpdate } from "../core/bridge";+import { Sound } from "../core/sound";+import { State } from "../core/state";+import type { Island } from "./island";++/** Which Credential Manager key backs each pill. */+const KEY_FOR: Record<string, string> = {+ integration_stripe: "stripe-api-key",+ integration_github: "github-token",+ integration_vercel: "vercel-token",+ integration_n8n: "n8n-api-key",+ integration_resend: "resend-api-key",+ integration_notion: "notion-api-key",+ integration_calcom: "calcom-api-key",+};++const clearTimers = new Map<string, number>();++export function registerIntegrationHandlers(island: Island) {+ void onEvent<IntegrationUpdate>("integration", (update) => handle(island, update));+ void refreshConfigured();+}++/** Asks Rust which keys exist so the idle cards can say so. */+export async function refreshConfigured() {+ for (const [id, key] of Object.entries(KEY_FOR)) {+ const present = (await Bridge.secretPresent(key)) ?? false;+ const info = State.integrations[id] ?? { data: {}, error: null, loaded: false, configured: false };+ State.integrations[id] = { ...info, configured: present };+ }+ const hooks = State.settings.hooksInstalled;+ const claude = State.integrations.integration_claude ?? {+ data: {}, error: null, loaded: false, configured: false,+ };+ State.integrations.integration_claude = { ...claude, configured: hooks };+ State.notify();+}++function handle(island: Island, update: IntegrationUpdate) {+ if (State.paused) return;++ const previous = State.integrations[update.id];+ State.integrations[update.id] = {+ data: update.error ? (previous?.data ?? {}) : update.data,+ error: update.error,+ loaded: update.error ? (previous?.loaded ?? false) : true,+ configured: previous?.configured ?? true,+ };++ const event = update.event;+ if (event) {+ const task = State.tasks.find((t) => t.id === update.id);+ if (task) {+ task.state = event.success ? "finished" : "error";+ task.steps = event.detail ? [event.label, event.detail] : [event.label];+ task.stepIndex = task.steps.length - 1;+ if (State.focusId !== update.id) {+ task.pillBadge = event.success ? "finished" : "error";+ }+ Sound.play(event.success ? "finish" : "error");+ // Same as the Swift pollers: show the compact island so the badge is seen,+ // but never steal the screen for a successful deploy.+ island.reveal();++ const existing = clearTimers.get(update.id);+ if (existing != null) window.clearTimeout(existing);+ clearTimers.set(+ update.id,+ window.setTimeout(() => {+ clearTimers.delete(update.id);+ const t = State.tasks.find((x) => x.id === update.id);+ if (!t || (t.state !== "finished" && t.state !== "error")) return;+ t.state = "idle";+ t.steps = [];+ t.stepIndex = 0;+ t.pillBadge = null;+ State.notify();+ }, 60_000),+ );+ }+ }++ State.notify();+}diff --git a/windows/src/island/island.ts b/windows/src/island/island.tsindex dbcf0d53..5ffb60af 100644--- a/windows/src/island/island.ts+++ b/windows/src/island/island.ts@@ -102,6 +102,22 @@ export class Island {const cwd = State.focusTask?.sessionCwd ?? null;void Bridge.openInVSCode(cwd);},+ // The ↗ button — same targets as openAgentTarget() on macOS.+ openTarget: () => {+ const task = State.focusTask;+ if (!task) return;+ const urls: Record<string, string> = {+ integration_resend: "https://resend.com/emails",+ integration_vercel: "https://vercel.com/dashboard",+ integration_github: "https://github.com",+ integration_stripe: "https://dashboard.stripe.com/payments",+ integration_notion: "https://notion.so",+ integration_calcom: "https://app.cal.com/bookings",+ };+ if (task.id === "integration_claude") void Bridge.openInVSCode(task.sessionCwd ?? null);+ else if (task.id === "integration_n8n") void Bridge.openN8n();+ else if (urls[task.id]) void Bridge.openUrl(urls[task.id]);+ },openUrl: (url) => {if (url) void Bridge.openUrl(url);},diff --git a/windows/src/main.ts b/windows/src/main.tsindex e9fe95e6..e7d6d48e 100644--- a/windows/src/main.ts+++ b/windows/src/main.ts@@ -6,6 +6,7 @@ import { Sound } from "./core/sound";import { State, type Settings } from "./core/state";import { Island } from "./island/island";import { registerHookHandlers } from "./island/hooks";+import { registerIntegrationHandlers, refreshConfigured } from "./island/integrations";async function main() {const root = document.getElementById("root");@@ -48,9 +49,12 @@ async function main() {await onEvent<Settings>("settings-changed", (s) => {State.settings = { ...State.settings, ...s };island.applySettings();+ State.loadIntegrationTasks();+ void refreshConfigured();});registerHookHandlers(island);+ registerIntegrationHandlers(island);island.launch();diff --git a/windows/src/settings/main.ts b/windows/src/settings/main.tsindex 2282b32c..7e3211d5 100644--- a/windows/src/settings/main.ts+++ b/windows/src/settings/main.ts@@ -233,6 +233,110 @@ function apiSection(hasKey: boolean): HTMLElement {);}+// ── Integrations section ──────────────────────────────────────────────────────++interface IntegrationDef {+ id: string;+ name: string;+ color: string;+ /** Credential Manager keys, in the order they are shown. */+ fields: { key: string; label: string; placeholder: string; secret: boolean }[];+}++const INTEGRATIONS: IntegrationDef[] = [+ { id: "integration_stripe", name: "Stripe", color: "#0570DE",+ fields: [{ key: "stripe-api-key", label: "Secret key", placeholder: "sk_live_…", secret: true }] },+ { id: "integration_github", name: "GitHub", color: "#F4505E",+ fields: [{ key: "github-token", label: "Token", placeholder: "ghp_…", secret: true }] },+ { id: "integration_vercel", name: "Vercel", color: "#7C5CFF",+ fields: [{ key: "vercel-token", label: "Token", placeholder: "…", secret: true }] },+ { id: "integration_n8n", name: "n8n", color: "#F29B38",+ fields: [+ { key: "n8n-url", label: "Instance URL", placeholder: "https://n8n.example.com", secret: false },+ { key: "n8n-api-key", label: "API key", placeholder: "…", secret: true },+ ] },+ { id: "integration_resend", name: "Resend", color: "#22C55E",+ fields: [{ key: "resend-api-key", label: "API key", placeholder: "re_…", secret: true }] },+ { id: "integration_notion", name: "Notion", color: "#8C8C8C",+ fields: [{ key: "notion-api-key", label: "Integration token", placeholder: "ntn_…", secret: true }] },+ { id: "integration_calcom", name: "Cal.com", color: "#C9956A",+ fields: [{ key: "calcom-api-key", label: "API key", placeholder: "cal_…", secret: true }] },+];++const MAX_ACTIVE = 4;++function integrationsSection(present: Record<string, boolean>): HTMLElement {+ const note = h("div", { class: "hint" });+ const list = h("div", { style: "display:flex;flex-direction:column;gap:14px" });++ function updateNote() {+ const used = settings.activeIntegrations.length;+ note.textContent = `Pick up to ${MAX_ACTIVE} pills to show next to Mochi — ${used}/${MAX_ACTIVE} in use. Keys are stored in the Windows Credential Manager, never on disk.`;+ }++ for (const def of INTEGRATIONS) {+ const active = settings.activeIntegrations.includes(def.id);+ const sw = h("button", { class: active ? "switch on" : "switch" });+ sw.addEventListener("click", () => {+ const on = settings.activeIntegrations.includes(def.id);+ if (on) {+ settings.activeIntegrations = settings.activeIntegrations.filter((x) => x !== def.id);+ } else {+ if (settings.activeIntegrations.length >= MAX_ACTIVE) return;+ settings.activeIntegrations = [...settings.activeIntegrations, def.id];+ }+ sw.classList.toggle("on", !on);+ updateNote();+ void save();+ });++ const rows = h("div", { style: "display:flex;flex-direction:column;gap:6px;flex:1 1 auto;min-width:0" });+ for (const field of def.fields) {+ const input = h("input", {+ type: field.secret ? "password" : "text",+ placeholder: present[field.key] ? "•••••••• (stored)" : field.placeholder,+ autocomplete: "off",+ spellcheck: "false",+ style: "flex:1 1 auto;min-width:0",+ }) as HTMLInputElement;+ const saveBtn = h("button", { text: "Save" });+ const dotEl = statusDot(present[field.key] ?? false);+ saveBtn.addEventListener("click", async () => {+ const value = input.value.trim();+ try {+ await Bridge.secretSet(field.key, value);+ present[field.key] = value.length > 0;+ input.value = "";+ input.placeholder = value ? "•••••••• (stored)" : field.placeholder;+ dotEl.style.background = value ? "#22c55e" : "#f4505e";+ } catch {+ dotEl.style.background = "#f5a524";+ }+ });+ rows.append(+ h("div", { class: "row" },+ h("label", { style: "min-width:104px", text: field.label }),+ input, saveBtn, dotEl,+ ),+ );+ }++ list.append(+ h("div", { style: "display:flex;gap:12px;align-items:flex-start" },+ h("div", { style: "display:flex;align-items:center;gap:8px;min-width:132px;padding-top:4px" },+ sw,+ h("i", { class: "dot", style: `background:${def.color}` }),+ h("span", { style: "font-size:12.5px", text: def.name }),+ ),+ rows,+ ),+ );+ }++ updateNote();+ return h("section", {}, h("h2", {}, h("span", { text: "Integrations" })), note, list);+}+// ── General section ───────────────────────────────────────────────────────────function generalSection(): HTMLElement {@@ -306,11 +410,19 @@ async function main() {const hasKey = (await Bridge.secretPresent("anthropic-api-key")) ?? false;+ const keys = [+ "stripe-api-key", "github-token", "vercel-token",+ "n8n-url", "n8n-api-key", "resend-api-key", "notion-api-key", "calcom-api-key",+ ];+ const present: Record<string, boolean> = {};+ for (const k of keys) present[k] = (await Bridge.secretPresent(k)) ?? false;+clear(root);root.append(h("h1", {}, h("span", { text: "Coucou" }), h("span", { class: "version", text: version })),claudeSection(status),apiSection(hasKey),+ integrationsSection(present),generalSection(),h("div", {class: "hint",diff --git a/windows/src/style.css b/windows/src/style.cssindex 553df9dc..10b01577 100644--- a/windows/src/style.css+++ b/windows/src/style.css@@ -987,3 +987,329 @@ input[type="range"]::-webkit-slider-thumb {filter: blur(5px);pointer-events: none;}++/* ── Integration cards (overview, left card) ────────────────────────────── */++.left-body {+ position: relative;+ z-index: 1;+ height: 100%;+}++.int-card {+ padding: 10px 12px 0 108px;+ display: flex;+ flex-direction: column;+}++.int-head {+ display: flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+ padding-right: 24px;+}++.int-head b {+ font: 600 12px var(--font);+ color: var(--ink);+}++.int-head > span {+ font: 400 11px var(--font);+ color: var(--dim-2);+ white-space: nowrap;+}++.int-total {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ margin-left: 2px;+}++.int-total span {+ font: 500 11px var(--font);+ color: #c5c8cd;+ font-variant-numeric: tabular-nums;+}++.pulse {+ width: 4px;+ height: 4px;+ border-radius: 50%;+ background: var(--green);+ animation: pulse 1.8s ease-in-out infinite;+}++@keyframes pulse {+ 0%, 100% { opacity: 0.2; }+ 50% { opacity: 1; }+}++.int-status {+ display: flex;+ align-items: center;+ gap: 5px;+ padding-top: 4px;+ font: 400 11px var(--font);+ color: var(--dim-3);+}++.int-actions {+ display: flex;+ align-items: center;+ gap: 8px;+ padding-top: 6px;+}++.int-rows {+ display: flex;+ flex-direction: column;+ gap: 3px;+ padding-top: 5px;+}++.int-rows.tight {+ gap: 2px;+ padding-top: 4px;+}++.int-row {+ display: flex;+ align-items: center;+ gap: 5px;+ padding: 3px 8px;+ border-radius: 5px;+ min-width: 0;+}++.int-name {+ font: 500 11px var(--font);+ color: #9398a1;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ min-width: 0;+}++.int-row.first .int-name {+ color: #c5c8cd;+}++.int-ago {+ font: 400 10px var(--font);+ color: var(--dim-3);+ flex: 0 0 auto;+}++.int-sub {+ font: 400 10px var(--font);+ color: #4d5159;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ min-width: 0;+}++.int-amount {+ font: 500 11px var(--mono);+ margin-left: auto;+ flex: 0 0 auto;+}++.int-time {+ font: 500 10px var(--mono);+ color: #c9956a;+ flex: 0 0 auto;+}++.int-more,+.int-back {+ border: 0;+ background: transparent;+ color: var(--dim-3);+ display: grid;+ place-items: center;+ cursor: default;+ flex: 0 0 auto;+}++.int-more {+ width: 18px;+ height: 18px;+}++.int-back {+ width: 28px;+ height: 28px;+}++.int-stats {+ display: flex;+ flex-direction: column;+ gap: 5px;+ padding-top: 8px;+ padding-right: 12px;+}++.int-stat {+ display: flex;+ align-items: center;+ gap: 7px;+}++.int-stat-icon {+ width: 14px;+ display: grid;+ place-items: center;+}++.int-stat-label {+ font: 400 11px var(--font);+ color: var(--dim-3);+}++.int-stat-value {+ margin-left: auto;+ font: 600 12px var(--font);+ color: #c5c8cd;+ font-variant-numeric: tabular-nums;+}++.int-balance {+ display: flex;+ align-items: baseline;+ gap: 3px;+ padding-top: 4px;+}++.int-balance span {+ font: 700 20px var(--mono);+ color: var(--ink);+}++.int-balance i {+ font: 600 9px var(--font);+ font-style: normal;+ color: var(--dim-3);+}++.int-page {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 4px 6px;+ border: 0;+ background: transparent;+ text-align: left;+ cursor: default;+ min-width: 0;+}++.int-page:hover {+ background: rgba(255, 255, 255, 0.05);+ border-radius: 5px;+}++.int-emoji {+ width: 14px;+ font-size: 10px;+ color: var(--dim-3);+ display: grid;+ place-items: center;+ flex: 0 0 auto;+ font-style: normal;+}++.int-empty {+ font: 400 11px var(--font);+ color: var(--dim-3);+ padding-left: 8px;+}++.int-pill {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ padding: 3px 8px;+ border-radius: 999px;+ border: 1px solid transparent;+ color: var(--dim-3);+ cursor: default;+ max-width: 100%;+ min-width: 0;+}++.int-detail-head {+ display: flex;+ align-items: center;+ gap: 7px;+ min-width: 0;+}++.int-detail-head b {+ font: 600 11px var(--font);+ color: var(--ink);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ min-width: 0;+}++.int-badge {+ font: 500 10px var(--font);+ padding: 2px 6px;+ border-radius: 999px;+ margin-left: auto;+ flex: 0 0 auto;+}++.int-detail-body {+ display: flex;+ flex-direction: column;+ gap: 4px;+ padding-top: 8px;+}++.int-commit {+ font: 400 10.5px var(--font);+ color: #c5c8cd;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+}++.int-meta {+ display: flex;+ gap: 8px;+ font: 400 10px var(--font);+ color: var(--dim-3);+}++.int-link {+ border: 0;+ background: transparent;+ font: 400 10px var(--mono);+ color: #7c5cffd9;+ text-align: left;+ cursor: default;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.int-detail-text {+ font: 400 10.5px/1.5 var(--mono);+ color: var(--dim);+ margin-top: 8px;+ max-height: 88px;+ overflow: auto;+ white-space: pre-wrap;+ user-select: text;+}++.int-card.detail {+ padding-top: 8px;+}diff --git a/windows/src/views/icons.ts b/windows/src/views/icons.tsindex 3a836d90..d2ff8247 100644--- a/windows/src/views/icons.ts+++ b/windows/src/views/icons.ts@@ -32,4 +32,10 @@ export const ICONS = {timer: "M12 4.2a7.8 7.8 0 1 0 0 15.6 7.8 7.8 0 0 0 0-15.6zm0 1.9a5.9 5.9 0 1 1 0 11.8 5.9 5.9 0 0 1 0-11.8zm-.95 2.3v4.2l3.3 2 .95-1.55-2.4-1.45V8.4h-1.85zM9.2 2h5.6v1.7H9.2V2z",// ellipsisellipsis: "M6 10.4a1.6 1.6 0 1 0 0 3.2 1.6 1.6 0 0 0 0-3.2zm6 0a1.6 1.6 0 1 0 0 3.2 1.6 1.6 0 0 0 0-3.2zm6 0a1.6 1.6 0 1 0 0 3.2 1.6 1.6 0 0 0 0-3.2z",+ // star.fill+ star: "M12 3.2l2.6 5.55 5.9.82-4.3 4.3 1.05 6.13L12 17.1l-5.25 2.9L7.8 13.87 3.5 9.57l5.9-.82L12 3.2z",+ // square.stack.fill+ stack: "M5 8h14v11.5H5V8zm1.8-3h10.4v1.6H6.8V5zm1.6-2.6h7.2V4H8.4V2.4z",+ // doc.text+ doc: "M6.5 2.6h7l4 4v14.8h-11V2.6zm6.6 1.6v3.3h3.3l-3.3-3.3zM8.6 11h6.8v1.5H8.6V11zm0 3.4h6.8v1.5H8.6v-1.5z",} as const;diff --git a/windows/src/views/integrations.ts b/windows/src/views/integrations.tsnew file mode 100644index 00000000..1bbd53c8--- /dev/null+++ b/windows/src/views/integrations.ts@@ -0,0 +1,431 @@+// Integration cards shown in the overview's left card — DOM ports of+// IntegrationCardView and friends from IslandViewContent.swift.+//+// Cal.com is the one simplification: macOS shows a three-level calendar+// (month → day → booking); here it is the list of upcoming bookings.++import { h, svg, clear, dot } from "./dom";+import { ICONS } from "./icons";+import { State, type AgentTask } from "../core/state";+import { Bridge } from "../core/bridge";++/** Same shape as the Swift `timeAgo` computed properties. */+export function timeAgo(value: unknown): string {+ const date = typeof value === "number" ? new Date(value) : new Date(String(value));+ const diff = (Date.now() - date.getTime()) / 1000;+ if (!Number.isFinite(diff)) return "";+ if (diff < 60) return "just now";+ if (diff < 3600) return `${Math.floor(diff / 60)}m`;+ if (diff < 86400) return `${Math.floor(diff / 3600)}h`;+ return `${Math.floor(diff / 86400)}d`;+}++function header(color: string, name: string, kind: string, extra?: Node): HTMLElement {+ const row = h("div", { class: "int-head" }, dot(color, 7), h("b", { text: name }), h("span", { text: kind }));+ if (extra) row.append(extra);+ return row;+}++/** Highlighted first row + plain rows, the layout every list card shares. */+function listRow(accent: string, first: boolean, ...children: Node[]): HTMLElement {+ const row = h("div", { class: first ? "int-row first" : "int-row" }, dot(accent, 5), ...children);+ if (first) row.style.background = `${accent}14`;+ return row;+}++function get(id: string): Record<string, unknown> {+ return (State.integrations[id]?.data ?? {}) as Record<string, unknown>;+}++function arr(id: string, key: string): Record<string, unknown>[] {+ const v = get(id)[key];+ return Array.isArray(v) ? (v as Record<string, unknown>[]) : [];+}++// ── Not configured / idle ─────────────────────────────────────────────────────++const OPEN_URLS: Record<string, string> = {+ integration_resend: "https://resend.com/emails",+ integration_vercel: "https://vercel.com/dashboard",+ integration_github: "https://github.com",+ integration_stripe: "https://dashboard.stripe.com/payments",+ integration_notion: "https://notion.so",+ integration_calcom: "https://app.cal.com/bookings",+};++function idleCard(task: AgentTask, openSettings: () => void): HTMLElement {+ const info = State.integrations[task.id];+ const configured = info?.configured ?? false;+ const error = info?.error ?? null;+ const label = error ?? (configured ? "Connected · loading…" : "Key not configured");+ const statusColor = error || !configured ? "#F4505E" : "#22C55E";++ const actions = h("div", { class: "int-actions" });+ if (task.id === "integration_claude") {+ actions.append(+ h("button", {+ class: "link-btn",+ style: `color:${task.color}b3`,+ text: "Open Visual Studio Code",+ onclick: () => void Bridge.openInVSCode(task.sessionCwd ?? null),+ }),+ );+ } else if (task.id === "integration_n8n") {+ actions.append(+ h("button", {+ class: "link-btn",+ style: `color:${task.color}d9`,+ text: "Open n8n",+ onclick: () => void Bridge.openN8n(),+ }),+ );+ } else if (OPEN_URLS[task.id]) {+ actions.append(+ h("button", {+ class: "link-btn",+ style: `color:${task.color}d9`,+ text: `Open ${task.name}`,+ onclick: () => void Bridge.openUrl(OPEN_URLS[task.id]),+ }),+ );+ }+ if (configured) {+ actions.append(+ h("button", {+ class: "link-btn",+ style: `color:${task.color}d9`,+ text: "Refresh",+ onclick: () => void Bridge.refreshIntegration(task.id),+ }),+ );+ } else {+ actions.append(+ h("button", { class: "link-btn", style: "color:#8e939c", text: "Settings…", onclick: openSettings }),+ );+ }++ return h(+ "div",+ { class: "int-card" },+ header(task.color, task.id === "integration_claude" ? "VS Code" : task.name, "Integration"),+ h("div", { class: "int-status" }, dot(statusColor, 5), h("span", { text: label })),+ actions,+ );+}++// ── Vercel ────────────────────────────────────────────────────────────────────++function vercelCard(onDetail: () => void): HTMLElement {+ const deployments = arr("integration_vercel", "deployments");+ const rows = h("div", { class: "int-rows" });+ deployments.slice(0, 3).forEach((d, i) => {+ const accent = d.state === "READY" ? "#22C55E" : "#F4505E";+ const name = h("span", { class: "int-name", text: String(d.projectName ?? "") });+ const ago = h("span", { class: "int-ago", text: timeAgo(d.createdAt) });+ if (i === 0) {+ const more = h(+ "button",+ { class: "int-more", title: "Details", onclick: onDetail },+ svg(ICONS.ellipsis, 8),+ );+ rows.append(listRow(accent, true, name, ago, more));+ } else {+ rows.append(listRow(accent, false, name, ago));+ }+ });+ return h("div", { class: "int-card" }, header("#7C5CFF", "Vercel", "Deployments"), rows);+}++function vercelDetail(onBack: () => void): HTMLElement {+ const d = arr("integration_vercel", "deployments")[0] ?? {};+ const success = d.state === "READY";+ const accent = success ? "#22C55E" : "#F4505E";+ const status = success ? "Ready" : d.state === "CANCELED" ? "Canceled" : "Error";+ const body = h("div", { class: "int-detail-body" });+ if (d.commitMessage) body.append(h("div", { class: "int-commit", text: String(d.commitMessage) }));+ const meta = h("div", { class: "int-meta" });+ if (d.branch) meta.append(h("span", { text: String(d.branch) }));+ meta.append(h("span", { text: `${timeAgo(d.createdAt)} ago` }));+ body.append(meta);+ if (d.url) {+ body.append(+ h("button", {+ class: "int-link",+ text: String(d.url),+ onclick: () => void Bridge.openUrl(`https://${d.url}`),+ }),+ );+ }+ return h(+ "div",+ { class: "int-card detail" },+ h(+ "div",+ { class: "int-detail-head" },+ h("button", { class: "int-back", onclick: onBack }, svg(ICONS.chevronLeft, 10, { stroke: 2.4 })),+ dot(accent, 6),+ h("b", { text: String(d.projectName ?? "Deployment") }),+ h("span", { class: "int-badge", style: `color:${accent};background:${accent}24`, text: status }),+ ),+ body,+ );+}++// ── Resend ────────────────────────────────────────────────────────────────────++function resendCard(): HTMLElement {+ const emails = arr("integration_resend", "emails");+ const total = get("integration_resend").total;+ const extra =+ total != null+ ? h("span", { class: "int-total" }, h("i", { class: "pulse" }), h("span", { text: String(total) }))+ : undefined;+ const rows = h("div", { class: "int-rows" });+ emails.slice(0, 3).forEach((e, i) => {+ const delivered = e.lastEvent === "delivered";+ const accent = delivered ? "#22C55E" : "#F4505E";+ const to = Array.isArray(e.to) ? String(e.to[0] ?? "?") : "?";+ const short = to.split("@")[0];+ const cells: Node[] = [+ h("span", { class: "int-name", text: short }),+ h("span", { class: "int-ago", text: timeAgo(e.createdAt) }),+ ];+ if (i === 0 && e.subject) cells.push(h("span", { class: "int-sub", text: String(e.subject) }));+ rows.append(listRow(accent, i === 0, ...cells));+ });+ return h("div", { class: "int-card" }, header("#22C55E", "Resend", "Emails", extra), rows);+}++// ── GitHub ────────────────────────────────────────────────────────────────────++function statRow(icon: string, color: string, label: string, value: string): HTMLElement {+ return h(+ "div",+ { class: "int-stat" },+ h("i", { class: "int-stat-icon", style: `color:${color}` }, svg(icon, 10)),+ h("span", { class: "int-stat-label", text: label }),+ h("span", { class: "int-stat-value", text: value }),+ );+}++function githubCard(): HTMLElement {+ const d = get("integration_github");+ const stars = Number(d.totalStars ?? 0);+ const repos = Number(d.totalRepos ?? 0);+ const fmt = (n: number) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n));+ return h(+ "div",+ { class: "int-card" },+ header("#F4505E", "GitHub", "Overview"),+ h(+ "div",+ { class: "int-stats" },+ statRow(ICONS.star, "#F5A524", "Total stars", fmt(stars)),+ statRow(ICONS.stack, "#6B7079", "Repositories", String(repos)),+ ),+ );+}++// ── Stripe ────────────────────────────────────────────────────────────────────++function stripeCard(): HTMLElement {+ const d = get("integration_stripe");+ const balance = (Number(d.balance ?? 0) / 100).toFixed(2);+ const currency = String(d.currency ?? "eur").toUpperCase();+ const rows = h("div", { class: "int-rows tight" });+ for (const p of arr("integration_stripe", "payments")) {+ const success = p.status === "succeeded";+ const accent = success ? "#22C55E" : "#F4505E";+ rows.append(+ h(+ "div",+ { class: "int-row" },+ dot(accent, 5),+ h("span", { class: "int-name", text: String(p.description ?? "Payment") }),+ h("span", {+ class: "int-amount",+ style: "color:#22c55e",+ text: `+${(Number(p.amount ?? 0) / 100).toFixed(2)}`,+ }),+ h("span", { class: "int-ago", text: timeAgo(p.createdAt) }),+ ),+ );+ }+ return h(+ "div",+ { class: "int-card" },+ header("#0570DE", "Stripe", "Payments"),+ h("div", { class: "int-balance" }, h("span", { text: balance }), h("i", { text: currency })),+ rows,+ );+}++// ── Notion ────────────────────────────────────────────────────────────────────++function notionCard(): HTMLElement {+ const rows = h("div", { class: "int-rows tight" });+ for (const p of arr("integration_notion", "pages").slice(0, 3)) {+ rows.append(+ h(+ "button",+ {+ class: "int-page",+ onclick: () => {+ if (typeof p.url === "string") void Bridge.openUrl(p.url);+ },+ },+ p.emoji+ ? h("span", { class: "int-emoji", text: String(p.emoji) })+ : h("i", { class: "int-emoji" }, svg(ICONS.doc, 9)),+ h("span", { class: "int-name", text: String(p.title ?? "Untitled") }),+ h("span", { class: "int-ago", text: timeAgo(p.lastEditedAt) }),+ ),+ );+ }+ return h("div", { class: "int-card" }, header("#E8E8E8", "Notion", "Recent"), rows);+}++// ── Cal.com ───────────────────────────────────────────────────────────────────++function calcomCard(): HTMLElement {+ const bookings = arr("integration_calcom", "bookings")+ .slice()+ .sort((a, b) => new Date(String(a.start)).getTime() - new Date(String(b.start)).getTime());+ const rows = h("div", { class: "int-rows tight" });+ if (bookings.length === 0) {+ rows.append(h("div", { class: "int-empty", text: "No calls scheduled" }));+ }+ for (const b of bookings.slice(0, 3)) {+ const when = new Date(String(b.start));+ const day = when.toLocaleDateString(undefined, { day: "2-digit", month: "2-digit" });+ const time = when.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });+ rows.append(+ h(+ "div",+ { class: "int-row" },+ dot("#C9956A", 4),+ h("span", { class: "int-time", text: `${day} ${time}` }),+ h("span", { class: "int-name", text: String(b.title ?? "Meeting") }),+ ),+ );+ }+ return h("div", { class: "int-card" }, header("#C9956A", "Cal.com", "Schedule"), rows);+}++// ── n8n ───────────────────────────────────────────────────────────────────────++function n8nCard(task: AgentTask, onDetail: () => void, openSettings: () => void): HTMLElement {+ const hasActivity = task.steps.length > 0 && (task.state === "finished" || task.state === "error");+ if (!hasActivity) return idleCard(task, openSettings);+ const success = task.state === "finished";+ const accent = success ? "#22C55E" : "#F4505E";+ return h(+ "div",+ { class: "int-card" },+ header("#F29B38", "n8n", "Workflow"),+ h(+ "div",+ { class: "int-actions" },+ h(+ "button",+ {+ class: "int-pill",+ style: `background:${accent}1a;border-color:${accent}38`,+ onclick: onDetail,+ },+ dot(accent, 5),+ h("span", { class: "int-name", text: task.steps[0] ?? "Workflow" }),+ svg(ICONS.ellipsis, 8),+ ),+ ),+ );+}++function n8nDetail(task: AgentTask, onBack: () => void): HTMLElement {+ const success = task.state === "finished";+ const accent = success ? "#22C55E" : "#F4505E";+ const detail = task.steps[1];+ return h(+ "div",+ { class: "int-card detail" },+ h(+ "div",+ { class: "int-detail-head" },+ h("button", { class: "int-back", onclick: onBack }, svg(ICONS.chevronLeft, 10, { stroke: 2.4 })),+ dot(accent, 6),+ h("b", { text: task.steps[0] ?? "Workflow" }),+ h("span", {+ class: "int-badge",+ style: `color:${accent};background:${accent}24`,+ text: success ? "Success" : "Failed",+ }),+ ),+ detail+ ? h("pre", { class: "int-detail-text", text: detail })+ : h("div", {+ class: "int-status",+ text: success ? "Completed successfully." : "No error details available.",+ }),+ );+}++// ── Dispatch ──────────────────────────────────────────────────────────────────++export interface IntegrationCardHooks {+ detailOpen: boolean;+ openDetail(): void;+ closeDetail(): void;+ openSettings(): void;+}++/** True when this integration has data worth showing instead of the idle card. */+export function hasIntegrationData(id: string): boolean {+ const info = State.integrations[id];+ if (!info || info.error) return false;+ switch (id) {+ case "integration_vercel":+ return arr(id, "deployments").length > 0;+ case "integration_resend":+ return arr(id, "emails").length > 0;+ case "integration_github":+ return get(id).totalRepos != null;+ case "integration_stripe":+ return info.loaded;+ case "integration_notion":+ return arr(id, "pages").length > 0;+ case "integration_calcom":+ return info.loaded;+ default:+ return false;+ }+}++export function renderIntegrationCard(task: AgentTask, hooks: IntegrationCardHooks): HTMLElement {+ if (task.id === "integration_n8n") {+ const hasActivity = task.steps.length > 0 && (task.state === "finished" || task.state === "error");+ return hooks.detailOpen && hasActivity+ ? n8nDetail(task, hooks.closeDetail)+ : n8nCard(task, hooks.openDetail, hooks.openSettings);+ }+ if (task.id === "integration_vercel" && hasIntegrationData(task.id)) {+ return hooks.detailOpen ? vercelDetail(hooks.closeDetail) : vercelCard(hooks.openDetail);+ }+ if (!hasIntegrationData(task.id)) return idleCard(task, hooks.openSettings);++ switch (task.id) {+ case "integration_resend":+ return resendCard();+ case "integration_github":+ return githubCard();+ case "integration_stripe":+ return stripeCard();+ case "integration_notion":+ return notionCard();+ case "integration_calcom":+ return calcomCard();+ default:+ return idleCard(task, hooks.openSettings);+ }+}++export { clear };diff --git a/windows/src/views/views.ts b/windows/src/views/views.tsindex f2d23b53..0051c720 100644--- a/windows/src/views/views.ts+++ b/windows/src/views/views.ts@@ -10,12 +10,15 @@ import { washRGBA, type IslandViewName, type Wash } from "../core/layout";import { createMiniBot, pruneMiniBots } from "../mochi/minibots";import { buildPrompt } from "./chat";import { buildChoose, buildUpload, buildUploading } from "./upload";+import { renderIntegrationCard, type IntegrationCardHooks } from "./integrations";export interface ViewActions {setView(v: IslandViewName): void;collapse(): void;setFocus(id: string): void;openTerminal(): void;+ /** The ↗ button: opens whatever the focused pill points at. */+ openTarget(): void;openUrl(url: string): void;decide(d: "allow" | "deny" | "always"): void;toggleSound(): void;@@ -114,12 +117,14 @@ export function buildHeader(actions: ViewActions): ViewHost {function buildOverview(actions: ViewActions): ViewHost {const ticker = new Ticker();const who = h("div", { class: "who" });+ const tickerBody = h("div", { class: "card-body" }, who, ticker.el);+ const leftBody = h("div", { class: "left-body" });const jump = h("button",- { class: "icon-btn jump", title: "Open", onclick: () => actions.openTerminal() },+ { class: "icon-btn jump", title: "Open", onclick: () => actions.openTarget() },svg(ICONS.arrowUpRight, 8),);- const left = card(null, h("div", { class: "card-body" }, who, ticker.el), jump);+ const left = card(null, leftBody, jump);const pills = h("div", { class: "pills" });const right = card(null, pills);@@ -129,16 +134,55 @@ function buildOverview(actions: ViewActions): ViewHost {);let pillIds = "";+ let detailOpen = false;+ let lastFocus: string | null = null;+ let mode: "ticker" | "card" | null = null;+ let cardKey = "";++ const hooks: IntegrationCardHooks = {+ get detailOpen() {+ return detailOpen;+ },+ openDetail() {+ detailOpen = true;+ cardKey = "";+ State.notify();+ },+ closeDetail() {+ detailOpen = false;+ cardKey = "";+ State.notify();+ },+ openSettings: () => actions.openSettingsWindow(),+ };return {el,sync() {const task = State.focusTask;- clear(who);- if (task) {+ if (task?.id !== lastFocus) {+ lastFocus = task?.id ?? null;+ detailOpen = false;+ cardKey = "";+ mode = null;+ }++ // VS Code with a live Claude Code session keeps the ticker; every other+ // pill shows its own card, exactly like IntegrationCardView.+ const sessionActive =+ task?.id === "integration_claude" && (task.state !== "idle" || task.steps.length > 0);++ if (task && sessionActive) {+ if (mode !== "ticker") {+ clear(leftBody);+ leftBody.append(tickerBody);+ mode = "ticker";+ cardKey = "";+ }+ clear(who);who.append(dot(task.color, 7),- h("span", { class: "name", text: task.id === "integration_claude" ? task.name : task.name }),+ h("span", { class: "name", text: task.name }),h("span", { class: "tool", text: task.source === "claudeCode" ? "Claude Code" : "n8n" }),);if (task.steps.length > 1) {@@ -147,13 +191,28 @@ function buildOverview(actions: ViewActions): ViewHost {text: `${Math.min(task.stepIndex + 1, task.steps.length)}/${task.steps.length}`,}));}+ ticker.sync(task);+ } else if (task) {+ const info = State.integrations[task.id];+ const key = [+ task.id, detailOpen, task.state, task.steps.join("|"),+ info?.loaded, info?.error, info?.configured,+ JSON.stringify(info?.data ?? {}),+ ].join("~");+ if (key !== cardKey) {+ cardKey = key;+ mode = "card";+ clear(leftBody);+ leftBody.append(renderIntegrationCard(task, hooks));+ }}- ticker.sync(task);++ jump.style.display = detailOpen ? "none" : "";const others = State.otherTasks.slice(0, 4);- const key = others.map((t) => `${t.id}:${t.pillBadge ?? ""}`).join("|");- if (key !== pillIds) {- pillIds = key;+ const pillKey = others.map((t) => `${t.id}:${t.pillBadge ?? ""}`).join("|");+ if (pillKey !== pillIds) {+ pillIds = pillKey;clear(pills);for (const t of others) pills.append(buildPill(t, actions));pruneMiniBots();