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
Plan usage pills in the island: Claude and Codex, as on the Mac
Claudec02923e27c3a
diff --git a/windows/README.md b/windows/README.mdindex 081142cb..3fa856f8 100644--- a/windows/README.md+++ b/windows/README.md@@ -69,6 +69,29 @@ in time, Coucou stays quiet and Claude Code asks in the terminal as usual.It 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` key in+ `%USERPROFILE%\.claude\settings.json`, takes a dated backup and writes only+ after your click: 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.+## Chat and keys**Settings… → Claude** takes your Anthropic API key. Keys live in the **Windows@@ -164,6 +187,10 @@ OpenCode, Amp and Hermes are not yet supported on Windows or Linux. Their integrattach it as context, and jumping to a specific terminal window — "Openterminal" opens the working folder in VS Code when `code` is on your `PATH`.- Cal.com shows the next bookings as a list rather than the Mac's calendar.+- 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).## Linux@@ -209,6 +236,11 @@ What changes on Linux:Unix socket at `$XDG_RUNTIME_DIR/coucou.sock`. Both ends check that the otherruns as the same user.- **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.- **Files**: preferences in `~/.config/coucou/`, the log at`~/.local/share/coucou/coucou.log`.- What the Windows build leaves out, this one does too: sending a file bydiff --git a/windows/src-tauri/src/codex_plan.rs b/windows/src-tauri/src/codex_plan.rsnew file mode 100644index 00000000..734ce7bf--- /dev/null+++ b/windows/src-tauri/src/codex_plan.rs@@ -0,0 +1,210 @@+// Codex plan usage — the same source as CodexPlanGauge.swift on the Mac.+//+// Coucou asks the Codex CLI itself: `codex app-server` (the JSON-RPC server+// behind Codex's /status) is started, asked `account/rateLimits/read`, and+// stopped. Coucou makes no network call of its own and reads no credential:+// Codex answers with its own sign-in, exactly as /status does, and nothing is+// installed or written. It runs only when the pill shows or is clicked, at most+// once at a time, for 15 s at most, and is skipped while Coucou is paused.++use std::cmp::Ordering;+use std::io::{BufRead, BufReader, Read, Write};+use std::process::{Command, Stdio};+use std::sync::atomic::{self, AtomicBool};+use std::sync::mpsc;+use std::time::Duration;++use serde_json::{json, Value};++use crate::platform;++/// The Mac gives Codex the same 15 s.+const TIMEOUT: Duration = Duration::from_secs(15);+/// One JSON-RPC line we are willing to read; the answer is a few hundred bytes.+const MAX_LINE: usize = 256 * 1024;+/// Everything we are willing to read before the answer shows up.+const MAX_TOTAL: usize = 2 * 1024 * 1024;++/// What the Mac sends: initialize, initialized, then the one question.+const REQUESTS: &str = concat!(+ r#"{"id":1,"method":"initialize","params":{"clientInfo":{"name":"coucou","version":"1"}}}"#,+ "\n",+ r#"{"method":"initialized"}"#,+ "\n",+ r#"{"id":2,"method":"account/rateLimits/read"}"#,+ "\n",+);++static BUSY: AtomicBool = AtomicBool::new(false);++struct NotBusy;+impl Drop for NotBusy {+ fn drop(&mut self) {+ BUSY.store(false, atomic::Ordering::Release);+ }+}++/// The limits part of Codex's `account/rateLimits/read` answer, or `None` when+/// Codex is not installed, not signed in, slow, already being asked, or Coucou+/// is paused. Blocking: call it off the main thread.+pub fn read() -> Option<Value> {+ if crate::integrations::PAUSED.load(atomic::Ordering::Relaxed) {+ return None;+ }+ if BUSY.swap(true, atomic::Ordering::AcqRel) {+ return None;+ }+ let _busy = NotBusy;++ let exe = platform::codex_candidates().into_iter().next()?;+ let mut cmd = Command::new(&exe);+ cmd.arg("app-server").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null());+ // An npm install is a `#!/usr/bin/env node` script (or a .cmd calling node):+ // its own folder first on PATH, as the Mac does, so it finds its Node.+ if let Some(dir) = exe.parent() {+ let mut dirs = vec![dir.to_path_buf()];+ if let Some(path) = std::env::var_os("PATH") {+ dirs.extend(std::env::split_paths(&path));+ }+ if let Ok(joined) = std::env::join_paths(dirs) {+ cmd.env("PATH", joined);+ }+ }+ platform::no_console(&mut cmd);+ let mut child = cmd.spawn().ok()?;++ let answer = (|| {+ let mut stdin = child.stdin.take()?;+ let stdout = child.stdout.take()?;+ let (tx, rx) = mpsc::channel();+ std::thread::spawn(move || {+ let _ = tx.send(first_answer(BufReader::new(stdout)));+ });+ stdin.write_all(REQUESTS.as_bytes()).ok()?;+ stdin.flush().ok()?;+ let answer = rx.recv_timeout(TIMEOUT).ok().flatten();+ // Closing its input is how app-server learns we are done.+ drop(stdin);+ answer+ })();+ let _ = child.kill();+ let _ = child.wait();+ answer.map(|result| limits_only(&result))+}++/// Reads JSON-RPC lines until the answer to request 2 and returns its `result`.+/// Gives up on a line or a stream that is far too long for what we expect.+pub fn first_answer(reader: impl BufRead) -> Option<Value> {+ let mut reader = reader;+ let mut total = 0usize;+ let mut line = Vec::new();+ loop {+ line.clear();+ let n = (&mut reader).take(MAX_LINE as u64 + 1).read_until(b'\n', &mut line).ok()?;+ if n == 0 {+ return None;+ }+ total += n;+ if total > MAX_TOTAL || line.len() > MAX_LINE {+ return None;+ }+ let Ok(message) = serde_json::from_slice::<Value>(&line) else { continue };+ if message.get("id").and_then(Value::as_i64) == Some(2) {+ return message.get("result").filter(|r| r.is_object()).cloned();+ }+ }+}++/// Only what the card shows goes to the webview: the limits and the free resets.+fn limits_only(result: &Value) -> Value {+ json!({+ "rateLimits": result.get("rateLimits").cloned().unwrap_or(Value::Null),+ "rateLimitResetCredits": result.get("rateLimitResetCredits").cloned().unwrap_or(Value::Null),+ })+}++/// Compares version-like names with their numbers as numbers ("v20.1" > "v9.12"),+/// like Foundation's `.numeric` comparison the Mac sorts nvm's folders with.+#[cfg_attr(windows, allow(dead_code))]+pub fn compare_versions(a: &str, b: &str) -> Ordering {+ fn parts(s: &str) -> Vec<Result<u64, String>> {+ let mut out = Vec::new();+ let mut cur = String::new();+ let mut digits = false;+ for c in s.chars() {+ if c.is_ascii_digit() != digits && !cur.is_empty() {+ out.push(if digits { Ok(cur.parse().unwrap_or(u64::MAX)) } else { Err(cur.clone()) });+ cur.clear();+ }+ digits = c.is_ascii_digit();+ cur.push(c);+ }+ if !cur.is_empty() {+ out.push(if digits { Ok(cur.parse().unwrap_or(u64::MAX)) } else { Err(cur) });+ }+ out+ }+ let (pa, pb) = (parts(a), parts(b));+ for (x, y) in pa.iter().zip(pb.iter()) {+ let ord = match (x, y) {+ (Ok(x), Ok(y)) => x.cmp(y),+ (Err(x), Err(y)) => x.cmp(y),+ (Ok(_), Err(_)) => Ordering::Less,+ (Err(_), Ok(_)) => Ordering::Greater,+ };+ if ord != Ordering::Equal {+ return ord;+ }+ }+ pa.len().cmp(&pb.len())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_answer_to_the_question_is_picked_out_of_the_conversation() {+ let stream = concat!(+ r#"{"id":1,"result":{"userAgent":"codex"}}"#, "\n",+ "not json at all\n",+ r#"{"method":"account/updated","params":{}}"#, "\n",+ r#"{"id":2,"result":{"rateLimits":{"primary":{"usedPercent":12.5,"resetsAt":1900000000}}}}"#, "\n",+ r#"{"id":3,"result":{}}"#, "\n",+ );+ let result = first_answer(stream.as_bytes()).unwrap();+ assert_eq!(result["rateLimits"]["primary"]["usedPercent"], 12.5);+ }++ #[test]+ fn an_error_a_closed_stream_or_a_flood_is_no_answer() {+ assert!(first_answer(r#"{"id":2,"error":{"message":"not signed in"}}"#.as_bytes()).is_none());+ assert!(first_answer(r#"{"id":1,"result":{}}"#.as_bytes()).is_none());+ assert!(first_answer(&b""[..]).is_none());+ let huge = "x".repeat(MAX_LINE + 10);+ assert!(first_answer(format!("{huge}\n{}\n", r#"{"id":2,"result":{}}"#).as_bytes()).is_none());+ // Many short lines add up too.+ let chatter = format!("{}\n", "y".repeat(1000)).repeat(MAX_TOTAL / 1000 + 10);+ assert!(first_answer(chatter.as_bytes()).is_none());+ }++ #[test]+ fn only_the_limits_reach_the_webview() {+ let result = json!({+ "rateLimits": { "planType": "plus" },+ "rateLimitResetCredits": { "availableCount": 1 },+ "account": { "email": "[email protected]" }+ });+ let kept = limits_only(&result);+ assert_eq!(kept["rateLimits"]["planType"], "plus");+ assert_eq!(kept["rateLimitResetCredits"]["availableCount"], 1);+ assert!(kept.get("account").is_none());+ }++ #[test]+ fn newest_node_first_like_the_mac() {+ let mut v = vec!["v9.12.0", "v20.1.0", "v18.20.4", "v20.11.1"];+ v.sort_by(|a, b| compare_versions(b, a));+ assert_eq!(v, ["v20.11.1", "v20.1.0", "v18.20.4", "v9.12.0"]);+ }+}diff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rsindex 264e4c3a..ef6cb424 100644--- a/windows/src-tauri/src/lib.rs+++ b/windows/src-tauri/src/lib.rs@@ -1,6 +1,7 @@// Coucou for Windows — app wiring and the commands the island calls.mod claude;+mod codex_plan;mod files;mod hooks;mod integrations;@@ -50,7 +51,9 @@ pub struct BootInfo {fn boot(app: AppHandle, shared: State<Shared>) -> BootInfo {let mut settings = shared.settings.lock().unwrap().clone();// The real state of ~/.claude/settings.json wins over whatever we stored.- settings.hooks_installed = hooks::status().installed;+ let hooks_status = hooks::status();+ settings.hooks_installed = hooks_status.installed;+ settings.plan_relay_installed = hooks_status.plan_relay_installed;let screen = island::screen_info(&app, &settings.screen);BootInfo {settings,@@ -222,6 +225,45 @@ fn hooks_apply(Ok(backup)}+/// The diff of putting the plan usage relay into (or taking it out of) the+/// status line: just the `statusLine` key, before and after.+#[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) {pipe::answer(&app, &request_id, &decision);@@ -409,6 +451,9 @@ pub fn run() {hooks_status,hooks_preview,hooks_apply,+ status_line_preview,+ status_line_apply,+ codex_plan_usage,approval_decision,approval_answer,approval_ack,diff --git a/windows/src-tauri/src/pipe.rs b/windows/src-tauri/src/pipe.rsindex 8d3566b3..8c04fa2b 100644--- a/windows/src-tauri/src/pipe.rs+++ b/windows/src-tauri/src/pipe.rs@@ -198,7 +198,10 @@ async fn handle(app: AppHandle, mut pipe: impl Relay) {.to_string();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 --git a/windows/src-tauri/src/platform/linux.rs b/windows/src-tauri/src/platform/linux.rsindex 8253961d..4d1be471 100644--- a/windows/src-tauri/src/platform/linux.rs+++ b/windows/src-tauri/src/platform/linux.rs@@ -208,6 +208,32 @@ pub fn find_on_path(stem: &str) -> Option<PathBuf> {})}+/// Where the Codex CLI may be, best first: $PATH, then the usual per-user+/// install folders, which a desktop launch often leaves out of $PATH (npm's+/// global prefix, Volta, Bun, pnpm, and nvm with its newest Node first).+pub fn codex_candidates() -> Vec<PathBuf> {+ let home = home_dir();+ let mut out: Vec<PathBuf> = find_on_path("codex").into_iter().collect();+ for dir in [".local/bin", ".npm-global/bin", ".volta/bin", ".bun/bin", ".local/share/pnpm"] {+ out.push(home.join(dir).join("codex"));+ }+ out.push(PathBuf::from("/usr/local/bin/codex"));+ out.push(PathBuf::from("/usr/bin/codex"));+ let nvm = home.join(".nvm/versions/node");+ if let Ok(entries) = std::fs::read_dir(&nvm) {+ let mut versions: Vec<String> =+ entries.filter_map(|e| e.ok()?.file_name().into_string().ok()).collect();+ versions.sort_by(|a, b| crate::codex_plan::compare_versions(b, a));+ out.extend(versions.iter().map(|v| nvm.join(v).join("bin/codex")));+ }+ out.retain(|p| {+ std::fs::metadata(p)+ .map(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)+ .unwrap_or(false)+ });+ out+}+// ── Cursor ────────────────────────────────────────────────────────────────────/// Nothing polls the cursor here: the page reports it over the island, and thediff --git a/windows/src-tauri/src/platform/windows.rs b/windows/src-tauri/src/platform/windows.rsindex 79bc6a12..dfc1dc49 100644--- a/windows/src-tauri/src/platform/windows.rs+++ b/windows/src-tauri/src/platform/windows.rs@@ -101,6 +101,27 @@ pub fn find_on_path(stem: &str) -> Option<PathBuf> {None}+/// Where the Codex CLI may be, best first: %PATH% (codex.exe or npm's+/// codex.cmd), then npm's global folder and the Volta / Bun / pnpm ones.+/// Rust quotes the one fixed argument safely for a `.cmd` (see find_on_path).+pub fn codex_candidates() -> Vec<PathBuf> {+ let mut out: Vec<PathBuf> = find_on_path("codex").into_iter().collect();+ let var = |k: &str| std::env::var_os(k).map(PathBuf::from).filter(|p| p.is_absolute());+ if let Some(appdata) = var("APPDATA") {+ out.push(appdata.join("npm").join("codex.cmd"));+ }+ if let Some(local) = var("LOCALAPPDATA") {+ out.push(local.join("Volta").join("bin").join("codex.exe"));+ out.push(local.join("pnpm").join("codex.cmd"));+ }+ if let Some(home) = var("USERPROFILE") {+ out.push(home.join(".bun").join("bin").join("codex.exe"));+ out.push(home.join(".local").join("bin").join("codex.exe"));+ }+ out.retain(|p| p.is_file());+ out+}+// ── Who we are ────────────────────────────────────────────────────────────────//// Named pipes share one machine-wide namespace, so the SID in the name is whatdiff --git a/windows/src-tauri/src/settings.rs b/windows/src-tauri/src/settings.rsindex 17f63e1c..205c579c 100644--- a/windows/src-tauri/src/settings.rs+++ b/windows/src-tauri/src/settings.rs@@ -23,6 +23,15 @@ pub struct Settings {pub hooks_installed: bool,/// Claude model used by the chat. Changeable in the settings window.pub model: String,+ /// Show the Claude plan pill (5 h and weekly limits) in the island's header.+ /// Off until the user turns it on, so the header stays as it shipped.+ pub show_plan_in_notch: bool,+ /// Coucou's status line relay is the one in Claude Code's settings.json.+ /// Like `hooks_installed`, the real state wins at launch over what was stored.+ pub plan_relay_installed: bool,+ /// Show the Codex plan pill (5 h / weekly limits from `codex app-server`).+ /// Off by default; nothing is installed for it.+ pub show_codex_plan_in_notch: bool,}fn default_model() -> String {@@ -46,6 +55,9 @@ impl Default for Settings {autostart: false,hooks_installed: false,model: default_model(),+ show_plan_in_notch: false,+ plan_relay_installed: false,+ show_codex_plan_in_notch: false,}}}@@ -306,7 +318,10 @@ mod tests {"screen": "cursor","autostart": true,"hooksInstalled": true,- "model": "some-model"+ "model": "some-model",+ "showPlanInNotch": true,+ "planRelayInstalled": true,+ "showCodexPlanInNotch": true}"#;fn custom() -> Value {@@ -632,6 +647,9 @@ mod tests {"autostart","hooksInstalled","model",+ "showPlanInNotch",+ "planRelayInstalled",+ "showCodexPlanInNotch",]);let _ = std::fs::remove_dir_all(&dir);diff --git a/windows/src/core/bridge.ts b/windows/src/core/bridge.tsindex c6121c15..b87d6743 100644--- a/windows/src/core/bridge.ts+++ b/windows/src/core/bridge.ts@@ -76,6 +76,19 @@ export const Bridge = {hooksApply: (install: boolean, fingerprint: string) =>callOrThrow<string>("hooks_apply", { install, fingerprint }),+ // ── Plan usage: the status line relay, installed apart from the hooks ──────+ /** Diff of the `statusLine` key only. `install: false` previews taking the relay out. */+ statusLinePreview: (install: boolean) => callOrThrow<HookPreview>("status_line_preview", { install }),+ /** Same rules as hooksApply: an explicit click, and only for the diff that was shown. */+ statusLineApply: (install: boolean, fingerprint: string) =>+ callOrThrow<string>("status_line_apply", { install, fingerprint }),+ /**+ * Asks the Codex CLI (`codex app-server`) for its plan limits, as Codex's+ * /status does. The raw `account/rateLimits/read` result, or null when Codex+ * is missing, not signed in or slow (15 s).+ */+ codexPlanUsage: () => call<unknown>("codex_plan_usage"),+approvalDecision: (requestId: string, decision: "allow" | "deny") =>call<void>("approval_decision", { requestId, decision }),/** "The card is up" — until this lands the relay only waits a moment. */@@ -127,6 +140,8 @@ export interface DroppedFile {export interface HookStatus {installed: boolean;+ /** Coucou's status line relay (plan usage) is the status line in settings.json. */+ planRelayInstalled: boolean;settingsPath: string;hookPath: string;hookReady: boolean;diff --git a/windows/src/core/plan.ts b/windows/src/core/plan.tsnew file mode 100644index 00000000..7b4f85b2--- /dev/null+++ b/windows/src/core/plan.ts@@ -0,0 +1,225 @@+// Plan usage gauges — the logic of ClaudePlanGauge.swift and CodexPlanGauge.swift+// on the Mac, with no DOM so it can be tested on its own. The pills and cards+// that show it are in views/usage.ts.+//+// Claude: the numbers come from Claude Code's own status line (`rate_limits` in+// what it hands its status line command), through the relay. Pro and Max only.+// Codex: the numbers come from the Codex CLI itself (`codex app-server`,+// `account/rateLimits/read`, the source of Codex's /status), asked by the app+// when the pill shows. Nothing is read from any credentials, nothing is fetched+// by Coucou itself.++export interface PlanWindow {+ /** 0–100, clamped. */+ usedPct: number;+ /** Epoch milliseconds. */+ resetsAt: number;+}++export interface PlanUsage {+ fiveHour?: PlanWindow;+ sevenDay?: PlanWindow;+ /** When the numbers arrived (epoch ms). */+ updatedAt: number;+}++export interface CodexPlanUsage extends PlanUsage {+ /** Free full resets available. */+ resetCredits?: number;+ /** Soonest expiry among the available ones (epoch ms). */+ resetCreditExpiresAt?: number;+ planType?: string;+}++const DAY_MS = 86_400_000;++/** Every user-visible string of the gauges, in one place. */+export const PLAN_TEXT = {+ claudeTitle: "Claude plan",+ codexTitle: "Codex plan",+ claudePillTitle: "Claude plan usage",+ codexPillTitle: "Codex plan usage",+ waiting: "Waiting for a response from Claude Code",+ askingCodex: "Asking Codex…",+ justNow: "just now",+ minAgo: (n: number) => `${n} min ago`,+ hAgo: (n: number) => `${n} h ago`,+ fiveHours: "5 hours",+ week: "Week",+ resets: "Resets",+ resetting: "Resetting…",+ inHM: (h: number, m: number) => `in ${h} h ${m}`,+ inM: (m: number) => `in ${m} min`,+ available: (n: number) => `${n} available`,+ until: (date: string) => ` · until ${date}`,+ none: "—",+};++const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];+const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];++const isNum = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);+const asObj = (v: unknown): Record<string, unknown> | null =>+ v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null;++// ── Claude ────────────────────────────────────────────────────────────────────++function parseClaudeWindow(raw: unknown, now: number): PlanWindow | undefined {+ const w = asObj(raw);+ const pct = w?.used_percentage;+ const epoch = w?.resets_at;+ if (!isNum(pct) || !isNum(epoch)) return undefined;+ // Anything outside 0–200 is not a percentage; 100–200 is a plan over its limit, shown full.+ if (pct < 0 || pct > 200) return undefined;+ // resets_at is epoch seconds. A date more than 400 days away is milliseconds in disguise.+ if (epoch <= 0 || epoch * 1000 > now + 400 * DAY_MS) return undefined;+ return { usedPct: Math.min(100, pct), resetsAt: epoch * 1000 };+}++/** ClaudePlanGauge.parse: `rate_limits` of a status line call, or null when it holds neither window. */+export function parseClaudePlan(rateLimits: unknown, now = Date.now()): PlanUsage | null {+ const rl = asObj(rateLimits);+ const fiveHour = parseClaudeWindow(rl?.five_hour, now);+ const sevenDay = parseClaudeWindow(rl?.seven_day, now);+ if (!fiveHour && !sevenDay) return null;+ const usage: PlanUsage = { updatedAt: now };+ if (fiveHour) usage.fiveHour = fiveHour;+ if (sevenDay) usage.sevenDay = sevenDay;+ return usage;+}++// ── Codex ─────────────────────────────────────────────────────────────────────++/**+ * CodexPlanGauge.parse: the result of `account/rateLimits/read`. `primary` and+ * `secondary` are not tied to a window, so they are sorted by duration: a day or+ * less is the 5-hour window, anything else (or no duration) the week.+ */+export function parseCodexPlan(result: unknown, now = Date.now()): CodexPlanUsage | null {+ const r = asObj(result);+ const limits = asObj(r?.rateLimits);+ if (!limits) return null;+ const usage: CodexPlanUsage = { updatedAt: now };+ if (typeof limits.planType === "string" && limits.planType) usage.planType = limits.planType;+ for (const key of ["primary", "secondary"]) {+ const w = asObj(limits[key]);+ if (!w || !isNum(w.usedPercent) || !isNum(w.resetsAt)) continue;+ const window: PlanWindow = {+ usedPct: Math.min(100, Math.max(0, w.usedPercent)),+ resetsAt: w.resetsAt * 1000,+ };+ if (Number.isInteger(w.windowDurationMins) && (w.windowDurationMins as number) <= 24 * 60) {+ usage.fiveHour = window;+ } else {+ usage.sevenDay = window;+ }+ }+ const credits = asObj(r?.rateLimitResetCredits);+ if (credits) {+ if (Number.isInteger(credits.availableCount)) usage.resetCredits = credits.availableCount as number;+ const expiries = (Array.isArray(credits.credits) ? credits.credits : [])+ .map(asObj)+ .filter((c) => c?.status === "available" && isNum(c.expiresAt))+ .map((c) => (c!.expiresAt as number) * 1000);+ if (expiries.length) usage.resetCreditExpiresAt = Math.min(...expiries);+ }+ return usage.fiveHour || usage.sevenDay ? usage : null;+}++// ── Shared ────────────────────────────────────────────────────────────────────++/** What to show for a window: 0 once its reset time has passed. */+export const effectivePct = (w: PlanWindow, now = Date.now()): number => (w.resetsAt <= now ? 0 : w.usedPct);++/** The higher of the two effective percentages; null when there are no windows. */+export function dominantPct(u: PlanUsage | null | undefined, now = Date.now()): number | null {+ const pcts = [u?.fiveHour, u?.sevenDay].filter((w): w is PlanWindow => !!w).map((w) => effectivePct(w, now));+ return pcts.length ? Math.max(...pcts) : null;+}++/** Green below 50 %, orange up to 80 %, red above, grey without data. */+export function planColor(pct: number | null): string {+ if (pct == null) return "#6B7079";+ if (pct < 50) return "#22C55E";+ if (pct < 80) return "#F59E0B";+ return "#F4505E";+}++/** "Claude 73%" / "Codex 12%" on the pill; "Claude —" while there are no numbers. */+export function pillLabel(name: "Claude" | "Codex", u: PlanUsage | null | undefined, now = Date.now()): string {+ const pct = dominantPct(u, now);+ return pct == null ? `${name} ${PLAN_TEXT.none}` : `${name} ${Math.round(pct)}%`;+}++/** "just now", "12 min ago", "3 h ago". */+export function ageLabel(updatedAt: number, now = Date.now()): string {+ const secs = (now - updatedAt) / 1000;+ if (secs < 60) return PLAN_TEXT.justNow;+ const mins = Math.floor(secs / 60);+ return mins < 60 ? PLAN_TEXT.minAgo(mins) : PLAN_TEXT.hAgo(Math.floor(mins / 60));+}++/** "in 1 h 20" / "in 5 min" for the 5-hour window, "Mon 9:00" for the week. */+export function resetLabel(w: PlanWindow, weekly: boolean, now = Date.now()): string {+ const secs = (w.resetsAt - now) / 1000;+ if (secs <= 0) return PLAN_TEXT.resetting;+ if (weekly) {+ const d = new Date(w.resetsAt);+ return `${WEEKDAYS[d.getDay()]} ${d.getHours()}:${String(d.getMinutes()).padStart(2, "0")}`;+ }+ const hours = Math.floor(secs / 3600);+ const mins = Math.floor((secs % 3600) / 60);+ return hours > 0 ? PLAN_TEXT.inHM(hours, mins) : PLAN_TEXT.inM(mins);+}++/** The Claude card's subtitle. */+export function claudeSubtitle(u: PlanUsage | null, now = Date.now()): string {+ return u ? ageLabel(u.updatedAt, now) : PLAN_TEXT.waiting;+}++/** The Codex card's subtitle: "plus · 3 min ago". */+export function codexSubtitle(u: CodexPlanUsage | null, now = Date.now()): string {+ if (!u) return PLAN_TEXT.askingCodex;+ return (u.planType ? `${u.planType} · ` : "") + ageLabel(u.updatedAt, now);+}++/** "2 available · until Oct 9", or "—" when Codex said nothing about resets. */+export function codexResetsLabel(u: CodexPlanUsage | null): string {+ if (u?.resetCredits == null) return PLAN_TEXT.none;+ let text = PLAN_TEXT.available(u.resetCredits);+ if (u.resetCredits > 0 && u.resetCreditExpiresAt != null) {+ const d = new Date(u.resetCreditExpiresAt);+ text += PLAN_TEXT.until(`${MONTHS[d.getMonth()]} ${d.getDate()}`);+ }+ return text;+}++/** How long a Codex answer stays good before the pill asks again (as on the Mac). */+export const CODEX_STALE_MS = 60_000;++/** True when the Codex numbers are missing or older than a minute. */+export const codexIsStale = (u: CodexPlanUsage | null, now = Date.now()): boolean =>+ !u || now - u.updatedAt >= CODEX_STALE_MS;++/** A stored Claude usage, if it still looks like one (the last numbers survive a restart). */+export function restorePlanUsage(raw: string | null): PlanUsage | null {+ if (!raw) return null;+ try {+ const v = asObj(JSON.parse(raw));+ if (!v || !isNum(v.updatedAt)) return null;+ const win = (w: unknown): PlanWindow | undefined => {+ const o = asObj(w);+ return o && isNum(o.usedPct) && isNum(o.resetsAt) && o.usedPct >= 0 && o.usedPct <= 100+ ? { usedPct: o.usedPct, resetsAt: o.resetsAt }+ : undefined;+ };+ const usage: PlanUsage = { updatedAt: v.updatedAt };+ const fh = win(v.fiveHour);+ const sd = win(v.sevenDay);+ if (fh) usage.fiveHour = fh;+ if (sd) usage.sevenDay = sd;+ return fh || sd ? usage : null;+ } catch {+ return null;+ }+}diff --git a/windows/src/core/state.ts b/windows/src/core/state.tsindex 4785897a..f79c162e 100644--- a/windows/src/core/state.ts+++ b/windows/src/core/state.ts@@ -2,6 +2,7 @@import type { BotEmoteName, BotStateName, IslandMode, IslandViewName } from "./layout";import type { EyeShape } from "../mochi/engine";+import type { CodexPlanUsage, PlanUsage } from "./plan";export type AgentSource = "claudeCode" | "n8n" | "agent";export type PillBadge = "approval" | "finished" | "error";@@ -107,6 +108,12 @@ export interface Settings {hooksInstalled: boolean;/** Claude model used by the chat. */model: string;+ /** Show the Claude plan pill (5 h and weekly limits) in the island's header. */+ showPlanInNotch: boolean;+ /** Coucou's status line relay is installed in Claude Code's settings. */+ planRelayInstalled: boolean;+ /** Show the Codex plan pill in the island's header. */+ showCodexPlanInNotch: boolean;}export const DEFAULT_SETTINGS: Settings = {@@ -121,6 +128,9 @@ export const DEFAULT_SETTINGS: Settings = {autostart: false,hooksInstalled: false,model: "claude-opus-5",+ showPlanInNotch: false,+ planRelayInstalled: false,+ showCodexPlanInNotch: false,};type Listener = () => void;@@ -155,6 +165,15 @@ class AppState {integrations: Record<string, IntegrationInfo> = {};+ /** Claude's 5 h / weekly limits, from the status line (null until the first call). */+ planUsage: PlanUsage | null = null;+ /** Codex's limits, from `codex app-server` (null until it has answered). */+ codexPlanUsage: CodexPlanUsage | null = null;+ /** A plan card is open in place of the overview's left card. */+ showingPlanDetail = false;+ /** Which one: the Codex card rather than Claude's. */+ planDetailIsCodex = false;+lastActivity = performance.now();settings: Settings = { ...DEFAULT_SETTINGS };@@ -187,6 +206,7 @@ class AppState {const t = this.tasks.find((x) => x.id === id);if (!t) return;this.focusId = id;+ this.showingPlanDetail = false;t.pillBadge = null;this.notify();}diff --git a/windows/src/island/hooks.ts b/windows/src/island/hooks.tsindex ff03a72f..146a80d3 100644--- a/windows/src/island/hooks.ts+++ b/windows/src/island/hooks.ts@@ -7,6 +7,8 @@ import { Bridge, onEvent } from "../core/bridge";import { Sound } from "../core/sound";import { State, type AskedQuestion } from "../core/state";import type { Island } from "./island";+import { parseClaudePlan, restorePlanUsage } from "../core/plan";+import { setClaudePlanUsage, storedClaudePlanUsage } from "../views/usage";const CLAUDE_ID = "integration_claude";@@ -50,6 +52,8 @@ interface HookPayload {tool_input?: Record<string, unknown>;/** Optional agent tag: lowercase, digits and hyphens, ≤ 24 chars. */coucou_agent?: string;+ /** StatusLine (the plan usage relay): Claude Code's 5-hour and weekly limits. */+ rate_limits?: unknown;}/** Same rule as HookServer.validateAgent on macOS. "claude" is reserved. */@@ -185,10 +189,20 @@ function clearSession() {}export function registerHookHandlers(island: Island) {+ // The last plan numbers seen survive a restart, as on the Mac.+ State.planUsage ??= restorePlanUsage(storedClaudePlanUsage());void onEvent<HookPayload>("hook", (payload) => handleHook(island, payload));}function handleHook(island: Island, payload: HookPayload) {+ // Account-wide numbers from the status line relay, not part of any session:+ // keep the latest, nothing else (no reveal, no sound), paused or not.+ if (payload.hook_event_name === "StatusLine") {+ const usage = parseClaudePlan(payload.rate_limits);+ if (usage) setClaudePlanUsage(usage);+ return;+ }+if (State.paused) {// Silence here used to cost Claude Code nearly two minutes: the relay waited// for a decision from an island that had already decided not to look. Say so,diff --git a/windows/src/island/island.ts b/windows/src/island/island.tsindex 54dbf5f0..ede219b1 100644--- a/windows/src/island/island.ts+++ b/windows/src/island/island.ts@@ -17,6 +17,7 @@ import { Greeting } from "../mochi/greeting";import { createMiniBot, pruneMiniBots, syncMiniBotStates, tickMiniBots } from "../mochi/minibots";import { UploadCanvas } from "../upload/canvas";import { USC, UploadSeq } from "../upload/sequence";+import { closePlanCard, openPlanColor, planCardOpen } from "../views/usage";import { buildHeader, buildViews, type ViewActions, type ViewHost } from "../views/views";import { h } from "../views/dom";import { IslandStateMachine } from "./fsm";@@ -288,6 +289,7 @@ export class Island {void Bridge.focusWindow(false);}if (mode !== "expanded") {+ closePlanCard();this.engine.resetMorph();// Nothing can be seen of the sequence once the island is shut, and leaving// it running would keep the frame loop awake — the island must cost@@ -311,6 +313,7 @@ export class Island {expand(view: IslandViewName) {this.stopSequenceIfLeaving(view);+ if (view !== "overview") closePlanCard();State.view = view;if (State.mode !== "expanded") this.setMode("expanded");else this.animateGeometry(false);@@ -321,6 +324,7 @@ export class Island {setView(view: IslandViewName) {this.stopSequenceIfLeaving(view);+ if (view !== "overview") closePlanCard();if (State.mode !== "expanded") {this.fsm.forceHome();State.view = view;@@ -839,7 +843,12 @@ export class Island {if (!ctx) return;const focus = State.focusTask;- this.engine.bodyColor = focus?.isIntegration ? hexToRGB(focus.color) : null;+ // While a plan card is open Mochi wears the plan's colour, like its pill.+ this.engine.bodyColor = planCardOpen()+ ? hexToRGB(openPlanColor())+ : focus?.isIntegration+ ? hexToRGB(focus.color)+ : null;this.engine.particleOverhang = BOT_OVERHANG;this.engine.lookX = this.lookX();this.engine.lookY = this.lookY();diff --git a/windows/src/settings/main.ts b/windows/src/settings/main.tsindex ccc1b77f..4369c597 100644--- a/windows/src/settings/main.ts+++ b/windows/src/settings/main.ts@@ -3,7 +3,7 @@// integrations land here too in a later stage.import "./settings.css";-import { Bridge, onEvent, type HookStatus } from "../core/bridge";+import { Bridge, onEvent, type HookPreview, type HookStatus } from "../core/bridge";import { DEFAULT_SETTINGS, type Settings } from "../core/state";import { h, clear } from "../views/dom";@@ -46,6 +46,90 @@ function renderDiff(text: string): HTMLElement {return box;}+// ── Changes to Claude Code's settings.json ────────────────────────────────────++/** One kind of change to ~/.claude/settings.json, with the words that go with it. */+interface Change {+ preview: (install: boolean) => Promise<HookPreview | null>;+ apply: (install: boolean, fingerprint: string) => Promise<string | null>;+ installText: string;+ removeText: string;+ installButton: string;+ removeButton: string;+ done: (backup: string) => string;+}++const HOOKS_CHANGE: Change = {+ preview: Bridge.hooksPreview,+ apply: Bridge.hooksApply,+ installText: "This is exactly what will change in your settings.json. Your own hooks are left untouched.",+ removeText: "This removes Coucou's entries only. Your own hooks are left untouched.",+ installButton: "Back up and write",+ removeButton: "Back up and remove",+ done: (backup) => `Done. Previous settings saved as ${backup}. Open a new Claude Code session to pick the hooks up.`,+};++const STATUS_LINE_CHANGE: Change = {+ preview: Bridge.statusLinePreview,+ apply: Bridge.statusLineApply,+ installText: "This is exactly what will change: only the status line. If you already have one it keeps working, Coucou's relay runs it for you.",+ removeText: "This puts your previous status line back, or removes the entry if there was none.",+ installButton: "Back up and write",+ removeButton: "Back up and remove",+ done: (backup) => `Done. Previous settings saved as ${backup}. The numbers appear after the next reply of a Claude Code session.`,+};++/**+ * Shows the diff of a change in `body` and writes it only after an explicit+ * click, and only if settings.json still matches the diff that was shown.+ * `back` redraws the section; `applied` runs a moment after a successful write.+ */+async function reviewChange(+ body: HTMLElement,+ change: Change,+ install: boolean,+ back: () => void,+ applied: () => void,+) {+ let preview;+ try {+ preview = await change.preview(install);+ } catch (err) {+ // An unreadable or invalid settings.json stops here rather than being+ // treated as empty and written over.+ clear(body);+ body.append(+ h("div", { class: "notice err", text: String(err).replace(/^Error:\s*/, "") }),+ h("div", { class: "row" }, h("button", { text: "Back", onclick: back })),+ );+ return;+ }+ if (!preview) return;+ clear(body);+ body.append(+ h("div", { class: "hint", text: install ? change.installText : change.removeText }),+ renderDiff(preview.diff),+ h("div", { class: "row" }, h("span", { class: "path", text: `Backup → ${preview.backup}` })),+ );+ const confirm = h("button", {+ class: install ? "primary" : "danger",+ text: install ? change.installButton : change.removeButton,+ });+ confirm.addEventListener("click", async () => {+ confirm.disabled = true;+ try {+ const backup = await change.apply(install, preview.fingerprint);+ clear(body);+ body.append(h("div", { class: "notice ok", text: change.done(String(backup)) }));+ window.setTimeout(applied, 2600);+ } catch (err) {+ confirm.disabled = false;+ body.append(h("div", { class: "notice err", text: `Could not write: ${String(err)}` }));+ }+ });+ body.append(h("div", { class: "row" }, confirm, h("button", { text: "Cancel", onclick: back })));+}+// ── Claude Code section ───────────────────────────────────────────────────────function claudeSection(status: HookStatus): HTMLElement {@@ -57,11 +141,14 @@ function claudeSection(status: HookStatus): HTMLElement {body,);+ const redraw = () => {+ clear(body);+ draw();+ };const rebuild = async () => {const fresh = await Bridge.hooksStatus();if (fresh) Object.assign(status, fresh);- clear(body);- draw();+ redraw();const head = section.querySelector("h2")!;clear(head);head.append(statusDot(status.installed), h("span", { text: "Claude Code" }));@@ -97,7 +184,7 @@ function claudeSection(status: HookStatus): HTMLElement {const install = h("button", {class: "primary",text: status.installed ? "Reinstall hooks…" : "Install hooks…",- onclick: () => showPreview(true),+ onclick: () => void reviewChange(body, HOOKS_CHANGE, true, redraw, () => void rebuild()),});// Writing hook commands that point at a relay which isn't there would give// every Claude Code session a broken hook and nothing to show for it.@@ -110,66 +197,98 @@ function claudeSection(status: HookStatus): HTMLElement {actions.append(h("button", {class: "danger",text: "Uninstall hooks…",- onclick: () => showPreview(false),+ onclick: () => void reviewChange(body, HOOKS_CHANGE, false, redraw, () => void rebuild()),}));}body.append(actions);}- async function showPreview(install: boolean) {- let preview;- try {- preview = await Bridge.hooksPreview(install);- } catch (err) {- // An unreadable or invalid settings.json stops here rather than being- // treated as empty and written over.- clear(body);- body.append(- h("div", { class: "notice err", text: String(err).replace(/^Error:\s*/, "") }),- h("div", { class: "row" }, h("button", {- text: "Back",- onclick: () => { clear(body); draw(); },- })),- );- return;- }- if (!preview) return;+ draw();+ return section;+}++// ── Plan usage section ────────────────────────────────────────────────────────++/**+ * The 5-hour and weekly limits in the island's header. They come from Claude+ * Code's status line, so the relay has to be the status line first: turning the+ * switch on without it starts the install, and the switch only stays on once+ * that has been confirmed. A status line the user had keeps working.+ */+const PLAN_SETTINGS_TEXT = {+ claude: "Shows your Claude plan usage (5-hour and weekly limits) in the island's header. Coucou adds a status line relay in ~/.claude/settings.json. If you already have a status line, it keeps working as before. Pro and Max plans only.",+ showClaude: "Show in notch",+ codex: "Shows your Codex plan usage (weekly limit and free resets left) in the island's header. Coucou asks the Codex CLI (codex app-server) when the pill shows; nothing is installed. Codex must be signed in with ChatGPT.",+ showCodex: "Show Codex plan in the notch",+};++function planSection(status: HookStatus): HTMLElement {+ const body = h("div", { style: "display:flex;flex-direction:column;gap:12px" });+ const section = h("section", {}, h("h2", {}, h("span", { text: "Plan usage" })), body);++ const redraw = () => {clear(body);+ draw();+ };+ const rebuild = async () => {+ const fresh = await Bridge.hooksStatus();+ if (fresh) Object.assign(status, fresh);+ settings.planRelayInstalled = status.planRelayInstalled;+ // Cancelled or failed: a switch that was waiting for the install falls back.+ if (!status.planRelayInstalled) settings.showPlanInNotch = false;+ redraw();+ };++ function draw() {+ // The switch shows "on" while the install it asked for is being reviewed.+ const sw = toggle(settings.showPlanInNotch, (on) => {+ if (!on) {+ settings.showPlanInNotch = false;+ void save();+ } else if (status.planRelayInstalled) {+ settings.showPlanInNotch = true;+ void save();+ } else {+ // Turned on before the relay is in: install it first; it stays on once confirmed.+ void reviewChange(body, STATUS_LINE_CHANGE, true, () => void rebuild(), () => {+ settings.planRelayInstalled = true;+ settings.showPlanInNotch = true;+ void save().then(rebuild);+ });+ }+ });body.append(h("div", {class: "hint",- text: install- ? "This is exactly what will change in your settings.json. Your own hooks are left untouched."- : "This removes Coucou's entries only. Your own hooks are left untouched.",+ text: PLAN_SETTINGS_TEXT.claude,}),- renderDiff(preview.diff),+ h("div", { class: "row" }, h("label", { text: PLAN_SETTINGS_TEXT.showClaude }), sw),h("div", { class: "row" },- h("span", { class: "path", text: `Backup → ${preview.backup}` }),+ h("label", { text: "Relay" }),+ statusDot(status.planRelayInstalled),+ h("span", { class: "hint", text: status.planRelayInstalled ? "installed" : "not installed" }),+ status.planRelayInstalled+ ? h("button", {+ class: "danger",+ text: "Uninstall relay…",+ onclick: () => void reviewChange(body, STATUS_LINE_CHANGE, false, redraw, () => void rebuild()),+ })+ : h("button", {+ class: "primary",+ text: "Install relay…",+ onclick: () => void reviewChange(body, STATUS_LINE_CHANGE, true, redraw, () => void rebuild()),+ }),+ ),+ // Codex: nothing to install, Coucou asks the Codex CLI when the pill shows.+ h("div", { class: "hint", text: PLAN_SETTINGS_TEXT.codex }),+ h("div", { class: "row" },+ h("label", { text: PLAN_SETTINGS_TEXT.showCodex }),+ toggle(settings.showCodexPlanInNotch, (on) => {+ settings.showCodexPlanInNotch = on;+ void save();+ }),),);- const confirm = h("button", {- class: install ? "primary" : "danger",- text: install ? "Back up and write" : "Back up and remove",- });- confirm.addEventListener("click", async () => {- confirm.disabled = true;- try {- const backup = await Bridge.hooksApply(install, preview.fingerprint);- clear(body);- body.append(h("div", {- class: "notice ok",- text: `Done. Previous settings saved as ${backup}. Open a new Claude Code session to pick the hooks up.`,- }));- window.setTimeout(() => void rebuild(), 2600);- } catch (err) {- confirm.disabled = false;- body.append(h("div", { class: "notice err", text: `Could not write: ${String(err)}` }));- }- });- body.append(h("div", { class: "row" }, confirm, h("button", {- text: "Cancel",- onclick: () => { clear(body); draw(); },- })));}draw();@@ -446,7 +565,7 @@ async function main() {version = boot.version;}const status = (await Bridge.hooksStatus()) ?? {- installed: false, settingsPath: "", hookPath: "", hookReady: false,+ installed: false, planRelayInstalled: false, settingsPath: "", hookPath: "", hookReady: false,};const hasKey = (await Bridge.secretPresent("anthropic-api-key")) ?? false;@@ -462,6 +581,7 @@ async function main() {root.append(h("h1", {}, h("span", { text: "Coucou" }), h("span", { class: "version", text: version })),claudeSection(status),+ planSection(status),apiSection(hasKey),integrationsSection(present),generalSection(),diff --git a/windows/src/style.css b/windows/src/style.cssindex 335ed159..59817c47 100644--- a/windows/src/style.css+++ b/windows/src/style.css@@ -1389,3 +1389,155 @@ input[type="range"]::-webkit-slider-thumb {.int-card.detail {padding-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;+}diff --git a/windows/src/views/icons.ts b/windows/src/views/icons.tsindex d2ff8247..ecda77f1 100644--- a/windows/src/views/icons.ts+++ b/windows/src/views/icons.ts@@ -17,6 +17,8 @@ export const ICONS = {speakerOff: "M11 4.5 6.5 8.2H3.4v7.6h3.1L11 19.5v-15zm3.6 4.1 1.27-1.27 2.33 2.33 2.33-2.33 1.27 1.27L19.47 11l2.33 2.33-1.27 1.27-2.33-2.33-2.33 2.33-1.27-1.27L16.93 11 14.6 8.6z",// arrow.up.rightarrowUpRight: "M8.5 7h8.5v8.5h-2V10.4l-7.1 7.1-1.4-1.4 7.1-7.1H8.5V7z",+ // arrow.clockwise (stroke)+ arrowClockwise: "M19 12a7 7 0 1 1-2.05-4.95M19 4.5V8h-3.5",// chevron.rightchevronRight: "M9 5.5 15.5 12 9 18.5",chevronLeft: "M15 5.5 8.5 12 15 18.5",diff --git a/windows/src/views/usage.ts b/windows/src/views/usage.tsnew file mode 100644index 00000000..1813f98a--- /dev/null+++ b/windows/src/views/usage.ts@@ -0,0 +1,213 @@+// Plan usage in the island: the Claude and Codex pills in the header and the+// card behind each. Same behaviour as ClaudePlanHeaderPill, ClaudePlanCardView+// and CodexPlanCardView on the Mac; the numbers and labels come from+// core/plan.ts.+//+// The pills sit in the header's right side, before the gear, on the overview+// only, Claude first. Clicking one puts its card in place of the overview's+// left card (clicking it again, or the other pill, closes or swaps it), and+// Mochi wears the plan's colour while it is open. It closes when the view, the+// mode or the focused pill changes.++import { Bridge } from "../core/bridge";+import {+ PLAN_TEXT, claudeSubtitle, codexIsStale, codexResetsLabel, codexSubtitle, dominantPct,+ effectivePct, parseCodexPlan, pillLabel, planColor, resetLabel,+ type CodexPlanUsage, type PlanUsage, type PlanWindow,+} from "../core/plan";+import { State } from "../core/state";+import { clear, dot, h, svg } from "./dom";+import { ICONS } from "./icons";++/** The Claude pill is in the header: overview, turned on, relay in. */+export function claudePillVisible(): boolean {+ const s = State.settings;+ return State.view === "overview" && s.showPlanInNotch && s.planRelayInstalled;+}++/** The Codex pill is in the header: overview, turned on (nothing to install). */+export function codexPillVisible(): boolean {+ return State.view === "overview" && State.settings.showCodexPlanInNotch;+}++/** A plan card is open and its pill is still there. */+export function planCardOpen(): boolean {+ if (!State.showingPlanDetail) return false;+ return State.planDetailIsCodex ? codexPillVisible() : claudePillVisible();+}++const claudeColor = (now = Date.now()) => planColor(dominantPct(State.planUsage, now));+const codexColor = (now = Date.now()) => planColor(dominantPct(State.codexPlanUsage, now));++/** The colour of the open card's plan, which Mochi wears while it is open. */+export function openPlanColor(): string {+ return State.planDetailIsCodex ? codexColor() : claudeColor();+}++/** Closes the plan card (view, mode or focus changed). */+export function closePlanCard(): void {+ State.showingPlanDetail = false;+}++// ── Claude numbers ────────────────────────────────────────────────────────────++const STORE_KEY = "coucou.claudePlanUsage";++/** New numbers from the status line; kept so they survive a restart, as on the Mac. */+export function setClaudePlanUsage(usage: PlanUsage): void {+ const prev = State.planUsage;+ const same = JSON.stringify([prev?.fiveHour, prev?.sevenDay]) === JSON.stringify([usage.fiveHour, usage.sevenDay]);+ State.planUsage = usage;+ if (!same) {+ try {+ window.localStorage?.setItem(STORE_KEY, JSON.stringify(usage));+ } catch {+ // Storage off or full: the numbers just will not outlive this run.+ }+ }+ // The relay calls in with every Claude Code update: a hidden island is only+ // woken when the numbers actually moved.+ if (!same || State.mode === "expanded") State.notify();+}++/** The last numbers seen, if any were kept. */+export function storedClaudePlanUsage(): string | null {+ try {+ return window.localStorage?.getItem(STORE_KEY) ?? null;+ } catch {+ return null;+ }+}++// ── Codex numbers ─────────────────────────────────────────────────────────────++let codexInFlight = false;++/**+ * Asks Codex again when the numbers are missing or older than a minute. Only+ * from the pill (shown or clicked), never on a timer, and never while paused:+ * `codex app-server` talks to Codex's own service.+ */+export function refreshCodexPlanUsage(): void {+ if (codexInFlight || State.paused || !codexIsStale(State.codexPlanUsage)) return;+ codexInFlight = true;+ void Bridge.codexPlanUsage()+ .then((result) => {+ const usage = parseCodexPlan(result);+ if (usage) {+ State.codexPlanUsage = usage;+ State.notify();+ }+ })+ .finally(() => {+ codexInFlight = false;+ });+}++// ── Pill ──────────────────────────────────────────────────────────────────────++export interface PlanPill {+ el: HTMLElement;+ sync(): void;+}++/** One pill: colour dot and label, lit while hovered or while its card is open. */+export function buildPlanPill(codex: boolean): PlanPill {+ const label = h("span", { class: "plan-pill-label" });+ const dotEl = h("i", { class: "plan-pill-dot" });+ const isOpen = () => State.showingPlanDetail && State.planDetailIsCodex === codex;+ const el = h("button", {+ class: "plan-pill",+ title: codex ? PLAN_TEXT.codexPillTitle : PLAN_TEXT.claudePillTitle,+ onclick: () => {+ const open = isOpen();+ State.planDetailIsCodex = codex;+ State.showingPlanDetail = !open;+ if (codex) refreshCodexPlanUsage();+ State.notify();+ },+ }, dotEl, label);+ return {+ el,+ sync() {+ const color = codex ? codexColor() : claudeColor();+ el.style.setProperty("--plan", color);+ el.classList.toggle("active", isOpen());+ dotEl.style.background = color;+ label.textContent = codex+ ? pillLabel("Codex", State.codexPlanUsage)+ : pillLabel("Claude", State.planUsage);+ },+ };+}++// ── Card ──────────────────────────────────────────────────────────────────────++function gaugeRow(label: string, w: PlanWindow | undefined, weekly: boolean, now: number): HTMLElement {+ const row = h("div", { class: "plan-row" }, h("span", { class: "plan-label", text: label }));+ if (!w) {+ row.append(h("span", { class: "plan-none", text: PLAN_TEXT.none }));+ return row;+ }+ const pct = effectivePct(w, now);+ const fill = h("i", { class: "plan-fill" });+ fill.style.width = `${pct}%`;+ fill.style.background = planColor(pct);+ row.append(+ h("span", { class: "plan-bar" }, fill),+ h("span", { class: "plan-pct", text: `${Math.round(pct)}%` }),+ h("span", { class: "plan-reset-icon" }, svg(ICONS.arrowClockwise, 8, { stroke: 2.6 })),+ h("span", { class: "plan-reset", text: resetLabel(w, weekly, now) }),+ );+ return row;+}++function head(color: string, title: string, subtitle: string): HTMLElement {+ return h("div", { class: "plan-head" },+ dot(color, 7),+ h("span", { class: "plan-title", text: title }),+ h("span", { class: "plan-sub", text: subtitle }),+ );+}++/** The card that stands in for the overview's left card while a pill is open. */+export class PlanCard {+ readonly el = h("div", { class: "plan-card" });+ private key = "";++ /** Re-renders when the numbers change, or every 30 s for the countdowns. */+ sync(now = Date.now()) {+ const codex = State.planDetailIsCodex;+ const u = codex ? State.codexPlanUsage : State.planUsage;+ const key = `${codex}|${JSON.stringify(u)}|${Math.floor(now / 30_000)}`;+ if (key === this.key) return;+ this.key = key;+ clear(this.el);+ if (codex) this.drawCodex(State.codexPlanUsage, now);+ else this.drawClaude(State.planUsage, now);+ }++ private drawClaude(u: PlanUsage | null, now: number) {+ this.el.append(+ head(claudeColor(now), PLAN_TEXT.claudeTitle, claudeSubtitle(u, now)),+ h("div", { class: "plan-rows" },+ gaugeRow(PLAN_TEXT.fiveHours, u?.fiveHour, false, now),+ gaugeRow(PLAN_TEXT.week, u?.sevenDay, true, now),+ ),+ );+ }++ private drawCodex(u: CodexPlanUsage | null, now: number) {+ const rows = h("div", { class: "plan-rows" });+ // Codex plans without a 5-hour window show the week alone, as on the Mac.+ if (u?.fiveHour) rows.append(gaugeRow(PLAN_TEXT.fiveHours, u.fiveHour, false, now));+ rows.append(+ gaugeRow(PLAN_TEXT.week, u?.sevenDay, true, now),+ h("div", { class: "plan-row" },+ h("span", { class: "plan-label", text: PLAN_TEXT.resets }),+ h("span", { class: "plan-credits", text: codexResetsLabel(u) }),+ ),+ );+ this.el.append(head(codexColor(now), PLAN_TEXT.codexTitle, codexSubtitle(u, now)), rows);+ }+}diff --git a/windows/src/views/views.ts b/windows/src/views/views.tsindex e433651d..b1174a9b 100644--- a/windows/src/views/views.ts+++ b/windows/src/views/views.ts@@ -11,6 +11,9 @@ import { createMiniBot, pruneMiniBots } from "../mochi/minibots";import { buildPrompt } from "./chat";import { buildChoose, buildUpload, buildUploading } from "./upload";import { renderIntegrationCard, type IntegrationCardHooks } from "./integrations";+import {+ PlanCard, buildPlanPill, claudePillVisible, codexPillVisible, planCardOpen, refreshCodexPlanUsage,+} from "./usage";export interface ViewActions {setView(v: IslandViewName): void;@@ -90,6 +93,11 @@ export function buildHeader(actions: ViewActions): ViewHost {const gearBtn = h("button", { title: "Settings", onclick: () => go("settings") }, svg(ICONS.gear, 14));const soundBtn = h("button", { title: "Mute", onclick: () => actions.toggleSound() }, svg(ICONS.speakerOn, 14));+ // Plan usage pills (off by default): before the gear, Claude first, as on the Mac.+ const claudePill = buildPlanPill(false);+ const codexPill = buildPlanPill(true);+ const planPills = h("div", { class: "plan-pills" }, claudePill.el, codexPill.el);+ let codexShown = false;function go(v: IslandViewName) {actions.blip();@@ -100,8 +108,9 @@ export function buildHeader(actions: ViewActions): ViewHost {"div",{ id: "header" },h("div", { class: "tabs" }, tabHome, tabChat, tabDrop),- h("div", { class: "header-actions" }, gearBtn, soundBtn),+ h("div", { class: "header-actions" }, planPills, gearBtn, soundBtn),);+ const headerActions = el.lastElementChild as HTMLElement;return {el,@@ -115,9 +124,26 @@ export function buildHeader(actions: ViewActions): ViewHost {gearBtn.append(svg(v === "settings" ? ICONS.gearFill : ICONS.gear, 14));clear(soundBtn);soundBtn.append(svg(State.settings.soundEnabled ? ICONS.speakerOn : ICONS.speakerOff, 14));+ syncPlanPills();el.style.opacity = v === "confused" ? "0" : "1";},};++ function syncPlanPills() {+ const claudeOn = claudePillVisible();+ const codexOn = codexPillVisible();+ claudePill.el.style.display = claudeOn ? "" : "none";+ codexPill.el.style.display = codexOn ? "" : "none";+ planPills.classList.toggle("on", claudeOn || codexOn);+ // Both pills: the right side tightens so it still clears the screen edge.+ headerActions.classList.toggle("both-plans", claudeOn && codexOn);+ if (claudeOn) claudePill.sync();+ if (codexOn) codexPill.sync();+ // Codex is asked when its pill comes into view (stale answers only).+ const shown = codexOn && State.mode === "expanded";+ if (shown && !codexShown) refreshCodexPlanUsage();+ codexShown = shown;+ }}// ── Overview ──────────────────────────────────────────────────────────────────@@ -135,6 +161,9 @@ function buildOverview(actions: ViewActions): ViewHost {const left = card(null, leftBody, jump);const pills = h("div", { class: "pills" });const right = card(null, pills);+ // Opened from a plan pill in the header: stands in for the left card.+ const plan = new PlanCard();+ let planTimer: number | null = null;const el = h("div", { class: "view overview" },h("div", { class: "left" }, left),@@ -144,7 +173,7 @@ function buildOverview(actions: ViewActions): ViewHost {let pillIds = "";let detailOpen = false;let lastFocus: string | null = null;- let mode: "ticker" | "card" | null = null;+ let mode: "ticker" | "card" | "plan" | null = null;let cardKey = "";const hooks: IntegrationCardHooks = {@@ -164,6 +193,20 @@ function buildOverview(actions: ViewActions): ViewHost {openSettings: () => actions.openSettingsWindow(),};+ /** The countdowns move every 30 s while a card is open, and only then. */+ function syncPlanTimer(open: boolean) {+ const stop = () => {+ if (planTimer != null) window.clearInterval(planTimer);+ planTimer = null;+ };+ if (!open) return stop();+ if (planTimer != null) return;+ planTimer = window.setInterval(() => {+ if (planCardOpen() && State.mode === "expanded") State.notify();+ else stop();+ }, 30_000);+ }+return {el,tick(nowMs: number) {@@ -185,7 +228,21 @@ function buildOverview(actions: ViewActions): ViewHost {const sessionActive =task?.id === "integration_claude" && (task.state !== "idle" || task.steps.length > 0);- if (task && sessionActive) {+ const planOpen = planCardOpen();+ if (mode === "plan" && !planOpen) {+ mode = null;+ cardKey = "";+ }+ syncPlanTimer(planOpen);++ if (planOpen) {+ if (mode !== "plan") {+ clear(leftBody);+ leftBody.append(plan.el);+ mode = "plan";+ }+ plan.sync();+ } else if (task && sessionActive) {if (mode !== "ticker") {clear(leftBody);leftBody.append(tickerBody);@@ -220,7 +277,7 @@ function buildOverview(actions: ViewActions): ViewHost {}}- jump.style.display = detailOpen ? "none" : "";+ jump.style.display = detailOpen || mode === "plan" ? "none" : "";const others = State.otherTasks.slice(0, 4);const pillKey = others.map((t) => `${t.id}:${t.pillBadge ?? ""}`).join("|");diff --git a/windows/tests/plan.test.mjs b/windows/tests/plan.test.mjsnew file mode 100644index 00000000..29b5f763--- /dev/null+++ b/windows/tests/plan.test.mjs@@ -0,0 +1,261 @@+// Plan usage gauges (src/core/plan.ts, src/views/usage.ts): a port of the Mac's+// tests/ClaudePlanGaugeTests.swift, the Codex parsing of CodexPlanGauge.swift,+// and the pills' rules (where they show, what a click opens, what closes it).++import { beforeEach, test } from "node:test";+import assert from "node:assert/strict";+import {+ claudeSubtitle, codexIsStale, codexResetsLabel, codexSubtitle, dominantPct, effectivePct,+ parseClaudePlan, parseCodexPlan, pillLabel, planColor, resetLabel, restorePlanUsage,+} from "../src/core/plan.ts";+import { emit } from "./tauri.mjs";+import { registerHookHandlers } from "../src/island/hooks.ts";+import {+ claudePillVisible, codexPillVisible, openPlanColor, planCardOpen,+} from "../src/views/usage.ts";+import { DEFAULT_SETTINGS, State } from "../src/core/state.ts";++const NOW = Date.UTC(2026, 9, 7, 12, 0, 0);+const future = NOW / 1000 + 7200; // 2 hours from now, epoch seconds+const past = NOW / 1000 - 100;+const claude = (rl) => parseClaudePlan(rl, NOW);+const win = (pct, epochS) => ({ usedPct: pct, resetsAt: epochS * 1000 });++// ── ClaudePlanGauge.parse ─────────────────────────────────────────────────────++test("a full payload gives both windows", () => {+ const u = claude({+ five_hour: { used_percentage: 23.5, resets_at: future },+ seven_day: { used_percentage: 67.0, resets_at: future },+ });+ assert.equal(u.fiveHour.usedPct, 23.5);+ assert.equal(u.sevenDay.usedPct, 67);+ assert.equal(u.fiveHour.resetsAt, future * 1000);+ assert.equal(u.updatedAt, NOW);+});++test("missing or empty rate_limits is nothing", () => {+ assert.equal(claude(undefined), null);+ assert.equal(claude({}), null);+ assert.equal(claude("x"), null);+});++test("percentages: 150 is shown full, above 200 or below 0 is dropped, ints are fine", () => {+ const one = (pct) => claude({ five_hour: { used_percentage: pct, resets_at: future } })?.fiveHour;+ assert.equal(one(250), undefined);+ assert.equal(one(201), undefined);+ assert.equal(one(-5), undefined);+ assert.equal(one(150).usedPct, 100);+ assert.equal(one(42).usedPct, 42);+ assert.equal(one("42"), undefined);+});++test("a reset more than 400 days away is milliseconds in disguise", () => {+ const far = NOW / 1000 + 401 * 86400;+ assert.equal(claude({ five_hour: { used_percentage: 50, resets_at: far } }), null);+ assert.equal(claude({ five_hour: { used_percentage: 50, resets_at: NOW } }), null);+ assert.equal(claude({ five_hour: { used_percentage: 50, resets_at: 0 } }), null);+});++test("one good window is enough", () => {+ const u = claude({+ five_hour: { used_percentage: 250, resets_at: future },+ seven_day: { used_percentage: 10, resets_at: future },+ });+ assert.equal(u.fiveHour, undefined);+ assert.equal(u.sevenDay.usedPct, 10);+});++// ── effectivePct / dominantPct ────────────────────────────────────────────────++test("a window whose reset has passed counts as 0", () => {+ assert.equal(effectivePct(win(80, past), NOW), 0);+ assert.equal(effectivePct(win(80, future), NOW), 80);+});++test("the dominant percentage is the higher window", () => {+ const both = { fiveHour: win(30, future), sevenDay: win(70, future), updatedAt: NOW };+ const fhOnly = { fiveHour: win(55, future), updatedAt: NOW };+ const empty = { updatedAt: NOW };+ assert.equal(dominantPct(both, NOW), 70);+ assert.equal(dominantPct(fhOnly, NOW), 55);+ assert.equal(dominantPct(empty, NOW), null);+ assert.equal(dominantPct(null, NOW), null);+ // An expired week no longer dominates.+ assert.equal(dominantPct({ fiveHour: win(30, future), sevenDay: win(90, past), updatedAt: NOW }, NOW), 30);+});++// ── color / labels ────────────────────────────────────────────────────────────++test("colours: grey, then green below 50, orange below 80, red", () => {+ assert.equal(planColor(null), "#6B7079");+ assert.equal(planColor(0), "#22C55E");+ assert.equal(planColor(49), "#22C55E");+ assert.equal(planColor(50), "#F59E0B");+ assert.equal(planColor(79), "#F59E0B");+ assert.equal(planColor(80), "#F4505E");+ assert.equal(planColor(100), "#F4505E");+});++test("pill labels read like the Mac's header pill", () => {+ const both = { fiveHour: win(30, future), sevenDay: win(70, future), updatedAt: NOW };+ assert.equal(pillLabel("Claude", null, NOW), "Claude —");+ assert.equal(pillLabel("Claude", { updatedAt: NOW }, NOW), "Claude —");+ assert.equal(pillLabel("Claude", both, NOW), "Claude 70%");+ assert.equal(pillLabel("Codex", { sevenDay: win(12.4, future), updatedAt: NOW }, NOW), "Codex 12%");+ assert.equal(pillLabel("Codex", null, NOW), "Codex —");+});++test("reset times: a countdown for 5 hours, a weekday for the week", () => {+ assert.equal(resetLabel(win(10, NOW / 1000 + 4800), false, NOW), "in 1 h 20");+ assert.equal(resetLabel(win(10, NOW / 1000 + 300), false, NOW), "in 5 min");+ assert.equal(resetLabel(win(10, past), false, NOW), "Resetting…");+ const at = new Date(2026, 9, 12, 9, 5); // a Monday, local time+ assert.equal(resetLabel({ usedPct: 1, resetsAt: at.getTime() }, true, at.getTime() - 3600_000), "Mon 9:05");+});++test("subtitles say how old the numbers are", () => {+ assert.equal(claudeSubtitle(null, NOW), "Waiting for a response from Claude Code");+ assert.equal(claudeSubtitle({ updatedAt: NOW - 30_000 }, NOW), "just now");+ assert.equal(claudeSubtitle({ updatedAt: NOW - 12 * 60_000 }, NOW), "12 min ago");+ assert.equal(claudeSubtitle({ updatedAt: NOW - 3 * 3600_000 }, NOW), "3 h ago");+ assert.equal(codexSubtitle(null, NOW), "Asking Codex…");+ assert.equal(codexSubtitle({ planType: "plus", updatedAt: NOW - 120_000 }, NOW), "plus · 2 min ago");+});++test("the last Claude numbers survive a restart, and junk does not", () => {+ const u = { fiveHour: win(30, future), updatedAt: NOW };+ assert.deepEqual(restorePlanUsage(JSON.stringify(u)), u);+ assert.equal(restorePlanUsage(null), null);+ assert.equal(restorePlanUsage("{"), null);+ assert.equal(restorePlanUsage(JSON.stringify({ updatedAt: NOW, fiveHour: { usedPct: 900, resetsAt: 1 } })), null);+});++// ── CodexPlanGauge.parse ──────────────────────────────────────────────────────++test("Codex windows are sorted by duration, not by primary/secondary", () => {+ const u = parseCodexPlan({+ rateLimits: {+ planType: "plus",+ primary: { usedPercent: 64, resetsAt: future + 86400, windowDurationMins: 10080 },+ secondary: { usedPercent: 12.5, resetsAt: future, windowDurationMins: 300 },+ },+ }, NOW);+ assert.equal(u.planType, "plus");+ assert.equal(u.fiveHour.usedPct, 12.5);+ assert.equal(u.sevenDay.usedPct, 64);+ assert.equal(u.sevenDay.resetsAt, (future + 86400) * 1000);+});++test("a Codex window without a duration is the week; percentages are clamped", () => {+ const u = parseCodexPlan({ rateLimits: { primary: { usedPercent: 140, resetsAt: future } } }, NOW);+ assert.equal(u.fiveHour, undefined);+ assert.equal(u.sevenDay.usedPct, 100);+ const low = parseCodexPlan({ rateLimits: { primary: { usedPercent: -3, resetsAt: future } } }, NOW);+ assert.equal(low.sevenDay.usedPct, 0);+});++test("free resets: the count and the soonest available expiry", () => {+ const u = parseCodexPlan({+ rateLimits: { primary: { usedPercent: 5, resetsAt: future, windowDurationMins: 10080 } },+ rateLimitResetCredits: {+ availableCount: 2,+ credits: [+ { status: "available", expiresAt: Date.UTC(2026, 10, 20, 12) / 1000 },+ { status: "used", expiresAt: Date.UTC(2026, 9, 1, 12) / 1000 },+ { status: "available", expiresAt: Date.UTC(2026, 9, 9, 12) / 1000 },+ ],+ },+ }, NOW);+ assert.equal(u.resetCredits, 2);+ assert.equal(u.resetCreditExpiresAt, Date.UTC(2026, 9, 9, 12));+ assert.equal(codexResetsLabel(u), "2 available · until Oct 9");+ assert.equal(codexResetsLabel({ ...u, resetCredits: 0 }), "0 available");+ assert.equal(codexResetsLabel({ updatedAt: NOW }), "—");+ assert.equal(codexResetsLabel(null), "—");+});++test("no Codex limits, or only broken ones, is nothing", () => {+ assert.equal(parseCodexPlan(null, NOW), null);+ assert.equal(parseCodexPlan({}, NOW), null);+ assert.equal(parseCodexPlan({ rateLimits: { primary: { usedPercent: "5", resetsAt: future } } }, NOW), null);+ assert.equal(parseCodexPlan({ rateLimits: { primary: { usedPercent: 5 } } }, NOW), null);+});++test("Codex is asked again only once its numbers are a minute old", () => {+ assert.equal(codexIsStale(null, NOW), true);+ assert.equal(codexIsStale({ updatedAt: NOW - 59_000 }, NOW), false);+ assert.equal(codexIsStale({ updatedAt: NOW - 60_000 }, NOW), true);+});++// ── The pills in the island ───────────────────────────────────────────────────++registerHookHandlers({ alert() {}, setView() {}, reveal() {}, dropPin() {} });++beforeEach(() => {+ State.settings = { ...DEFAULT_SETTINGS };+ State.view = "overview";+ State.paused = false;+ State.planUsage = null;+ State.codexPlanUsage = null;+ State.showingPlanDetail = false;+ State.planDetailIsCodex = false;+});++test("both pills are off by default, so the header is as it shipped", () => {+ assert.equal(claudePillVisible(), false);+ assert.equal(codexPillVisible(), false);+});++test("the Claude pill needs the switch and the relay, and the overview", () => {+ State.settings.showPlanInNotch = true;+ assert.equal(claudePillVisible(), false);+ State.settings.planRelayInstalled = true;+ assert.equal(claudePillVisible(), true);+ State.view = "prompt";+ assert.equal(claudePillVisible(), false);+});++test("the Codex pill needs only its switch, on the overview", () => {+ State.settings.showCodexPlanInNotch = true;+ assert.equal(codexPillVisible(), true);+ State.view = "settings";+ assert.equal(codexPillVisible(), false);+});++test("an open card follows its pill, and Mochi wears that plan's colour", () => {+ State.settings.showPlanInNotch = true;+ State.settings.planRelayInstalled = true;+ State.showingPlanDetail = true;+ assert.equal(planCardOpen(), true);+ assert.equal(openPlanColor(), "#6B7079");+ // The Codex card cannot be open without its pill.+ State.planDetailIsCodex = true;+ assert.equal(planCardOpen(), false);+ State.settings.showCodexPlanInNotch = true;+ assert.equal(planCardOpen(), true);+ State.codexPlanUsage = { sevenDay: win(85, Date.now() / 1000 + 3600), updatedAt: Date.now() };+ assert.equal(openPlanColor(), "#F4505E");+});++test("focusing another pill closes the plan card", () => {+ State.loadIntegrationTasks();+ State.showingPlanDetail = true;+ State.setFocus(State.tasks[0].id);+ assert.equal(State.showingPlanDetail, false);+});++test("a status line call updates the numbers and nothing else, even when paused", () => {+ State.paused = true;+ const tasks = JSON.stringify(State.tasks);+ emit("hook", {+ hook_event_name: "StatusLine",+ session_id: "s1",+ rate_limits: { five_hour: { used_percentage: 42, resets_at: Date.now() / 1000 + 3600 } },+ });+ assert.equal(State.planUsage.fiveHour.usedPct, 42);+ assert.equal(JSON.stringify(State.tasks), tasks);+ // Without limits (API-key users) the last numbers stay.+ emit("hook", { hook_event_name: "StatusLine", session_id: "s1" });+ assert.equal(State.planUsage.fiveHour.usedPct, 42);+});