Skip to content

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

Windows and Linux: new version in the island, one click to install it on Windows

Claudefc6f039661bf
diff --git a/README.md b/README.md
index b7d0aa75..c3c7692f 100644
--- a/README.md
+++ b/README.md
@@ -89,7 +89,7 @@ Flow dictation and the Notetaker are on the Mac for now; Windows and Linux are n
- 🤖 **Coucou for Android** — your agents, approvals with your fingerprint, questions, chat and home-screen widgets on an Android phone, linked to Coucou on Windows or Linux over your Wi-Fi. By [@Rhytam23](https://github.com/Rhytam23). See [Coucou for Android](#coucou-for-android).
- 📅 **Weekly recap** *(macOS)* — every Monday morning Coucou shows a summary of the past week: time coding, sessions, files, lines changed, commands, permissions, top agent and project, busiest day and longest session. Share it as a 1080 × 1920 image with Mochi — project names optional. All local, no sync.
- 🌍 **10 languages** — English, 中文, हिन्दी, Español, العربية, Français, বাংলা, Português, Русский, Bahasa Indonesia. Pick one in Settings → General → Language; community translations welcome.
-- 🔒 **Private by design** — no telemetry, no account. Keys live in your macOS Keychain, Windows Credential Manager or Linux Secret Service (GNOME Keyring, KWallet). The app only talks to the services you plug in.
+- 🔒 **Private by design** — no telemetry, no account. Keys live in your macOS Keychain, Windows Credential Manager or Linux Secret Service (GNOME Keyring, KWallet). The app only talks to the services you plug in (and, on Windows and Linux once you agree, to GitHub's releases API to tell you about new versions).
## Coucou on iPhone
@@ -240,6 +240,8 @@ There is no notch on a PC, so the island slides out of the top edge of the scree
instead of hiding inside one. See [`windows/README.md`](windows/README.md) for the
rest of the differences.
+**New versions.** Once you agree (the island asks once, or Settings → General → Updates), Coucou for Windows and Linux tells you when a new version is out; on Windows, **Update now** downloads the installer you used, checks its SHA-256 against the one GitHub publishes and installs it in one click. See [`windows/README.md`](windows/README.md#new-versions).
+
### Linux
**Coucou for Linux 0.5.0** is out (x86_64): [AppImage](https://github.com/Louis-CFM/coucou/releases/download/linux-v0.5.0/Coucou-Linux-0.5.0-x86_64.AppImage) · [.deb](https://github.com/Louis-CFM/coucou/releases/download/linux-v0.5.0/Coucou-Linux-0.5.0-amd64.deb) · [.rpm](https://github.com/Louis-CFM/coucou/releases/download/linux-v0.5.0/Coucou-Linux-0.5.0-x86_64.rpm) · [all files and checksums](https://github.com/Louis-CFM/coucou/releases/tag/linux-v0.5.0). The newest AppImage is always at [`linux-latest`](https://github.com/Louis-CFM/coucou/releases/download/linux-latest/Coucou-Linux-x86_64.AppImage).
diff --git a/windows/README.md b/windows/README.md
index ad316f1f..49a7175e 100644
--- a/windows/README.md
+++ b/windows/README.md
@@ -61,7 +61,7 @@ You can also [build it yourself](#build-it-yourself).
| Click a file in the session ticker | Its diff opens in the island; ↗ opens the file in VS Code, ‹ or `Esc` goes back |
| `Esc` | Closes the island |
| Put a file named like one of Mochi's sounds (`finish.wav`, `approval.mp3`, `greet.m4a`…) in the sounds folder | It replaces that sound after **Settings → General → Reload sounds**. **Open sounds folder** shows the folder: `~/.config/coucou/sounds` on Linux, `%APPDATA%\Coucou\sounds` on Windows |
-| Tray icon | Open, Weekly recap, Wardrobe…, Settings…, Pause, Quit |
+| Tray icon | Open, Weekly recap, Wardrobe…, Settings…, Pause, Quit — and **Update Coucou to X…** while a new version is out |
| `Ctrl+Alt+Space` | Opens the chat, from any app |
| `Ctrl+Alt+A` | Jumps to the waiting permission or question |
| `Ctrl+Alt+T` | Brings the session's window forward ("Open terminal") |
@@ -280,7 +280,8 @@ goes where you told Coucou to send it. The gateway's host is written to the log
once; the key never is.
No telemetry. The only network requests Coucou makes are to the services you
-configure yourself.
+configure yourself, and — once you agree — to GitHub's releases API, to tell you
+about new versions (see [New versions](#new-versions)).
## GitHub
@@ -303,6 +304,48 @@ minute while a CI is running, and as soon as you open the card on data older
than a minute; contributions every 30 minutes. Nothing is fetched while the pill
is off or Coucou is paused.
+## New versions
+
+Coucou can tell you when a new version is out, and on Windows install it in one
+click. Nothing goes to GitHub before you agree: about 30 seconds after launch the
+island asks once, **Get new versions from the island?** (asked again a day later
+at most if you leave the card unanswered, never over a permission or a question).
+**Settings → General → Updates** has the same switch, and **Check now**, which
+looks once even with the switch off.
+
+Once allowed, Coucou asks GitHub at launch and every 6 hours:
+`GET https://api.github.com/repos/Louis-CFM/coucou/releases?per_page=30`,
+unauthenticated, no cookies, nothing about you. It keeps the published
+`windows-vX.Y.Z` releases (`linux-vX.Y.Z` on Linux — never the rolling
+`windows-latest` / `linux-latest`, drafts or prereleases) and takes the highest.
+When it is newer than yours, the island opens on it once a day at most, with
+Mochi surprised: **Coucou X is out**, the first line of its *What's new*, and the
+version you have; **Update now · What's new · Later**. The tray menu offers
+**Update Coucou to X…** for as long as it is out.
+
+**Update now** (Windows) uses the installer this copy came from:
+
+- the per-user `setup.exe` (Coucou in `%LOCALAPPDATA%\Coucou`, with its
+ `uninstall.exe`): `Coucou-Windows-X.Y.Z-setup.exe /P /UPDATE /R` — passive,
+ no "reinstall or uninstall?" step, the old uninstaller never runs, your
+ shortcuts and settings stay, and the installer starts Coucou again;
+- the per-machine `.msi` (Coucou in `Program Files\Coucou`):
+ `msiexec /i Coucou-Windows-X.Y.Z.msi /passive AUTOLAUNCHAPP=True`, which asks
+ for admin rights as installing it by hand does, then starts Coucou again;
+- anything else — the portable exe, a build — gets **Get it on GitHub**, the
+ release page, instead.
+
+The installer is downloaded into a temporary folder, following redirects only to
+`github.com`, `api.github.com` and `*.githubusercontent.com`, and checked
+against the SHA-256 GitHub publishes for that file (the asset's `digest`). No
+checksum, or one that doesn't match, and nothing is installed. Then it runs and
+Coucou quits. The checksum proves the file is exactly the one on the release
+page; like a download by hand, it doesn't prove who uploaded it (the installer
+isn't code-signed yet).
+
+On Linux the card and the tray item point to the release page: AppImage, .deb,
+.rpm and the Arch package are updated the way you installed them.
+
## Build it yourself
You need [Rust](https://rustup.rs), [Node 20+](https://nodejs.org), and the
@@ -475,6 +518,10 @@ own window.
a window to attach it as context. On the Mac, email goes through Resend or
Apple Mail's scripting; neither has a safe equivalent that attaches a file
here, and the drop card would need a third button it doesn't have.
+- New versions: the Mac checks the downloaded app's Developer ID signature and
+ notarization; the Windows installer isn't code-signed yet, so it is checked
+ against the SHA-256 GitHub publishes for it, and the installer (not Coucou)
+ replaces the app and starts it again.
- Cal.com shows the next bookings as a list rather than the Mac's calendar.
- The Cursor pill carries both Cursor Agent's own hooks and Claude Code running
in Cursor's terminal.
@@ -653,6 +700,9 @@ What changes on Linux:
where it is missing, the island says so and Save still works.
- What the Windows build leaves out, this one does too: sending a file by
email and dragging Mochi onto a window.
+- **New versions** are announced (once you agree), but **Update now** opens
+ the release page: update the AppImage, .deb, .rpm or Arch package the way
+ you installed it.
- **Open terminal** walks up from the relay through `/proc` (stopping at
systemd, logins, ssh, session managers and panels, and at any process of
another user) to the terminal or editor the session runs in, then brings its
diff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rs
index b4ea3cb8..98e1f8ec 100644
--- a/windows/src-tauri/src/lib.rs
+++ b/windows/src-tauri/src/lib.rs
@@ -34,6 +34,7 @@ mod sounds;
mod speech;
mod spotify;
mod tray;
+mod update;
mod voice;
#[cfg(windows)]
mod webview_drop;
@@ -862,6 +863,15 @@ pub fn run() {
notes::notes_export,
voice::voice_done,
voice::voice_say_native,
+ update::update_status,
+ update::update_set_consent,
+ update::update_check,
+ update::update_shown,
+ update::update_show,
+ update::update_later,
+ update::update_dismiss,
+ update::update_install,
+ update::update_open_page,
])
.setup(move |app| {
let handle = app.handle().clone();
@@ -904,6 +914,8 @@ pub fn run() {
integrations::start(handle.clone());
spotify::sync(&handle, &loaded.active_integrations);
shortcuts::apply(&handle, &loaded.shortcuts);
+ // New versions: nothing goes to GitHub until the user agrees (update.rs).
+ update::start(handle.clone());
if loaded.autostart {
// Login items written before 0.5 start Coucou without --autostart:
// writing it again adds it, so the window stays hidden at login.
diff --git a/windows/src-tauri/src/tray.rs b/windows/src-tauri/src/tray.rs
index 44d2bd71..ff23a012 100644
--- a/windows/src-tauri/src/tray.rs
+++ b/windows/src-tauri/src/tray.rs
@@ -1,10 +1,14 @@
// Notification-area icon: Open, Weekly recap, Wardrobe, Settings, Pause, Quit.
+// "Update Coucou to X…" shows under Open only while a new version is out
+// (update.rs).
+
+use std::sync::Mutex;
use tauri::menu::{Menu, MenuItem, PredefinedMenuItem};
use tauri::tray::TrayIconBuilder;
use tauri::{AppHandle, Emitter, Manager, Wry};
-use crate::i18n::{n_, t};
+use crate::i18n::{n_, t, tf};
use crate::island::WINDOW_LABEL;
/// The menu's items, id and English label, in order. The labels are shown in
@@ -21,6 +25,17 @@ const ITEMS: [(&str, &str); 6] = [
/// Kept so a language change relabels the menu without rebuilding the tray.
struct Items(Vec<(&'static str, MenuItem<Wry>)>);
+/// "Update Coucou to X…": in the menu only while `version` is set.
+struct UpdateItem {
+ menu: Menu<Wry>,
+ item: MenuItem<Wry>,
+ version: Mutex<Option<String>>,
+}
+
+fn update_label(version: &str) -> String {
+ tf("Update Coucou to {version}…", &[("version", version)])
+}
+
pub fn build(app: &AppHandle) -> tauri::Result<()> {
let mut items = Vec::new();
for (id, label) in ITEMS {
@@ -32,6 +47,9 @@ pub fn build(app: &AppHandle) -> tauri::Result<()> {
let menu = Menu::with_items(app, &[open, recap, &sep1, wardrobe, settings, pause, &sep2, quit])?;
app.manage(Items(items));
+ // Its click goes to the island like the others (id "update"): it opens the update card.
+ let update = MenuItem::with_id(app, "update", "", true, None::<&str>)?;
+ app.manage(UpdateItem { menu: menu.clone(), item: update, version: Mutex::new(None) });
let mut builder = TrayIconBuilder::with_id("coucou")
.tooltip("Coucou")
@@ -60,4 +78,30 @@ pub fn retitle(app: &AppHandle) {
for (label, item) in &items.0 {
let _ = item.set_text(t(label));
}
+ if let Some(update) = app.try_state::<UpdateItem>() {
+ if let Some(version) = update.version.lock().unwrap().as_deref() {
+ let _ = update.item.set_text(update_label(version));
+ }
+ }
+}
+
+/// Shows "Update Coucou to `version`…" right under Open, or takes it out (None).
+pub fn set_update(app: &AppHandle, version: Option<&str>) {
+ let Some(update) = app.try_state::<UpdateItem>() else { return };
+ let mut shown = update.version.lock().unwrap();
+ if shown.as_deref() == version {
+ return;
+ }
+ match version {
+ Some(v) => {
+ let _ = update.item.set_text(update_label(v));
+ if shown.is_none() {
+ let _ = update.menu.insert(&update.item, 1);
+ }
+ }
+ None => {
+ let _ = update.menu.remove(&update.item);
+ }
+ }
+ *shown = version.map(str::to_string);
}
diff --git a/windows/src-tauri/src/update.rs b/windows/src-tauri/src/update.rs
new file mode 100644
index 00000000..2b3304c2
--- /dev/null
+++ b/windows/src-tauri/src/update.rs
@@ -0,0 +1,1024 @@
+// "Coucou 0.6.0 is out" in the island, and on Windows one click to install it.
+// Port of MacUpdate.swift / MacUpdater.swift (the Mac's GitHub build).
+//
+// Nothing is asked of GitHub before the user says yes: the island asks once
+// (again a day later at most if the card was left unanswered), or Settings →
+// General → Updates. "Check now" is a click, so it works either way. Once
+// allowed, Coucou looks at launch and every 6 hours: one unauthenticated
+// `GET /repos/Louis-CFM/coucou/releases`, no cookies, nothing about the user.
+//
+// Windows: the installer this copy came from — the per-user setup.exe in
+// %LOCALAPPDATA%\Coucou, the per-machine .msi under Program Files — is
+// downloaded from GitHub only (redirects to github.com, api.github.com and
+// *.githubusercontent.com, nothing else), checked against the SHA-256 GitHub
+// publishes for that asset, then run; Coucou quits and the installer starts it
+// again. Anything else (the portable exe, every Linux package) gets the
+// release page: people update those the way they installed them.
+//
+// The rules are pure functions below, unit-tested at the bottom of the file.
+
+use std::path::{Path, PathBuf};
+use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
+use std::time::Duration;
+
+use reqwest::Url;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use tauri::{AppHandle, Emitter};
+
+use crate::i18n::t;
+use crate::island::WINDOW_LABEL;
+
+pub const RELEASES_URL: &str = "https://api.github.com/repos/Louis-CFM/coucou/releases?per_page=30";
+/// Where "What's new" goes when no release is known.
+pub const RELEASES_PAGE: &str = "https://github.com/Louis-CFM/coucou/releases";
+
+/// This platform's release tags: `windows-vX.Y.Z` / `linux-vX.Y.Z`. Never the
+/// rolling `windows-latest` / `linux-latest`, nor the Mac's `v…` or Android's.
+#[cfg(windows)]
+pub const TAG_PREFIX: &str = "windows-v";
+#[cfg(not(windows))]
+pub const TAG_PREFIX: &str = "linux-v";
+
+/// Once allowed, a look every 6 hours (GitHub allows 60 unauthenticated calls an hour).
+pub const CHECK_INTERVAL: i64 = 6 * 3600;
+/// "Later", or the card shown once: that version stays quiet for a day. A newer one shows at once.
+pub const SNOOZE: i64 = 24 * 3600;
+/// The question comes back a day later at most when it was left unanswered.
+pub const ASK_AGAIN: i64 = 24 * 3600;
+/// The first look, after launch: never on top of the greeting.
+const FIRST_TICK: Duration = Duration::from_secs(30);
+/// How often the schedule is looked at; GitHub is only called when `should_check` says so.
+const TICK: Duration = Duration::from_secs(3600);
+/// An installer bigger than this is not Coucou's (0.5.0's .msi is 14 MB).
+const MAX_INSTALLER: u64 = 512 * 1024 * 1024;
+
+// ── Releases ──────────────────────────────────────────────────────────────────
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Asset {
+ pub name: String,
+ pub url: String,
+ pub size: u64,
+ /// GitHub's `digest` for the file, `sha256:<hex>`.
+ pub digest: Option<String>,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Release {
+ pub version: String,
+ pub tag: String,
+ pub page_url: String,
+ /// The first "What's new" line, without its Markdown.
+ pub headline: Option<String>,
+ pub assets: Vec<Asset>,
+}
+
+/// "windows-v0.5.1" → "0.5.1" with the prefix "windows-v"; "windows-latest",
+/// "v0.5.1", "linux-v0.5.0" or "windows-v0.5.0-beta" → None.
+pub fn version_from_tag(tag: &str, prefix: &str) -> Option<String> {
+ let v = tag.strip_prefix(prefix)?;
+ let parts: Vec<&str> = v.split('.').collect();
+ let numeric = parts.iter().all(|p| !p.is_empty() && p.len() <= 9 && p.bytes().all(|b| b.is_ascii_digit()));
+ ((2..=4).contains(&parts.len()) && numeric).then(|| v.to_string())
+}
+
+fn numbers(v: &str) -> Vec<u64> {
+ v.split('.').map(|p| p.parse().unwrap_or(0)).collect()
+}
+
+/// Numeric comparison: 0.10.0 is newer than 0.9.3, 0.5.1 than 0.5.
+pub fn is_newer(a: &str, than: &str) -> bool {
+ let (x, y) = (numbers(a), numbers(than));
+ for i in 0..x.len().max(y.len()) {
+ let (l, r) = (x.get(i).copied().unwrap_or(0), y.get(i).copied().unwrap_or(0));
+ if l != r {
+ return l > r;
+ }
+ }
+ false
+}
+
+/// The bold part of the first bullet under "## What's new", else the bullet's
+/// start, as on the Mac.
+pub fn headline(body: Option<&str>) -> Option<String> {
+ let lines: Vec<&str> = body?.lines().collect();
+ let start = lines.iter().position(|l| l.trim().to_lowercase().starts_with("## what"))?;
+ for line in &lines[start + 1..] {
+ let t = line.trim();
+ if t.starts_with("## ") {
+ break;
+ }
+ let Some(item) = t.strip_prefix("- ").or_else(|| t.strip_prefix("* ")) else { continue };
+ if let Some(rest) = item.strip_prefix("**") {
+ if let Some(end) = rest.find("**") {
+ return Some(rest[..end].to_string());
+ }
+ }
+ let plain = item.replace('*', "");
+ return Some(if plain.chars().count() > 70 {
+ format!("{}…", plain.chars().take(68).collect::<String>())
+ } else {
+ plain
+ });
+ }
+ None
+}
+
+/// Only GitHub serves the update (its assets redirect to githubusercontent.com).
+pub fn allowed_host(host: Option<&str>) -> bool {
+ let Some(h) = host.map(str::to_ascii_lowercase) else { return false };
+ h == "github.com" || h == "api.github.com" || h.ends_with(".githubusercontent.com")
+}
+
+pub fn allowed_url(url: &str) -> bool {
+ Url::parse(url).is_ok_and(|u| u.scheme() == "https" && allowed_host(u.host_str()))
+}
+
+/// The newest published release with this platform's tag in `GET /releases`.
+pub fn latest(json: &[u8], prefix: &str) -> Option<Release> {
+ let Ok(Value::Array(list)) = serde_json::from_slice::<Value>(json) else { return None };
+ let releases = list.iter().filter_map(|r| {
+ if r.get("draft").and_then(Value::as_bool) == Some(true)
+ || r.get("prerelease").and_then(Value::as_bool) == Some(true)
+ {
+ return None;
+ }
+ let tag = r.get("tag_name")?.as_str()?;
+ let version = version_from_tag(tag, prefix)?;
+ let page_url = r.get("html_url")?.as_str().filter(|u| allowed_url(u))?.to_string();
+ let assets = r
+ .get("assets")
+ .and_then(Value::as_array)
+ .map(|assets| {
+ assets
+ .iter()
+ .filter_map(|a| {
+ Some(Asset {
+ name: a.get("name")?.as_str()?.to_string(),
+ url: a.get("browser_download_url")?.as_str()?.to_string(),
+ size: a.get("size").and_then(Value::as_u64).unwrap_or(0),
+ digest: a.get("digest").and_then(Value::as_str).map(str::to_string),
+ })
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+ Some(Release {
+ version,
+ tag: tag.to_string(),
+ page_url,
+ headline: headline(r.get("body").and_then(Value::as_str)),
+ assets,
+ })
+ });
+ releases.fold(None, |best: Option<Release>, r| match best {
+ Some(b) if !is_newer(&r.version, &b.version) => Some(b),
+ _ => Some(r),
+ })
+}
+
+/// "sha256:E823…" → the 64 lowercase hex digits; anything else → None.
+pub fn parse_digest(digest: &str) -> Option<String> {
+ let hex = digest.strip_prefix("sha256:")?;
+ (hex.len() == 64 && hex.bytes().all(|b| b.is_ascii_hexdigit())).then(|| hex.to_ascii_lowercase())
+}
+
+// ── How this copy was installed ───────────────────────────────────────────────
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub enum InstallKind {
+ /// The per-user setup.exe (NSIS): %LOCALAPPDATA%\Coucou.
+ Setup,
+ /// The per-machine .msi (WiX): Program Files\Coucou.
+ Msi,
+ /// Anything else — the portable exe, a build, Linux: the release page only.
+ Manual,
+}
+
+/// A Windows path for comparing: backslashes, no trailing one, lowercase.
+fn win_path(p: &str) -> String {
+ p.replace('/', "\\").trim_end_matches('\\').to_lowercase()
+}
+
+/// The installer that put `exe` where it is, from its folder alone: Tauri's
+/// NSIS installer (per user) uses %LOCALAPPDATA%\Coucou, its MSI (per machine)
+/// Program Files\Coucou. `has_uninstaller` is whether NSIS's uninstall.exe sits
+/// next to it, so a portable exe someone copied into that folder isn't taken
+/// for an installed one.
+#[cfg_attr(not(windows), allow(dead_code))]
+pub fn install_kind(exe: &str, has_uninstaller: bool, local_app_data: Option<&str>, program_files: &[String]) -> InstallKind {
+ let exe = win_path(exe);
+ let Some((dir, _)) = exe.rsplit_once('\\') else { return InstallKind::Manual };
+ if let Some(local) = local_app_data.filter(|l| !l.trim().is_empty()) {
+ if dir == format!("{}\\coucou", win_path(local)) {
+ return if has_uninstaller { InstallKind::Setup } else { InstallKind::Manual };
+ }
+ }
+ if program_files.iter().filter(|p| !p.trim().is_empty()).any(|p| dir == format!("{}\\coucou", win_path(p))) {
+ return InstallKind::Msi;
+ }
+ InstallKind::Manual
+}
+
+/// The release asset for an install kind: exactly the name the release
+/// workflow publishes, nothing else.
+pub fn asset_name(kind: InstallKind, version: &str) -> Option<String> {
+ match kind {
+ InstallKind::Setup => Some(format!("Coucou-Windows-{version}-setup.exe")),
+ InstallKind::Msi => Some(format!("Coucou-Windows-{version}.msi")),
+ InstallKind::Manual => None,
+ }
+}
+
+pub fn pick_asset(release: &Release, kind: InstallKind) -> Option<&Asset> {
+ let name = asset_name(kind, &release.version)?;
+ release.assets.iter().find(|a| a.name == name && allowed_url(&a.url))
+}
+
+/// What runs the downloaded installer. The setup.exe with Tauri's own update
+/// flags: `/P` passive (a progress bar, no questions), `/UPDATE` (no "reinstall
+/// or uninstall?" step, the old uninstaller never runs, shortcuts are left as
+/// they are), `/R` (start Coucou again once done). The MSI through msiexec,
+/// passive, with Tauri's `AUTOLAUNCHAPP` to start it again; being per machine
+/// it asks for admin rights, as installing it by hand does.
+pub fn installer_command(kind: InstallKind, file: &Path, system_root: Option<&str>) -> Option<(PathBuf, Vec<String>)> {
+ let file_arg = file.to_string_lossy().to_string();
+ match kind {
+ InstallKind::Setup => Some((file.to_path_buf(), vec!["/P".into(), "/UPDATE".into(), "/R".into()])),
+ InstallKind::Msi => {
+ let msiexec = match system_root.filter(|r| !r.trim().is_empty()) {
+ Some(root) => PathBuf::from(format!("{}\\System32\\msiexec.exe", root.trim_end_matches(['\\', '/']))),
+ None => PathBuf::from("msiexec.exe"),
+ };
+ Some((msiexec, vec!["/i".into(), file_arg, "/passive".into(), "AUTOLAUNCHAPP=True".into()]))
+ }
+ InstallKind::Manual => None,
+ }
+}
+
+// ── Schedule ──────────────────────────────────────────────────────────────────
+
+/// A clock set back counts as due, so a wrong date can't stop the checks for good.
+fn due(last: Option<i64>, now: i64, interval: i64) -> bool {
+ last.is_none_or(|last| now - last >= interval || now < last)
+}
+
+pub fn should_check(last: Option<i64>, now: i64) -> bool {
+ due(last, now, CHECK_INTERVAL)
+}
+
+pub fn should_ask(asked_at: Option<i64>, now: i64) -> bool {
+ due(asked_at, now, ASK_AGAIN)
+}
+
+/// Whether Mochi says "Coucou X is out": newer than what runs, and not shown
+/// or put off for that version in the last day.
+pub fn should_announce(version: &str, current: &str, snoozed_version: Option<&str>, snoozed_at: Option<i64>, now: i64) -> bool {
+ if !is_newer(version, current) {
+ return false;
+ }
+ !(snoozed_version == Some(version) && !due(snoozed_at, now, SNOOZE))
+}
+
+// ── State ─────────────────────────────────────────────────────────────────────
+
+/// update.json in the config folder. Not secrets.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+struct Prefs {
+ /// None: not asked yet. true: Coucou may look at GitHub. false: never on its own.
+ consent: Option<bool>,
+ last_check: Option<i64>,
+ snoozed_version: Option<String>,
+ snoozed_at: Option<i64>,
+ asked_at: Option<i64>,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize)]
+#[serde(tag = "kind", rename_all = "camelCase")]
+pub enum Phase {
+ Idle,
+ Downloading { fraction: f64 },
+ Verifying,
+ Installing,
+ Error { message: String },
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub enum CheckState {
+ None,
+ Checking,
+ UpToDate,
+ Unreachable,
+}
+
+#[derive(Clone, Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LatestView {
+ version: String,
+ headline: Option<String>,
+ page_url: String,
+}
+
+/// What the island and the settings window show.
+#[derive(Clone, Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Status {
+ consent: Option<bool>,
+ current: String,
+ latest: Option<LatestView>,
+ /// "Update now" can install it here (Windows, setup.exe or MSI install).
+ can_install: bool,
+ phase: Phase,
+ check: CheckState,
+ platform: &'static str,
+}
+
+struct Inner {
+ prefs: Prefs,
+ latest: Option<Release>,
+ phase: Phase,
+ check: CheckState,
+}
+
+impl Inner {
+ fn busy(&self) -> bool {
+ matches!(self.phase, Phase::Downloading { .. } | Phase::Verifying | Phase::Installing)
+ }
+}
+
+fn state() -> MutexGuard<'static, Inner> {
+ static S: OnceLock<Mutex<Inner>> = OnceLock::new();
+ S.get_or_init(|| {
+ Mutex::new(Inner { prefs: load_prefs(), latest: None, phase: Phase::Idle, check: CheckState::None })
+ })
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+}
+
+pub fn current_version() -> &'static str {
+ env!("CARGO_PKG_VERSION")
+}
+
+fn now() -> i64 {
+ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)
+}
+
+fn prefs_path() -> PathBuf {
+ crate::platform::config_dir().join("update.json")
+}
+
+fn load_prefs() -> Prefs {
+ std::fs::read(prefs_path()).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()
+}
+
+fn save_prefs(prefs: &Prefs) {
+ let path = prefs_path();
+ let Some(dir) = path.parent() else { return };
+ let temp = path.with_extension(format!("json.coucou-{}", std::process::id()));
+ let written = crate::platform::ensure_private_dir(dir)
+ .and_then(|()| serde_json::to_vec(prefs).map_err(std::io::Error::other))
+ .and_then(|json| std::fs::write(&temp, json))
+ .and_then(|()| std::fs::rename(&temp, &path));
+ if let Err(err) = written {
+ let _ = std::fs::remove_file(&temp);
+ crate::log::line(format!("update: could not save update.json: {err}"));
+ }
+}
+
+/// How this copy was installed, for "Update now".
+pub fn this_install() -> InstallKind {
+ #[cfg(windows)]
+ {
+ let Ok(exe) = std::env::current_exe() else { return InstallKind::Manual };
+ let has_uninstaller = exe.parent().is_some_and(|d| d.join("uninstall.exe").is_file());
+ let env = |k: &str| std::env::var(k).ok();
+ let program_files: Vec<String> =
+ ["ProgramFiles", "ProgramW6432", "ProgramFiles(x86)"].iter().filter_map(|k| env(k)).collect();
+ install_kind(&exe.to_string_lossy(), has_uninstaller, env("LOCALAPPDATA").as_deref(), &program_files)
+ }
+ // Linux: AppImage, .deb, .rpm and the Arch package update the way they were installed.
+ #[cfg(not(windows))]
+ {
+ InstallKind::Manual
+ }
+}
+
+fn can_install(latest: Option<&Release>) -> bool {
+ let kind = this_install();
+ latest.is_some_and(|r| pick_asset(r, kind).is_some())
+}
+
+pub fn status() -> Status {
+ let s = state();
+ let latest = s.latest.as_ref().filter(|r| is_newer(&r.version, current_version()));
+ Status {
+ consent: s.prefs.consent,
+ current: current_version().to_string(),
+ latest: latest.map(|r| LatestView {
+ version: r.version.clone(),
+ headline: r.headline.clone(),
+ page_url: r.page_url.clone(),
+ }),
+ can_install: can_install(latest),
+ phase: s.phase.clone(),
+ check: s.check,
+ platform: if cfg!(windows) { "windows" } else { "linux" },
+ }
+}
+
+/// Tells both windows, and the tray's "Update Coucou to X…".
+fn changed(app: &AppHandle) {
+ let status = status();
+ crate::tray::set_update(app, status.latest.as_ref().map(|l| l.version.as_str()));
+ let _ = app.emit("update-status", status);
+}
+
+/// Asks the island to open its update card: "ask", "announce" or "show". The
+/// island opens it only when nothing else waits there, and says so with
+/// `update_shown`.
+fn offer(app: &AppHandle, kind: &str) {
+ let _ = app.emit_to(WINDOW_LABEL, "update-offer", kind.to_string());
+}
+
+fn set_phase(app: &AppHandle, phase: Phase) {
+ state().phase = phase;
+ changed(app);
+}
+
+// ── Schedule loop ─────────────────────────────────────────────────────────────
+
+/// At launch: a first look 30 s in, then every hour (GitHub only every 6 h).
+/// The task sleeps in between: nothing runs while nothing is due.
+pub fn start(app: AppHandle) {
+ remove_old_downloads();
+ tauri::async_runtime::spawn(async move {
+ tokio::time::sleep(FIRST_TICK).await;
+ let mut launch = true;
+ loop {
+ tick(&app, launch).await;
+ launch = false;
+ tokio::time::sleep(TICK).await;
+ }
+ });
+}
+
+async fn tick(app: &AppHandle, launch: bool) {
+ // Paused means paused: no call out, no card.
+ if crate::integrations::PAUSED.load(std::sync::atomic::Ordering::Relaxed) {
+ return;
+ }
+ let (consent, asked_at, last_check) = {
+ let s = state();
+ (s.prefs.consent, s.prefs.asked_at, s.prefs.last_check)
+ };
+ match consent {
+ None if should_ask(asked_at, now()) => offer(app, "ask"),
+ Some(true) if launch || should_check(last_check, now()) => check(app, false).await,
+ Some(true) => announce_if_due(app),
+ _ => {}
+ }
+}
+
+fn announce_if_due(app: &AppHandle) {
+ let due = {
+ let s = state();
+ !s.busy()
+ && s.latest.as_ref().is_some_and(|r| {
+ should_announce(&r.version, current_version(), s.prefs.snoozed_version.as_deref(), s.prefs.snoozed_at, now())
+ })
+ };
+ if due {
+ offer(app, "announce");
+ }
+}
+
+// ── Check ─────────────────────────────────────────────────────────────────────
+
+/// The client for GitHub: no cookies (reqwest keeps none), a bare user agent
+/// (GitHub refuses requests without one), and redirects followed only to
+/// GitHub over https.
+fn github_client(timeout: Duration) -> Result<reqwest::Client, String> {
+ let policy = reqwest::redirect::Policy::custom(|attempt| {
+ if attempt.previous().len() >= 5 {
+ attempt.error("too many redirects")
+ } else if attempt.url().scheme() == "https" && allowed_host(attempt.url().host_str()) {
+ attempt.follow()
+ } else {
+ attempt.stop()
+ }
+ });
+ reqwest::Client::builder()
+ .connect_timeout(Duration::from_secs(15))
+ .timeout(timeout)
+ .user_agent("Coucou")
+ .redirect(policy)
+ .build()
+ .map_err(|e| e.to_string())
+}
+
+async fn fetch_latest() -> Result<Option<Release>, String> {
+ let response = github_client(Duration::from_secs(30))?
+ .get(RELEASES_URL)
+ .header("Accept", "application/vnd.github+json")
+ .send()
+ .await
+ .map_err(|e| e.to_string())?;
+ if response.status().as_u16() != 200 {
+ return Err(format!("HTTP {}", response.status().as_u16()));
+ }
+ let body = crate::net::read_capped(response, crate::net::MAX_BODY).await?;
+ Ok(latest(&body, TAG_PREFIX))
+}
+
+/// One look at GitHub. `manual`: "Check now" in Settings, which opens the card
+/// when a new version is out.
+pub async fn check(app: &AppHandle, manual: bool) {
+ {
+ let mut s = state();
+ if s.busy() || s.check == CheckState::Checking {
+ return;
+ }
+ s.check = CheckState::Checking;
+ }
+ changed(app);
+ let result = fetch_latest().await;
+ let newer = {
+ let mut s = state();
+ s.prefs.last_check = Some(now());
+ save_prefs(&s.prefs);
+ match result {
+ Err(err) => {
+ crate::log::line(format!("update: GitHub unreachable: {err}"));
+ s.check = CheckState::Unreachable;
+ false
+ }
+ Ok(Some(release)) if is_newer(&release.version, current_version()) => {
+ if s.latest.as_ref().map(|r| &r.version) != Some(&release.version) {
+ crate::log::line(format!("update: {} is out (running {})", release.version, current_version()));
+ }
+ s.latest = Some(release);
+ s.check = CheckState::None;
+ true
+ }
+ Ok(_) => {
+ s.latest = None;
+ s.check = CheckState::UpToDate;
+ if matches!(s.phase, Phase::Error { .. }) {
+ s.phase = Phase::Idle;
+ }
+ false
+ }
+ }
+ };
+ changed(app);
+ if newer {
+ if manual {
+ offer(app, "show");
+ } else {
+ announce_if_due(app);
+ }
+ }
+}
+
+// ── Install (Windows) ─────────────────────────────────────────────────────────
+
+/// Old downloads left in the temp folder by an update that ran: Coucou quits
+/// before the installer is done with its file, so they go at the next launch.
+fn remove_old_downloads() {
+ let Ok(entries) = std::fs::read_dir(std::env::temp_dir()) else { return };
+ for entry in entries.flatten() {
+ if entry.file_name().to_string_lossy().starts_with("coucou-update-") {
+ let _ = std::fs::remove_dir_all(entry.path());
+ }
+ }
+}
+
+/// "Update now": downloads, checks and runs the installer, then quits.
+pub fn install(app: &AppHandle) {
+ let kind = this_install();
+ let release = {
+ let mut s = state();
+ if s.busy() {
+ return;
+ }
+ let Some(release) = s.latest.clone().filter(|r| is_newer(&r.version, current_version())) else { return };
+ if pick_asset(&release, kind).is_none() {
+ // Nothing to install here: the card offers the release page instead.
+ return;
+ }
+ s.phase = Phase::Downloading { fraction: 0.0 };
+ release
+ };
+ changed(app);
+ let app = app.clone();
+ tauri::async_runtime::spawn(async move {
+ match run(&app, &release, kind).await {
+ Ok(()) => {
+ crate::log::line(format!("update: running the {kind:?} installer for {}, quitting", release.version));
+ set_phase(&app, Phase::Installing);
+ // Long enough for the card to say so; the installer closes a Coucou still open.
+ tokio::time::sleep(Duration::from_millis(1200)).await;
+ app.exit(0);
+ }
+ Err(message) => {
+ crate::log::line(format!("update: failed: {message}"));
+ set_phase(&app, Phase::Error { message });
+ }
+ }
+ });
+}
+
+async fn run(app: &AppHandle, release: &Release, kind: InstallKind) -> Result<(), String> {
+ let asset = pick_asset(release, kind).ok_or_else(|| t("The download failed. Try again, or get the new version on GitHub."))?;
+ let expected = asset
+ .digest
+ .as_deref()
+ .and_then(parse_digest)
+ .ok_or_else(|| t("GitHub gave no checksum for this download, so nothing was installed."))?;
+ if asset.size == 0 || asset.size > MAX_INSTALLER {
+ return Err(t("The download isn't the file GitHub published for this version, so nothing was installed."));
+ }
+ let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_nanos()).unwrap_or(0);
+ let dir = std::env::temp_dir().join(format!("coucou-update-{}-{nonce}", std::process::id()));
+ std::fs::create_dir_all(&dir).map_err(|_| t("The download failed. Try again, or get the new version on GitHub."))?;
+ let path = dir.join(&asset.name);
+
+ let got = download(app, asset, &path).await.inspect_err(|_| {
+ let _ = std::fs::remove_dir_all(&dir);
+ })?;
+ set_phase(app, Phase::Verifying);
+ if got != expected {
+ let _ = std::fs::remove_dir_all(&dir);
+ return Err(t("The download isn't the file GitHub published for this version, so nothing was installed."));
+ }
+
+ let system_root = std::env::var("SystemRoot").ok();
+ let (program, args) = installer_command(kind, &path, system_root.as_deref())
+ .ok_or_else(|| t("The download failed. Try again, or get the new version on GitHub."))?;
+ std::process::Command::new(program).args(args).spawn().map_err(|err| {
+ crate::log::line(format!("update: could not start the installer: {err}"));
+ t("Windows blocked the installer. Get the new version from its release page instead.")
+ })?;
+ Ok(())
+}
+
+/// Streams the asset to `path` from GitHub only, hashing as it comes, with the
+/// progress on the card. Returns the SHA-256 of exactly `asset.size` bytes.
+async fn download(app: &AppHandle, asset: &Asset, path: &Path) -> Result<String, String> {
+ use std::io::Write;
+ let failed = || t("The download failed. Try again, or get the new version on GitHub.");
+ if !allowed_url(&asset.url) {
+ return Err(failed());
+ }
+ let mut response = github_client(Duration::from_secs(900))?
+ .get(&asset.url)
+ .header("Accept", "application/octet-stream")
+ .send()
+ .await
+ .map_err(|_| failed())?;
+ if response.status().as_u16() != 200 || response.url().scheme() != "https" || !allowed_host(response.url().host_str()) {
+ return Err(failed());
+ }
+ let mut out = std::fs::File::create(path).map_err(|_| failed())?;
+ let mut hash = ring::digest::Context::new(&ring::digest::SHA256);
+ let mut got: u64 = 0;
+ let mut last_emit = std::time::Instant::now();
+ while let Some(chunk) = response.chunk().await.map_err(|_| failed())? {
+ got += chunk.len() as u64;
+ if got > asset.size {
+ return Err(t("The download isn't the file GitHub published for this version, so nothing was installed."));
+ }
+ // Defender holding or removing the file shows up here.
+ out.write_all(&chunk).map_err(|_| t("Windows blocked the installer. Get the new version from its release page instead."))?;
+ hash.update(&chunk);
+ if last_emit.elapsed() > Duration::from_millis(250) {
+ last_emit = std::time::Instant::now();
+ set_phase(app, Phase::Downloading { fraction: got as f64 / asset.size as f64 });
+ }
+ }
+ out.flush().map_err(|_| failed())?;
+ drop(out);
+ if got != asset.size {
+ return Err(failed());
+ }
+ Ok(hash.finish().as_ref().iter().map(|b| format!("{b:02x}")).collect())
+}
+
+// ── Commands ──────────────────────────────────────────────────────────────────
+
+#[tauri::command]
+pub fn update_status() -> Status {
+ status()
+}
+
+/// The island's question, or Settings' toggle.
+#[tauri::command]
+pub fn update_set_consent(app: AppHandle, allowed: bool) {
+ {
+ let mut s = state();
+ s.prefs.consent = Some(allowed);
+ save_prefs(&s.prefs);
+ }
+ changed(&app);
+ if allowed {
+ tauri::async_runtime::spawn(async move { check(&app, false).await });
+ }
+}
+
+/// "Check now" (a click: works with the toggle off too).
+#[tauri::command]
+pub async fn update_check(app: AppHandle) -> Status {
+ check(&app, true).await;
+ status()
+}
+
+/// The island opened the card it was offered: the question waits a day before
+/// coming back, the announced version a day before it is announced again.
+#[tauri::command]
+pub fn update_shown(kind: String) {
+ let mut s = state();
+ match kind.as_str() {
+ "ask" => s.prefs.asked_at = Some(now()),
+ "announce" => {
+ let Some(version) = s.latest.as_ref().map(|r| r.version.clone()) else { return };
+ s.prefs.snoozed_version = Some(version);
+ s.prefs.snoozed_at = Some(now());
+ }
+ _ => return,
+ }
+ save_prefs(&s.prefs);
+}
+
+/// Settings → "Install X": opens the island's card on it.
+#[tauri::command]
+pub fn update_show(app: AppHandle) {
+ offer(&app, "show");
+}
+
+/// "Later": this version stays quiet for a day; the tray and Settings keep offering it.
+#[tauri::command]
+pub fn update_later(app: AppHandle) {
+ {
+ let mut s = state();
+ if let Some(version) = s.latest.as_ref().map(|r| r.version.clone()) {
+ s.prefs.snoozed_version = Some(version);
+ s.prefs.snoozed_at = Some(now());
+ save_prefs(&s.prefs);
+ }
+ if matches!(s.phase, Phase::Error { .. }) {
+ s.phase = Phase::Idle;
+ }
+ }
+ changed(&app);
+}
+
+/// "OK" on a failed update: back to offering it.
+#[tauri::command]
+pub fn update_dismiss(app: AppHandle) {
+ {
+ let mut s = state();
+ if matches!(s.phase, Phase::Error { .. }) {
+ s.phase = Phase::Idle;
+ }
+ }
+ changed(&app);
+}
+
+#[tauri::command]
+pub fn update_install(app: AppHandle) {
+ install(&app);
+}
+
+/// "What's new" / "Get it on GitHub": the release's page (only ever a github.com address).
+#[tauri::command]
+pub fn update_open_page() {
+ let page = state().latest.as_ref().map(|r| r.page_url.clone()).filter(|u| allowed_url(u));
+ crate::platform::open_url(page.as_deref().unwrap_or(RELEASES_PAGE));
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A trimmed `GET /releases` answer, as GitHub gave it on 2026-10-20: Mac,
+ /// Linux, Android and Windows releases mixed, the rolling `*-latest` ones,
+ /// drafts and a prerelease.
+ fn fixture() -> Vec<u8> {
+ serde_json::json!([
+ { "tag_name": "windows-v0.6.0", "draft": true, "prerelease": false,
+ "html_url": "https://github.com/Louis-CFM/coucou/releases/tag/windows-v0.6.0", "assets": [] },
+ { "tag_name": "windows-v0.7.0", "draft": false, "prerelease": true,
+ "html_url": "https://github.com/Louis-CFM/coucou/releases/tag/windows-v0.7.0", "assets": [] },
+ { "tag_name": "v0.9.0", "draft": false, "prerelease": false,
+ "html_url": "https://github.com/Louis-CFM/coucou/releases/tag/v0.9.0",
+ "body": "## What's new\n\n- **WhatsApp in one click** — Mac",
+ "assets": [{ "name": "Coucou.zip", "size": 34228988,
+ "browser_download_url": "https://github.com/Louis-CFM/coucou/releases/download/v0.9.0/Coucou.zip",
+ "digest": "sha256:24175a765704082c8b2e751f8b5ccb76b1eb3440ff2fd1e9c4cbe780c2193baa" }] },
+ { "tag_name": "windows-v0.5.0", "draft": false, "prerelease": false,
+ "html_url": "https://github.com/Louis-CFM/coucou/releases/tag/windows-v0.5.0",
+ "body": "Coucou for Windows 0.5.0 — Mochi at the top of your screen.\n\n## What's new\n\n- **Flow dictation** on Windows — hold right Ctrl\n- Other things",
+ "assets": [
+ { "name": "Coucou-Windows-0.5.0-setup.exe", "size": 10950620,
+ "browser_download_url": "https://github.com/Louis-CFM/coucou/releases/download/windows-v0.5.0/Coucou-Windows-0.5.0-setup.exe",
+ "digest": "sha256:e8234a092e8fe1bf6eed0395e6db13052be8fe47413949c2b7fa368467342337" },
+ { "name": "Coucou-Windows-0.5.0.msi", "size": 14086144,
+ "browser_download_url": "https://github.com/Louis-CFM/coucou/releases/download/windows-v0.5.0/Coucou-Windows-0.5.0.msi",
+ "digest": "sha256:79bced83c414722e84d47e99005a37910147624dc5e4edf55aa66ff6462cd09f" }] },
+ { "tag_name": "windows-latest", "draft": false, "prerelease": false,
+ "html_url": "https://github.com/Louis-CFM/coucou/releases/tag/windows-latest",
+ "assets": [{ "name": "Coucou-Windows-setup.exe", "size": 10950620,
+ "browser_download_url": "https://github.com/Louis-CFM/coucou/releases/download/windows-latest/Coucou-Windows-setup.exe",
+ "digest": "sha256:e8234a092e8fe1bf6eed0395e6db13052be8fe47413949c2b7fa368467342337" }] },
+ { "tag_name": "linux-v0.5.0", "draft": false, "prerelease": false,
+ "html_url": "https://github.com/Louis-CFM/coucou/releases/tag/linux-v0.5.0", "body": "Coucou for Linux 0.5.0",
+ "assets": [{ "name": "Coucou-Linux-0.5.0-x86_64.AppImage", "size": 107960824,
+ "browser_download_url": "https://github.com/Louis-CFM/coucou/releases/download/linux-v0.5.0/Coucou-Linux-0.5.0-x86_64.AppImage",
+ "digest": "sha256:b59e0a8e432b782ea029cc825d37675033e7ff4069d70d376c1d268495a242af" }] },
+ { "tag_name": "linux-latest", "draft": false, "prerelease": false,
+ "html_url": "https://github.com/Louis-CFM/coucou/releases/tag/linux-latest", "assets": [] },
+ { "tag_name": "android-v0.2.0", "draft": false, "prerelease": false,
+ "html_url": "https://github.com/Louis-CFM/coucou/releases/tag/android-v0.2.0", "assets": [] },
+ { "tag_name": "windows-v0.10.0", "draft": false, "prerelease": false,
+ "html_url": "https://evil.example.com/windows-v0.10.0", "assets": [] },
+ { "tag_name": "windows-v0.4.0", "draft": false, "prerelease": false,
+ "html_url": "https://github.com/Louis-CFM/coucou/releases/tag/windows-v0.4.0", "assets": [] },
+ { "tag_name": "linux-v0.4.0", "draft": false, "prerelease": false,
+ "html_url": "https://github.com/Louis-CFM/coucou/releases/tag/linux-v0.4.0", "assets": [] }
+ ])
+ .to_string()
+ .into_bytes()
+ }
+
+ #[test]
+ fn only_this_platforms_numbered_tags_count() {
+ assert_eq!(version_from_tag("windows-v0.5.1", "windows-v").as_deref(), Some("0.5.1"));
+ assert_eq!(version_from_tag("windows-v1.2", "windows-v").as_deref(), Some("1.2"));
+ assert_eq!(version_from_tag("linux-v0.5.0", "linux-v").as_deref(), Some("0.5.0"));
+ for tag in ["windows-latest", "v0.5.1", "linux-v0.5.0", "android-v0.2.0", "windows-v0.5.0-beta", "windows-v", "windows-v1", "windows-v1..2", "windows-v1.2.3.4.5"] {
+ assert_eq!(version_from_tag(tag, "windows-v"), None, "{tag}");
+ }
+ assert_eq!(version_from_tag("windows-v0.5.0", "linux-v"), None);
+ }
+
+ #[test]
+ fn versions_compare_as_numbers() {
+ assert!(is_newer("0.10.0", "0.9.3"));
+ assert!(is_newer("0.5.1", "0.5"));
+ assert!(is_newer("1.0", "0.99.99"));
+ assert!(!is_newer("0.5.0", "0.5.0"));
+ assert!(!is_newer("0.5", "0.5.0"));
+ assert!(!is_newer("0.4.9", "0.5.0"));
+ }
+
+ #[test]
+ fn the_newest_published_release_of_this_platform_is_picked() {
+ let w = latest(&fixture(), "windows-v").unwrap();
+ // Not the draft 0.6.0, the prerelease 0.7.0, the Mac's 0.9.0 or the 0.10.0 whose page isn't GitHub's.
+ assert_eq!(w.version, "0.5.0");
+ assert_eq!(w.tag, "windows-v0.5.0");
+ assert_eq!(w.page_url, "https://github.com/Louis-CFM/coucou/releases/tag/windows-v0.5.0");
+ assert_eq!(w.headline.as_deref(), Some("Flow dictation"));
+ assert_eq!(w.assets.len(), 2);
+ let l = latest(&fixture(), "linux-v").unwrap();
+ assert_eq!(l.version, "0.5.0");
+ assert_eq!(l.headline, None);
+ assert_eq!(latest(b"{\"message\":\"API rate limit exceeded\"}", "windows-v"), None);
+ assert_eq!(latest(b"not json", "windows-v"), None);
+ assert_eq!(latest(b"[]", "windows-v"), None);
+ }
+
+ #[test]
+ fn the_headline_is_the_first_bold_bullet_of_whats_new() {
+ let h = |s: &str| headline(Some(s));
+ assert_eq!(h("Intro\n\n## What's new\n\n- **WhatsApp in one click** *(macOS)* — more\n- second").as_deref(), Some("WhatsApp in one click"));
+ assert_eq!(h("## What’s new\n* Plain *first* item\n").as_deref(), Some("Plain first item"));
+ assert_eq!(h("## What's new\n\n## Install\n- **Not this**"), None);
+ assert_eq!(h("- **No section**"), None);
+ assert_eq!(headline(None), None);
+ let long = format!("## What's new\n- {}", "a".repeat(80));
+ let got = h(&long).unwrap();
+ assert_eq!(got.chars().count(), 69);
+ assert!(got.ends_with('…'));
+ }
+
+ #[test]
+ fn only_github_may_serve_the_download() {
+ for host in ["github.com", "api.github.com", "objects.githubusercontent.com", "release-assets.githubusercontent.com", "GitHub.com"] {
+ assert!(allowed_host(Some(host)), "{host}");
+ }
+ for host in ["evil.com", "github.com.evil.com", "githubusercontent.com.evil.com", "notgithub.com", "githubusercontent.com", ""] {
+ assert!(!allowed_host(Some(host)), "{host}");
+ }
+ assert!(!allowed_host(None));
+ assert!(allowed_url("https://github.com/Louis-CFM/coucou/releases/download/x/y.msi"));
+ assert!(!allowed_url("http://github.com/Louis-CFM/coucou"));
+ assert!(!allowed_url("file:///C:/Windows/notepad.exe"));
+ assert!(!allowed_url("not a url"));
+ }
+
+ #[test]
+ fn the_installer_follows_how_this_copy_was_installed() {
+ let local = Some(r"C:\Users\Ana\AppData\Local");
+ let pf = vec![r"C:\Program Files".to_string(), r"C:\Program Files (x86)".to_string()];
+ let kind = |exe: &str, uninst: bool| install_kind(exe, uninst, local, &pf);
+ assert_eq!(kind(r"C:\Users\Ana\AppData\Local\Coucou\coucou.exe", true), InstallKind::Setup);
+ assert_eq!(kind(r"c:\users\ana\appdata\local\COUCOU\Coucou.exe", true), InstallKind::Setup);
+ // A portable exe copied there: no NSIS uninstaller next to it.
+ assert_eq!(kind(r"C:\Users\Ana\AppData\Local\Coucou\coucou.exe", false), InstallKind::Manual);
+ assert_eq!(kind(r"C:\Program Files\Coucou\coucou.exe", false), InstallKind::Msi);
+ assert_eq!(kind(r"C:\Program Files (x86)\Coucou\coucou.exe", false), InstallKind::Msi);
+ // The portable exe, a build, a folder that only looks alike.
+ assert_eq!(kind(r"C:\Users\Ana\Downloads\coucou.exe", true), InstallKind::Manual);
+ assert_eq!(kind(r"C:\dev\coucou\windows\target\release\coucou.exe", false), InstallKind::Manual);
+ assert_eq!(kind(r"C:\Program Files\Coucou\bin\coucou.exe", false), InstallKind::Manual);
+ assert_eq!(kind(r"C:\Users\Ana\AppData\Local\Coucou\bin\coucou-hook.exe", true), InstallKind::Manual);
+ assert_eq!(kind("coucou.exe", true), InstallKind::Manual);
+ assert_eq!(install_kind(r"C:\Program Files\Coucou\coucou.exe", false, None, &[]), InstallKind::Manual);
+ assert_eq!(install_kind("/opt/Coucou/coucou", false, Some(""), &[String::new()]), InstallKind::Manual);
+ }
+
+ #[test]
+ fn the_asset_is_the_exact_installer_for_the_kind() {
+ let w = latest(&fixture(), "windows-v").unwrap();
+ assert_eq!(pick_asset(&w, InstallKind::Setup).unwrap().name, "Coucou-Windows-0.5.0-setup.exe");
+ assert_eq!(pick_asset(&w, InstallKind::Msi).unwrap().name, "Coucou-Windows-0.5.0.msi");
+ assert_eq!(pick_asset(&w, InstallKind::Manual), None);
+ // A look-alike name, or one served from elsewhere, is never picked.
+ let mut odd = w.clone();
+ odd.assets = vec![
+ Asset { name: "Coucou-Windows-setup.exe".into(), url: w.assets[0].url.clone(), size: 1, digest: None },
+ Asset { name: "Coucou-Windows-0.5.0.msi".into(), url: "https://evil.example.com/x.msi".into(), size: 1, digest: None },
+ ];
+ assert_eq!(pick_asset(&odd, InstallKind::Setup), None);
+ assert_eq!(pick_asset(&odd, InstallKind::Msi), None);
+ }
+
+ #[test]
+ fn digests_are_sha256_hex_only() {
+ let hex = "e8234a092e8fe1bf6eed0395e6db13052be8fe47413949c2b7fa368467342337";
+ assert_eq!(parse_digest(&format!("sha256:{hex}")).as_deref(), Some(hex));
+ assert_eq!(parse_digest(&format!("sha256:{}", hex.to_uppercase())).as_deref(), Some(hex));
+ assert_eq!(parse_digest(hex), None);
+ assert_eq!(parse_digest(&format!("sha512:{hex}")), None);
+ assert_eq!(parse_digest(&format!("sha256:{}", &hex[1..])), None);
+ assert_eq!(parse_digest(&format!("sha256:{}z", &hex[1..])), None);
+ assert_eq!(parse_digest(""), None);
+ }
+
+ #[test]
+ fn installers_run_with_tauris_update_flags() {
+ let file = Path::new(r"C:\Temp\coucou-update-1\Coucou-Windows-0.6.0-setup.exe");
+ let (program, args) = installer_command(InstallKind::Setup, file, Some(r"C:\Windows")).unwrap();
+ assert_eq!(program, file);
+ assert_eq!(args, ["/P", "/UPDATE", "/R"]);
+ let msi = Path::new(r"C:\Temp\coucou-update-1\Coucou-Windows-0.6.0.msi");
+ let (program, args) = installer_command(InstallKind::Msi, msi, Some(r"C:\Windows\")).unwrap();
+ assert_eq!(program, PathBuf::from(r"C:\Windows\System32\msiexec.exe"));
+ assert_eq!(args, ["/i", r"C:\Temp\coucou-update-1\Coucou-Windows-0.6.0.msi", "/passive", "AUTOLAUNCHAPP=True"]);
+ assert_eq!(installer_command(InstallKind::Msi, msi, None).unwrap().0, PathBuf::from("msiexec.exe"));
+ assert_eq!(installer_command(InstallKind::Manual, file, None), None);
+ }
+
+ #[test]
+ fn checks_every_six_hours_and_asks_again_after_a_day() {
+ let now = 1_000_000;
+ assert!(should_check(None, now));
+ assert!(!should_check(Some(now - CHECK_INTERVAL + 1), now));
+ assert!(should_check(Some(now - CHECK_INTERVAL), now));
+ assert!(should_check(Some(now + 60), now)); // clock set back
+ assert!(should_ask(None, now));
+ assert!(!should_ask(Some(now - 3600), now));
+ assert!(should_ask(Some(now - ASK_AGAIN), now));
+ }
+
+ #[test]
+ fn a_version_is_announced_once_a_day_and_a_newer_one_at_once() {
+ let now = 1_000_000;
+ assert!(should_announce("0.6.0", "0.5.0", None, None, now));
+ assert!(!should_announce("0.5.0", "0.5.0", None, None, now));
+ assert!(!should_announce("0.4.0", "0.5.0", None, None, now));
+ assert!(!should_announce("0.6.0", "0.5.0", Some("0.6.0"), Some(now - 3600), now));
+ assert!(should_announce("0.6.0", "0.5.0", Some("0.6.0"), Some(now - SNOOZE), now));
+ assert!(should_announce("0.6.1", "0.5.0", Some("0.6.0"), Some(now - 60), now));
+ assert!(should_announce("0.6.0", "0.5.0", Some("0.6.0"), Some(now + 600), now));
+ }
+
+ #[test]
+ fn prefs_load_from_older_or_partial_files() {
+ let p: Prefs = serde_json::from_str(r#"{"consent":true}"#).unwrap();
+ assert_eq!(p.consent, Some(true));
+ assert_eq!(p.last_check, None);
+ let p: Prefs = serde_json::from_str("{}").unwrap();
+ assert_eq!(p, Prefs::default());
+ let round: Prefs = serde_json::from_str(&serde_json::to_string(&Prefs {
+ consent: Some(false), last_check: Some(5), snoozed_version: Some("0.6.0".into()), snoozed_at: Some(6), asked_at: Some(7),
+ }).unwrap()).unwrap();
+ assert_eq!(round.snoozed_version.as_deref(), Some("0.6.0"));
+ assert_eq!(round.asked_at, Some(7));
+ }
+}
diff --git a/windows/src/core/bridge.ts b/windows/src/core/bridge.ts
index 2c56b8d8..4fd245cb 100644
--- a/windows/src/core/bridge.ts
+++ b/windows/src/core/bridge.ts
@@ -8,6 +8,7 @@ import { getCurrentWebview } from "@tauri-apps/api/webview";
import type { Settings } from "./state";
import type { RecapHistory, RecapPrefs } from "../recap/summary";
import type { SpotifyState } from "./spotify";
+import type { UpdateStatus } from "./update";
export const IS_TAURI =
typeof window !== "undefined" && "__TAURI_INTERNALS__" in window;
@@ -409,6 +410,23 @@ export const Bridge = {
spotifyOpen: () => call<boolean>("spotify_open"),
/** Whether there is a Spotify to launch (Settings). */
spotifyInstalled: () => call<boolean>("spotify_installed"),
+
+ // ── New versions (src-tauri/src/update.rs) ────────────────────────────────
+ updateStatus: () => call<UpdateStatus>("update_status"),
+ /** The island's question or Settings' toggle: may Coucou look at GitHub on its own? */
+ updateSetConsent: (allowed: boolean) => call<void>("update_set_consent", { allowed }),
+ /** "Check now": one look at GitHub, the toggle on or off. */
+ updateCheck: () => call<UpdateStatus>("update_check"),
+ /** The island opened the card Rust offered ("ask" or "announce"). */
+ updateShown: (kind: "ask" | "announce") => call<void>("update_shown", { kind }),
+ /** Settings → Install X: opens the island's update card. */
+ updateShow: () => call<void>("update_show"),
+ updateLater: () => call<void>("update_later"),
+ updateDismiss: () => call<void>("update_dismiss"),
+ /** "Update now" (Windows): download, check the SHA-256, run the installer, quit. */
+ updateInstall: () => call<void>("update_install"),
+ /** The release's page on github.com. */
+ updateOpenPage: () => call<void>("update_open_page"),
};
export type SpotifyAction = "playPause" | "next" | "previous" | "seek" | "shuffle" | "repeat" | "volume";
diff --git a/windows/src/core/layout.ts b/windows/src/core/layout.ts
index 9853591e..ba07e136 100644
--- a/windows/src/core/layout.ts
+++ b/windows/src/core/layout.ts
@@ -23,7 +23,8 @@ export type IslandViewName =
| "settings"
| "greeting"
| "recap"
- | "wardrobe";
+ | "wardrobe"
+ | "update";
export type BotStateName =
| "idle"
@@ -93,6 +94,8 @@ export const VIEW_LAYOUTS: Record<IslandViewName, ViewLayout> = {
// to the shared image.
recap: { height: 184, botX: 62, botY: null, botDiameter: 58, agentMode: "column" },
wardrobe: { height: 160, botX: 68, botY: null, botDiameter: 58, agentMode: "none" },
+ // New version: Mochi on the left, the version and Update now (Mac: .update).
+ update: { height: 160, botX: 62, botY: null, botDiameter: 58, agentMode: "none" },
};
// The upload views above are only the fallback geometry. Once a file is actually
diff --git a/windows/src/core/update.ts b/windows/src/core/update.ts
new file mode 100644
index 00000000..641faef3
--- /dev/null
+++ b/windows/src/core/update.ts
@@ -0,0 +1,78 @@
+// New versions of Coucou (src-tauri/src/update.rs): what Rust reports, and the
+// small rules the island applies to it. Pure, so tests/update.test.mjs checks them.
+
+import type { IslandMode, IslandViewName } from "./layout";
+
+export type UpdatePhase =
+ | { kind: "idle" }
+ | { kind: "downloading"; fraction: number }
+ | { kind: "verifying" }
+ | { kind: "installing" }
+ | { kind: "error"; message: string };
+
+export type UpdateCheck = "none" | "checking" | "upToDate" | "unreachable";
+
+export interface UpdateStatus {
+ /** null: not asked yet. true: Coucou may look at GitHub on its own. */
+ consent: boolean | null;
+ /** The version running. */
+ current: string;
+ /** The newest release of this platform, only while it is newer than `current`. */
+ latest: { version: string; headline: string | null; pageUrl: string } | null;
+ /** "Update now" installs it here (Windows, installed with setup.exe or the MSI). */
+ canInstall: boolean;
+ phase: UpdatePhase;
+ check: UpdateCheck;
+ platform: "windows" | "linux";
+}
+
+/** Rust's offers: the question, a version to announce, or the card asked for (tray, Check now). */
+export type UpdateOffer = "ask" | "announce" | "show";
+
+export const NO_UPDATE: UpdateStatus = {
+ consent: null,
+ current: "",
+ latest: null,
+ canInstall: false,
+ phase: { kind: "idle" },
+ check: "none",
+ platform: "windows",
+};
+
+export interface IslandNow {
+ paused: boolean;
+ /** A permission or a question waits for an answer. */
+ pending: boolean;
+ mode: IslandMode;
+ view: IslandViewName;
+}
+
+/**
+ * Whether the island may open its update card for `offer`. Never over a
+ * waiting permission or question. The question and an announcement come
+ * only when nothing else is open (Mac: islandFree); the card the user asked
+ * for (tray, Settings) may replace an ordinary view.
+ */
+export function mayOffer(offer: UpdateOffer, now: IslandNow): boolean {
+ if (now.pending) return false;
+ if (offer === "show") return true;
+ if (now.paused) return false;
+ return now.mode !== "expanded" || now.view === "update";
+}
+
+/** Download progress as a whole percentage, 0–100. */
+export function percent(fraction: number): number {
+ if (!Number.isFinite(fraction)) return 0;
+ return Math.round(Math.max(0, Math.min(1, fraction)) * 100);
+}
+
+/** The line under "Coucou X is out": the first "What's new" bullet, then "You have Y". */
+export function headerLine(headline: string | null | undefined, youHave: string): string {
+ const h = headline?.trim();
+ return h ? `${h} · ${youHave}` : youHave;
+}
+
+/** Download, check, install: the card shows progress and offers nothing else meanwhile. */
+export function isBusy(phase: UpdatePhase): boolean {
+ return phase.kind === "downloading" || phase.kind === "verifying" || phase.kind === "installing";
+}
diff --git a/windows/src/i18n/extra.json b/windows/src/i18n/extra.json
index c9ac1938..c9ba9338 100644
--- a/windows/src/i18n/extra.json
+++ b/windows/src/i18n/extra.json
@@ -4350,6 +4350,303 @@
"pt-BR": "O Coucou não conseguiu responder: verifique sua chave do Claude em Notch → Chat.",
"ru": "Coucou не смог ответить: проверьте ключ Claude в Notch → Чат.",
"id": "Coucou tidak bisa menjawab: periksa kunci Claude-mu di Notch → Obrolan."
+ },
+ "Get new versions from the island?": {
+ "zh-Hans": "在岛里获取新版本?",
+ "hi": "नए वर्ज़न आइलैंड में पाएँ?",
+ "es": "¿Recibir las nuevas versiones en la isla?",
+ "ar": "هل تريد تلقي الإصدارات الجديدة في الشريط؟",
+ "fr": "Recevoir les nouvelles versions dans l'île ?",
+ "bn": "নতুন সংস্করণ আইল্যান্ডে পেতে চান?",
+ "pt-BR": "Receber as novas versões na ilha?",
+ "ru": "Получать новые версии прямо в острове?",
+ "id": "Dapatkan versi baru dari pulau?"
+ },
+ "Mochi checks Coucou's releases on GitHub a few times a day and tells you when one is out. Nothing about you is sent.": {
+ "zh-Hans": "Mochi 每天会在 GitHub 上查看几次 Coucou 的版本,有新版本时告诉你。不会发送任何关于你的信息。",
+ "hi": "Mochi दिन में कुछ बार GitHub पर Coucou के रिलीज़ देखता है और नया आने पर बताता है। आपके बारे में कुछ नहीं भेजा जाता।",
+ "es": "Mochi revisa las versiones de Coucou en GitHub unas veces al día y te avisa cuando sale una. No se envía nada sobre ti.",
+ "ar": "يتحقق Mochi من إصدارات Coucou على GitHub بضع مرات يوميًا ويخبرك عند صدور إصدار جديد. لا يُرسَل أي شيء عنك.",
+ "fr": "Mochi regarde les versions de Coucou sur GitHub quelques fois par jour et te prévient quand il y en a une. Rien sur toi n’est envoyé.",
+ "bn": "Mochi দিনে কয়েকবার GitHub-এ Coucou-র রিলিজ দেখে এবং নতুন এলে জানায়। আপনার সম্পর্কে কিছুই পাঠানো হয় না।",
+ "pt-BR": "O Mochi verifica as versões do Coucou no GitHub algumas vezes por dia e avisa quando sai uma. Nada sobre você é enviado.",
+ "ru": "Mochi несколько раз в день проверяет релизы Coucou на GitHub и сообщает о новых. О вас ничего не отправляется.",
+ "id": "Mochi memeriksa rilis Coucou di GitHub beberapa kali sehari dan memberi tahu saat ada yang baru. Tidak ada data tentangmu yang dikirim."
+ },
+ "Yes, tell me": {
+ "zh-Hans": "好的,提醒我",
+ "hi": "हाँ, बताओ",
+ "es": "Sí, avísame",
+ "ar": "نعم، أخبرني",
+ "fr": "Oui, préviens-moi",
+ "bn": "হ্যাঁ, জানাও",
+ "pt-BR": "Sim, me avise",
+ "ru": "Да, сообщать",
+ "id": "Ya, beri tahu saya"
+ },
+ "No thanks": {
+ "zh-Hans": "不用了",
+ "hi": "नहीं, धन्यवाद",
+ "es": "No, gracias",
+ "ar": "لا، شكرًا",
+ "fr": "Non merci",
+ "bn": "না, ধন্যবাদ",
+ "pt-BR": "Não, obrigado",
+ "ru": "Нет, спасибо",
+ "id": "Tidak, terima kasih"
+ },
+ "Coucou {version} is out": {
+ "zh-Hans": "Coucou {version} 已发布",
+ "hi": "Coucou {version} आ गया है",
+ "es": "Ya salió Coucou {version}",
+ "ar": "صدر Coucou {version}",
+ "fr": "Coucou {version} est sorti",
+ "bn": "Coucou {version} এসে গেছে",
+ "pt-BR": "Saiu o Coucou {version}",
+ "ru": "Вышел Coucou {version}",
+ "id": "Coucou {version} sudah rilis"
+ },
+ "You have {version}": {
+ "zh-Hans": "当前版本 {version}",
+ "hi": "आपके पास {version} है",
+ "es": "Tienes la {version}",
+ "ar": "لديك {version}",
+ "fr": "Tu as la {version}",
+ "bn": "আপনার কাছে {version}",
+ "pt-BR": "Você tem a {version}",
+ "ru": "У вас {version}",
+ "id": "Kamu punya {version}"
+ },
+ "Update now": {
+ "zh-Hans": "立即更新",
+ "hi": "अभी अपडेट करें",
+ "es": "Actualizar ahora",
+ "ar": "التحديث الآن",
+ "fr": "Mettre à jour",
+ "bn": "এখনই আপডেট",
+ "pt-BR": "Atualizar agora",
+ "ru": "Обновить",
+ "id": "Perbarui sekarang"
+ },
+ "What's new": {
+ "zh-Hans": "新功能",
+ "hi": "क्या नया है",
+ "es": "Novedades",
+ "ar": "ما الجديد",
+ "fr": "Nouveautés",
+ "bn": "নতুন কী",
+ "pt-BR": "Novidades",
+ "ru": "Что нового",
+ "id": "Yang baru"
+ },
+ "Later": {
+ "zh-Hans": "稍后",
+ "hi": "बाद में",
+ "es": "Más tarde",
+ "ar": "لاحقًا",
+ "fr": "Plus tard",
+ "bn": "পরে",
+ "pt-BR": "Depois",
+ "ru": "Позже",
+ "id": "Nanti"
+ },
+ "Get it on GitHub": {
+ "zh-Hans": "前往 GitHub",
+ "hi": "GitHub खोलें",
+ "es": "Abrir GitHub",
+ "ar": "فتح GitHub",
+ "fr": "Ouvrir GitHub",
+ "bn": "GitHub খুলুন",
+ "pt-BR": "Abrir o GitHub",
+ "ru": "Открыть GitHub",
+ "id": "Buka GitHub"
+ },
+ "Downloading from GitHub… {percent} %": {
+ "zh-Hans": "正在从 GitHub 下载… {percent} %",
+ "hi": "GitHub से डाउनलोड हो रहा है… {percent} %",
+ "es": "Descargando desde GitHub… {percent} %",
+ "ar": "جارٍ التنزيل من GitHub… {percent} %",
+ "fr": "Téléchargement depuis GitHub… {percent} %",
+ "bn": "GitHub থেকে ডাউনলোড হচ্ছে… {percent} %",
+ "pt-BR": "Baixando do GitHub… {percent} %",
+ "ru": "Загрузка с GitHub… {percent} %",
+ "id": "Mengunduh dari GitHub… {percent} %"
+ },
+ "Installing… Coucou closes and comes back by itself.": {
+ "zh-Hans": "正在安装… Coucou 会关闭并自动重新打开。",
+ "hi": "इंस्टॉल हो रहा है… Coucou बंद होकर अपने आप फिर खुल जाएगा।",
+ "es": "Instalando… Coucou se cierra y vuelve a abrirse solo.",
+ "ar": "جارٍ التثبيت… سيُغلق Coucou ثم يعود من تلقاء نفسه.",
+ "fr": "Installation… Coucou se ferme et revient tout seul.",
+ "bn": "ইনস্টল হচ্ছে… Coucou বন্ধ হয়ে নিজে থেকেই আবার খুলবে।",
+ "pt-BR": "Instalando… O Coucou fecha e volta sozinho.",
+ "ru": "Установка… Coucou закроется и сам откроется снова.",
+ "id": "Memasang… Coucou akan menutup lalu terbuka lagi dengan sendirinya."
+ },
+ "The update didn't go through": {
+ "zh-Hans": "更新未完成",
+ "hi": "अपडेट पूरा नहीं हुआ",
+ "es": "La actualización no se completó",
+ "ar": "لم يكتمل التحديث",
+ "fr": "La mise à jour n’a pas abouti",
+ "bn": "আপডেট সম্পন্ন হয়নি",
+ "pt-BR": "A atualização não foi concluída",
+ "ru": "Обновление не удалось",
+ "id": "Pembaruan tidak berhasil"
+ },
+ "Coucou is up to date": {
+ "zh-Hans": "Coucou 已是最新版本",
+ "hi": "Coucou अप-टू-डेट है",
+ "es": "Coucou está actualizado",
+ "ar": "Coucou محدَّث",
+ "fr": "Coucou est à jour",
+ "bn": "Coucou হালনাগাদ আছে",
+ "pt-BR": "O Coucou está atualizado",
+ "ru": "Coucou обновлён",
+ "id": "Coucou sudah terbaru"
+ },
+ "Updates": {
+ "zh-Hans": "更新",
+ "hi": "अपडेट",
+ "es": "Actualizaciones",
+ "ar": "التحديثات",
+ "fr": "Mises à jour",
+ "bn": "আপডেট",
+ "pt-BR": "Atualizações",
+ "ru": "Обновления",
+ "id": "Pembaruan"
+ },
+ "Tell me when a new version is out": {
+ "zh-Hans": "有新版本时提醒我",
+ "hi": "नया वर्ज़न आने पर बताएँ",
+ "es": "Avisarme cuando salga una nueva versión",
+ "ar": "أخبرني عند صدور إصدار جديد",
+ "fr": "Me prévenir quand une nouvelle version sort",
+ "bn": "নতুন সংস্করণ এলে জানাও",
+ "pt-BR": "Me avisar quando sair uma nova versão",
+ "ru": "Сообщать о выходе новой версии",
+ "id": "Beri tahu saya saat ada versi baru"
+ },
+ "Check now": {
+ "zh-Hans": "立即检查",
+ "hi": "अभी जाँचें",
+ "es": "Comprobar ahora",
+ "ar": "التحقق الآن",
+ "fr": "Vérifier maintenant",
+ "bn": "এখনই দেখুন",
+ "pt-BR": "Verificar agora",
+ "ru": "Проверить сейчас",
+ "id": "Periksa sekarang"
+ },
+ "Install {version}": {
+ "zh-Hans": "安装 {version}",
+ "hi": "{version} इंस्टॉल करें",
+ "es": "Instalar la {version}",
+ "ar": "تثبيت {version}",
+ "fr": "Installer la {version}",
+ "bn": "{version} ইনস্টল করুন",
+ "pt-BR": "Instalar a {version}",
+ "ru": "Установить {version}",
+ "id": "Pasang {version}"
+ },
+ "Get {version} on GitHub": {
+ "zh-Hans": "在 GitHub 上获取 {version}",
+ "hi": "{version} GitHub से लें",
+ "es": "Descargar la {version} en GitHub",
+ "ar": "احصل على {version} من GitHub",
+ "fr": "Récupérer la {version} sur GitHub",
+ "bn": "GitHub থেকে {version} নিন",
+ "pt-BR": "Baixar a {version} no GitHub",
+ "ru": "Скачать {version} на GitHub",
+ "id": "Ambil {version} di GitHub"
+ },
+ "Couldn't reach GitHub": {
+ "zh-Hans": "无法连接 GitHub",
+ "hi": "GitHub से संपर्क नहीं हो सका",
+ "es": "No se pudo contactar con GitHub",
+ "ar": "تعذّر الوصول إلى GitHub",
+ "fr": "GitHub ne répond pas",
+ "bn": "GitHub-এ পৌঁছানো যায়নি",
+ "pt-BR": "Não foi possível acessar o GitHub",
+ "ru": "Не удалось связаться с GitHub",
+ "id": "Tidak dapat menghubungi GitHub"
+ },
+ "Coucou looks at its own releases on GitHub a few times a day. An update is installed only after your click, once its SHA-256 matches the one GitHub publishes.": {
+ "zh-Hans": "Coucou 每天会在 GitHub 上查看几次自己的版本。只有在你点击后,并且其 SHA-256 与 GitHub 公布的一致时,才会安装更新。",
+ "hi": "Coucou दिन में कुछ बार GitHub पर अपने रिलीज़ देखता है। अपडेट आपके क्लिक के बाद ही इंस्टॉल होता है, और तभी जब उसका SHA-256 GitHub के प्रकाशित SHA-256 से मेल खाए।",
+ "es": "Coucou revisa sus propias versiones en GitHub unas veces al día. Una actualización solo se instala después de tu clic, una vez que su SHA-256 coincide con el que publica GitHub.",
+ "ar": "يتحقق Coucou من إصداراته على GitHub بضع مرات يوميًا. لا يُثبَّت أي تحديث إلا بعد نقرتك، وبعد مطابقة SHA-256 الخاص به مع الذي ينشره GitHub.",
+ "fr": "Coucou regarde ses propres versions sur GitHub quelques fois par jour. Une mise à jour ne s'installe qu'après ton clic, une fois son SHA-256 vérifié avec celui que publie GitHub.",
+ "bn": "Coucou দিনে কয়েকবার GitHub-এ নিজের রিলিজ দেখে। আপনার ক্লিকের পরেই আপডেট ইনস্টল হয়, তাও কেবল যখন এর SHA-256 GitHub-এর প্রকাশিত SHA-256-এর সঙ্গে মেলে।",
+ "pt-BR": "O Coucou verifica as próprias versões no GitHub algumas vezes por dia. Uma atualização só é instalada depois do seu clique, quando o SHA-256 dela bate com o que o GitHub publica.",
+ "ru": "Coucou несколько раз в день проверяет свои релизы на GitHub. Обновление устанавливается только после вашего нажатия и только если его SHA-256 совпадает с тем, что публикует GitHub.",
+ "id": "Coucou memeriksa rilisnya sendiri di GitHub beberapa kali sehari. Pembaruan hanya dipasang setelah kamu mengeklik, dan setelah SHA-256-nya cocok dengan yang diterbitkan GitHub."
+ },
+ "Coucou looks at its own releases on GitHub a few times a day and tells you when one is out. Update it the way you installed it: AppImage, .deb, .rpm or your package manager.": {
+ "zh-Hans": "Coucou 每天会在 GitHub 上查看几次自己的版本,有新版本时告诉你。请用你安装它的方式更新:AppImage、.deb、.rpm 或你的包管理器。",
+ "hi": "Coucou दिन में कुछ बार GitHub पर अपने रिलीज़ देखता है और नया आने पर बताता है। इसे उसी तरह अपडेट करें जैसे आपने इंस्टॉल किया था: AppImage, .deb, .rpm या आपका पैकेज मैनेजर।",
+ "es": "Coucou revisa sus propias versiones en GitHub unas veces al día y te avisa cuando sale una. Actualízalo como lo instalaste: AppImage, .deb, .rpm o tu gestor de paquetes.",
+ "ar": "يتحقق Coucou من إصداراته على GitHub بضع مرات يوميًا ويخبرك عند صدور إصدار جديد. حدّثه بالطريقة التي ثبّته بها: AppImage أو ‎.deb أو ‎.rpm أو مدير الحزم لديك.",
+ "fr": "Coucou regarde ses propres versions sur GitHub quelques fois par jour et te prévient quand il y en a une. Mets-le à jour comme tu l'as installé : AppImage, .deb, .rpm ou ton gestionnaire de paquets.",
+ "bn": "Coucou দিনে কয়েকবার GitHub-এ নিজের রিলিজ দেখে এবং নতুন এলে জানায়। যেভাবে ইনস্টল করেছিলেন সেভাবেই আপডেট করুন: AppImage, .deb, .rpm বা আপনার প্যাকেজ ম্যানেজার।",
+ "pt-BR": "O Coucou verifica as próprias versões no GitHub algumas vezes por dia e avisa quando sai uma. Atualize do jeito que você instalou: AppImage, .deb, .rpm ou seu gerenciador de pacotes.",
+ "ru": "Coucou несколько раз в день проверяет свои релизы на GitHub и сообщает о новых. Обновляйте его так же, как устанавливали: AppImage, .deb, .rpm или менеджер пакетов.",
+ "id": "Coucou memeriksa rilisnya sendiri di GitHub beberapa kali sehari dan memberi tahu saat ada yang baru. Perbarui dengan cara kamu memasangnya: AppImage, .deb, .rpm, atau manajer paketmu."
+ },
+ "The download failed. Try again, or get the new version on GitHub.": {
+ "zh-Hans": "下载失败。请重试,或前往 GitHub 获取新版本。",
+ "hi": "डाउनलोड नहीं हुआ। फिर कोशिश करें, या नया वर्ज़न GitHub से लें।",
+ "es": "La descarga falló. Inténtalo de nuevo o descarga la nueva versión en GitHub.",
+ "ar": "فشل التنزيل. حاول مجددًا أو احصل على الإصدار الجديد من GitHub.",
+ "fr": "Le téléchargement a échoué. Réessaie, ou récupère la nouvelle version sur GitHub.",
+ "bn": "ডাউনলোড ব্যর্থ। আবার চেষ্টা করুন, অথবা নতুন সংস্করণটি GitHub থেকে নিন।",
+ "pt-BR": "O download falhou. Tente de novo ou baixe a nova versão no GitHub.",
+ "ru": "Загрузка не удалась. Попробуйте снова или скачайте новую версию на GitHub.",
+ "id": "Unduhan gagal. Coba lagi, atau ambil versi barunya di GitHub."
+ },
+ "GitHub gave no checksum for this download, so nothing was installed.": {
+ "zh-Hans": "GitHub 没有提供此下载的校验值,因此没有安装任何内容。",
+ "hi": "GitHub ने इस डाउनलोड का चेकसम नहीं दिया, इसलिए कुछ भी इंस्टॉल नहीं हुआ।",
+ "es": "GitHub no dio ninguna suma de verificación para esta descarga, así que no se instaló nada.",
+ "ar": "لم يقدّم GitHub مجموع تحقق لهذا التنزيل، لذا لم يُثبَّت شيء.",
+ "fr": "GitHub n'a donné aucune somme de contrôle pour ce téléchargement : rien n'a été installé.",
+ "bn": "GitHub এই ডাউনলোডের কোনো চেকসাম দেয়নি, তাই কিছুই ইনস্টল হয়নি।",
+ "pt-BR": "O GitHub não informou o checksum deste download, então nada foi instalado.",
+ "ru": "GitHub не указал контрольную сумму для этой загрузки, поэтому ничего не установлено.",
+ "id": "GitHub tidak memberi checksum untuk unduhan ini, jadi tidak ada yang dipasang."
+ },
+ "The download isn't the file GitHub published for this version, so nothing was installed.": {
+ "zh-Hans": "下载的文件不是 GitHub 为此版本发布的文件,因此没有安装任何内容。",
+ "hi": "डाउनलोड की गई फ़ाइल वह नहीं है जो GitHub ने इस वर्ज़न के लिए प्रकाशित की थी, इसलिए कुछ भी इंस्टॉल नहीं हुआ।",
+ "es": "La descarga no es el archivo que GitHub publicó para esta versión, así que no se instaló nada.",
+ "ar": "الملف الذي تم تنزيله ليس الملف الذي نشره GitHub لهذا الإصدار، لذا لم يُثبَّت شيء.",
+ "fr": "Le téléchargement n'est pas le fichier publié sur GitHub pour cette version : rien n'a été installé.",
+ "bn": "ডাউনলোড করা ফাইলটি এই সংস্করণের জন্য GitHub-এ প্রকাশিত ফাইল নয়, তাই কিছুই ইনস্টল হয়নি।",
+ "pt-BR": "O download não é o arquivo que o GitHub publicou para esta versão, então nada foi instalado.",
+ "ru": "Загруженный файл не совпадает с тем, что GitHub опубликовал для этой версии, поэтому ничего не установлено.",
+ "id": "Unduhan ini bukan file yang diterbitkan GitHub untuk versi ini, jadi tidak ada yang dipasang."
+ },
+ "Windows blocked the installer. Get the new version from its release page instead.": {
+ "zh-Hans": "Windows 阻止了安装程序。请改从发布页面获取新版本。",
+ "hi": "Windows ने इंस्टॉलर रोक दिया। इसके बजाय नया वर्ज़न रिलीज़ पेज से लें।",
+ "es": "Windows bloqueó el instalador. Descarga la nueva versión desde su página de lanzamiento.",
+ "ar": "حظر Windows أداة التثبيت. احصل على الإصدار الجديد من صفحة الإصدار بدلًا من ذلك.",
+ "fr": "Windows a bloqué l'installeur. Récupère plutôt la nouvelle version sur sa page de publication.",
+ "bn": "Windows ইনস্টলারটি আটকে দিয়েছে। এর বদলে রিলিজ পেজ থেকে নতুন সংস্করণটি নিন।",
+ "pt-BR": "O Windows bloqueou o instalador. Baixe a nova versão pela página de lançamento.",
+ "ru": "Windows заблокировала установщик. Скачайте новую версию со страницы релиза.",
+ "id": "Windows memblokir pemasangnya. Ambil versi barunya dari halaman rilis saja."
+ },
+ "Update Coucou to {version}…": {
+ "zh-Hans": "将 Coucou 更新到 {version}…",
+ "hi": "Coucou को {version} पर अपडेट करें…",
+ "es": "Actualizar Coucou a la {version}…",
+ "ar": "تحديث Coucou إلى {version}…",
+ "fr": "Mettre à jour Coucou vers la {version}…",
+ "bn": "Coucou {version}-এ আপডেট করুন…",
+ "pt-BR": "Atualizar o Coucou para a {version}…",
+ "ru": "Обновить Coucou до {version}…",
+ "id": "Perbarui Coucou ke {version}…"
}
}
}
diff --git a/windows/src/island/update.ts b/windows/src/island/update.ts
new file mode 100644
index 00000000..bd8d5cd9
--- /dev/null
+++ b/windows/src/island/update.ts
@@ -0,0 +1,95 @@
+// New versions in the island — port of MacUpdater's card side. Rust
+// (src-tauri/src/update.rs) does the looking, the downloading and the
+// schedule; it offers the card ("update-offer") and the island opens it only
+// when nothing else waits there, then says so (`update_shown`), which starts
+// the day before the same question or version comes back.
+
+import { Bridge, onEvent } from "../core/bridge";
+import type { BotEmoteName, IslandViewName } from "../core/layout";
+import { Sound } from "../core/sound";
+import { State } from "../core/state";
+import { NO_UPDATE, mayOffer, type UpdateOffer, type UpdateStatus } from "../core/update";
+
+/** What the update card needs from the island. */
+export interface UpdateHost {
+ alert(view: IslandViewName): void;
+ collapse(): void;
+ emote(name: BotEmoteName): void;
+}
+
+class UpdateController {
+ status: UpdateStatus = { ...NO_UPDATE };
+ /** The card asks "Get new versions from the island?". */
+ asking = false;
+ private host: UpdateHost | null = null;
+
+ async register(host: UpdateHost) {
+ this.host = host;
+ const status = await Bridge.updateStatus();
+ if (status) this.status = status;
+ await onEvent<UpdateStatus>("update-status", (s) => {
+ this.status = s;
+ State.notify();
+ });
+ await onEvent<UpdateOffer>("update-offer", (offer) => this.offer(offer));
+ }
+
+ offer(offer: UpdateOffer) {
+ const host = this.host;
+ if (!host) return;
+ const now = {
+ paused: State.paused,
+ pending: State.pendingApproval != null,
+ mode: State.mode,
+ view: State.view,
+ };
+ if (!mayOffer(offer, now)) return;
+ if (offer === "ask") {
+ this.asking = true;
+ void Bridge.updateShown("ask");
+ host.alert("update");
+ return;
+ }
+ // Rust offers only a version that is out; the status may just be a moment behind.
+ if (!this.status.latest && offer === "announce") return;
+ this.asking = false;
+ host.alert("update");
+ if (offer === "announce") {
+ void Bridge.updateShown("announce");
+ host.emote("surprised");
+ Sound.play("peek");
+ }
+ }
+
+ /** Tray → "Update Coucou to X…", Settings → Install X. */
+ show() {
+ this.offer("show");
+ }
+
+ answer(yes: boolean) {
+ this.asking = false;
+ void Bridge.updateSetConsent(yes);
+ this.host?.collapse();
+ }
+
+ install() {
+ void Bridge.updateInstall();
+ }
+
+ openPage() {
+ void Bridge.updateOpenPage();
+ }
+
+ later() {
+ void Bridge.updateLater();
+ this.host?.collapse();
+ }
+
+ /** OK on a failed update or on "up to date". */
+ dismiss() {
+ void Bridge.updateDismiss();
+ this.host?.collapse();
+ }
+}
+
+export const Updates = new UpdateController();
diff --git a/windows/src/main.ts b/windows/src/main.ts
index a2db5b28..b3b4ceeb 100644
--- a/windows/src/main.ts
+++ b/windows/src/main.ts
@@ -13,6 +13,7 @@ import { registerVoiceHandlers } from "./island/voice";
import { applySpotify, registerSpotifyHandlers } from "./island/spotify";
import { SPOTIFY_ID } from "./core/spotify";
import { Recap } from "./recap/recap";
+import { Updates } from "./island/update";
import { onLanguageChange, resolveLanguage, setLanguage, systemLanguages } from "./i18n/i18n";
/** Shows the language Settings asks for ("" = the system's, when Coucou has it). */
@@ -84,6 +85,11 @@ async function main() {
setPaused(false);
island.alert("wardrobe");
break;
+ // "Update Coucou to X…", only in the menu while a new version is out.
+ case "update":
+ setPaused(false);
+ Updates.show();
+ break;
case "pause":
setPaused(!State.paused);
if (State.paused) island.fsm.forceHidden();
@@ -141,6 +147,8 @@ async function main() {
registerShortcutHandlers(island, () => setPaused(false));
registerVoiceHandlers();
registerSpotifyHandlers(island);
+ // New versions: Rust offers the card, the island opens it when nothing else waits.
+ await Updates.register(island);
// Rust may have read Spotify before this page listened: ask once.
if (State.settings.activeIntegrations.includes(SPOTIFY_ID)) {
void Bridge.spotifyRefresh().then((s) => s && applySpotify(island, s));
diff --git a/windows/src/settings/main.ts b/windows/src/settings/main.ts
index 437363f0..e4acfb6c 100644
--- a/windows/src/settings/main.ts
+++ b/windows/src/settings/main.ts
@@ -11,6 +11,7 @@ import {
recordPress, type Binding,
} from "../core/shortcuts";
import { DEFAULT_SETTINGS, type Settings } from "../core/state";
+import type { UpdateStatus } from "../core/update";
import { SOUND_NAMES } from "../core/sound";
import {
MAX_DECLARED, PILL_CATEGORIES, availablePills, chooseMainPill, isComingSoon, mainPillChoices,
@@ -21,6 +22,7 @@ import { startHub, type PageId } from "../hub/shell";
import { FLOW_PAGE_RENDERERS } from "../hub/pages";
import { agentsSection } from "./agents";
import { phoneSection } from "./phone";
+import { updateRows, updatesListener } from "./updates";
import { colorDot } from "./colors";
import { renderDiff, statusDot } from "./parts";
import {
@@ -972,6 +974,7 @@ function generalSection(): HTMLElement {
toggle(settings.autostart, (v) => { settings.autostart = v; void save(); }),
),
...recapRows(),
+ ...updateRows(toggle, version),
languageRow(),
);
}
@@ -1297,6 +1300,7 @@ async function main() {
});
void onEvent<ShortcutsReport>("shortcuts-status", (fresh) => shortcutsListener?.report(fresh));
+ void onEvent<UpdateStatus>("update-status", (fresh) => updatesListener?.(fresh));
void onEvent<Settings>("settings-changed", (s) => {
const before = `${settings.chatProvider}|${settings.ollamaUrl}|${settings.lmstudioUrl}|${settings.customUrl}`;
settings = { ...settings, ...s };
diff --git a/windows/src/settings/updates.ts b/windows/src/settings/updates.ts
new file mode 100644
index 00000000..f05e0b29
--- /dev/null
+++ b/windows/src/settings/updates.ts
@@ -0,0 +1,75 @@
+// Settings → General → Updates — port of UpdateSettingsSection
+// (MacUpdateViews.swift): the toggle, what it does, "Check now" (a click, so
+// it works with the toggle off), and "Install X" once a new version is out.
+
+import { Bridge } from "../core/bridge";
+import { NO_UPDATE, isBusy, type UpdateStatus } from "../core/update";
+import { h } from "../views/dom";
+import { t } from "../i18n/i18n";
+
+type Toggle = (on: boolean, onChange: (v: boolean) => void) => HTMLElement;
+
+/** The rows on screen, told about "update-status" (listened to once in main.ts). */
+export let updatesListener: ((status: UpdateStatus) => void) | null = null;
+
+export function updateRows(toggle: Toggle, version: string): HTMLElement[] {
+ let status: UpdateStatus = { ...NO_UPDATE, current: version };
+ const sw = toggle(false, (on) => void Bridge.updateSetConsent(on));
+ const install = h("button", {
+ onclick: () => void (status.canInstall ? Bridge.updateShow() : Bridge.updateOpenPage()),
+ }) as HTMLButtonElement;
+ const check = h("button", {
+ text: t("Check now"),
+ onclick: async () => {
+ check.disabled = true;
+ feedback.textContent = "";
+ const fresh = await Bridge.updateCheck();
+ if (fresh) status = fresh;
+ draw();
+ },
+ }) as HTMLButtonElement;
+ const feedback = h("span", { class: "hint" });
+ const footer = h("span", { class: "hint", style: "flex:1 1 0;min-width:0" });
+ const current = h("span", { class: "hint" });
+
+ function draw() {
+ sw.classList.toggle("on", status.consent === true);
+ sw.setAttribute("aria-pressed", String(status.consent === true));
+ const r = status.latest;
+ install.style.display = r ? "" : "none";
+ if (r) {
+ install.textContent = status.canInstall
+ ? t("Install {version}", { version: r.version })
+ : t("Get {version} on GitHub", { version: r.version });
+ }
+ check.disabled = status.check === "checking" || isBusy(status.phase);
+ feedback.textContent =
+ status.check === "upToDate" ? t("Coucou is up to date")
+ : status.check === "unreachable" ? t("Couldn't reach GitHub")
+ : "";
+ footer.textContent = status.platform === "linux"
+ ? t("Coucou looks at its own releases on GitHub a few times a day and tells you when one is out. Update it the way you installed it: AppImage, .deb, .rpm or your package manager.")
+ : t("Coucou looks at its own releases on GitHub a few times a day. An update is installed only after your click, once its SHA-256 matches the one GitHub publishes.");
+ current.textContent = t("You have {version}", { version: status.current || version });
+ }
+
+ updatesListener = (fresh) => {
+ status = fresh;
+ draw();
+ };
+ void Bridge.updateStatus().then((fresh) => {
+ if (fresh) updatesListener?.(fresh);
+ });
+ draw();
+
+ return [
+ h("div", { class: "row" },
+ h("label", { text: t("Updates") }),
+ sw,
+ h("span", { class: "hint", text: t("Tell me when a new version is out") }),
+ ),
+ h("div", { class: "row" }, h("label", {}), install, check, feedback),
+ h("div", { class: "row" }, h("label", {}), footer),
+ h("div", { class: "row" }, h("label", {}), current),
+ ];
+}
diff --git a/windows/src/style.css b/windows/src/style.css
index 1a56c61b..bdd12274 100644
--- a/windows/src/style.css
+++ b/windows/src/style.css
@@ -2331,6 +2331,33 @@ input[type="range"]::-webkit-slider-thumb {
pointer-events: none;
}
+/* ── New version (views/update.ts) — UpdateCardView on macOS ────────────────── */
+
+.update-line {
+ font-size: 12px;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+
+/* The download's progress: the Mac's green, 260 px at most. */
+.update-bar {
+ width: 100%;
+ max-width: 260px;
+ height: 4px;
+ border-radius: 999px;
+ background: rgba(255, 255, 255, 0.12);
+ overflow: hidden;
+}
+
+.update-bar .fill {
+ height: 100%;
+ width: 0;
+ background: #34d399;
+ transition: width 0.25s linear;
+}
+
/* ── Spotify: the pill's controls and the now-playing card ──────────────────
SpotifyPill, MusicControlButton and SpotifyCardView (SpotifyViews.swift,
NowPlayingViews.swift): sizes and colours are the Mac's. */
diff --git a/windows/src/views/update.ts b/windows/src/views/update.ts
new file mode 100644
index 00000000..e851100d
--- /dev/null
+++ b/windows/src/views/update.ts
@@ -0,0 +1,112 @@
+// The update card — port of UpdateCardView (MacUpdateViews.swift): the
+// one-time question, "Coucou X is out" with Update now · What's new · Later,
+// then the download's progress, or what went wrong. Same green wash and the
+// same left inset as the other cards, Mochi on the left.
+
+import { h, clear } from "./dom";
+import { washRGBA } from "../core/layout";
+import { headerLine, percent } from "../core/update";
+import { Updates } from "../island/update";
+import type { ViewHost } from "./views";
+import { language, t } from "../i18n/i18n";
+
+function btn(label: string, kind: "primary" | "secondary", onClick: () => void): HTMLButtonElement {
+ return h("button", { class: `btn ${kind}`, onclick: onClick }, h("span", { text: label }));
+}
+
+export function buildUpdate(): ViewHost {
+ const title = h("div", { class: "title one-line" });
+ const line = h("div", { class: "sub update-line" });
+ const fill = h("div", { class: "fill" });
+ const bar = h("div", { class: "update-bar" }, fill);
+ const row = h("div", { class: "actions" });
+ const stack = h("div", { class: "stack" }, title, line, bar, row);
+ stack.style.padding = "4px 16px 4px 116px";
+ const card = h("div", { class: "card wash" }, stack);
+ card.style.setProperty("--wash", washRGBA("green"));
+ const el = h("div", { class: "view" }, card);
+
+ // The buttons are only rebuilt when what they offer changes: rebuilding them
+ // between a mouse-down and a mouse-up would swallow the click.
+ let rowKey = "";
+ function buttons(state: string, make: () => HTMLElement[]) {
+ const key = `${state}~${language()}`;
+ if (key === rowKey) return;
+ rowKey = key;
+ clear(row);
+ row.append(...make());
+ }
+
+ return {
+ el,
+ sync() {
+ const s = Updates.status;
+ const r = s.latest;
+ const youHave = t("You have {version}", { version: s.current });
+ bar.style.display = "none";
+ title.title = "";
+
+ if (Updates.asking) {
+ title.textContent = t("Get new versions from the island?");
+ line.textContent = t("Mochi checks Coucou's releases on GitHub a few times a day and tells you when one is out. Nothing about you is sent.");
+ buttons("ask", () => [
+ btn(t("Yes, tell me"), "primary", () => Updates.answer(true)),
+ btn(t("No thanks"), "secondary", () => Updates.answer(false)),
+ ]);
+ return;
+ }
+
+ const phase = s.phase;
+ if (phase.kind === "error") {
+ title.textContent = t("The update didn't go through");
+ line.textContent = phase.message;
+ buttons("error", () => [
+ btn(t("Get it on GitHub"), "primary", () => Updates.openPage()),
+ btn(t("OK"), "secondary", () => Updates.dismiss()),
+ ]);
+ return;
+ }
+
+ if (!r) {
+ title.textContent = t("Coucou is up to date");
+ line.textContent = youHave;
+ buttons("none", () => [btn(t("OK"), "secondary", () => Updates.dismiss())]);
+ return;
+ }
+
+ title.textContent = t("Coucou {version} is out", { version: r.version });
+ title.title = title.textContent;
+ switch (phase.kind) {
+ case "downloading": {
+ bar.style.display = "";
+ fill.style.width = `${percent(phase.fraction)}%`;
+ line.textContent = t("Downloading from GitHub… {percent} %", { percent: percent(phase.fraction) });
+ buttons("busy", () => []);
+ return;
+ }
+ case "verifying":
+ line.textContent = t("Checking the download…");
+ buttons("busy", () => []);
+ return;
+ case "installing":
+ line.textContent = t("Installing… Coucou closes and comes back by itself.");
+ buttons("busy", () => []);
+ return;
+ case "idle":
+ line.textContent = headerLine(r.headline, youHave);
+ // The portable exe and Linux update the way they were installed: the release page.
+ buttons(s.canInstall ? "install" : "page", () => s.canInstall
+ ? [
+ btn(t("Update now"), "primary", () => Updates.install()),
+ btn(t("What's new"), "secondary", () => Updates.openPage()),
+ btn(t("Later"), "secondary", () => Updates.later()),
+ ]
+ : [
+ btn(t("Get it on GitHub"), "primary", () => Updates.openPage()),
+ btn(t("Later"), "secondary", () => Updates.later()),
+ ]);
+ return;
+ }
+ },
+ };
+}
diff --git a/windows/src/views/views.ts b/windows/src/views/views.ts
index 5f866dd6..067825ff 100644
--- a/windows/src/views/views.ts
+++ b/windows/src/views/views.ts
@@ -21,6 +21,7 @@ import { lastTextStep } from "../core/diff";
import { Bridge } from "../core/bridge";
import { buildRecap } from "./recap";
import { buildWardrobe } from "./wardrobe";
+import { buildUpdate } from "./update";
import { buildSpotifyCard, buildSpotifyPill, type SpotifyPillHost } from "./spotify";
import { SPOTIFY_ID } from "../core/spotify";
import type { Outfit, OutfitSelection } from "../mochi/wardrobe";
@@ -821,6 +822,7 @@ export function buildViews(
map.set("choose", buildChoose(actions));
map.set("recap", buildRecap(actions));
map.set("wardrobe", buildWardrobe(actions));
+ map.set("update", buildUpdate());
// Not in the Windows v1: sending a file by email, window attach + web result.
map.set("mail", buildPlaceholder(tl("Sending by email isn't in this version."), ""));
map.set("searching", buildPlaceholder(tl("Claude is searching…"), ""));
diff --git a/windows/tests/update.test.mjs b/windows/tests/update.test.mjs
new file mode 100644
index 00000000..dd4f5a05
--- /dev/null
+++ b/windows/tests/update.test.mjs
@@ -0,0 +1,142 @@
+// New versions in the island (src/core/update.ts, src/island/update.ts): when
+// the card may open, what it says, and what goes back to Rust — through the
+// real bridge, Rust's answers stubbed.
+
+import { afterEach, beforeEach, test } from "node:test";
+import assert from "node:assert/strict";
+import { calls, emit, internals, sent } from "./tauri.mjs";
+import { State } from "../src/core/state.ts";
+import { NO_UPDATE, headerLine, isBusy, mayOffer, percent } from "../src/core/update.ts";
+import { Updates } from "../src/island/update.ts";
+
+const free = { paused: false, pending: false, mode: "hidden", view: "overview" };
+
+test("the question and an announcement come only when the island is free", () => {
+ for (const offer of ["ask", "announce"]) {
+ assert.equal(mayOffer(offer, free), true);
+ assert.equal(mayOffer(offer, { ...free, mode: "compact" }), true);
+ assert.equal(mayOffer(offer, { ...free, mode: "expanded", view: "update" }), true);
+ assert.equal(mayOffer(offer, { ...free, mode: "expanded", view: "prompt" }), false, `${offer} over the chat`);
+ assert.equal(mayOffer(offer, { ...free, mode: "expanded", view: "overview" }), false);
+ assert.equal(mayOffer(offer, { ...free, pending: true }), false, `${offer} over an approval`);
+ assert.equal(mayOffer(offer, { ...free, paused: true }), false);
+ }
+});
+
+test("the card asked for (tray, Settings) opens over any view but never over an approval", () => {
+ assert.equal(mayOffer("show", { ...free, mode: "expanded", view: "prompt" }), true);
+ assert.equal(mayOffer("show", { ...free, paused: true }), true);
+ assert.equal(mayOffer("show", { ...free, mode: "expanded", view: "question", pending: true }), false);
+});
+
+test("progress, the header line and the busy phases", () => {
+ assert.equal(percent(0), 0);
+ assert.equal(percent(0.424), 42);
+ assert.equal(percent(1.7), 100);
+ assert.equal(percent(-1), 0);
+ assert.equal(percent(Number.NaN), 0);
+ assert.equal(headerLine("WhatsApp in one click", "You have 0.5.0"), "WhatsApp in one click · You have 0.5.0");
+ assert.equal(headerLine(null, "You have 0.5.0"), "You have 0.5.0");
+ assert.equal(headerLine(" ", "You have 0.5.0"), "You have 0.5.0");
+ assert.equal(isBusy({ kind: "downloading", fraction: 0.1 }), true);
+ assert.equal(isBusy({ kind: "verifying" }), true);
+ assert.equal(isBusy({ kind: "installing" }), true);
+ assert.equal(isBusy({ kind: "idle" }), false);
+ assert.equal(isBusy({ kind: "error", message: "x" }), false);
+});
+
+// ── The controller ────────────────────────────────────────────────────────────
+
+const original = internals.invoke;
+const OUT = {
+ ...NO_UPDATE,
+ consent: true,
+ current: "0.5.0",
+ latest: { version: "0.6.0", headline: "Flow dictation", pageUrl: "https://github.com/Louis-CFM/coucou/releases/tag/windows-v0.6.0" },
+ canInstall: true,
+};
+let shown;
+let emotes;
+let collapsed;
+const host = {
+ alert: (view) => shown.push(view),
+ collapse: () => collapsed++,
+ emote: (name) => emotes.push(name),
+};
+
+beforeEach(async () => {
+ calls.length = 0;
+ shown = [];
+ emotes = [];
+ collapsed = 0;
+ internals.invoke = async (cmd, args) => {
+ if (cmd === "update_status") return { ...NO_UPDATE, current: "0.5.0" };
+ return original(cmd, args);
+ };
+ State.mode = "hidden";
+ State.view = "overview";
+ State.paused = false;
+ State.pendingApproval = null;
+ await Updates.register(host);
+});
+
+afterEach(() => {
+ internals.invoke = original;
+});
+
+test("the question opens the card once Rust offers it, and says it was shown", () => {
+ emit("update-offer", "ask");
+ assert.deepEqual(shown, ["update"]);
+ assert.equal(Updates.asking, true);
+ assert.deepEqual(sent("update_shown"), [{ kind: "ask" }]);
+ Updates.answer(true);
+ assert.equal(Updates.asking, false);
+ assert.deepEqual(sent("update_set_consent"), [{ allowed: true }]);
+ assert.equal(collapsed, 1);
+});
+
+test("nothing opens over a waiting permission, and nothing is marked shown", () => {
+ State.pendingApproval = { requestId: "r1", tool: "Bash", command: "ls", pillId: "integration_claude" };
+ emit("update-status", OUT);
+ emit("update-offer", "ask");
+ emit("update-offer", "announce");
+ emit("update-offer", "show");
+ assert.deepEqual(shown, []);
+ assert.deepEqual(sent("update_shown"), []);
+});
+
+test("an announcement opens the card with Mochi surprised; Later snoozes it", () => {
+ emit("update-status", OUT);
+ assert.equal(Updates.status.latest.version, "0.6.0");
+ emit("update-offer", "announce");
+ assert.deepEqual(shown, ["update"]);
+ assert.deepEqual(emotes, ["surprised"]);
+ assert.deepEqual(sent("update_shown"), [{ kind: "announce" }]);
+ Updates.later();
+ assert.equal(sent("update_later").length, 1);
+ assert.equal(collapsed, 1);
+});
+
+test("an announcement with no version known yet, or while the chat is open, waits", () => {
+ emit("update-status", { ...OUT, latest: null });
+ emit("update-offer", "announce");
+ emit("update-status", OUT);
+ State.mode = "expanded";
+ State.view = "prompt";
+ emit("update-offer", "announce");
+ assert.deepEqual(shown, []);
+});
+
+test("the tray's Update Coucou to X… opens the card without marking anything", () => {
+ emit("update-status", OUT);
+ State.mode = "expanded";
+ State.view = "prompt";
+ Updates.show();
+ assert.deepEqual(shown, ["update"]);
+ assert.deepEqual(emotes, []);
+ assert.deepEqual(sent("update_shown"), []);
+ Updates.install();
+ Updates.openPage();
+ assert.equal(sent("update_install").length, 1);
+ assert.equal(sent("update_open_page").length, 1);
+});