Claude plan usage in the notch: 5-hour and weekly limits

As on the Mac (docs/INTEGRATIONS.md, "Jauge de forfait Claude"), for the Tauri build:

- A pill in the header of the overview ("Claude 73%", green below 50 %, orange up to
  80 %, red above, grey without data). Clicking it puts the plan card in place of the
  left card (5 hours and week, reset times, how old the numbers are), and Mochi wears
  the plan's colour while it is open. It closes when the view, the mode or the focus
  changes. Off by default.
- The numbers come from Claude Code's own status line (`rate_limits`), like on the Mac,
  and are checked the same way: 100-200 % is shown full, anything else is dropped, a
  reset more than 400 days away is milliseconds in disguise, and a window whose reset
  has passed counts as 0 %.
- The relay runs as the status line (`coucou-hook --statusline`), passes the limits on
  and runs the status line the user had before with the same input, printing its output
  untouched (10 s limit). That one is kept in statusline-previous.json beside the relay.
- Installing and removing the relay is its own step, apart from the hooks: Settings ->
  Plan usage shows the diff of the `statusLine` key only, backs settings.json up and
  writes after a click. Only `command` is swapped, so padding and the like stay;
  removing puts the previous status line back, or the key goes if there was none, and a
  status line the user changed since is left alone.
- Settings -> Plan usage -> Show in the notch turns it on and starts the install first
  when the relay is not in yet.

Calls using the older `coucou-hook StatusLine` form keep working.
This commit is contained in:
Justin Minkmar committed 2026-10-03 13:27:48 +02:00
1 parent d40e63fd7b
commit 273efa050d
14 files changed
+899 -63

No files matched your search

+7
View File
@@ -194,6 +194,13 @@ What changes on Linux:
overview's left card opens a small editor (the changed lines in red and green with
a few lines of context from the file, then the last command and what it printed);
the button in its corner goes back. Nothing opens by itself.
- **Plan usage**, as on the Mac: a small pill in the island's header ("Claude 73%", green
below 50 %, orange up to 80 %, red above) shows your 5-hour and weekly Claude limits,
and clicking it opens the details and reset times. Settings → Plan usage →
**Show in the notch** turns it on and installs a status line relay after showing you the
diff of `~/.claude/settings.json`; a status line you already have keeps working (the relay
runs it) and **Uninstall relay** puts it back. Pro and Max plans only, and the numbers
arrive with Claude Code's replies.
- **Open terminal** jumps to the Konsole tab the session runs in: the relay passes
Konsole's D-Bus names, the app switches the tab over D-Bus and asks KWin (a
short script, via `gdbus`) to raise that window. In any other terminal it opens
+158 -2
View File
@@ -14,11 +14,13 @@
//! island is the whole point. No answer means empty stdout, and Claude Code
//! asks in the terminal exactly as if Coucou were not installed.
//!
//! Usage: `coucou-hook <EventName>` (the name is also read from the JSON).
//! Usage: `coucou-hook <EventName>` (the name is also read from the JSON), or
//! `coucou-hook --statusline` as Claude Code's status line command: it passes the
//! plan limits on and runs the status line the user had before, so that keeps working.
use std::io::{Read, Write};
use std::sync::mpsc;
use std::time::Duration;
use std::time::{Duration, Instant};
/// Budget for getting a pipe connection. Beyond this Claude Code wins, always.
const CONNECT_TIMEOUT: Duration = Duration::from_millis(300);
@@ -26,6 +28,8 @@ const CONNECT_TIMEOUT: Duration = Duration::from_millis(300);
const FIRE_AND_FORGET_BUDGET: Duration = Duration::from_secs(2);
/// How long a permission prompt may stay on screen before the terminal takes over.
const DECISION_BUDGET: Duration = Duration::from_secs(110);
/// How long the user's own status line may take before we give up on it.
const PREVIOUS_STATUS_LINE_BUDGET: Duration = Duration::from_secs(10);
/// Fields that are pointless to forward and can be enormous (a whole file read,
/// a full command output). The island never shows them.
@@ -48,6 +52,9 @@ mod unix;
use unix::connect;
fn main() {
if std::env::args().any(|a| a == "--statusline") {
run_status_line();
}
let Some((payload, event)) = read_event() else { std::process::exit(0) };
let waits_for_answer = event == "PermissionRequest";
@@ -73,6 +80,102 @@ fn main() {
std::process::exit(0);
}
/// `coucou-hook --statusline`: the status line command of Claude Code.
///
/// It gets the session's JSON on stdin and whatever it prints becomes the status
/// line. Coucou only wants the plan limits in it, so they go on in the background
/// (never delaying the status line), and if the user had a status line of their
/// own it is run with the same input and its output passed on untouched.
fn run_status_line() -> ! {
let mut raw = Vec::new();
let _ = std::io::stdin().read_to_end(&mut raw);
if raw.starts_with(&[0xEF, 0xBB, 0xBF]) {
raw.drain(..3);
}
let sent = serde_json::from_slice::<serde_json::Value>(&raw)
.ok()
.and_then(|v| status_line_payload(v.as_object()?))
.map(|line| {
let (tx, rx) = mpsc::channel();
std::thread::spawn(move || {
let _ = tx.send(talk(&line, false));
});
rx
});
if let Some(command) = previous_status_line() {
if let Some(out) = run_previous(&command, &raw, PREVIOUS_STATUS_LINE_BUDGET) {
let mut stdout = std::io::stdout();
let _ = stdout.write_all(&out);
let _ = stdout.flush();
}
}
// Coucou's share is a few hundred milliseconds at most.
if let Some(rx) = sent {
let _ = rx.recv_timeout(CONNECT_TIMEOUT);
}
std::process::exit(0);
}
/// The command of the status line the user had before Coucou's relay took its place,
/// saved by the installer next to this program.
fn previous_status_line() -> Option<String> {
let path = std::env::current_exe().ok()?.with_file_name("statusline-previous.json");
let saved: serde_json::Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;
saved.get("command")?.as_str().filter(|c| !c.trim().is_empty()).map(str::to_string)
}
/// Runs `command` through the shell with `input` on stdin and returns what it
/// printed, or nothing if it could not start or ran past `budget` (then it is killed).
fn run_previous(command: &str, input: &[u8], budget: Duration) -> Option<Vec<u8>> {
use std::process::{Command, Stdio};
#[cfg(unix)]
let mut cmd = {
let mut c = Command::new("/bin/sh");
c.args(["-c", command]);
c
};
#[cfg(windows)]
let mut cmd = {
use std::os::windows::process::CommandExt;
let mut c = Command::new("cmd");
c.args(["/C", command]).creation_flags(0x0800_0000); // no console window
c
};
let mut child =
cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().ok()?;
// Feed and drain on their own threads: a long input or output cannot deadlock us.
let mut stdin = child.stdin.take()?;
let data = input.to_vec();
std::thread::spawn(move || {
let _ = stdin.write_all(&data);
});
let mut stdout = child.stdout.take()?;
let (tx, rx) = mpsc::channel();
std::thread::spawn(move || {
let mut out = Vec::new();
let _ = stdout.read_to_end(&mut out);
let _ = tx.send(out);
});
let deadline = Instant::now() + budget;
loop {
match child.try_wait() {
Ok(Some(_)) => break,
Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(10)),
_ => {
let _ = child.kill();
let _ = child.wait();
return None;
}
}
}
rx.recv_timeout(Duration::from_millis(500)).ok()
}
/// The documented PermissionRequest output. Anything we do not recognise prints
/// nothing at all rather than guessing — silence is the safe answer.
/// See https://code.claude.com/docs/en/hooks
@@ -131,6 +234,13 @@ fn read_event() -> Option<(String, String)> {
.unwrap_or(arg_event);
map.insert("hook_event_name".into(), serde_json::Value::String(event.clone()));
// Claude Code's status line hands us its usage limits (5 h, weekly). That is
// all the island wants of it, so only that goes on; without limits (API-key
// users) there is nothing to send. The command's own output stays empty.
if event == "StatusLine" {
return status_line_payload(map).map(|line| (line, event));
}
// What a finished command printed is dropped with the rest of `tool_response`,
// except its last lines: the island shows them under the command, like a
// terminal pane. Never the whole output — it may hold anything.
@@ -186,6 +296,20 @@ fn read_event() -> Option<(String, String)> {
Some((line, event))
}
/// The one line the island gets from a status-line call: the limits and which
/// session they came from.
fn status_line_payload(map: &serde_json::Map<String, serde_json::Value>) -> Option<String> {
let limits = map.get("rate_limits").filter(|v| v.is_object())?;
let mut line = serde_json::json!({
"hook_event_name": "StatusLine",
"session_id": map.get("session_id").cloned().unwrap_or(serde_json::Value::Null),
"rate_limits": limits,
})
.to_string();
line.push('\n');
Some(line)
}
/// The last few non-empty lines a command printed (stdout, else stderr), without
/// colour codes and cut to a width the island can show.
fn output_tail(response: &serde_json::Value) -> Option<Vec<String>> {
@@ -306,6 +430,38 @@ mod tests {
assert!(decision_json(r#"{"permissionDecision":"allow"}"#).is_none());
}
#[cfg(unix)]
#[test]
fn the_users_own_status_line_gets_the_same_input_and_its_output_comes_back() {
let out = run_previous("cat; echo ' tail'", b"{\"a\":1}", Duration::from_secs(5)).unwrap();
assert_eq!(String::from_utf8(out).unwrap(), "{\"a\":1} tail\n");
}
#[cfg(unix)]
#[test]
fn a_status_line_that_hangs_is_killed_and_prints_nothing() {
let started = Instant::now();
assert!(run_previous("sleep 5", b"{}", Duration::from_millis(200)).is_none());
assert!(started.elapsed() < Duration::from_secs(2));
}
#[test]
fn a_status_line_call_forwards_only_the_limits() {
let input = serde_json::json!({
"session_id": "s1", "cwd": "/secret", "model": { "id": "x" },
"rate_limits": { "five_hour": { "used_percentage": 42, "resets_at": 1 } }
});
let line = status_line_payload(input.as_object().unwrap()).unwrap();
let v: serde_json::Value = serde_json::from_str(line.trim()).unwrap();
assert_eq!(v["rate_limits"]["five_hour"]["used_percentage"], 42);
assert!(v.get("cwd").is_none() && v.get("model").is_none());
// No limits (API-key users): nothing is sent.
assert!(
status_line_payload(serde_json::json!({ "session_id": "s1" }).as_object().unwrap())
.is_none()
);
}
#[test]
fn only_the_last_lines_of_a_command_survive_and_without_colours() {
let out = serde_json::json!({ "stdout": "a\n\n\u{1b}[32mPASS\u{1b}[0m tests/x.ts\n ✓ works (3 ms)\nTests: 1 passed\n" });
+161 -3
View File
@@ -40,6 +40,8 @@ const MARKER: &str = "coucou-hook";
#[serde(rename_all = "camelCase")]
pub struct HookStatus {
pub installed: bool,
/// Coucou's status line relay (plan usage) is the one in settings.json.
pub plan_relay_installed: bool,
pub settings_path: String,
pub hook_path: String,
pub hook_ready: bool,
@@ -139,6 +141,12 @@ fn entry_is_ours(entry: &Value) -> bool {
.unwrap_or(false)
}
/// The status line in settings.json is Coucou's relay (old installs wrote
/// `coucou-hook StatusLine`, new ones `coucou-hook --statusline`; both match).
fn status_line_is_ours(v: &Value) -> bool {
v.get("command").and_then(Value::as_str).is_some_and(|c| c.contains(MARKER))
}
/// Settings with Coucou's hooks added; everything else is left untouched.
fn merged(existing: &Value) -> Value {
let mut root = existing.as_object().cloned().unwrap_or_default();
@@ -253,6 +261,7 @@ pub fn status() -> HookStatus {
let hook_path = settings::hook_exe_path();
HookStatus {
installed,
plan_relay_installed: plan_relay_installed(&current),
settings_path: settings_path().to_string_lossy().to_string(),
hook_ready: hook_path.exists(),
hook_path: hook_path.to_string_lossy().to_string(),
@@ -260,10 +269,19 @@ pub fn status() -> HookStatus {
}
pub fn preview(install: bool) -> Result<HookPreview, String> {
preview_with(|current| if install { merged(current) } else { without_ours(current) }, pretty)
}
/// The diff of what `next` makes of settings.json, shown with `view` (the whole
/// file, or just the key that changes).
fn preview_with(
next: impl Fn(&Value) -> Value,
view: fn(&Value) -> String,
) -> Result<HookPreview, String> {
let current = read_settings()?;
let next = if install { merged(&current) } else { without_ours(&current) };
let next = next(&current);
Ok(HookPreview {
diff: unified_diff(&pretty(&current), &pretty(&next)),
diff: unified_diff(&view(&current), &view(&next)),
backup: backup_path().to_string_lossy().to_string(),
settings_path: settings_path().to_string_lossy().to_string(),
fingerprint: current_fingerprint(),
@@ -277,6 +295,10 @@ pub fn preview(install: bool) -> Result<HookPreview, String> {
/// and make them look at a fresh diff, because the only thing worse than not
/// installing the hooks is silently reverting somebody else's edit.
pub fn write(install: bool, fingerprint: &str) -> Result<String, String> {
write_with(|current| if install { merged(current) } else { without_ours(current) }, fingerprint)
}
fn write_with(next: impl Fn(&Value) -> Value, fingerprint: &str) -> Result<String, String> {
let path = settings_path();
let dir = path.parent().unwrap_or(Path::new("."));
std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
@@ -296,7 +318,7 @@ pub fn write(install: bool, fingerprint: &str) -> Result<String, String> {
std::fs::copy(&path, &backup).map_err(|e| format!("backup failed: {e}"))?;
}
let next = if install { merged(&current) } else { without_ours(&current) };
let next = next(&current);
let mut text = pretty(&next);
text.push('\n');
@@ -319,6 +341,99 @@ pub fn write(install: bool, fingerprint: &str) -> Result<String, String> {
Ok(backup.to_string_lossy().to_string())
}
// ── Status line (plan usage) ──────────────────────────────────────────────────
//
// Claude Code runs one `statusLine` command and hands it the plan limits. Coucou
// puts its relay there; a status line the user already had is kept in
// statusline-previous.json beside the relay, and the relay still runs it, so it
// keeps working. Installing and removing it is separate from the hooks.
/// Where the user's own status line waits while the relay stands in for it.
pub fn status_line_previous_path() -> PathBuf {
settings::hook_exe_path().with_file_name("statusline-previous.json")
}
fn read_status_line_previous() -> Option<Value> {
let bytes = std::fs::read(status_line_previous_path()).ok()?;
serde_json::from_slice::<Value>(&bytes).ok().filter(Value::is_object)
}
/// True when the `statusLine` in settings.json is Coucou's relay.
pub fn plan_relay_installed(settings: &Value) -> bool {
settings.get("statusLine").is_some_and(status_line_is_ours)
}
/// `statusLine` as it reads after installing or removing the relay. `None`: the
/// key goes. Installing swaps only `command`, so `padding`, `refreshInterval`
/// and the rest of the user's status line stay as they were.
fn status_line_after(existing: Option<&Value>, install: bool, previous: Option<&Value>) -> Option<Value> {
if install {
let mut sl = existing.filter(|v| v.is_object()).cloned().unwrap_or_else(|| json!({}));
let obj = sl.as_object_mut().expect("an object");
obj.entry("type").or_insert_with(|| json!("command"));
obj.insert("command".into(), json!(hook_command("--statusline")));
Some(sl)
} else if existing.is_some_and(status_line_is_ours) {
previous.cloned()
} else {
existing.cloned() // not ours any more (the user changed it): leave it alone
}
}
fn status_line_settings(current: &Value, install: bool, previous: Option<&Value>) -> Value {
let mut root = current.as_object().cloned().unwrap_or_default();
match status_line_after(root.get("statusLine"), install, previous) {
Some(sl) => root.insert("statusLine".into(), sl),
None => root.remove("statusLine"),
};
Value::Object(root)
}
/// Only the `statusLine` key, which is all the diff of this change is about.
fn status_line_view(settings: &Value) -> String {
pretty(&json!({ "statusLine": settings.get("statusLine").cloned().unwrap_or(Value::Null) }))
}
/// The diff the user has to look at before the relay goes in or out.
pub fn status_line_preview(install: bool) -> Result<HookPreview, String> {
let previous = read_status_line_previous();
preview_with(|current| status_line_settings(current, install, previous.as_ref()), status_line_view)
}
/// Installs or removes the relay, after the same backup and fingerprint checks as
/// the hooks. Installing first saves a status line of the user's own, removing
/// puts it back (or removes the key if there was none).
pub fn status_line_write(install: bool, fingerprint: &str) -> Result<String, String> {
let before = read_settings()?;
let previous = read_status_line_previous();
let own = before.get("statusLine").filter(|v| !status_line_is_ours(v)).cloned();
let saved = install && own.is_some() && save_status_line_previous(own.as_ref().expect("some")).is_ok();
if install && own.is_some() && !saved {
return Err("could not save your current status line next to the relay; nothing was changed".into());
}
let backup = write_with(|current| status_line_settings(current, install, previous.as_ref()), fingerprint);
match &backup {
// Back in settings.json: the saved copy has done its job.
Ok(_) if !install => {
let _ = std::fs::remove_file(status_line_previous_path());
}
// Nothing was written: do not leave a stale copy behind.
Err(_) if saved => {
let _ = std::fs::remove_file(status_line_previous_path());
}
_ => {}
}
backup
}
fn save_status_line_previous(status_line: &Value) -> std::io::Result<()> {
let path = status_line_previous_path();
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
write_like(&path, &path, pretty(status_line).as_bytes())
}
/// Writes `bytes` to `temp`, which is about to replace `original`.
///
/// On Linux a fresh file would get the umask's 0644, and settings.json can hold
@@ -511,6 +626,49 @@ mod tests {
const WHERE: &str = "settings.json";
#[test]
fn the_hooks_leave_the_status_line_alone() {
let theirs = json!({ "statusLine": { "type": "command", "command": "~/bin/my-line" } });
assert_eq!(merged(&theirs)["statusLine"], theirs["statusLine"]);
assert_eq!(without_ours(&theirs)["statusLine"], theirs["statusLine"]);
assert!(merged(&json!({})).get("statusLine").is_none());
}
#[test]
fn the_relay_takes_the_status_line_and_keeps_the_users_other_fields() {
// None yet: ours is added.
let fresh = status_line_settings(&json!({ "model": "opus" }), true, None);
assert!(status_line_is_ours(&fresh["statusLine"]));
assert_eq!(fresh["statusLine"]["type"], "command");
assert_eq!(fresh["model"], "opus");
// Their own: only the command is swapped; padding and refresh stay.
let own = json!({ "statusLine": { "type": "command", "command": "~/bin/my-line", "padding": 2, "refreshInterval": 5 } });
let taken = status_line_settings(&own, true, None);
assert!(status_line_is_ours(&taken["statusLine"]));
assert_eq!(taken["statusLine"]["padding"], 2);
assert_eq!(taken["statusLine"]["refreshInterval"], 5);
// Installing again keeps ours and its extra fields.
let again = status_line_settings(&taken, true, None);
assert_eq!(again["statusLine"]["padding"], 2);
assert!(status_line_is_ours(&again["statusLine"]));
}
#[test]
fn removing_the_relay_restores_what_was_there_and_never_touches_anything_else() {
let previous = json!({ "type": "command", "command": "~/bin/my-line", "padding": 2 });
let ours = status_line_settings(&json!({}), true, None);
// There was one before: it comes back exactly.
assert_eq!(status_line_settings(&ours, false, Some(&previous))["statusLine"], previous);
// There was none: the key goes.
assert!(status_line_settings(&ours, false, None).get("statusLine").is_none());
// The user changed it since: not ours, so untouched.
let theirs = json!({ "statusLine": { "type": "command", "command": "~/bin/other" } });
assert_eq!(status_line_settings(&theirs, false, Some(&previous))["statusLine"], theirs["statusLine"]);
}
#[test]
fn a_utf8_bom_is_stripped_not_treated_as_corruption() {
// PowerShell 5's `Set-Content -Encoding utf8` produces exactly this.
+31 -1
View File
@@ -50,7 +50,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,
@@ -255,6 +257,32 @@ 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;
let _ = settings::save(&current);
current.clone()
};
let _ = app.emit("settings-changed", updated);
Ok(backup)
}
#[tauri::command]
fn approval_decision(app: AppHandle, request_id: String, decision: String) {
pipe::answer(&app, &request_id, &decision);
@@ -437,6 +465,8 @@ pub fn run() {
hooks_status,
hooks_preview,
hooks_apply,
status_line_preview,
status_line_apply,
approval_decision,
approval_ack,
approval_decline,
+10
View File
@@ -24,6 +24,14 @@ pub struct Settings {
/// chat's answer language and the island's step labels.
#[serde(default = "default_language")]
pub language: String,
/// Show the plan usage 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.
#[serde(default)]
pub show_plan_in_notch: bool,
/// Coucou's status line relay is the one in settings.json. Like
/// `hooks_installed`, the real state wins at launch over what was stored.
#[serde(default)]
pub plan_relay_installed: bool,
}
fn default_language() -> String {
@@ -52,6 +60,8 @@ impl Default for Settings {
hooks_installed: false,
model: default_model(),
language: default_language(),
show_plan_in_notch: false,
plan_relay_installed: false,
}
}
}
+9
View File
@@ -83,6 +83,13 @@ 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 }),
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. */
@@ -140,6 +147,8 @@ export interface Snippet {
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;
+12
View File
@@ -2,6 +2,7 @@
import type { BotEmoteName, BotStateName, IslandMode, IslandViewName } from "./layout";
import type { EyeShape } from "../mochi/engine";
import type { PlanUsage } from "../views/usage";
export type AgentSource = "claudeCode" | "n8n" | "agent";
export type PillBadge = "approval" | "finished" | "error";
@@ -104,6 +105,10 @@ export interface Settings {
model: string;
/** "auto" (system language), "en", "de" or "fr". */
language: string;
/** Show the plan usage 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;
}
export const DEFAULT_SETTINGS: Settings = {
@@ -119,6 +124,8 @@ export const DEFAULT_SETTINGS: Settings = {
hooksInstalled: false,
model: "claude-opus-5",
language: "auto",
showPlanInNotch: false,
planRelayInstalled: false,
};
type Listener = () => void;
@@ -143,6 +150,10 @@ class AppState {
uploadProgress = 0;
uploadDuration = 2.4;
fileDragOver = false;
/** Claude's 5 h / weekly limits, from the status line (null until the first call). */
planUsage: PlanUsage | null = null;
/** The plan card is open in place of the overview's left card. */
showingPlanDetail = false;
promptContext: PromptContext | null = null;
droppedFile: { name: string; path: string } | null = null;
@@ -190,6 +201,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();
}
+13
View File
@@ -9,6 +9,7 @@ import { Sound } from "../core/sound";
import { State } from "../core/state";
import type { Island } from "./island";
import { beginTurn, dropSession, endTurn, hasSession, toolFinished, toolStarted } from "../views/session";
import { parsePlanUsage } from "../views/usage";
const CLAUDE_ID = "integration_claude";
@@ -35,6 +36,8 @@ interface HookPayload {
tool_tail?: string[];
/** PostToolUseFailure: why the tool failed. */
error?: string;
/** StatusLine: Claude Code's usage limits. */
rate_limits?: unknown;
}
/** Same rule as HookServer.validateAgent on macOS. "claude" is reserved. */
@@ -160,6 +163,16 @@ function noteTerminal(payload: HookPayload) {
}
function handleHook(island: Island, payload: HookPayload) {
// Account-wide numbers, not part of any session: just keep the latest.
if (payload.hook_event_name === "StatusLine") {
const usage = parsePlanUsage(payload.rate_limits);
if (usage) {
State.planUsage = usage;
State.notify();
}
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,
+11 -1
View File
@@ -17,6 +17,7 @@ import { createMiniBot, pruneMiniBots, syncMiniBotStates, tickMiniBots } from ".
import { UploadCanvas } from "../upload/canvas";
import { USC, UploadSeq } from "../upload/sequence";
import { openSession } from "../views/open-session";
import { currentPlanColor, planPillVisible } from "../views/usage";
import { buildHeader, buildViews, type ViewActions, type ViewHost } from "../views/views";
import { h } from "../views/dom";
import { IslandStateMachine } from "./fsm";
@@ -282,6 +283,7 @@ export class Island {
void Bridge.focusWindow(false);
}
if (mode !== "expanded") {
State.showingPlanDetail = false;
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
@@ -305,6 +307,7 @@ export class Island {
expand(view: IslandViewName) {
this.stopSequenceIfLeaving(view);
if (view !== "overview") State.showingPlanDetail = false;
State.view = view;
if (State.mode !== "expanded") this.setMode("expanded");
else this.animateGeometry(false);
@@ -315,6 +318,7 @@ export class Island {
setView(view: IslandViewName) {
this.stopSequenceIfLeaving(view);
if (view !== "overview") State.showingPlanDetail = false;
if (State.mode !== "expanded") {
this.fsm.forceHome();
State.view = view;
@@ -839,7 +843,13 @@ export class Island {
if (!ctx) return;
const focus = State.focusTask;
this.engine.bodyColor = focus?.isIntegration ? hexToRGB(focus.color) : null;
// While the plan card is open Mochi wears the plan's colour, like the pill.
this.engine.bodyColor =
State.showingPlanDetail && planPillVisible()
? hexToRGB(currentPlanColor())
: focus?.isIntegration
? hexToRGB(focus.color)
: null;
this.engine.particleOverhang = BOT_OVERHANG;
this.engine.lookX = this.lookX();
this.engine.lookY = this.lookY();
+154 -52
View File
@@ -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";
@@ -41,6 +41,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 {
@@ -52,11 +136,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" }));
@@ -92,7 +179,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.
@@ -105,66 +192,80 @@ 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.
*/
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);
// 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.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: "Shows your Claude plan usage (5-hour and weekly limits) in the island's header. Coucou adds a status line relay to ~/.claude/settings.json; if you already have a status line, it keeps working as before. Pro and Max plans only.",
}),
renderDiff(preview.diff),
h("div", { class: "row" }, h("label", { text: "Show in the notch" }), 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()),
}),
),
);
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();
@@ -450,7 +551,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;
@@ -466,6 +567,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(),
+123
View File
@@ -1675,6 +1675,129 @@ input[type="range"]::-webkit-slider-thumb {
.tok-f { color: #f2c070; }
.tok-c { color: var(--dim-4); font-style: italic; }
/* ── Plan usage: the pill in the header and the card behind it ─────────────── */
.header-actions {
align-items: center;
}
.plan-pill {
--plan: #6b7079;
display: flex;
align-items: center;
gap: 5px;
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);
white-space: nowrap;
cursor: default;
transition: background 0.18s, border-color 0.18s, color 0.18s;
}
.plan-pill:hover,
.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-sub {
flex: 0 1 auto !important; /* 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);
}
/* The overview's left card opens the code view when there is code to show. */
.expand-hint {
position: absolute;
+1
View File
@@ -19,6 +19,7 @@ const FA = {
pen: [512, 512, "M352.9 21.2L308 66.1 445.9 204 490.8 159.1C504.4 145.6 512 127.2 512 108s-7.6-37.6-21.2-51.1L455.1 21.2C441.6 7.6 423.2 0 404 0s-37.6 7.6-51.1 21.2zM274.1 100L58.9 315.1c-10.7 10.7-18.5 24.1-22.6 38.7L.9 481.6c-2.3 8.3 0 17.3 6.2 23.4s15.1 8.5 23.4 6.2l127.8-35.5c14.6-4.1 27.9-11.8 38.7-22.6L412 237.9 274.1 100z"],
expand: [512, 512, "M344 0L488 0c13.3 0 24 10.7 24 24l0 144c0 9.7-5.8 18.5-14.8 22.2s-19.3 1.7-26.2-5.2l-39-39-87 87c-9.4 9.4-24.6 9.4-33.9 0l-32-32c-9.4-9.4-9.4-24.6 0-33.9l87-87-39-39c-6.9-6.9-8.9-17.2-5.2-26.2S334.3 0 344 0zM168 512L24 512c-13.3 0-24-10.7-24-24L0 344c0-9.7 5.8-18.5 14.8-22.2S34.1 320.2 41 327l39 39 87-87c9.4-9.4 24.6-9.4 33.9 0l32 32c9.4 9.4 9.4 24.6 0 33.9l-87 87 39 39c6.9 6.9 8.9 17.2 5.2 26.2S177.7 512 168 512z"],
compress: [512, 512, "M439.5 7c9.4-9.4 24.6-9.4 33.9 0l32 32c9.4 9.4 9.4 24.6 0 33.9l-87 87 39 39c6.9 6.9 8.9 17.2 5.2 26.2S450.2 240 440.5 240l-144 0c-13.3 0-24-10.7-24-24l0-144c0-9.7 5.8-18.5 14.8-22.2s19.3-1.7 26.2 5.2l39 39 87-87zM72.5 272l144 0c13.3 0 24 10.7 24 24l0 144c0 9.7-5.8 18.5-14.8 22.2s-19.3 1.7-26.2-5.2l-39-39-87 87c-9.4 9.4-24.6 9.4-33.9 0l-32-32c-9.4-9.4-9.4-24.6 0-33.9l87-87-39-39c-6.9-6.9-8.9-17.2-5.2-26.2S62.8 272 72.5 272z"],
arrowRotateRight: [512, 512, "M436.7 74.7L448 85.4 448 32c0-17.7 14.3-32 32-32s32 14.3 32 32l0 128c0 17.7-14.3 32-32 32l-128 0c-17.7 0-32-14.3-32-32s14.3-32 32-32l47.9 0-7.6-7.2c-.2-.2-.4-.4-.6-.6-75-75-196.5-75-271.5 0s-75 196.5 0 271.5 196.5 75 271.5 0c8.2-8.2 15.5-16.9 21.9-26.1 10.1-14.5 30.1-18 44.6-7.9s18 30.1 7.9 44.6c-8.5 12.2-18.2 23.8-29.1 34.7-100 100-262.1 100-362 0S-25 175 75 75c99.9-99.9 261.7-100 361.7-.3z"],
fileLines: [384, 512, "M0 64C0 28.7 28.7 0 64 0L213.5 0c17 0 33.3 6.7 45.3 18.7L365.3 125.3c12 12 18.7 28.3 18.7 45.3L384 448c0 35.3-28.7 64-64 64L64 512c-35.3 0-64-28.7-64-64L0 64zm208-5.5l0 93.5c0 13.3 10.7 24 24 24L325.5 176 208 58.5zM120 256c-13.3 0-24 10.7-24 24s10.7 24 24 24l144 0c13.3 0 24-10.7 24-24s-10.7-24-24-24l-144 0zm0 96c-13.3 0-24 10.7-24 24s10.7 24 24 24l144 0c13.3 0 24-10.7 24-24s-10.7-24-24-24l-144 0z"],
} as const;
+186
View File
@@ -0,0 +1,186 @@
// Claude plan usage: the 5-hour and weekly limits, as a pill in the island's header
// and a card behind it. Same behaviour as ClaudePlanGauge / ClaudePlanCardView on
// the Mac (docs/INTEGRATIONS.md, "Jauge de forfait Claude").
//
// The numbers come from Claude Code's own status line (`rate_limits` in what it
// hands its status-line command), through the relay: nothing is read from any
// credentials and nothing is fetched. They exist for Pro and Max plans only.
import { localized, uiLocale } from "../core/i18n";
import { State } from "../core/state";
import { clear, dot, h } from "./dom";
import { fa } from "./fa";
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;
}
const DAY_MS = 86_400_000;
function parseWindow(raw: unknown, now: number): PlanWindow | undefined {
const w = raw as { used_percentage?: unknown; resets_at?: unknown } | null;
if (typeof w?.used_percentage !== "number" || typeof w.resets_at !== "number") return undefined;
// Anything outside 0–200 is not a percentage; 100–200 is a plan over its limit, shown full.
if (!(w.used_percentage >= 0 && w.used_percentage <= 200)) return undefined;
// resets_at is epoch seconds. A date more than 400 days away is milliseconds in disguise.
if (!(w.resets_at > 0) || w.resets_at * 1000 > now + 400 * DAY_MS) return undefined;
return { usedPct: Math.min(100, w.used_percentage), resetsAt: w.resets_at * 1000 };
}
/** `rate_limits` from a status-line call, or null when it holds neither window. */
export function parsePlanUsage(rateLimits: unknown, now = Date.now()): PlanUsage | null {
const rl = rateLimits as { five_hour?: unknown; seven_day?: unknown } | null;
const fiveHour = parseWindow(rl?.five_hour, now);
const sevenDay = parseWindow(rl?.seven_day, now);
return fiveHour || sevenDay ? { fiveHour, sevenDay, updatedAt: now } : null;
}
/** 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, 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";
return pct < 50 ? "#22C55E" : pct < 80 ? "#F59E0B" : "#F4505E";
}
/** The colour the pill (and Mochi, while the card is open) has right now. */
export const currentPlanColor = (): string => planColor(dominantPct(State.planUsage));
/** The pill is in the header: on the overview, once turned on, once the relay is in. */
export function planPillVisible(): boolean {
return State.view === "overview" && State.settings.showPlanInNotch && State.settings.planRelayInstalled;
}
const TEXT = {
en: {
plan: "Claude plan", waiting: "Waiting for a Claude Code reply", justNow: "just now",
minAgo: (n: number) => `${n} min ago`, hAgo: (n: number) => `${n} h ago`,
fiveHours: "5 hours", week: "Week", resetting: "Resetting…",
inH: (h: number, m: number) => `in ${h} h ${m}`, inMin: (m: number) => `in ${m} min`,
},
de: {
plan: "Claude-Abo", waiting: "Warte auf eine Antwort von Claude Code", justNow: "gerade eben",
minAgo: (n: number) => `vor ${n} Min.`, hAgo: (n: number) => `vor ${n} Std.`,
fiveHours: "5 Stunden", week: "Woche", resetting: "Setzt zurück…",
inH: (h: number, m: number) => `in ${h} Std. ${m}`, inMin: (m: number) => `in ${m} Min.`,
},
fr: {
plan: "Forfait Claude", waiting: "En attente d'une réponse de Claude Code", justNow: "à l'instant",
minAgo: (n: number) => `il y a ${n} min`, hAgo: (n: number) => `il y a ${n} h`,
fiveHours: "5 heures", week: "Semaine", resetting: "Réinitialisation…",
inH: (h: number, m: number) => `dans ${h} h ${m}`, inMin: (m: number) => `dans ${m} min`,
},
};
/** "Claude 73%" on the pill; "Claude —" while no numbers have come in. */
export function pillLabel(): string {
const pct = dominantPct(State.planUsage);
return pct == null ? "Claude —" : `Claude ${Math.round(pct)}%`;
}
/** The pill itself: colour dot and label, lit while hovered or while the card is open. */
export function buildPlanPill(): { el: HTMLElement; sync: () => void } {
const label = h("span", { class: "plan-pill-label" });
const dotEl = h("i", { class: "plan-pill-dot" });
const el = h("button", {
class: "plan-pill",
title: "Claude plan usage",
onclick: () => {
State.showingPlanDetail = !State.showingPlanDetail;
State.notify();
},
}, dotEl, label);
return {
el,
sync() {
const color = currentPlanColor();
el.style.setProperty("--plan", color);
el.classList.toggle("active", State.showingPlanDetail);
dotEl.style.background = color;
label.textContent = pillLabel();
},
};
}
function subtitle(u: PlanUsage | null, now: number): string {
const t = localized(TEXT);
if (!u) return t.waiting;
const mins = Math.floor((now - u.updatedAt) / 60_000);
return mins < 1 ? t.justNow : mins < 60 ? t.minAgo(mins) : t.hAgo(Math.floor(mins / 60));
}
/** "in 1 h 20" / "in 5 min" for the 5-hour window, "Mon 9:00" for the week. */
function resetLabel(w: PlanWindow, weekly: boolean, now: number): string {
const t = localized(TEXT);
const secs = (w.resetsAt - now) / 1000;
if (secs <= 0) return t.resetting;
if (weekly) {
return new Date(w.resetsAt).toLocaleString(uiLocale(), { weekday: "short", hour: "numeric", minute: "2-digit", hour12: false });
}
const hours = Math.floor(secs / 3600);
const mins = Math.floor((secs % 3600) / 60);
return hours > 0 ? t.inH(hours, mins) : t.inMin(mins);
}
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: "—" }));
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" }, fa("arrowRotateRight", 8)),
h("span", { class: "plan-reset", text: resetLabel(w, weekly, now) }),
);
return row;
}
/** The card that replaces the left card while the pill is open. */
export class PlanCard {
readonly el = h("div", { class: "plan-card" });
private key = "";
/** Re-renders when the numbers change or a minute has gone by (the countdowns). */
sync(now = Date.now()) {
const u = State.planUsage;
const key = `${JSON.stringify(u)}|${State.settings.language}|${Math.floor(now / 60_000)}`;
if (key === this.key) return;
this.key = key;
clear(this.el);
const t = localized(TEXT);
this.el.append(
h("div", { class: "plan-head" },
dot(currentPlanColor(), 7),
h("span", { class: "plan-title", text: t.plan }),
h("span", { class: "plan-sub", text: subtitle(u, now) }),
),
h("div", { class: "plan-rows" },
gaugeRow(t.fiveHours, u?.fiveHour, false, now),
gaugeRow(t.week, u?.sevenDay, true, now),
),
);
}
}
+23 -4
View File
@@ -11,6 +11,7 @@ import { washRGBA, type IslandViewName, type Wash } from "../core/layout";
import { createMiniBot, pruneMiniBots } from "../mochi/minibots";
import { buildPrompt } from "./chat";
import { buildSession, hasSession } from "./session";
import { PlanCard, buildPlanPill, planPillVisible } from "./usage";
import { buildChoose, buildUpload, buildUploading } from "./upload";
import { renderIntegrationCard, type IntegrationCardHooks } from "./integrations";
@@ -84,6 +85,7 @@ export function buildHeader(actions: ViewActions): ViewHost {
const tabChat = h("button", { class: "tab", title: "Ask", onclick: () => go("prompt") }, fa("comment", 15));
const tabDrop = h("button", { class: "tab", title: "Drop", onclick: () => go("upload") }, fa("plus", 14));
const planPill = buildPlanPill();
const gearBtn = h("button", { title: "Settings", onclick: () => go("settings") }, fa("gear", 16));
const soundBtn = h("button", { title: "Mute", onclick: () => actions.toggleSound() }, fa("volumeHigh", 16));
@@ -96,7 +98,7 @@ 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" }, planPill.el, gearBtn, soundBtn),
);
return {
@@ -111,6 +113,9 @@ export function buildHeader(actions: ViewActions): ViewHost {
gearBtn.append(fa("gear", 16));
clear(soundBtn);
soundBtn.append(fa(State.settings.soundEnabled ? "volumeHigh" : "volumeXmark", 16));
const pillOn = planPillVisible();
planPill.el.style.display = pillOn ? "" : "none";
if (pillOn) planPill.sync();
el.style.opacity = v === "confused" ? "0" : "1";
},
};
@@ -137,6 +142,8 @@ function buildOverview(actions: ViewActions): ViewHost {
});
const pills = h("div", { class: "pills" });
const right = card(null, pills);
// Opened from the plan pill in the header: stands in for the left card.
const plan = new PlanCard();
const el = h("div", { class: "view overview" },
h("div", { class: "left" }, left),
@@ -146,7 +153,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 = {
@@ -170,6 +177,7 @@ function buildOverview(actions: ViewActions): ViewHost {
el,
tick(nowMs: number) {
if (mode === "ticker") ticker.tick(nowMs);
if (mode === "plan") plan.sync();
},
sync() {
const task = State.focusTask;
@@ -185,7 +193,18 @@ function buildOverview(actions: ViewActions): ViewHost {
const sessionActive =
task?.id === "integration_claude" && (task.state !== "idle" || task.steps.length > 0);
if (task && sessionActive) {
const planOpen = State.showingPlanDetail && planPillVisible();
if (mode === "plan" && !planOpen) mode = null;
if (planOpen) {
if (mode !== "plan") {
clear(leftBody);
leftBody.append(plan.el);
mode = "plan";
cardKey = "";
}
plan.sync();
} else if (task && sessionActive) {
if (mode !== "ticker") {
clear(leftBody);
leftBody.append(tickerBody);
@@ -220,7 +239,7 @@ function buildOverview(actions: ViewActions): ViewHost {
}
}
jump.style.display = detailOpen ? "none" : "";
jump.style.display = detailOpen || mode === "plan" ? "none" : "";
left.classList.toggle("expandable", mode === "ticker" && hasSession());
const others = State.otherTasks.slice(0, 4);