A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.
Swift ai-agentsanthropicantigravityclaudeclaude-codecodexcursordynamic-islandgemini-cliiosiphonlinuxmacosmacos-appmenubar-appnotchopen-sourceswiftswiftuiwindows
Merge port/weekly-recap: weekly recap history, card, shared image and settings
Claude7be8f59b5d78
diff --cc windows/README.mdindex 1bc5870a,02f7ffac..331e7d39--- a/windows/README.md+++ b/windows/README.md@@@ -44,74 -44,13 +44,74 @@@ installs for the current user only —| Click Mochi | It gets annoyed. Three times in a row and it goes dizzy || Rest the pointer on Mochi for two seconds | Hearts || Drag a file onto the island | Mochi turns into a box, swallows it, then offers to answer questions about it |+| 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 |- | Tray icon | Open, Settings…, Pause, Quit |+ | Tray icon | Open, Weekly recap, Settings…, Pause, Quit |+| `Ctrl+Alt+Space` | Opens the chat, from any app |+| `Ctrl+Alt+A` | Jumps to the waiting permission or question |- | `Ctrl+Alt+T` | Opens the session's folder in VS Code ("Open terminal") |++| `Ctrl+Alt+T` | Brings the session's window forward ("Open terminal") |+| `Ctrl+Alt+→` / `Ctrl+Alt+←` | Next / previous pill |+| `Ctrl+Alt+S` | Mutes or unmutes Mochi |+| `Ctrl+Alt+G` | Opens the wardrobe |+| `Ctrl+Alt+N` | Opens and closes the island (off until you turn it on) |+| In the open island: `Ctrl+→` `Ctrl+←`, `Ctrl+1`–`Ctrl+9` | Switch pills |+| In the open island: `Ctrl+Enter`, `Ctrl+K` | Send, start a new chat |+| In the open island: `Ctrl+,`, `Ctrl+P` | Settings, keep the island open |++### Keyboard shortcuts++Every global shortcut can be changed or turned off in **Settings… → Shortcuts**:+click it and press the new keys. A combination another app already holds is+flagged *In use*, and two Coucou shortcuts on the same keys are flagged *Used+twice*. While you record a new one, Coucou lets go of its own so the keys reach+the recorder.++The defaults are not the Mac's `⌃⌥` letters. On Windows, `Ctrl+Alt` is `AltGr`,+so a global `Ctrl+Alt+E` would swallow every `€` typed on a French or German+keyboard. The defaults were checked against the AltGr layer of the French,+German, Spanish, Italian, Portuguese and Brazilian (ABNT2) layouts — that is why+pill switching uses the arrows rather than `[` `]`, and mute is `S` rather than+`M` (`AltGr+M` is `µ` in German). On top of that, Coucou asks Windows what each+`Ctrl+Alt` combination types on the layouts you have installed and leaves any+that types a character unregistered, flagged *Types “ą”* in Settings: Polish,+for one, puts `ą` on `AltGr+A` and `ś` on `AltGr+S`. The recorder refuses such+a combination too.++Older Intel graphics drivers rotate the screen on `Ctrl+Alt+←` / `→`; if yours+still does, those two show up as *In use*.Everything else happens on its own: a Claude Code permission request opens the-island with **Deny / Allow**, a finished session shows what it did, and+island with **Deny / Allow**, a question from Claude Code shows its options to+pick from, a finished session shows what it did, andyour integrations sit in the coloured pills next to Mochi.+A permission card or a question stays until you answer it: the mouse leaving+never folds it, it comes up even when the island is already open or another+pill is in front, and the pill you were on comes back once you answer. To keep+it for later, fold it with the **⌃** in its corner (or `Esc` in the island): the+island shrinks to its compact size and stays on screen, nothing is answered, and+opening it again shows the card. **Open terminal** brings the window the session+runs in to the front.++**Live diff.** Every file Claude edits (Edit, MultiEdit, Write) shows up in the+session ticker with its **+N −M** lines; click it for the diff. Same limits as the+Mac: past 200 KB or 4 000 lines only the counts are kept, at most 50 diffs per+session, and they are forgotten an hour after the last edit or when the session+ends. When Claude finishes, the card keeps the first paragraph of its final+answer on one line, still, until the next prompt.++## Your pills++**Settings… → Active pills** lists the tools you use, from the same catalog as+the Mac app. Pick your **main tool** — VS Code, Cursor, Codex or Antigravity —+which is always there and doesn't take a slot, then declare up to four more:+agents (Gemini CLI, Copilot CLI, Muse Code, OpenCode, Amp, Hermes, Claude+Desktop), the chat providers (Anthropic, Google AI, OpenAI, Ollama, LM Studio),+and the services under **Integrations**. A pill fed by hooks says whether its+hooks are installed, never asks for a key; a local model server's pill says+whether the chat is connected to it. A session on a pill you didn't+declare still shows up, for as long as it runs.+## Claude Code<img src="screenshots/settings.png" width="562" alt="The settings window">@@@ -129,29 -68,24 +129,47 @@@ in time, Coucou stays quiet and ClaudeIt works from any terminal — Windows Terminal, PowerShell, VS Code, Git Bash.+### Plan usage++As on the Mac, the island's header can show your plan limits: a small pill+("Claude 73%", green below 50 %, orange up to 80 %, red above) for the 5-hour and+weekly Claude limits, and another for Codex. Click one for the details and the+reset times. Both are off by default; turn them on in **Settings… → Plan usage**.++- **Claude** (Pro and Max plans): the numbers come from Claude Code's own status+ line. **Show in notch** first shows you the diff of the `statusLine` change in+ `%USERPROFILE%\.claude\settings.json`, takes a dated backup and writes only+ after your click, with the same writer as the hooks: the status line becomes `coucou-hook --statusline`, which+ passes only the limits on (300 ms at most) and runs the status line you had+ before — kept in `statusline-previous.json` next to the relay — with the same+ input, printing what it prints. On Windows that one runs through Git Bash, as+ Claude Code runs it (`CLAUDE_CODE_GIT_BASH_PATH`, then the Git for Windows that+ `git.exe` on `PATH` belongs to, then the usual install folders); it gets 10 s+ and 64 KB of output. **Uninstall relay** puts your status line back. The+ numbers arrive with Claude Code's replies.+- **Codex**: nothing is installed. When the pill shows (or is clicked, at most+ once a minute) Coucou starts `codex app-server` and asks it+ `account/rateLimits/read`, as Codex's `/status` does, then stops it (15 s at+ most, never while paused). Codex must be signed in with ChatGPT.++ ## Weekly recap++ On Monday from 8 am, the first time Coucou starts, an agent starts working or+ you wake the island, a card sums up the past week: time spent, sessions, files+ and lines changed, commands run, permissions and questions, your top agent,+ top project, busiest day and longest session. **Tray → Weekly recap** opens it+ any day.++ **Share image** turns it into a 1080 × 1920 picture with Mochi. **Save image**+ writes it to your Pictures folder (Downloads if there is none) as+ `Coucou weekly recap YYYY-MM-DD.png`, never over an existing file; **Copy** puts+ it on the clipboard. **Hide project names** leaves the project out of the image.++ The history is `recap.json` next to the log, a 12-week rolling window: counts,+ the agent and the project folder's name — never a command, a file path, file+ contents or a prompt. It never leaves your machine. **Settings → General →+ Weekly recap** turns it off or clears it.+## Chat and keys**Settings… → Claude** takes your Anthropic API key. Keys live in the **Windows@@@ -330,52 -180,24 +351,67 @@@ own windowthe top edge instead of hiding in a notch.- Permission approval works from **any** terminal; the Mac build only listens toVS Code sessions.-- Not in this version: sending a file by email, dragging Mochi onto a window to- attach it as context, and jumping to a specific terminal window — "Open- terminal" opens the working folder in VS Code when `code` is on your `PATH`.+- "Open terminal" finds the session's window by walking up from the relay's+ process to the terminal or editor that runs it. A session in a classic+ console window (`cmd.exe` or PowerShell without Windows Terminal) has no such+ ancestor — conhost owns that window — so its folder opens in VS Code instead,+ as it does when `code` is on your `PATH` and nothing was found.+- No global keyboard shortcuts yet: a waiting card is folded with its **⌃** or+ `Esc` in the island, and reopened by clicking the island or Open in the tray.+- Apple Music, the one pill from the Mac catalog with nothing behind it here,+ is left out.+- Not in this version: sending a dropped file by email and dragging Mochi onto+ 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.- 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.+- Hermes: Coucou writes the plugin but does not run the `hermes` CLI, so it is+ turned on once by hand. Hermes runs natively on Linux; on Windows it is+ untested.+- Plan usage: the user's previous status line runs through Git Bash on Windows+ (`/bin/sh` on Linux and Mac); without Git Bash it is not run, rather than+ guessed at with `cmd`. The Codex CLI is looked for on `PATH` and in npm's,+ Volta's, Bun's and pnpm's folders (and nvm's on Linux).+- The chat's model picker opens inside the chat card instead of a popover, and+ it also offers OpenRouter and any OpenAI-compatible server, which the Mac+ does not. Google AI, OpenAI and OpenRouter can see an image you dropped (sent+ inline), where the Mac sends its name only.+- Live diff: the relay forwards an edit's text whole only once the edit is done+ (PostToolUse), up to 256 KB per string and 512 KB per event. A bigger edit+ shows its "Modifie · file" step without counts rather than wrong ones. The+ diff's ↗ needs `code` on your `PATH`; without it, it opens the file's folder —+ never the file itself. Counts and diffs come from Claude Code's Edit,+ MultiEdit and Write, on whichever pill its session is on (VS Code, Cursor,+ Claude Desktop); other agents' edits show as plain steps.+- The GitHub lists are clicked, not walked with the arrow keys, and there is no+ iPhone to keep fetching them while the pill is off.+- Keyboard shortcuts use `Ctrl+Alt` where the Mac uses `⌃⌥`, with different+ keys (see [Keyboard shortcuts](#keyboard-shortcuts)), and `Ctrl` where the+ Mac uses `⌘` inside the island. "Bring the terminal forward" is "Open+ terminal" here. Not in this version: sending Mochi to the desktop, attaching+ the front window (their ids are kept for later), moving through a card's+ list (`⌘↑` `⌘↓` `⌘O`) and the diff (`⌘E`). The island only reads its own+ shortcuts while it has the keyboard: in the chat, or after a global shortcut+ opened it. **Go to alert** brings up any agent's waiting card on its own pill;+ **Toggle the island** folds a waiting card rather than dropping it, like `Esc`+ in the island.+ - Weekly recap:+ - Sharing happens inside the island instead of a separate panel, and Save+ writes straight into Pictures (or Downloads) instead of asking where. There+ is no system Share sheet; Copy uses the web clipboard.- - Questions are counted when an agent asks one (`AskUserQuestion`), not when- it is answered from the island, which can't answer questions yet.++ - Questions are counted when an agent asks one (`AskUserQuestion`), whether++ it is then answered in the island or in the terminal. Permissions count the++ Allow and Deny clicks on the island's card, for every agent that gets one.+ - There is no sleep/wake notification to listen to without a background+ loop, so after the machine wakes the Monday card waits for the first agent+ to start or for you to hover the island.+ - The card is 24 px taller than the Mac's: it also lists top agent, project,+ busiest day, longest session, permissions and questions, which the Mac+ leaves to the image. A turn cut short by the session ending still counts.+ - Tray → Pause doesn't stop the history (it stays on the machine anyway);+ switch it off in Settings → General.## Linux@@@ -419,34 -226,14 +455,38 @@@ What changes on Linuxgives no app the cursor position anywhere else.- **Claude Code hooks** go through `~/.local/share/coucou/bin/coucou-hook` and aUnix socket at `$XDG_RUNTIME_DIR/coucou.sock`. Both ends check that the other- runs as the same user.+ runs as the same user. Every other agent uses the same relay, single-quoted+ for `sh`, and its config under `~` (see Supported agents). A config that is a+ symlink (dotfiles) is written through to its target, with its permissions+ kept.+- **Global shortcuts** are X11 key grabs, so they work in an X11 session.+ On X11, AltGr is a modifier of its own and never clashes with `Ctrl+Alt`;+ combinations the desktop already uses (GNOME's `Ctrl+Alt+T` terminal and+ `Ctrl+Alt+←`/`→` workspace switching) show up as *In use*. Wayland has no+ key grabs — the GlobalShortcuts portal isn't supported yet — so nothing is+ registered there, and **Settings → Shortcuts** lists commands to bind in your+ desktop's own keyboard settings instead:+ `coucou --shortcut openChat` (or the AppImage's path) runs the action in the+ Coucou that is already open. The ids are `toggleIsland`, `openChat`,+ `goToAlert`, `jumpToTerminal`, `nextPill`, `prevPill`, `muteToggle` and+ `wardrobeToggle`.- **Keys** live in the Secret Service (GNOME Keyring, KWallet).+- **Plan usage**: the status line relay is `~/.local/share/coucou/bin/coucou-hook+ --statusline` and runs your previous status line with `/bin/sh -c`, like Claude+ Code. Codex is found on `$PATH`, in `~/.local/bin`, npm's global prefix, Volta,+ Bun, pnpm, or nvm (newest Node first), since a desktop launch often has a+ shorter `$PATH` than your shell.+- **Mochi's greeting** uses the full name in your account's GECOS field+ (`chfn` sets it); without one the chat stays neutral.- **Files**: preferences in `~/.config/coucou/`, the log at- `~/.local/share/coucou/coucou.log`.+ `~/.local/share/coucou/coucou.log`, the weekly recap history beside it in+ `recap.json`. A saved recap image goes to the pictures folder named in+ `~/.config/user-dirs.dirs`, else `~/Pictures`, else `~/Downloads`.+ - **Copying the recap image** needs a WebKitGTK with image clipboard support;+ 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, dragging Mochi onto a window, and jumping to a specific terminal- window — "Open terminal" opens the folder in VS Code.+ email and dragging Mochi onto a window.+- **Open terminal** opens the folder in VS Code: Wayland lets no app bring+ another app's window forward, and X11 would need a window-manager client this+ build doesn't carry.+- No **Claude Desktop** pill: the Claude app has no Linux build.diff --cc windows/src-tauri/src/lib.rsindex c660bb86,69520e5a..37a95e18--- a/windows/src-tauri/src/lib.rs+++ b/windows/src-tauri/src/lib.rs@@@ -1,30 -1,17 +1,31 @@@// Coucou for Windows — app wiring and the commands the island calls.+mod agent_hooks;+mod agents;+mod chat;mod claude;+mod config_file;+mod codex_plan;mod files;+mod github;mod hooks;+mod identity;mod integrations;mod island;+mod local_chat;mod log;+mod net;+mod openai_compat;mod pipe;mod platform;+ mod recap;mod secrets;+mod session_window;mod settings;+mod shortcuts;mod tray;+#[cfg(windows)]+mod webview_drop;use std::process::Command;use std::sync::atomic::Ordering;@@@ -295,85 -214,12 +296,88 @@@ fn hooks_applyOk(backup)}+// ── Other agents' hooks and plugins ──────────────────────────────────────────++#[tauri::command]+fn agent_hooks_list() -> Vec<agents::AgentStatus> {+ agents::list()+}++/// The diff the user has to look at before anything is written.+#[tauri::command]+fn agent_hooks_preview(agent: String, install: bool) -> Result<config_file::Plan, String> {+ agents::preview(&agent, install)+}++/// Only ever called from an explicit click in the settings window, with the+/// fingerprint of the preview the user looked at.+#[tauri::command]+fn agent_hooks_apply(agent: String, install: bool, fingerprint: String) -> Result<String, String> {+ let backups = agents::apply(&agent, install, &fingerprint)?;+ let done = if install { "installed" } else { "removed" };+ log::line(format!("agent hooks {done} for {agent}"));+ Ok(backups)+}++// ── Plan usage ────────────────────────────────────────────────────────────────++/// The diff of putting the plan usage relay into (or taking it out of) the+/// status line, before anything is written.+#[tauri::command]+fn status_line_preview(install: bool) -> Result<HookPreview, String> {+ hooks::status_line_preview(install)+}++/// Only ever called from an explicit click in the settings window.+#[tauri::command]+fn status_line_apply(+ app: AppHandle,+ shared: State<Shared>,+ install: bool,+ fingerprint: String,+) -> Result<String, String> {+ let backup = hooks::status_line_write(install, &fingerprint)?;+ let updated = {+ let mut current = shared.settings.lock().unwrap();+ current.plan_relay_installed = install;+ // As on the Mac: taking the relay out turns the pill off with it.+ if !install {+ current.show_plan_in_notch = false;+ }+ if let Err(err) = settings::save(¤t) {+ log::line(format!("could not save settings: {err}"));+ }+ current.clone()+ };+ let _ = app.emit("settings-changed", updated);+ Ok(backup)+}++/// Codex plan usage, asked of the Codex CLI (`codex app-server`) when its pill+/// shows. Off the main thread: it can take a few seconds.+#[tauri::command]+async fn codex_plan_usage() -> Option<serde_json::Value> {+ tauri::async_runtime::spawn_blocking(codex_plan::read).await.ok().flatten()+}+#[tauri::command]fn approval_decision(app: AppHandle, request_id: String, decision: String) {+ recap::record_decision(&app, &request_id, &decision);pipe::answer(&app, &request_id, &decision);}+/// An option picked on the island for a question Claude Code asked.+#[tauri::command]+fn approval_answer(+ app: AppHandle,+ request_id: String,+ answers: std::collections::HashMap<String, serde_json::Value>,+) {++ // An answered question is not an Allow / Deny: nothing for the recap.++ recap::forget_request(&app, &request_id);+ pipe::answer_question(&app, &request_id, &answers);+}+/// The island has the card on screen, so the long wait for a human may begin./// Until this arrives the relay only waits a few hundred milliseconds, which is/// what stops a paused or unresponsive island from freezing Claude Code.@@@ -600,7 -379,7 +605,8 @@@ pub fn run()}).manage(Pending::default()).manage(Chat::default())+ .manage(shortcuts::Registry::default())+ .manage(recap::load()).invoke_handler(tauri::generate_handler![boot,save_settings,@@@ -643,8 -407,14 +649,16 @@@open_n8n,open_settings_window,set_paused,+ shortcuts_status,+ shortcuts_suspend,+ recap::recap_history,+ recap::recap_prefs,+ recap::recap_set_enabled,+ recap::recap_set_hide_projects,+ recap::recap_mark_shown,+ recap::recap_clear,+ recap::recap_save_png,+ recap::recap_reveal_saved,]).setup(move |app| {let handle = app.handle().clone();diff --cc windows/src-tauri/src/pipe.rsindex d5b7a99a,b8c60d39..e668728d--- a/windows/src-tauri/src/pipe.rs+++ b/windows/src-tauri/src/pipe.rs@@@ -206,13 -195,11 +206,15 @@@ async fn handle(app: AppHandle, mut pip.unwrap_or_default().to_string();+ note_session_window(&pipe, &payload, &event);+ // Counts for the weekly recap — never the command, path or prompt itself.+ crate::recap::observe(&app, &payload);if event != "PermissionRequest" {- log::line(format!("hook {event}"));+ // The status line relay calls in with every Claude Code update: not log-worthy.+ if event != "StatusLine" {+ log::line(format!("hook {event}"));+ }let _ = app.emit_to(WINDOW_LABEL, "hook", payload);pipe.finish();return;diff --cc windows/src-tauri/src/recap.rsindex 00000000,e6b0d7cd..bedc5682mode 000000,100644..100644--- a/windows/src-tauri/src/recap.rs+++ b/windows/src-tauri/src/recap.rs@@@ -1,0 -1,1024 +1,1045 @@@+ // Weekly recap history — port of RecapStore.swift.+ //+ // Every hook event the relay forwards also passes through here. A "turn" runs+ // from a prompt (or the first tool call) to Stop, and only its counts and two+ // names are kept: the agent's pill ID and the project folder's last path+ // component. Never a command, a file path, file contents or a prompt.+ //+ // The history lives in recap.json under platform::local_dir()+ // (%LOCALAPPDATA%\Coucou on Windows, ~/.local/share/coucou on Linux), keeps a+ // 12-week rolling window and a hard cap on its length, and is written whole to+ // a temporary file then renamed over the old one, so a crash never leaves half+ // a file. Nothing in it ever leaves the machine.+ //+ // Aggregation (weeks, top agent, busiest day…) happens in the island+ // (src/recap/summary.ts): it needs the user's time zone, which JavaScript has+ // and plain Rust does not.++ use std::collections::{HashMap, HashSet};+ use std::io::{ErrorKind, Write};+ use std::path::{Path, PathBuf};+ use std::sync::{Mutex, MutexGuard, PoisonError};+ use std::time::{SystemTime, UNIX_EPOCH};++ use serde::{Deserialize, Serialize};+ use serde_json::Value;+ use tauri::{AppHandle, Emitter, Manager, State};++ use crate::island::WINDOW_LABEL;+ use crate::platform;++ /// 12 weeks, like the Mac.+ pub const WINDOW_SECS: i64 = 12 * 7 * 86_400;+ /// A turn with no event for two hours is closed at its last event (agent+ /// crashed, or never sent Stop) — RecapStore.pruneStale.+ const STALE_SECS: i64 = 2 * 3600;+ /// Hard caps, whatever the window holds: about 2 MB of JSON at most.+ const MAX_TURNS: usize = 10_000;+ const MAX_DECISIONS: usize = 10_000;+ const MAX_DRAFTS: usize = 256;+ const MAX_REQUESTS: usize = 64;+ const MAX_NAME_CHARS: usize = 64;+ /// A recap.json larger than this was not written by us: set it aside.+ const MAX_FILE_BYTES: u64 = 16 << 20;+ /// A 1080 × 1920 PNG is ~1 MB; anything far larger is not our image.+ const MAX_PNG_BYTES: usize = 24 << 20;++ /// Same limits as DiffEngine.swift: beyond them, lines are counted, not diffed.+ const DIFF_MAX_BYTES: usize = 200 * 1024;+ const DIFF_MAX_LINES: usize = 4000;+ const DIFF_MAX_CELLS: usize = 1_000_000;++ /// Tool names that run a shell command, across the agents the relay serves.+ const COMMAND_TOOLS: &[&str] = &[+ "Bash",+ "PowerShell",+ "Execute",+ "mcp__ide__executeCode",+ "run_shell_command",+ "shell",+ "local_shell",+ "exec_command",++ // Antigravity, and Copilot CLI's toolName, after the relay's normaliser.++ "run_command",++ "bash",+ ];++ // ── Persisted model ───────────────────────────────────────────────────────────++ /// One finished turn. Times are Unix seconds.+ #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+ #[serde(rename_all = "camelCase")]+ pub struct Turn {+ pub agent: String,+ pub project: String,+ pub start: i64,+ pub end: i64,+ pub files_changed: u32,+ pub lines_added: u32,+ pub lines_removed: u32,+ pub commands_run: u32,+ pub questions: u32,+ }++ /// A click on Allow or Deny in the island.+ #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+ #[serde(rename_all = "camelCase")]+ pub struct Decision {+ pub agent: String,+ pub date: i64,+ /// "allow" or "deny".+ pub decision: String,+ }++ #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+ #[serde(rename_all = "camelCase", default)]+ pub struct Prefs {+ /// "Keep a history of my coding sessions" — on by default, like the Mac.+ pub enabled: bool,+ /// Leave the project name out of the shared image.+ pub hide_projects: bool,+ /// Monday (YYYY-MM-DD) of the week the recap was last shown on its own.+ pub last_shown_week: String,+ }++ impl Default for Prefs {+ fn default() -> Self {+ Self { enabled: true, hide_projects: false, last_shown_week: String::new() }+ }+ }++ #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+ #[serde(rename_all = "camelCase", default)]+ struct History {+ schema_version: u32,+ turns: Vec<Turn>,+ decisions: Vec<Decision>,+ prefs: Prefs,+ }++ impl Default for History {+ fn default() -> Self {+ Self { schema_version: 1, turns: Vec::new(), decisions: Vec::new(), prefs: Prefs::default() }+ }+ }++ /// What the island reads: the part of the history it asked for.+ #[derive(Debug, Serialize)]+ #[serde(rename_all = "camelCase")]+ pub struct HistoryView {+ pub turns: Vec<Turn>,+ pub decisions: Vec<Decision>,+ pub prefs: Prefs,+ }++ /// A turn in progress, in memory only. The paths are only there to count+ /// distinct files and are never written anywhere.+ #[derive(Debug)]+ struct Draft {+ agent: String,+ project: String,+ start: i64,+ last_event: i64,+ paths: HashSet<String>,+ lines_added: u32,+ lines_removed: u32,+ commands_run: u32,+ questions: u32,+ }++ impl Draft {+ fn into_turn(self, end: i64) -> Turn {+ Turn {+ agent: self.agent,+ project: self.project,+ start: self.start,+ end: end.max(self.start),+ files_changed: self.paths.len().min(u32::MAX as usize) as u32,+ lines_added: self.lines_added,+ lines_removed: self.lines_removed,+ commands_run: self.commands_run,+ questions: self.questions,+ }+ }+ }++ // ── Store ─────────────────────────────────────────────────────────────────────++ pub struct Recap {+ path: PathBuf,+ history: History,+ drafts: HashMap<String, Draft>,+ /// Permission request ID → agent, until the island answers it.+ requests: HashMap<String, String>,+ /// The last image saved, so "Show in folder" never takes a path from the page.+ last_saved: Option<PathBuf>,+ }++ impl Recap {+ /// Reads `path`. A file that cannot be used is renamed aside, never lost.+ pub fn load(path: PathBuf, now: i64) -> Self {+ let history = read_history(&path);+ let mut recap = Self {+ path,+ history,+ drafts: HashMap::new(),+ requests: HashMap::new(),+ last_saved: None,+ };+ recap.prune(now);+ recap+ }++ /// One hook event, as the relay delivered it.+ pub fn observe(&mut self, payload: &Value, now: i64) {+ if !self.history.prefs.enabled {+ return;+ }+ self.close_stale(now);+ let event = text(payload, "hook_event_name");+ let agent = agent_id(payload);+ let key = session_key(payload, &agent);++ match event {+ "UserPromptSubmit" => {+ self.draft(&key, &agent, payload, now);+ }+ "PreToolUse" => {+ let tool = text(payload, "tool_name");+ let draft = self.draft(&key, &agent, payload, now);+ if COMMAND_TOOLS.contains(&tool) {+ draft.commands_run = draft.commands_run.saturating_add(1);+ }+ if tool == "AskUserQuestion" {+ draft.questions = draft.questions.saturating_add(1);+ }+ }+ "PostToolUse" => {+ let tool = text(payload, "tool_name");+ let input = payload.get("tool_input").unwrap_or(&Value::Null);+ let change = file_change(tool, input);+ let draft = self.draft(&key, &agent, payload, now);+ if let Some((path, added, removed)) = change {+ draft.paths.insert(path);+ draft.lines_added = draft.lines_added.saturating_add(added);+ draft.lines_removed = draft.lines_removed.saturating_add(removed);+ }+ }+ // Unlike the Mac, SessionEnd closes the turn instead of dropping it:+ // a session quit mid-turn still worked.+ "Stop" | "StopFailure" | "Interrupt" | "SessionEnd" => {+ if let Some(draft) = self.drafts.remove(&key) {+ self.history.turns.push(draft.into_turn(now));+ self.prune(now);+ self.save();+ }+ }+ _ => {}+ }+ }++ /// The draft for `key`, created on the first event of a turn.+ fn draft(&mut self, key: &str, agent: &str, payload: &Value, now: i64) -> &mut Draft {+ if !self.drafts.contains_key(key) && self.drafts.len() >= MAX_DRAFTS {+ self.close_oldest_draft();+ }+ let draft = self.drafts.entry(key.to_string()).or_insert_with(|| Draft {+ agent: agent.to_string(),+ project: project_name(text(payload, "cwd")),+ start: now,+ last_event: now,+ paths: HashSet::new(),+ lines_added: 0,+ lines_removed: 0,+ commands_run: 0,+ questions: 0,+ });+ draft.last_event = now;+ draft+ }++ fn close_oldest_draft(&mut self) {+ let Some(key) = self+ .drafts+ .iter()+ .min_by_key(|(_, d)| d.last_event)+ .map(|(k, _)| k.clone())+ else {+ return;+ };+ if let Some(draft) = self.drafts.remove(&key) {+ let end = draft.last_event;+ self.history.turns.push(draft.into_turn(end));+ }+ }++ /// RecapStore.pruneStale: turns silent for two hours count up to their+ /// last event instead of being lost.+ fn close_stale(&mut self, now: i64) {+ let stale: Vec<String> = self+ .drafts+ .iter()+ .filter(|(_, d)| d.last_event < now - STALE_SECS)+ .map(|(k, _)| k.clone())+ .collect();+ if stale.is_empty() {+ return;+ }+ for key in stale {+ if let Some(draft) = self.drafts.remove(&key) {+ let end = draft.last_event;+ self.history.turns.push(draft.into_turn(end));+ }+ }+ self.prune(now);+ self.save();+ }++ /// A permission request reached the island: remember whose it is.+ pub fn note_request(&mut self, request_id: &str, payload: &Value) {+ if self.requests.len() >= MAX_REQUESTS {+ self.requests.clear();+ }+ self.requests.insert(request_id.to_string(), agent_id(payload));+ }++ /// The request was handed back to the terminal: nothing to record.+ pub fn forget_request(&mut self, request_id: &str) {+ self.requests.remove(request_id);+ }++ /// A click on Allow or Deny.+ pub fn record_decision(&mut self, request_id: &str, decision: &str, now: i64) {+ let agent = self+ .requests+ .remove(request_id)+ .unwrap_or_else(|| "integration_claude".to_string());+ if !self.history.prefs.enabled {+ return;+ }+ let word = match decision {+ "allow" | "always" => "allow",+ "deny" => "deny",+ _ => return,+ };+ self.history.decisions.push(Decision { agent, date: now, decision: word.to_string() });+ self.prune(now);+ self.save();+ }++ /// Everything from `since` on (Unix seconds).+ pub fn view(&self, since: i64) -> HistoryView {+ HistoryView {+ turns: self.history.turns.iter().filter(|t| t.start >= since).cloned().collect(),+ decisions: self.history.decisions.iter().filter(|d| d.date >= since).cloned().collect(),+ prefs: self.history.prefs.clone(),+ }+ }++ pub fn prefs(&self) -> &Prefs {+ &self.history.prefs+ }++ pub fn set_enabled(&mut self, enabled: bool) {+ self.history.prefs.enabled = enabled;+ if !enabled {+ self.drafts.clear();+ self.requests.clear();+ }+ self.save();+ }++ pub fn set_hide_projects(&mut self, hide: bool) {+ self.history.prefs.hide_projects = hide;+ self.save();+ }++ /// `week` is the Monday the recap was shown for, as YYYY-MM-DD.+ pub fn mark_shown(&mut self, week: &str) {+ if !is_week_key(week) {+ return;+ }+ self.history.prefs.last_shown_week = week.to_string();+ self.save();+ }++ /// Settings → General → Clear history. The preferences stay.+ pub fn clear(&mut self) {+ self.history.turns.clear();+ self.history.decisions.clear();+ self.drafts.clear();+ self.save();+ }++ /// 12-week window, then the hard caps (oldest first out).+ fn prune(&mut self, now: i64) {+ let cutoff = now - WINDOW_SECS;+ self.history.turns.retain(|t| t.start >= cutoff);+ self.history.decisions.retain(|d| d.date >= cutoff);+ if self.history.turns.len() > MAX_TURNS {+ self.history.turns.sort_by_key(|t| t.start);+ let excess = self.history.turns.len() - MAX_TURNS;+ self.history.turns.drain(..excess);+ }+ if self.history.decisions.len() > MAX_DECISIONS {+ self.history.decisions.sort_by_key(|d| d.date);+ let excess = self.history.decisions.len() - MAX_DECISIONS;+ self.history.decisions.drain(..excess);+ }+ }++ fn save(&self) {+ if let Err(err) = write_history(&self.path, &self.history) {+ note(format!("could not save the weekly recap history: {err}"));+ }+ }+ }++ // ── Reading and writing recap.json ────────────────────────────────────────────++ fn read_history(path: &Path) -> History {+ let too_big = std::fs::metadata(path).is_ok_and(|m| m.len() > MAX_FILE_BYTES);+ let bytes = if too_big {+ None+ } else {+ match std::fs::read(path) {+ Ok(bytes) => Some(bytes),+ Err(err) if err.kind() == ErrorKind::NotFound => return History::default(),+ Err(err) => {+ note(format!("can't read {}: {err}", path.display()));+ // Unreadable is not corrupt: leave it, and start over in memory.+ // The first save will replace it, which only costs old counts.+ return History::default();+ }+ }+ };+ if let Some(history) = bytes.and_then(|b| serde_json::from_slice::<History>(&b).ok()) {+ return history;+ }+ // Keep the file as recap.json.corrupt-YYYYMMDD-HHMMSS, like the Mac.+ let t = platform::local_time();+ let aside = path.with_extension(format!(+ "json.corrupt-{:04}{:02}{:02}-{:02}{:02}{:02}",+ t.year, t.month, t.day, t.hour, t.minute, t.second+ ));+ match std::fs::rename(path, &aside) {+ Ok(()) => note(format!("{} was not usable — kept as {}", path.display(), aside.display())),+ Err(err) => note(format!("{} was not usable and could not be set aside: {err}", path.display())),+ }+ History::default()+ }++ /// Whole file to a temporary sibling, flushed, then renamed over the old one.+ fn write_history(path: &Path, history: &History) -> std::io::Result<()> {+ if let Some(dir) = path.parent() {+ platform::ensure_private_dir(dir)?;+ }+ let json = serde_json::to_vec(history)+ .map_err(|e| std::io::Error::new(ErrorKind::InvalidData, e))?;+ let temp = path.with_extension(format!("json.coucou-{}", std::process::id()));+ let mut options = std::fs::OpenOptions::new();+ options.write(true).create(true).truncate(true);+ #[cfg(unix)]+ std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);+ let written = options+ .open(&temp)+ .and_then(|mut file| {+ file.write_all(&json)?;+ file.sync_all()+ })+ .and_then(|()| std::fs::rename(&temp, path));+ if written.is_err() {+ let _ = std::fs::remove_file(&temp);+ }+ written+ }++ /// One line in coucou.log. Tests must never write to the real one.+ fn note(message: String) {+ #[cfg(not(test))]+ crate::log::line(message);+ #[cfg(test)]+ eprintln!("{message}");+ }++ // ── Reading a hook payload ────────────────────────────────────────────────────++ fn text<'a>(payload: &'a Value, key: &str) -> &'a str {+ payload.get(key).and_then(Value::as_str).unwrap_or_default()+ }+-/// Same routing as hooks.ts: a valid `coucou_agent` → `agent_<name>`, anything-/// else → the Claude Code pill. "claude" is reserved.++/// Same routing as hooks.ts, so a turn counts for the pill it showed on: a++/// valid `coucou_agent` → `agent_<name>` (every agent the relay normalises,++/// Claude Desktop included); otherwise Claude Code's own pill — Cursor's when++/// it runs in Cursor's terminal, VS Code's else. "claude" is reserved.+ fn agent_id(payload: &Value) -> String {+ let raw = text(payload, "coucou_agent");+ let valid = !raw.is_empty()+ && raw.len() <= 24+ && raw != "claude"+ && raw.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');- if valid { format!("agent_{raw}") } else { "integration_claude".to_string() }++ if valid {++ format!("agent_{raw}")++ } else if text(payload, "term_editor") == "cursor" {++ "agent_cursor".to_string()++ } else {++ "integration_claude".to_string()++ }+ }++ /// Concurrent sessions are tracked apart; one without an ID is keyed by its+ /// agent and folder, as HookServer.swift does.+ fn session_key(payload: &Value, agent: &str) -> String {+ let id = text(payload, "session_id");+ if id.is_empty() || id == "unknown" {+ format!("{agent}+{}", text(payload, "cwd"))+ } else {+ id.to_string()+ }+ }++ /// The working folder's last component — the only part of a path ever kept.+ fn project_name(cwd: &str) -> String {+ let trimmed = cwd.trim_end_matches(['/', '\\']);+ let last = trimmed.rsplit(['/', '\\']).next().unwrap_or_default();+ clean_name(last)+ }++ fn clean_name(raw: &str) -> String {+ raw.chars().filter(|c| !c.is_control()).take(MAX_NAME_CHARS).collect()+ }++ /// The file an Edit, MultiEdit or Write touched, with lines added and removed.+ fn file_change(tool: &str, input: &Value) -> Option<(String, u32, u32)> {+ let path = input.get("file_path").and_then(Value::as_str)?;+ let (added, removed) = match tool {+ "Edit" => {+ let old = input.get("old_string").and_then(Value::as_str)?;+ let new = input.get("new_string").and_then(Value::as_str)?;+ line_diff(old, new)+ }+ "MultiEdit" => {+ let edits = input.get("edits").and_then(Value::as_array)?;+ edits.iter().fold((0u32, 0u32), |(a, r), edit| {+ let old = edit.get("old_string").and_then(Value::as_str).unwrap_or_default();+ let new = edit.get("new_string").and_then(Value::as_str).unwrap_or_default();+ let (da, dr) = line_diff(old, new);+ (a.saturating_add(da), r.saturating_add(dr))+ })+ }+ "Write" => {+ let content = input.get("content").and_then(Value::as_str)?;+ (count(split_lines(content).len()), 0)+ }+ _ => return None,+ };+ (added > 0 || removed > 0).then(|| (path.to_string(), added, removed))+ }++ fn count(n: usize) -> u32 {+ n.min(u32::MAX as usize) as u32+ }++ /// DiffEngine.splitLines: CRLF → LF, no trailing empty line.+ fn split_lines(text: &str) -> Vec<&str> {+ if text.is_empty() {+ return Vec::new();+ }+ let mut lines: Vec<&str> = text.split('\n').map(|l| l.strip_suffix('\r').unwrap_or(l)).collect();+ if lines.last() == Some(&"") {+ lines.pop();+ }+ lines+ }++ /// Lines added and removed between `old` and `new`, from their longest common+ /// subsequence — the counts DiffEngine.fromEdit gives. Past its size limits+ /// every old line counts as removed and every new one as added.+ pub fn line_diff(old: &str, new: &str) -> (u32, u32) {+ let a = split_lines(old);+ let b = split_lines(new);+ let fallback = (count(b.len()), count(a.len()));+ if old.len() + new.len() > DIFF_MAX_BYTES+ || a.len() + b.len() > DIFF_MAX_LINES+ || a.len().saturating_mul(b.len()) > DIFF_MAX_CELLS+ {+ return fallback;+ }+ let mut prev = vec![0usize; b.len() + 1];+ let mut row = vec![0usize; b.len() + 1];+ for x in &a {+ for (j, y) in b.iter().enumerate() {+ row[j + 1] = if x == y { prev[j] + 1 } else { prev[j + 1].max(row[j]) };+ }+ std::mem::swap(&mut prev, &mut row);+ }+ let lcs = prev[b.len()];+ (count(b.len() - lcs), count(a.len() - lcs))+ }++ fn is_week_key(week: &str) -> bool {+ week.len() == 10+ && week.bytes().enumerate().all(|(i, b)| if i == 4 || i == 7 { b == b'-' } else { b.is_ascii_digit() })+ }++ // ── Saving the shared image ───────────────────────────────────────────────────++ /// Standard base64, with or without a `data:…;base64,` prefix.+ fn decode_base64(data: &str) -> Option<Vec<u8>> {+ let body = match data.split_once(',') {+ Some((head, rest)) if head.starts_with("data:") => rest,+ _ => data,+ };+ let mut out = Vec::with_capacity(body.len() / 4 * 3);+ let mut acc = 0u32;+ let mut bits = 0u32;+ let mut padding = false;+ for b in body.bytes() {+ let v = match b {+ b'A'..=b'Z' => b - b'A',+ b'a'..=b'z' => b - b'a' + 26,+ b'0'..=b'9' => b - b'0' + 52,+ b'+' => 62,+ b'/' => 63,+ b'=' => {+ padding = true;+ continue;+ }+ b'\r' | b'\n' => continue,+ _ => return None,+ };+ if padding {+ return None;+ }+ acc = (acc << 6) | u32::from(v);+ bits += 6;+ if bits >= 8 {+ bits -= 8;+ out.push((acc >> bits) as u8);+ acc &= (1 << bits) - 1;+ }+ }+ Some(out)+ }++ const PNG_SIGNATURE: &[u8] = &[0x89, b'P', b'N', b'G', b'\r', b'\n', 0x1A, b'\n'];++ /// Writes `bytes` as `<stem>.png` in `dir`, or `<stem> (2).png`… when that name+ /// is taken. An existing file is never replaced.+ fn write_unique(dir: &Path, stem: &str, bytes: &[u8]) -> std::io::Result<PathBuf> {+ for n in 1..1000 {+ let name = if n == 1 { format!("{stem}.png") } else { format!("{stem} ({n}).png") };+ let path = dir.join(name);+ match std::fs::OpenOptions::new().write(true).create_new(true).open(&path) {+ Ok(mut file) => {+ let written = file.write_all(bytes).and_then(|()| file.sync_all());+ drop(file);+ if let Err(err) = written {+ let _ = std::fs::remove_file(&path);+ return Err(err);+ }+ return Ok(path);+ }+ Err(err) if err.kind() == ErrorKind::AlreadyExists => continue,+ Err(err) => return Err(err),+ }+ }+ Err(std::io::Error::new(ErrorKind::AlreadyExists, "too many recap images with this name"))+ }++ /// The PNG the page rendered, checked and written to the first pictures folder+ /// that exists.+ fn save_png(dirs: &[PathBuf], data: &str, week: &str) -> Result<PathBuf, String> {+ if data.len() > MAX_PNG_BYTES / 3 * 4 + 64 {+ return Err("The image is too large.".into());+ }+ let bytes = decode_base64(data).ok_or("The image could not be read.")?;+ if !bytes.starts_with(PNG_SIGNATURE) {+ return Err("The image could not be read.".into());+ }+ let dir = dirs.iter().find(|d| d.is_dir()).ok_or("No Pictures or Downloads folder to save into.")?;+ let stem = if is_week_key(week) {+ format!("Coucou weekly recap {week}")+ } else {+ "Coucou weekly recap".to_string()+ };+ write_unique(dir, &stem, &bytes).map_err(|err| format!("Could not save the image: {err}"))+ }++ // ── Tauri glue ────────────────────────────────────────────────────────────────++ pub struct Store(Mutex<Recap>);++ impl Store {+ fn lock(&self) -> MutexGuard<'_, Recap> {+ self.0.lock().unwrap_or_else(PoisonError::into_inner)+ }+ }++ fn now() -> i64 {+ SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)+ }++ pub fn load() -> Store {+ Store(Mutex::new(Recap::load(platform::local_dir().join("recap.json"), now())))+ }++ /// Called by the relay server for every hook event. An agent starting work is+ /// also one of the moments the Monday recap may show up.+ pub fn observe(app: &AppHandle, payload: &Value) {+ if let Some(store) = app.try_state::<Store>() {+ store.lock().observe(payload, now());+ }+ if matches!(text(payload, "hook_event_name"), "SessionStart" | "UserPromptSubmit") {+ let _ = app.emit_to(WINDOW_LABEL, "recap-check", ());+ }+ }++ pub fn note_request(app: &AppHandle, request_id: &str, payload: &Value) {+ if let Some(store) = app.try_state::<Store>() {+ store.lock().note_request(request_id, payload);+ }+ }++ pub fn forget_request(app: &AppHandle, request_id: &str) {+ if let Some(store) = app.try_state::<Store>() {+ store.lock().forget_request(request_id);+ }+ }++ pub fn record_decision(app: &AppHandle, request_id: &str, decision: &str) {+ if let Some(store) = app.try_state::<Store>() {+ store.lock().record_decision(request_id, decision, now());+ }+ }++ #[tauri::command]+ pub fn recap_history(store: State<Store>, since: i64) -> HistoryView {+ store.lock().view(since)+ }++ #[tauri::command]+ pub fn recap_prefs(store: State<Store>) -> Prefs {+ store.lock().prefs().clone()+ }++ #[tauri::command]+ pub fn recap_set_enabled(store: State<Store>, enabled: bool) {+ store.lock().set_enabled(enabled);+ }++ #[tauri::command]+ pub fn recap_set_hide_projects(store: State<Store>, hide: bool) {+ store.lock().set_hide_projects(hide);+ }++ #[tauri::command]+ pub fn recap_mark_shown(store: State<Store>, week: String) {+ store.lock().mark_shown(&week);+ }++ #[tauri::command]+ pub fn recap_clear(store: State<Store>) {+ store.lock().clear();+ }++ /// `data` is the canvas's PNG as a data URL. Returns where it was written.+ #[tauri::command]+ pub fn recap_save_png(store: State<Store>, data: String, week: String) -> Result<String, String> {+ let path = save_png(&platform::picture_dirs(), &data, &week)?;+ let shown = path.to_string_lossy().to_string();+ store.lock().last_saved = Some(path);+ Ok(shown)+ }++ /// Opens the folder of the image saved last — never a path from the page.+ #[tauri::command]+ pub fn recap_reveal_saved(store: State<Store>) {+ let dir = store.lock().last_saved.as_ref().and_then(|p| p.parent().map(Path::to_path_buf));+ if let Some(dir) = dir {+ platform::reveal_folder(&dir.to_string_lossy());+ }+ }++ // ── Tests ─────────────────────────────────────────────────────────────────────++ #[cfg(test)]+ mod tests {+ use super::*;+ use serde_json::json;++ const HOUR: i64 = 3600;+ /// Monday 5 October 2026, 00:00 UTC — the exact zone does not matter here.+ const T0: i64 = 1_791_158_400;++ fn scratch(name: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!("coucou-recap-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+ }++ fn event(name: &str, session: &str, extra: Value) -> Value {+ let mut v = json!({ "hook_event_name": name, "session_id": session, "cwd": "/home/me/code/coucou" });+ if let (Some(obj), Value::Object(more)) = (v.as_object_mut(), extra) {+ obj.extend(more);+ }+ v+ }++ fn on_disk(path: &Path) -> Value {+ serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()+ }++ #[test]+ fn a_turn_is_counted_from_prompt_to_stop() {+ let dir = scratch("turn");+ let file = dir.join("recap.json");+ let mut r = Recap::load(file.clone(), T0);+ r.observe(&event("UserPromptSubmit", "s1", json!({ "prompt": "secret plan" })), T0);+ r.observe(&event("PreToolUse", "s1", json!({ "tool_name": "Bash", "tool_input": { "command": "rm -rf /tmp/x" } })), T0 + 10);+ r.observe(&event("PreToolUse", "s1", json!({ "tool_name": "Read" })), T0 + 20);+ r.observe(&event("PreToolUse", "s1", json!({ "tool_name": "AskUserQuestion" })), T0 + 25);+ r.observe(&event("PostToolUse", "s1", json!({ "tool_name": "Edit", "tool_input": {+ "file_path": "/home/me/code/coucou/a.rs", "old_string": "a\nb\nc", "new_string": "a\nB\nc\nd" } })), T0 + 30);+ r.observe(&event("PostToolUse", "s1", json!({ "tool_name": "Write", "tool_input": {+ "file_path": "/home/me/code/coucou/b.rs", "content": "one\ntwo\nthree\n" } })), T0 + 40);+ r.observe(&event("PostToolUse", "s1", json!({ "tool_name": "Edit", "tool_input": {+ "file_path": "/home/me/code/coucou/a.rs", "old_string": "x", "new_string": "y" } })), T0 + 50);+ r.observe(&event("Stop", "s1", json!({})), T0 + HOUR);++ let view = r.view(0);+ assert_eq!(view.turns, vec![Turn {+ agent: "integration_claude".into(),+ project: "coucou".into(),+ start: T0,+ end: T0 + HOUR,+ files_changed: 2,+ lines_added: 2 + 3 + 1,+ lines_removed: 1 + 1,+ commands_run: 1,+ questions: 1,+ }]);++ // Only counts and names reach the disk.+ let written = std::fs::read_to_string(&file).unwrap();+ for secret in ["secret plan", "rm -rf", "a.rs", "/home/me", "one\\ntwo"] {+ assert!(!written.contains(secret), "{secret} must not be stored");+ }+ assert_eq!(on_disk(&file)["turns"][0]["project"], "coucou");+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn concurrent_sessions_and_agents_are_kept_apart() {+ let dir = scratch("sessions");+ let mut r = Recap::load(dir.join("recap.json"), T0);+ r.observe(&event("UserPromptSubmit", "a", json!({})), T0);+ r.observe(&event("UserPromptSubmit", "b", json!({ "coucou_agent": "gemini", "cwd": "C:\\Users\\me\\side-project\\" })), T0 + 60);+ r.observe(&event("PreToolUse", "b", json!({ "coucou_agent": "gemini", "tool_name": "run_shell_command" })), T0 + 70);+ r.observe(&event("Stop", "a", json!({})), T0 + 120);+ r.observe(&event("Stop", "b", json!({ "coucou_agent": "gemini" })), T0 + 180);+ let turns = r.view(0).turns;+ assert_eq!(turns.len(), 2);+ assert_eq!((turns[0].agent.as_str(), turns[0].commands_run), ("integration_claude", 0));+ assert_eq!(turns[1].agent, "agent_gemini");+ assert_eq!(turns[1].project, "side-project");+ assert_eq!(turns[1].commands_run, 1);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn invalid_or_reserved_agent_tags_fall_back_to_claude_code() {+ for tag in ["claude", "Gemini", "has space", "a-very-long-agent-name-over-24"] {+ assert_eq!(agent_id(&json!({ "coucou_agent": tag })), "integration_claude", "{tag}");+ }+ assert_eq!(agent_id(&json!({ "coucou_agent": "codex" })), "agent_codex");+ }+++ #[test]++ fn a_turn_counts_for_the_pill_it_showed_on() {++ // Claude Code in Cursor's terminal is the Cursor pill, as in hooks.ts.++ assert_eq!(agent_id(&json!({ "term_editor": "cursor" })), "agent_cursor");++ // An explicit agent wins over the terminal it runs in.++ assert_eq!(agent_id(&json!({ "coucou_agent": "claude-desktop", "term_editor": "cursor" })), "agent_claude-desktop");++ assert_eq!(agent_id(&json!({ "coucou_agent": "copilot" })), "agent_copilot");++ assert_eq!(agent_id(&json!({})), "integration_claude");++ }+++ #[test]+ fn a_turn_silent_for_two_hours_ends_at_its_last_event() {+ let dir = scratch("stale");+ let mut r = Recap::load(dir.join("recap.json"), T0);+ r.observe(&event("UserPromptSubmit", "s1", json!({})), T0);+ r.observe(&event("PreToolUse", "s1", json!({ "tool_name": "Bash" })), T0 + 600);+ // Next event, from another session, three hours later.+ r.observe(&event("UserPromptSubmit", "s2", json!({})), T0 + 3 * HOUR);+ let turns = r.view(0).turns;+ assert_eq!(turns.len(), 1);+ assert_eq!((turns[0].start, turns[0].end), (T0, T0 + 600));+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn decisions_are_recorded_with_the_agent_that_asked() {+ let dir = scratch("decisions");+ let mut r = Recap::load(dir.join("recap.json"), T0);+ r.note_request("r1", &json!({ "coucou_agent": "codex" }));+ r.record_decision("r1", "always", T0);+ r.record_decision("unknown", "deny", T0 + 1);+ r.record_decision("r3", "maybe", T0 + 2);+ r.note_request("r4", &json!({}));+ r.forget_request("r4");+ let d = r.view(0).decisions;+ assert_eq!(d.len(), 2);+ assert_eq!((d[0].agent.as_str(), d[0].decision.as_str()), ("agent_codex", "allow"));+ assert_eq!((d[1].agent.as_str(), d[1].decision.as_str()), ("integration_claude", "deny"));+ assert!(r.requests.is_empty());+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn twelve_weeks_are_kept_and_older_entries_pruned() {+ let dir = scratch("prune");+ let file = dir.join("recap.json");+ let mut r = Recap::load(file.clone(), T0);+ let old = T0 - WINDOW_SECS - 1;+ let edge = T0 - WINDOW_SECS;+ for start in [old, edge, T0 - HOUR] {+ r.history.turns.push(Turn {+ agent: "integration_claude".into(), project: "p".into(), start, end: start + 60,+ files_changed: 0, lines_added: 0, lines_removed: 0, commands_run: 0, questions: 0,+ });+ }+ r.history.decisions.push(Decision { agent: "integration_claude".into(), date: old, decision: "allow".into() });+ r.prune(T0);+ r.save();+ assert_eq!(r.view(0).turns.iter().map(|t| t.start).collect::<Vec<_>>(), [edge, T0 - HOUR]);+ assert!(r.view(0).decisions.is_empty());+ // Loading later prunes again.+ let later = Recap::load(file, T0 + 2 * HOUR);+ assert_eq!(later.view(0).turns.len(), 1);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn the_history_never_grows_past_its_cap() {+ let dir = scratch("cap");+ let mut r = Recap::load(dir.join("recap.json"), T0);+ for i in 0..(MAX_TURNS as i64 + 5) {+ r.history.turns.push(Turn {+ agent: "a".into(), project: "p".into(), start: T0 - i, end: T0,+ files_changed: 0, lines_added: 0, lines_removed: 0, commands_run: 0, questions: 0,+ });+ }+ r.prune(T0);+ assert_eq!(r.history.turns.len(), MAX_TURNS);+ // The oldest went.+ assert_eq!(r.history.turns.first().unwrap().start, T0 - MAX_TURNS as i64 + 1);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn names_are_cut_short_and_cleaned() {+ let long = "x".repeat(200);+ assert_eq!(project_name(&format!("/a/{long}")).chars().count(), MAX_NAME_CHARS);+ assert_eq!(project_name("/a/b\u{7}c/"), "bc");+ assert_eq!(project_name(""), "");+ assert_eq!(project_name("C:\\work\\korus"), "korus");+ }++ #[test]+ fn line_counts_match_the_diff_engine() {+ assert_eq!(line_diff("a\nb\nc", "a\nb\nc"), (0, 0));+ assert_eq!(line_diff("a\nb\nc", "a\nx\nc"), (1, 1));+ assert_eq!(line_diff("", "a\nb\n"), (2, 0));+ assert_eq!(line_diff("a\r\nb\r\n", "a\nb\nc\n"), (1, 0));+ // Too big to diff: everything counts.+ let big_old = "l\n".repeat(3000);+ let big_new = "l\n".repeat(1500);+ assert_eq!(line_diff(&big_old, &big_new), (1500, 3000));+ assert_eq!(file_change("Read", &json!({ "file_path": "/x" })), None);+ assert_eq!(file_change("Edit", &json!({ "file_path": "/x", "old_string": "a", "new_string": "a" })), None);+ let multi = json!({ "file_path": "/x", "edits": [+ { "old_string": "a", "new_string": "b" }, { "old_string": "", "new_string": "c\nd" } ] });+ assert_eq!(file_change("MultiEdit", &multi), Some(("/x".into(), 3, 1)));+ }++ #[test]+ fn a_disabled_history_records_nothing_and_clear_keeps_the_prefs() {+ let dir = scratch("disabled");+ let file = dir.join("recap.json");+ let mut r = Recap::load(file.clone(), T0);+ r.observe(&event("UserPromptSubmit", "s", json!({})), T0);+ r.observe(&event("Stop", "s", json!({})), T0 + 60);+ r.set_hide_projects(true);+ r.mark_shown("2026-10-05");+ r.mark_shown("not a week");+ r.clear();+ assert!(r.view(0).turns.is_empty());+ let reloaded = Recap::load(file.clone(), T0);+ assert_eq!(reloaded.prefs(), &Prefs { enabled: true, hide_projects: true, last_shown_week: "2026-10-05".into() });++ r.set_enabled(false);+ r.observe(&event("UserPromptSubmit", "s", json!({})), T0);+ r.observe(&event("Stop", "s", json!({})), T0 + 60);+ r.note_request("r", &json!({}));+ r.record_decision("r", "allow", T0);+ assert!(r.view(0).turns.is_empty() && r.view(0).decisions.is_empty());+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_corrupt_file_is_set_aside_and_writes_leave_nothing_behind() {+ let dir = scratch("corrupt");+ let file = dir.join("recap.json");+ std::fs::write(&file, b"{ not json").unwrap();+ let mut r = Recap::load(file.clone(), T0);+ assert!(r.view(0).turns.is_empty());+ let names = |d: &Path| -> Vec<String> {+ let mut n: Vec<String> = std::fs::read_dir(d).unwrap()+ .map(|e| e.unwrap().file_name().to_string_lossy().to_string()).collect();+ n.sort();+ n+ };+ let aside = names(&dir);+ assert_eq!(aside.len(), 1);+ assert!(aside[0].starts_with("recap.json.corrupt-"), "{aside:?}");+ assert_eq!(std::fs::read(dir.join(&aside[0])).unwrap(), b"{ not json");++ r.observe(&event("UserPromptSubmit", "s", json!({})), T0);+ r.observe(&event("Stop", "s", json!({})), T0 + 60);+ let mut expected = vec!["recap.json".to_string(), aside[0].clone()];+ expected.sort();+ assert_eq!(names(&dir), expected);+ assert_eq!(on_disk(&file)["schemaVersion"], 1);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn base64_round_trips_and_rejects_junk() {+ assert_eq!(decode_base64("data:image/png;base64,aGVsbG8=").unwrap(), b"hello");+ assert_eq!(decode_base64("aGk=").unwrap(), b"hi");+ assert_eq!(decode_base64("YWJj").unwrap(), b"abc");+ assert!(decode_base64("a$b").is_none());+ assert!(decode_base64("aGk=aGk=").is_none());+ }++ #[test]+ fn a_saved_image_never_replaces_an_existing_file() {+ let dir = scratch("png");+ let missing = dir.join("missing");+ let png = "data:image/png;base64,iVBORw0KGgo=";+ let first = save_png(&[missing.clone(), dir.clone()], png, "2026-10-05").unwrap();+ let second = save_png(&[dir.clone()], png, "2026-10-05").unwrap();+ assert_eq!(first, dir.join("Coucou weekly recap 2026-10-05.png"));+ assert_eq!(second, dir.join("Coucou weekly recap 2026-10-05 (2).png"));+ // The week is a date or nothing: no path tricks through it.+ let third = save_png(&[dir.clone()], png, "../../x").unwrap();+ assert_eq!(third, dir.join("Coucou weekly recap.png"));+ // Not a PNG: refused.+ assert!(save_png(&[dir.clone()], "data:image/png;base64,aGVsbG8=", "").is_err());+ assert!(save_png(&[missing], png, "").is_err());+ let _ = std::fs::remove_dir_all(&dir);+ }+ }diff --cc windows/src/core/bridge.tsindex 51967792,1054998f..01328da6--- a/windows/src/core/bridge.ts+++ b/windows/src/core/bridge.ts@@@ -156,25 -101,21 +157,38 @@@ export const Bridge =/** Tray → Pause. Stops the integration pollers, not just the island. */setPaused: (paused: boolean) => call<void>("set_paused", { paused }),+ // ── Global shortcuts ──────────────────────────────────────────────────────+ /** How each global shortcut went when Rust last registered them. */+ shortcutsStatus: () => call<ShortcutsReport>("shortcuts_status"),+ /** Lets go of every global shortcut while Settings records a new one. */+ shortcutsSuspend: (suspended: boolean) => call<void>("shortcuts_suspend", { suspended }),+ // ── Weekly recap ──────────────────────────────────────────────────────────+ /** Turns and decisions from `since` (Unix seconds) on, plus the recap prefs. */+ recapHistory: (since: number) => call<RecapHistory>("recap_history", { since: Math.floor(since) }),+ recapPrefs: () => call<RecapPrefs>("recap_prefs"),+ recapSetEnabled: (enabled: boolean) => call<void>("recap_set_enabled", { enabled }),+ recapSetHideProjects: (hide: boolean) => call<void>("recap_set_hide_projects", { hide }),+ /** `week` is the Monday (YYYY-MM-DD) the recap opened on its own for. */+ recapMarkShown: (week: string) => call<void>("recap_mark_shown", { week }),+ recapClear: () => call<void>("recap_clear"),+ /** Writes the PNG (a data URL) into Pictures or Downloads; returns its path. */+ recapSavePng: (data: string, week: string) => callOrThrow<string>("recap_save_png", { data, week }),+ /** Opens the folder of the image saved last. */+ recapRevealSaved: () => call<void>("recap_reveal_saved"),};+export type ShortcutStatus =+ | "active" | "off" | "inUse" | "duplicate" | "invalid"+ | "typesCharacter" | "unsupported" | "notPorted";++export interface ShortcutsReport {+ actions: { id: string; status: ShortcutStatus; typed?: string }[];+ /** "wayland" or "no-display" when no global shortcut can be registered. */+ blocked: string | null;+ /** `<executable> --shortcut`: append an action id for a desktop shortcut. */+ command: string;+}+export interface IntegrationUpdate {id: string;data: Record<string, unknown>;diff --cc windows/src/main.tsindex c93edc20,acdbf922..9457960e--- a/windows/src/main.ts+++ b/windows/src/main.ts@@@ -7,7 -7,7 +7,8 @@@ import { State, type Settings } from ".import { Island } from "./island/island";import { registerHookHandlers } from "./island/hooks";import { registerIntegrationHandlers, refreshConfigured } from "./island/integrations";+import { registerShortcutHandlers } from "./island/shortcuts";+ import { Recap } from "./recap/recap";async function main() {const root = document.getElementById("root");@@@ -68,8 -68,13 +73,14 @@@registerHookHandlers(island);registerIntegrationHandlers(island);+ registerShortcutHandlers(island, () => setPaused(false));+ // Monday recap: app start (greeting over), an agent starting work, waking up.+ const checkRecap = () => void Recap.check(island);+ island.onGreetingDone = checkRecap;+ island.onWake = checkRecap;+ await onEvent<null>("recap-check", checkRecap);+island.launch();// In a plain browser there is no wake strip behind the cursor: make the wholediff --cc windows/src/recap/summary.tsindex 00000000,b62cc8d0..94960313mode 000000,100644..100644--- a/windows/src/recap/summary.ts+++ b/windows/src/recap/summary.ts@@@ -1,0 -1,251 +1,252 @@@+ // Weekly recap — pure aggregation, port of RecapStore.weeklySummary.+ // Rust (src-tauri/src/recap.rs) records the turns; this file turns them into+ // one week's numbers. It lives on the JavaScript side because weeks, days and+ // "Monday 8 am" are local time, and the webview knows the user's time zone.+ // No DOM, no Tauri: tests/recap.test.mjs runs it as it is.++ /** One finished turn, as recap.rs stores it. Times are Unix seconds. */+ export interface RecapTurn {+ agent: string;+ project: string;+ start: number;+ end: number;+ filesChanged: number;+ linesAdded: number;+ linesRemoved: number;+ commandsRun: number;+ questions: number;+ }++ export interface RecapDecision {+ agent: string;+ date: number;+ decision: string;+ }++ export interface RecapPrefs {+ enabled: boolean;+ hideProjects: boolean;+ /** Monday (YYYY-MM-DD) of the week the recap last opened on its own. */+ lastShownWeek: string;+ }++ export interface RecapHistory {+ turns: RecapTurn[];+ decisions: RecapDecision[];+ prefs: RecapPrefs;+ }++ export interface WeeklySummary {+ weekStart: Date;+ /** Last second of the week (Sunday 23:59:59). */+ weekEnd: Date;+ totalMinutes: number;+ sessionCount: number;+ filesChanged: number;+ linesAdded: number;+ linesRemoved: number;+ commandsRun: number;+ questions: number;+ permissionsAllowed: number;+ permissionsDenied: number;+ /** Display name. */+ topAgent: string | null;+ topProject: string | null;+ busiestDay: string | null;+ longestSessionMinutes: number;+ }++ export const DEFAULT_PREFS: RecapPrefs = { enabled: true, hideProjects: false, lastShownWeek: "" };++ // ── Weeks (ISO 8601: Monday to Sunday, local time) ────────────────────────────++ /** Local midnight `n` days after `d`'s date — DST-safe, unlike adding ms. */+ export function addDays(d: Date, n: number): Date {+ return new Date(d.getFullYear(), d.getMonth(), d.getDate() + n);+ }++ /** Monday 00:00 (local) of the week holding `d`. */+ export function mondayOf(d: Date): Date {+ const sinceMonday = (d.getDay() + 6) % 7;+ return addDays(d, -sinceMonday);+ }++ /** Monday 00:00 of the last completed week. */+ export function previousWeekStart(now: Date): Date {+ return addDays(mondayOf(now), -7);+ }++ /** YYYY-MM-DD of a local date. */+ export function dayKey(d: Date): string {+ const p = (n: number) => String(n).padStart(2, "0");+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;+ }++ /** The Monday recap opens on its own once per week, from 8 am on. */+ export const RECAP_HOUR = 8;++ export function shouldAutoShow(now: Date, lastShownWeek: string): boolean {+ return now.getDay() === 1 && now.getHours() >= RECAP_HOUR && dayKey(mondayOf(now)) !== lastShownWeek;+ }++ // ── Aggregation ───────────────────────────────────────────────────────────────++ const DAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];++ /** Pill IDs → names, from PillCatalog.swift. Claude Code hooks come from any+ * terminal here, so its pill reads "Claude Code" rather than "VS Code". */+ const AGENT_NAMES: Record<string, string> = {+ integration_claude: "Claude Code",+ agent_cursor: "Cursor",+ agent_antigravity: "Antigravity",+ agent_codex: "Codex",+ agent_gemini: "Gemini CLI",+ agent_copilot: "Copilot CLI",+ agent_muse: "Muse Code",+ agent_opencode: "OpenCode",+ agent_amp: "Amp",+ agent_hermes: "Hermes",++ "agent_claude-desktop": "Claude Desktop",+ };++ export function agentName(id: string): string {+ const known = AGENT_NAMES[id];+ if (known) return known;+ const raw = id.replace(/^agent_/, "");+ return raw ? raw.charAt(0).toUpperCase() + raw.slice(1) : id;+ }++ /** The most frequent key; ties go to whatever `order` ranks first. */+ function topKey<K>(counts: Map<K, number>, order: (a: K, b: K) => number): K | null {+ let best: K | null = null;+ let bestCount = 0;+ for (const [key, n] of counts) {+ if (n > bestCount || (n === bestCount && best !== null && order(key, best) < 0)) {+ best = key;+ bestCount = n;+ }+ }+ return best;+ }++ /** Wall time covered by the turns, overlapping ones counted once. Seconds. */+ export function mergedSeconds(turns: RecapTurn[]): number {+ const sorted = turns.filter((t) => t.end > t.start).sort((a, b) => a.start - b.start);+ let total = 0;+ let segStart = 0;+ let segEnd = -Infinity;+ for (const t of sorted) {+ if (t.start <= segEnd) {+ segEnd = Math.max(segEnd, t.end);+ } else {+ if (segEnd > segStart) total += segEnd - segStart;+ segStart = t.start;+ segEnd = t.end;+ }+ }+ if (segEnd > segStart) total += segEnd - segStart;+ return total;+ }++ /** The week starting at `weekStart` (a local Monday 00:00), or null when nothing ran. */+ export function summarize(history: RecapHistory, weekStart: Date): WeeklySummary | null {+ const end = addDays(weekStart, 7);+ const from = weekStart.getTime() / 1000;+ const to = end.getTime() / 1000;+ const turns = history.turns.filter((t) => t.start >= from && t.start < to);+ if (turns.length === 0) return null;+ const decisions = history.decisions.filter((d) => d.date >= from && d.date < to);+ const sum = (f: (t: RecapTurn) => number) => turns.reduce((n, t) => n + f(t), 0);++ const byAgent = new Map<string, number>();+ const byProject = new Map<string, number>();+ const byDay = new Map<number, number>();+ for (const t of turns) {+ byAgent.set(t.agent, (byAgent.get(t.agent) ?? 0) + 1);+ if (t.project) byProject.set(t.project, (byProject.get(t.project) ?? 0) + 1);+ const day = new Date(t.start * 1000).getDay();+ byDay.set(day, (byDay.get(day) ?? 0) + 1);+ }+ const byName = (a: string, b: string) => a.localeCompare(b);+ // Ties go to the earlier day of the (Monday-first) week.+ const byWeekOrder = (a: number, b: number) => ((a + 6) % 7) - ((b + 6) % 7);+ const topAgent = topKey(byAgent, byName);+ const busiest = topKey(byDay, byWeekOrder);+ const longest = Math.max(0, ...turns.map((t) => t.end - t.start));++ return {+ weekStart,+ weekEnd: new Date(end.getTime() - 1000),+ totalMinutes: Math.floor(mergedSeconds(turns) / 60),+ sessionCount: turns.length,+ filesChanged: sum((t) => t.filesChanged),+ linesAdded: sum((t) => t.linesAdded),+ linesRemoved: sum((t) => t.linesRemoved),+ commandsRun: sum((t) => t.commandsRun),+ questions: sum((t) => t.questions),+ permissionsAllowed: decisions.filter((d) => d.decision === "allow" || d.decision === "always").length,+ permissionsDenied: decisions.filter((d) => d.decision === "deny").length,+ topAgent: topAgent === null ? null : agentName(topAgent),+ topProject: topKey(byProject, byName),+ busiestDay: busiest === null ? null : DAY_NAMES[busiest],+ longestSessionMinutes: Math.floor(longest / 60),+ };+ }++ // ── Formatting ────────────────────────────────────────────────────────────────++ export function formatDuration(minutes: number): string {+ if (minutes < 60) return `${minutes}m`;+ const h = Math.floor(minutes / 60);+ const m = minutes % 60;+ return m === 0 ? `${h}h` : `${h}h ${m}m`;+ }++ /** 1234 → "1,234"; 12345 → "12.3k" — keeps a stat chip narrow. */+ export function formatCount(n: number): string {+ if (n >= 10_000) return `${(n / 1000).toFixed(n >= 100_000 ? 0 : 1)}k`;+ return n.toLocaleString("en-US");+ }++ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];++ /** "Sep 28 – Oct 4". */+ export function weekRangeLabel(s: Pick<WeeklySummary, "weekStart" | "weekEnd">): string {+ const f = (d: Date) => `${MONTHS[d.getMonth()]} ${d.getDate()}`;+ return `${f(s.weekStart)} – ${f(s.weekEnd)}`;+ }++ // ── Sample week ───────────────────────────────────────────────────────────────++ /**+ * The fake week of scripts/test-weekly-recap.swift, starting on `monday`.+ * Used by the tests and by `npm run dev` in a plain browser, where there is+ * no Rust side to read a history from.+ */+ export function sampleHistory(monday: Date): RecapHistory {+ const at = (day: number, hour: number, minute = 0) =>+ Math.floor(new Date(monday.getFullYear(), monday.getMonth(), monday.getDate() + day, hour, minute).getTime() / 1000);+ const turn = (+ agent: string, project: string, start: number, end: number,+ filesChanged: number, linesAdded: number, linesRemoved: number, commandsRun: number, questions: number,+ ): RecapTurn => ({ agent, project, start, end, filesChanged, linesAdded, linesRemoved, commandsRun, questions });+ const claude = "integration_claude";+ return {+ turns: [+ turn(claude, "coucou", at(0, 9), at(0, 11, 30), 8, 312, 87, 14, 2),+ turn(claude, "coucou", at(0, 14), at(0, 15, 45), 3, 95, 20, 5, 0),+ turn("agent_gemini", "side-project", at(1, 10), at(1, 11), 2, 50, 10, 3, 1),+ turn(claude, "coucou", at(2, 9, 30), at(2, 12), 5, 180, 60, 8, 3),+ turn(claude, "coucou", at(3, 16), at(3, 17), 1, 40, 5, 2, 0),+ turn(claude, "coucou", at(4, 8), at(4, 13), 12, 540, 130, 22, 5),+ ],+ decisions: [+ { agent: claude, date: at(0, 9, 30), decision: "allow" },+ { agent: claude, date: at(0, 10), decision: "allow" },+ { agent: claude, date: at(2, 10), decision: "deny" },+ { agent: claude, date: at(4, 9), decision: "always" },+ { agent: claude, date: at(4, 10), decision: "allow" },+ ],+ prefs: { ...DEFAULT_PREFS },+ };+ }diff --cc windows/src/settings/main.tsindex b7587410,36b239dc..a9f3d359--- a/windows/src/settings/main.ts+++ b/windows/src/settings/main.ts@@@ -921,189 -418,51 +922,234 @@@ function generalSection(): HTMLElement);}+// ── Shortcuts section ─────────────────────────────────────────────────────────++const SHORTCUTS_UI = {+ title: "Shortcuts",+ hint: "Work from any app. Click a shortcut to change it, then press the new keys — Esc cancels, Backspace removes it.",+ global: "From anywhere",+ island: "In the open island",+ recording: "Press keys…",+ none: "None",+ reset: "Reset to defaults",+ inUse: "In use by another app",+ duplicate: "Used twice",+ invalid: "Not a valid shortcut",+ unavailable: "Not available",+ types: (ch: string) => `Types “${ch}”`,+ typesNote: (keys: string, ch: string) =>+ `${keys} types “${ch}” on your keyboard, so it can't be a shortcut. Pick another key.`,+ needsModifier: "Hold Ctrl, Alt or the Windows key with it.",+ unsupportedKey: "That key can't be used in a shortcut.",+ wayland:+ "Your Wayland desktop doesn't let apps listen for keys outside their own windows. Add the shortcuts in your system's keyboard settings instead, with these commands:",+ noDisplay: "No display server was found, so global shortcuts are off.",+} as const;++function shortcutsSection(initial: ShortcutsReport | null): HTMLElement {+ let report = initial;+ const list = h("div", { class: "shortcut-list" });+ const feedback = h("div", {});+ const blockedNote = h("div", {});++ let stopRecording: (() => void) | null = null;++ function store(id: string, binding: Binding) {+ settings.shortcuts = { ...settings.shortcuts, [id]: binding };+ void save();+ }++ function tagFor(id: string, dups: Set<string>): HTMLElement | null {+ if (dups.has(id)) return h("span", { class: "tag err", text: SHORTCUTS_UI.duplicate });+ const st = report?.actions.find((a) => a.id === id);+ switch (st?.status) {+ case "inUse": return h("span", { class: "tag warn", text: SHORTCUTS_UI.inUse });+ case "duplicate": return h("span", { class: "tag err", text: SHORTCUTS_UI.duplicate });+ case "invalid": return h("span", { class: "tag err", text: SHORTCUTS_UI.invalid });+ case "typesCharacter": return h("span", { class: "tag warn", text: SHORTCUTS_UI.types(st.typed ?? "?") });+ case "unsupported": return h("span", { class: "tag", text: SHORTCUTS_UI.unavailable });+ default: return null;+ }+ }++ function record(id: string, binding: Binding, button: HTMLButtonElement) {+ stopRecording?.();+ clear(feedback);+ button.classList.add("recording");+ button.textContent = SHORTCUTS_UI.recording;+ void Bridge.shortcutsSuspend(true);++ const onKey = (e: KeyboardEvent) => {+ e.preventDefault();+ e.stopPropagation();+ const result = recordPress(e);+ switch (result.kind) {+ case "pending":+ return;+ case "keys":+ finish();+ store(id, { keys: result.keys, enabled: true });+ return;+ case "clear":+ finish();+ store(id, { keys: "", enabled: binding.enabled });+ return;+ case "typesCharacter":+ finish();+ feedback.append(h("div", {+ class: "notice warn",+ text: SHORTCUTS_UI.typesNote(displayKeys(result.keys), result.typed),+ }));+ return;+ case "needsModifier":+ feedback.replaceChildren(h("div", { class: "notice warn", text: SHORTCUTS_UI.needsModifier }));+ return;+ case "unsupported":+ feedback.replaceChildren(h("div", { class: "notice warn", text: SHORTCUTS_UI.unsupportedKey }));+ return;+ case "cancel":+ finish();+ return;+ }+ };+ const onBlur = () => finish();++ function finish() {+ window.removeEventListener("keydown", onKey, true);+ window.removeEventListener("blur", onBlur);+ stopRecording = null;+ // Takes the global shortcuts back, from what is saved by now.+ void Bridge.shortcutsSuspend(false);+ draw();+ }+ stopRecording = finish;+ window.addEventListener("keydown", onKey, true);+ window.addEventListener("blur", onBlur);+ }++ function draw() {+ clear(list);+ const dups = duplicates(activeKeys(settings.shortcuts));+ for (const d of SHORTCUTS) {+ if (!d.ported) continue;+ const binding = effective(d, settings.shortcuts);+ const keycap = h("button", {+ class: "keycap",+ text: binding.keys ? displayKeys(binding.keys) : SHORTCUTS_UI.none,+ }) as HTMLButtonElement;+ keycap.disabled = !binding.enabled;+ keycap.addEventListener("click", () => record(d.id, binding, keycap));+ const sw = toggle(binding.enabled, (on) => store(d.id, { keys: binding.keys, enabled: on }));+ const tag = binding.enabled ? tagFor(d.id, dups) : null;+ list.append(h("div", { class: binding.enabled ? "row shortcut" : "row shortcut off" },+ sw,+ h("span", { class: "shortcut-name", text: SHORTCUT_TEXT[d.id] }),+ ...(tag ? [tag] : []),+ keycap,+ ));+ }++ clear(blockedNote);+ if (report?.blocked === "wayland") {+ const commands = h("div", { class: "diff" });+ for (const d of SHORTCUTS) {+ if (d.ported) commands.append(h("div", { class: "ctx", text: `${report.command} ${d.id}` }));+ }+ blockedNote.append(h("div", { class: "notice warn", text: SHORTCUTS_UI.wayland }), commands);+ } else if (report?.blocked) {+ blockedNote.append(h("div", { class: "notice warn", text: SHORTCUTS_UI.noDisplay }));+ }+ }++ const islandList = h("div", { class: "shortcut-list" });+ for (const row of ISLAND_SHORTCUTS) {+ islandList.append(h("div", { class: "row shortcut" },+ h("span", { class: "shortcut-name", text: row.description }),+ h("span", { class: "keycap static", text: row.keys }),+ ));+ }++ const reset = h("button", {+ text: SHORTCUTS_UI.reset,+ onclick: () => {+ stopRecording?.();+ settings.shortcuts = {};+ clear(feedback);+ void save();+ draw();+ },+ });++ void onEvent<ShortcutsReport>("shortcuts-status", (fresh) => {+ report = fresh;+ if (!stopRecording) draw();+ });+ void onEvent<Settings>("settings-changed", (s) => {+ settings = { ...settings, ...s };+ if (!stopRecording) draw();+ });++ draw();+ return h(+ "section",+ {},+ h("h2", {}, h("span", { text: SHORTCUTS_UI.title })),+ h("div", { class: "hint", text: SHORTCUTS_UI.hint }),+ h("div", { class: "subhead", text: SHORTCUTS_UI.global }),+ list,+ blockedNote,+ feedback,+ h("div", { class: "row" }, reset),+ h("div", { class: "subhead", text: SHORTCUTS_UI.island }),+ islandList,+ );+}++ /** Settings → General → Weekly recap. The prefs live with the history in Rust. */+ function recapRows(): HTMLElement[] {+ const T = {+ label: "Weekly recap",+ keep: "Keep a history of my coding sessions",+ clear: "Clear history",+ cleared: "History cleared.",+ about: "Counts and project names only — never commands, files or prompts. Kept on this computer for 12 weeks.",+ };+ const feedback = h("span", { class: "hint" });+ const sw = toggle(true, (v) => { void Bridge.recapSetEnabled(v); });+ void Bridge.recapPrefs().then((prefs) => {+ if (prefs) sw.classList.toggle("on", prefs.enabled);+ });+ const clearBtn = h("button", {+ class: "danger",+ text: T.clear,+ onclick: async () => {+ clearBtn.disabled = true;+ await Bridge.recapClear();+ feedback.textContent = T.cleared;+ window.setTimeout(() => {+ clearBtn.disabled = false;+ feedback.textContent = "";+ }, 2400);+ },+ }) as HTMLButtonElement;+ return [+ h("div", { class: "row" },+ h("label", { text: T.label }),+ sw,+ h("span", { class: "hint", text: T.keep }),+ ),+ h("div", { class: "row" },+ h("label", {}),+ clearBtn,+ feedback,+ ),+ h("div", { class: "row" },+ h("label", {}),+ h("span", { class: "hint", style: "flex:1 1 0;min-width:0", text: T.about }),+ ),+ ];+ }+// ── Boot ──────────────────────────────────────────────────────────────────────async function main() {diff --cc windows/src/style.cssindex 70a5644f,76c95fb4..1d3b6fa3--- a/windows/src/style.css+++ b/windows/src/style.css@@@ -1829,326 -1366,108 +1829,432 @@@ input[type="range"]::-webkit-slider-thupadding-top: 8px;}+/* ── Plan usage: the pills in the header and the card behind them ────────────+ ClaudePlanHeaderPill / ClaudePlanCardView / CodexPlanCardView on the Mac.+ Nothing here applies until a pill is turned on in Settings. */++/* Off: takes no room, so the header is exactly as it shipped. */+.plan-pills {+ display: none;+ align-items: center;+ gap: 5px;+ /* .header-actions spaces its items 14px apart; the Mac puts 8px between+ the pills and the gear. */+ margin-right: -6px;+}++.plan-pills.on {+ display: flex;+}++/* Both pills: the Mac tightens the right side (icons 10px apart, pills 5px+ from the gear, 8px from the edge). */+.header-actions.both-plans {+ gap: 10px;+ padding-right: 8px;+}++.header-actions.both-plans .plan-pills {+ margin-right: -5px;+}++.header-actions .plan-pill {+ --plan: #6b7079;+ display: flex;+ align-items: center;+ gap: 4px;+ padding: 4px 8px;+ border: 1px solid color-mix(in srgb, var(--plan) 14%, transparent);+ border-radius: 999px;+ background: #0e0f11;+ color: var(--dim-3);+ font: 600 10px var(--font);+ line-height: 12px;+ white-space: nowrap;+ cursor: default;+ transition: background 0.18s, border-color 0.18s, color 0.18s;+}++.header-actions .plan-pill:hover,+.header-actions .plan-pill.active {+ background: color-mix(in srgb, var(--plan) 18%, transparent);+ border-color: color-mix(in srgb, var(--plan) 55%, transparent);+ color: color-mix(in srgb, var(--plan) 70%, white);+}++.plan-pill-dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+}++.plan-card {+ position: relative;+ z-index: 1;+ padding-top: 10px;+}++.plan-head {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 0 36px 0 108px;+ white-space: nowrap;+}++.plan-head > * {+ flex: 0 0 auto;+}++.plan-title {+ font: 600 12px var(--font);+ color: var(--ink);+}++.plan-head > .plan-sub {+ flex: 0 1 auto; /* the one part that gives way, with an ellipsis */+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ font: 400 11px var(--font);+ color: var(--dim-2);+}++.plan-rows {+ display: flex;+ flex-direction: column;+ gap: 5px;+ padding: 8px 12px 0 108px;+}++.plan-row {+ display: flex;+ align-items: center;+ gap: 5px;+ font: 400 11px var(--font);+ white-space: nowrap;+}++.plan-label {+ flex: 0 0 40px;+ color: var(--dim-3);+}++.plan-bar {+ flex: 0 0 50px;+ height: 4px;+ border-radius: 2px;+ background: rgba(255, 255, 255, 0.08);+ overflow: hidden;+}++.plan-fill {+ display: block;+ height: 100%;+ border-radius: 2px;+}++.plan-pct {+ flex: 0 0 30px;+ text-align: right;+ font-weight: 600;+ font-variant-numeric: tabular-nums;+ color: #c5c8cd;+}++.plan-reset-icon {+ display: inline-flex;+ color: var(--dim-3);+}++.plan-reset {+ font-size: 10px;+ color: var(--dim-3);+}++.plan-none {+ color: var(--dim-3);+}++.plan-credits {+ font-weight: 600;+ color: #c5c8cd;+}++/* ── GitHub pulse (GitHubPulseCardView / GitHubDetailView) ─────────────── */++.gh-spark {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ border: 0;+ padding: 0;+ background: transparent;+ font: 400 11px var(--font);+ color: var(--dim-2);+ white-space: nowrap;+ cursor: default;+ min-width: 0;+}++.gh-mini {+ display: inline-flex;+ gap: 2px;+}++.gh-mini i,+.gh-cell {+ width: 7px;+ height: 7px;+ border-radius: 1.5px;+ flex: 0 0 auto;+}++.int-stats.gh-rows {+ gap: 4px;+ padding-top: 6px;+}++.gh-stat {+ border: 0;+ padding: 0;+ background: transparent;+ width: 100%;+ text-align: left;+ cursor: default;+}++.gh-detail-head {+ display: flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+}++.gh-back {+ display: inline-flex;+ align-items: center;+ gap: 3px;+ border: 0;+ padding: 0;+ background: transparent;+ font: 600 12px var(--font);+ color: var(--ink);+ white-space: nowrap;+ cursor: default;+ flex: 0 0 auto;+}++.gh-head-right {+ margin-left: auto;+ border: 0;+ padding: 0;+ background: transparent;+ font: 400 11px var(--font);+ color: var(--dim-2);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ min-width: 0;+ cursor: default;+}++.gh-list {+ display: flex;+ flex-direction: column;+ max-height: 60px; /* three 20 px rows; the rest scrolls */+ overflow-y: auto;+ margin-top: 4px;+ scrollbar-width: none;+}++.gh-list::-webkit-scrollbar {+ display: none;+}++.gh-list.fade {+ -webkit-mask-image: linear-gradient(to bottom, #000 0%, #000 80%, transparent 100%);+ mask-image: linear-gradient(to bottom, #000 0%, #000 80%, transparent 100%);+}++.gh-row {+ display: flex;+ align-items: center;+ gap: 5px;+ height: 20px;+ flex: 0 0 20px;+ padding: 0 4px 0 0;+ border: 0;+ border-radius: 4px;+ background: transparent;+ text-align: left;+ cursor: default;+ min-width: 0;+}++.gh-row:hover {+ background: rgba(255, 255, 255, 0.05);+}++.gh-gap {+ width: 5px;+ flex: 0 0 5px;+}++.gh-ref {+ font: 400 10.5px var(--font);+ color: #9398a1;+ white-space: nowrap;+ flex: 0 0 auto;+}++.gh-title {+ font: 400 11px var(--font);+ color: #c5c8cd;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ min-width: 0;+}++.gh-draft {+ font: 400 9.5px var(--font);+ color: var(--dim-3);+ flex: 0 0 auto;+}++.gh-word {+ margin-left: auto;+ padding-left: 4px;+ font: 400 10px var(--font);+ white-space: nowrap;+ flex: 0 0 auto;+}++.gh-empty {+ font: 400 10.5px var(--font);+ color: var(--dim-3);+ padding-top: 8px;+}++.gh-grid {+ display: flex;+ gap: 1.5px;+ padding-top: 5px;+}++.gh-week {+ display: flex;+ flex-direction: column;+ gap: 1.5px;+}++.gh-cell.empty {+ background: transparent;+}+++ /* ── Weekly recap ───────────────────────────────────────────────────────── */+ /* WeeklyRecapCardView: text from x = 116, indigo wash, chips of 17 px values. */++ .recap-stack {+ padding: 4px 16px 4px 116px;+ gap: 4px;+ }++ .recap-head {+ display: flex;+ align-items: baseline;+ gap: 6px;+ }++ .recap-title {+ font: 600 11px var(--font);+ color: #818cf8;+ }++ .recap-range {+ font: 400 10px var(--font);+ color: var(--dim-2);+ white-space: nowrap;+ }++ .recap-chips {+ display: flex;+ gap: 14px;+ white-space: nowrap;+ }++ .recap-chip .v {+ font: 700 17px var(--font);+ color: var(--ink-2);+ }++ .recap-chip .l {+ font: 400 9px var(--font);+ color: var(--dim-2);+ }++ .recap-meta {+ display: flex;+ gap: 5px;+ font: 400 11px var(--font);+ color: var(--dim-2);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ .recap-meta .n {+ color: var(--ink-2);+ font-weight: 600;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ .recap-meta .sep {+ color: var(--dim-4);+ }++ .recap-stack .actions {+ margin-top: 3px;+ }++ .recap-share {+ flex-direction: row;+ align-items: center;+ justify-content: flex-start;+ gap: 16px;+ padding: 8px 16px 8px 116px;+ }++ .recap-thumb {+ flex: 0 0 64px;+ width: 64px;+ height: 114px;+ border-radius: 8px;+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);+ }++ .recap-share-side {+ display: flex;+ flex-direction: column;+ gap: 8px;+ min-width: 0;+ }++ .recap-status {+ display: flex;+ align-items: baseline;+ gap: 8px;+ min-height: 14px;+ font: 400 11px var(--font);+ color: var(--dim);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ .recap-link {+ color: #818cf8;+ padding: 0;+ }diff --cc windows/src/views/views.tsindex d0d660fc,8fdaa117..72a9d459--- a/windows/src/views/views.ts+++ b/windows/src/views/views.ts@@@ -11,13 -11,7 +11,14 @@@ import { createMiniBot, pruneMiniBotsimport { buildPrompt } from "./chat";import { buildChoose, buildUpload, buildUploading } from "./upload";import { renderIntegrationCard, type IntegrationCardHooks } from "./integrations";+import { pillDefinition, sessionSubtitle } from "../core/pills";+import {+ PlanCard, buildPlanPill, claudePillVisible, codexPillVisible, planCardOpen, refreshCodexPlanUsage,+} from "./usage";+import { buildDiffCard } from "./diff";+import { lastTextStep } from "../core/diff";+import { Bridge } from "../core/bridge";+ import { buildRecap } from "./recap";export interface ViewActions {setView(v: IslandViewName): void;