Skip to content

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

Merge port/live-diff: live diff in the ticker, the diff card, and the final line

Claude03f8f13c4c39
diff --cc windows/README.md
index 0578f5f1,cf0bca82..6b3306f1
--- a/windows/README.md
+++ b/windows/README.md
@@@ -48,30 -49,16 +49,37 @@@ installs for the current user only —
| Tray icon | Open, Settings…, Pause, Quit |
Everything else happens on its own: a Claude Code permission request opens the
-island with **Deny / Allow**, a finished session shows what it did, and
+island with **Deny / Allow**, a question from Claude Code shows its options to
+pick from, a finished session shows what it did, and
your integrations sit in the coloured pills next to Mochi.
+A permission card or a question stays until you answer it: the mouse leaving
+never folds it, it comes up even when the island is already open or another
+pill is in front, and the pill you were on comes back once you answer. To keep
+it for later, fold it with the **⌃** in its corner (or `Esc` in the island): the
+island shrinks to its compact size and stays on screen, nothing is answered, and
+opening it again shows the card. **Open terminal** brings the window the session
+runs in to the front.
+
+ **Live diff.** Every file Claude edits (Edit, MultiEdit, Write) shows up in the
+ session ticker with its **+N −M** lines; click it for the diff. Same limits as the
+ Mac: past 200 KB or 4 000 lines only the counts are kept, at most 50 diffs per
+ session, and they are forgotten an hour after the last edit or when the session
+ ends. When Claude finishes, the card keeps the first paragraph of its final
+ answer on one line, still, until the next prompt.
+
+## Your pills
+
+**Settings… → Active pills** lists the tools you use, from the same catalog as
+the Mac app. Pick your **main tool** — VS Code, Cursor, Codex or Antigravity —
+which is always there and doesn't take a slot, then declare up to four more:
+agents (Gemini CLI, Copilot CLI, Muse Code, OpenCode, Amp, Hermes, Claude
+Desktop), the chat providers (Anthropic, Google AI, OpenAI, Ollama, LM Studio),
+and the services under **Integrations**. A pill fed by hooks says whether its
+hooks are installed, never asks for a key; a local model server's pill says
+whether the chat is connected to it. A session on a pill you didn't
+declare still shows up, for as long as it runs.
+
## Claude Code
<img src="screenshots/settings.png" width="562" alt="The settings window">
@@@ -269,33 -167,16 +277,41 @@@ own window
the top edge instead of hiding in a notch.
- Permission approval works from **any** terminal; the Mac build only listens to
VS Code sessions.
-- Not in this version: sending a file by email, dragging Mochi onto a window to
- attach it as context, and jumping to a specific terminal window — "Open
- terminal" opens the working folder in VS Code when `code` is on your `PATH`.
+- "Open terminal" finds the session's window by walking up from the relay's
+ process to the terminal or editor that runs it. A session in a classic
+ console window (`cmd.exe` or PowerShell without Windows Terminal) has no such
+ ancestor — conhost owns that window — so its folder opens in VS Code instead,
+ as it does when `code` is on your `PATH` and nothing was found.
+- No global keyboard shortcuts yet: a waiting card is folded with its **⌃** or
+ `Esc` in the island, and reopened by clicking the island or Open in the tray.
+- Apple Music, the one pill from the Mac catalog with nothing behind it here,
+ is left out.
+- Not in this version: sending a dropped file by email and dragging Mochi onto
+ a window to attach it as context. On the Mac, email goes through Resend or
+ Apple Mail's scripting; neither has a safe equivalent that attaches a file
+ here, and the drop card would need a third button it doesn't have.
- Cal.com shows the next bookings as a list rather than the Mac's calendar.
+- The Cursor pill carries both Cursor Agent's own hooks and Claude Code running
+ in Cursor's terminal.
+- Hermes: Coucou writes the plugin but does not run the `hermes` CLI, so it is
+ turned on once by hand. Hermes runs natively on Linux; on Windows it is
+ untested.
+- Plan usage: the user's previous status line runs through Git Bash on Windows
+ (`/bin/sh` on Linux and Mac); without Git Bash it is not run, rather than
+ guessed at with `cmd`. The Codex CLI is looked for on `PATH` and in npm's,
+ Volta's, Bun's and pnpm's folders (and nvm's on Linux).
+- The chat's model picker opens inside the chat card instead of a popover, and
+ it also offers OpenRouter and any OpenAI-compatible server, which the Mac
+ does not. Google AI, OpenAI and OpenRouter can see an image you dropped (sent
+ inline), where the Mac sends its name only.
+ - Live diff: the relay forwards an edit's text whole only once the edit is done
+ (PostToolUse), up to 256 KB per string and 512 KB per event. A bigger edit
+ shows its "Modifie · file" step without counts rather than wrong ones. The
+ diff's ↗ needs `code` on your `PATH`; without it, it opens the file's folder —
- never the file itself. The diff shows for the Claude Code pill only, since
- other agents' pills have no ticker here yet; there is no ⌘E-style shortcut.
++ never the file itself. Counts and diffs come from Claude Code's Edit,
++ MultiEdit and Write, on whichever pill its session is on (VS Code, Cursor,
++ Claude Desktop); other agents' edits show as plain steps. There is no
++ ⌘E-style shortcut.
## Linux
diff --cc windows/hook/src/main.rs
index 5d9ee1de,52ef9c7a..7510eb23
--- a/windows/hook/src/main.rs
+++ b/windows/hook/src/main.rs
@@@ -46,8 -34,17 +46,19 @@@ const DROPPED_FIELDS: &[&str] = &["tool
/// less than this anyway.
const MAX_FIELD_LEN: usize = 2_000;
+mod statusline;
+
+ /// The live diff needs the whole text of a file edit, once it has happened:
+ /// PostToolUse of these tools keeps its edit strings far longer than the rest.
+ const DIFF_TOOLS: &[&str] = &["Edit", "MultiEdit", "Write"];
+ /// The `tool_input` keys holding the text being replaced or written.
+ const DIFF_FIELDS: &[&str] = &["old_string", "new_string", "content"];
+ /// Per edit string. The island stops diffing at 200 KB anyway (DiffEngine).
+ const MAX_DIFF_FIELD_LEN: usize = 256 * 1024;
+ /// For all edit strings of one event together, so the line stays well under the
+ /// 1 MiB the app reads from the pipe even once JSON-escaped.
+ const MAX_DIFF_TOTAL: usize = 512 * 1024;
+
#[cfg(windows)]
mod win;
#[cfg(windows)]
@@@ -168,28 -143,22 +179,30 @@@ fn prepare(raw: &[u8], args: &Args, env
map.remove(*field);
}
- let cwd_missing = map
- .get("cwd")
- .and_then(|v| v.as_str())
- .map(str::is_empty)
- .unwrap_or(true);
- if cwd_missing {
- if let Ok(cwd) = std::env::current_dir() {
- map.insert(
- "cwd".into(),
- serde_json::Value::String(cwd.to_string_lossy().to_string()),
- );
- }
+ if map.get("cwd").and_then(Value::as_str).map(str::is_empty).unwrap_or(true) && !cwd.is_empty() {
+ map.insert("cwd".into(), Value::String(cwd.to_string()));
}
- // Which terminal the session runs in. Unlike macOS, Coucou here accepts
- // events from every terminal, so this is context only — never a filter.
+ add_terminal_context(map, env);
+
+ // Kept whole: what goes back to Claude Code must be its own input, not the
+ // shortened copy the island is shown.
+ let question = (map.get("tool_name").and_then(Value::as_str) == Some("AskUserQuestion"))
+ .then(|| map.get("tool_input").cloned())
+ .flatten();
+
- truncate_strings(&mut payload);
++ // Every string is capped, except the edit text of a finished Edit /
++ // MultiEdit / Write, which the live diff needs whole (within its own limits).
++ truncate_payload(&mut payload, &name);
+
+ let mut line = payload.to_string();
+ line.push('\n');
+ Some(Event { line, name, question })
+}
+
+/// Which terminal the session runs in. Unlike macOS, Coucou here accepts events
+/// from every terminal, so this is context only — never a filter.
+fn add_terminal_context(map: &mut Map<String, Value>, env: &dyn Fn(&str) -> Option<String>) {
for (key, var) in [
("term_program", "TERM_PROGRAM"),
("wt_session", "WT_SESSION"),
@@@ -198,51 -167,87 +211,104 @@@
("session_pid", "CLAUDE_CODE_SSE_PORT"),
] {
if !map.contains_key(key) {
- let value = std::env::var(var).unwrap_or_default();
- map.insert(key.into(), serde_json::Value::String(value));
+ map.insert(key.into(), Value::String(env(var).unwrap_or_default()));
}
}
+}
- truncate_payload(&mut payload, &event);
+/// The `coucou_agent` tag: `--agent` when given, otherwise `claude-desktop` for
+/// a Claude Code session started from the Claude desktop app, which says so in
+/// CLAUDE_CODE_ENTRYPOINT — the same rule as the Mac's relay (#191). Nothing
+/// for a plain Claude Code session.
+fn agent_tag(arg: &str, env: &dyn Fn(&str) -> Option<String>) -> Option<String> {
+ if !arg.is_empty() {
+ return Some(arg.to_string());
+ }
+ (env("CLAUDE_CODE_ENTRYPOINT").as_deref() == Some("claude-desktop"))
+ .then(|| "claude-desktop".to_string())
+}
- let mut line = payload.to_string();
- line.push('\n');
- Some((line, event))
+/// `cursor` when the session runs in Cursor's integrated terminal. Cursor sets
+/// TERM_PROGRAM=vscode like VS Code does, so it is told apart by its own trace
+/// variable, or by its executable behind VS Code's git helper.
+fn term_editor(env: &dyn Fn(&str) -> Option<String>) -> Option<&'static str> {
+ if env("CURSOR_TRACE_ID").is_some_and(|v| !v.is_empty()) {
+ return Some("cursor");
+ }
+ let helper = env("VSCODE_GIT_ASKPASS_NODE").unwrap_or_default();
+ let exe = helper.rsplit(['/', '\\']).next().unwrap_or_default().to_ascii_lowercase();
+ exe.starts_with("cursor").then_some("cursor")
}
+ /// Caps the strings of a payload: every field to MAX_FIELD_LEN, except the edit
+ /// strings of a finished Edit / MultiEdit / Write, which the live diff needs
+ /// whole. If even those had to be cut, `coucou_diff_truncated` tells the island
+ /// not to show counts it cannot trust.
+ fn truncate_payload(payload: &mut serde_json::Value, event: &str) {
+ let keeps_diff = event == "PostToolUse"
+ && payload
+ .get("tool_name")
+ .and_then(|v| v.as_str())
+ .is_some_and(|tool| DIFF_TOOLS.contains(&tool));
+ let input = if keeps_diff {
+ payload.as_object_mut().and_then(|map| map.remove("tool_input"))
+ } else {
+ None
+ };
+
+ truncate_strings(payload);
+
+ if let Some(mut input) = input {
+ let mut budget = MAX_DIFF_TOTAL;
+ let mut cut_any = false;
+ cap_diff_strings(&mut input, &mut budget, &mut cut_any);
+ if let Some(map) = payload.as_object_mut() {
+ map.insert("tool_input".into(), input);
+ if cut_any {
+ map.insert("coucou_diff_truncated".into(), serde_json::Value::Bool(true));
+ }
+ }
+ }
+ }
+
+ /// `tool_input` of a diff tool: edit strings share MAX_DIFF_TOTAL, each capped at
+ /// MAX_DIFF_FIELD_LEN; any other string gets the ordinary cap.
+ fn cap_diff_strings(value: &mut serde_json::Value, budget: &mut usize, cut_any: &mut bool) {
+ match value {
+ serde_json::Value::Object(map) => {
+ for (key, v) in map.iter_mut() {
+ match v {
+ serde_json::Value::String(s) if DIFF_FIELDS.contains(&key.as_str()) => {
+ let limit = MAX_DIFF_FIELD_LEN.min(*budget);
+ if cut(s, limit) {
+ *cut_any = true;
+ }
+ *budget = budget.saturating_sub(s.len());
+ }
+ _ => cap_diff_strings(v, budget, cut_any),
+ }
+ }
+ }
+ serde_json::Value::Array(items) => {
+ for item in items {
+ cap_diff_strings(item, budget, cut_any);
+ }
+ }
+ serde_json::Value::String(s) => {
+ cut(s, MAX_FIELD_LEN);
+ }
+ _ => {}
+ }
+ }
+
/// Caps every string in the payload. A single Write can carry a whole file.
-fn truncate_strings(value: &mut serde_json::Value) {
+fn truncate_strings(value: &mut Value) {
match value {
- serde_json::Value::String(s) => {
+ Value::String(s) => {
- if s.len() > MAX_FIELD_LEN {
- // Cut on a char boundary; a lone byte index can split UTF-8.
- let mut end = MAX_FIELD_LEN;
- while end > 0 && !s.is_char_boundary(end) {
- end -= 1;
- }
- s.truncate(end);
- s.push('…');
- }
+ cut(s, MAX_FIELD_LEN);
}
- serde_json::Value::Array(items) => items.iter_mut().for_each(truncate_strings),
- serde_json::Value::Object(map) => map.values_mut().for_each(truncate_strings),
+ Value::Array(items) => items.iter_mut().for_each(truncate_strings),
+ Value::Object(map) => map.values_mut().for_each(truncate_strings),
_ => {}
}
}
@@@ -332,55 -333,58 +413,128 @@@ mod tests
assert!(s.ends_with('…'));
}
+ #[test]
+ fn claude_code_payloads_are_forwarded_as_they_are() {
+ let (v, ev) = run(r#"{"hook_event_name":"PreToolUse","tool_name":"Bash","cwd":"/p"}"#, "", "PreToolUse");
+ assert_eq!(ev.name, "PreToolUse");
+ assert!(v.get("coucou_agent").is_none());
+ assert_eq!(v["cwd"], "/p");
+ assert_eq!(v["tool_name"], "Bash");
+ }
+
+ #[test]
+ fn an_agents_event_is_tagged_and_renamed() {
+ // Gemini CLI: its own name in the payload, ours on the command line.
+ let (v, ev) = run(r#"{"hook_event_name":"BeforeTool","toolCall":{"name":"shell","args":{"CommandLine":"ls"}}}"#, "gemini", "PreToolUse");
+ assert_eq!(ev.name, "PreToolUse");
+ assert_eq!(v["hook_event_name"], "PreToolUse");
+ assert_eq!(v["coucou_agent"], "gemini");
+ assert_eq!(v["tool_input"]["command"], "ls");
+ assert_eq!(v["cwd"], "/home/me/here");
+
+ // Copilot CLI sends no event name: the command line's camelCase one is used.
+ let (_, ev) = run(r#"{"toolName":"bash"}"#, "copilot", "permissionRequest");
+ assert_eq!(ev.name, "PermissionRequest");
+
+ // Cursor: a stop that failed, and its tool output left behind.
+ let (v, ev) = run(r#"{"hook_event_name":"stop","status":"error","tool_output":"huge"}"#, "cursor", "");
+ assert_eq!(ev.name, "StopFailure");
+ assert!(v.get("tool_output").is_none());
+ }
+
+ #[test]
+ fn a_question_is_kept_whole_and_only_for_ask_user_question() {
+ let long = "x".repeat(3000);
+ let raw = format!(r#"{{"hook_event_name":"PermissionRequest","tool_name":"AskUserQuestion","tool_input":{{"questions":[{{"question":"{long}"}}]}}}}"#);
+ let (v, ev) = run(&raw, "", "");
+ assert_eq!(ev.question.unwrap()["questions"][0]["question"].as_str().unwrap().len(), 3000);
+ assert!(v["tool_input"]["questions"][0]["question"].as_str().unwrap().ends_with('…'));
+ let (_, ev) = run(r#"{"hook_event_name":"PermissionRequest","tool_name":"Bash","tool_input":{"command":"ls"}}"#, "", "");
+ assert!(ev.question.is_none());
+ }
+
+ #[test]
+ fn what_cannot_be_read_is_not_forwarded() {
+ let args = Args { agent: "copilot".into(), event: "preToolUse".into() };
+ for raw in ["", "not json", "[1,2]"] {
+ assert!(prepare(raw.as_bytes(), &args, &|_| None, "/").is_none());
+ }
+ // A BOM is not a reason to drop the event.
+ let mut bom = vec![0xEF, 0xBB, 0xBF];
+ bom.extend_from_slice(br#"{"hook_event_name":"Stop"}"#);
+ assert!(prepare(&bom, &args, &|_| None, "/").is_some());
+ }
++
++ #[test]
++ fn the_live_diff_rule_holds_through_the_normalised_relay() {
++ let big = "z".repeat(10_000);
++ // Claude Code's finished Edit: kept whole.
++ let raw = format!(r#"{{"hook_event_name":"PostToolUse","tool_name":"Edit","tool_input":{{"old_string":"{big}","new_string":"a"}}}}"#);
++ let (v, _) = run(&raw, "", "");
++ assert_eq!(v["tool_input"]["old_string"].as_str().unwrap().len(), big.len());
++ // The same edit before it happens, or an agent's event renamed onto
++ // PreToolUse: the ordinary cap.
++ let raw = format!(r#"{{"hook_event_name":"PreToolUse","tool_name":"Edit","tool_input":{{"old_string":"{big}"}}}}"#);
++ let (v, _) = run(&raw, "", "");
++ assert!(v["tool_input"]["old_string"].as_str().unwrap().len() <= MAX_FIELD_LEN + 4);
++ let raw = format!(r#"{{"hook_event_name":"BeforeTool","tool_name":"Edit","tool_input":{{"content":"{big}"}}}}"#);
++ let (v, ev) = run(&raw, "gemini", "");
++ assert_eq!(ev.name, "PreToolUse");
++ assert!(v["tool_input"]["content"].as_str().unwrap().len() <= MAX_FIELD_LEN + 4);
++ }
++
+ #[test]
+ fn a_finished_edit_keeps_its_text_whole_for_the_live_diff() {
+ let big = "line\n".repeat(4_000); // 20 KB, well past MAX_FIELD_LEN
+ let mut v = serde_json::json!({
+ "tool_name": "Edit",
+ "tool_input": { "file_path": "/p/a.ts", "old_string": big, "new_string": big },
+ "cwd": "x".repeat(4_000),
+ });
+ truncate_payload(&mut v, "PostToolUse");
+ assert_eq!(v["tool_input"]["old_string"].as_str().unwrap().len(), big.len());
+ assert_eq!(v["tool_input"]["new_string"].as_str().unwrap().len(), big.len());
+ // Everything else keeps the ordinary cap, and nothing says "cut".
+ assert!(v["cwd"].as_str().unwrap().len() <= MAX_FIELD_LEN + 4);
+ assert!(v.get("coucou_diff_truncated").is_none());
+
+ let mut multi = serde_json::json!({
+ "tool_name": "MultiEdit",
+ "tool_input": { "edits": [{ "old_string": big, "new_string": "x" }] },
+ });
+ truncate_payload(&mut multi, "PostToolUse");
+ assert_eq!(multi["tool_input"]["edits"][0]["old_string"].as_str().unwrap().len(), big.len());
+ }
+
+ #[test]
+ fn edits_are_still_capped_before_they_happen_and_for_other_tools() {
+ let big = "é".repeat(4_000);
+ for (event, tool) in [("PreToolUse", "Edit"), ("PermissionRequest", "Write"), ("PostToolUse", "Bash")] {
+ let mut v = serde_json::json!({ "tool_name": tool, "tool_input": { "content": big } });
+ truncate_payload(&mut v, event);
+ assert!(v["tool_input"]["content"].as_str().unwrap().len() <= MAX_FIELD_LEN + 4, "{event} {tool}");
+ }
+ }
+
+ #[test]
+ fn an_edit_beyond_the_budget_is_cut_and_flagged() {
+ let huge = "x".repeat(MAX_DIFF_FIELD_LEN + 10);
+ let mut v = serde_json::json!({
+ "tool_name": "Write",
+ "tool_input": { "file_path": "/p/big.txt", "content": huge },
+ });
+ truncate_payload(&mut v, "PostToolUse");
+ assert!(v["tool_input"]["content"].as_str().unwrap().len() <= MAX_DIFF_FIELD_LEN + 4);
+ assert_eq!(v["coucou_diff_truncated"], serde_json::Value::Bool(true));
+
+ // Together, the edit strings never pass the shared budget.
+ let half = "y".repeat(MAX_DIFF_FIELD_LEN - 1);
+ let edits: Vec<_> = (0..4)
+ .map(|_| serde_json::json!({ "old_string": half, "new_string": half }))
+ .collect();
+ let mut multi = serde_json::json!({ "tool_name": "MultiEdit", "tool_input": { "edits": edits } });
+ truncate_payload(&mut multi, "PostToolUse");
+ assert!(multi.to_string().len() < MAX_DIFF_TOTAL + 64 * 1024);
+ assert_eq!(multi["coucou_diff_truncated"], serde_json::Value::Bool(true));
+ }
}
diff --cc windows/src-tauri/src/lib.rs
index ed909777,0cd30c1a..05bce4ab
--- a/windows/src-tauri/src/lib.rs
+++ b/windows/src-tauri/src/lib.rs
@@@ -186,27 -165,33 +186,54 @@@ fn open_in_vscode(path: Option<String>
false
}
+/// "Open terminal": brings forward the terminal or editor window the session
+/// runs in, when it was found (Windows, see session_window.rs); otherwise opens
+/// the folder in VS Code, as before.
+#[tauri::command]
+fn open_session(session_id: Option<String>, path: Option<String>) -> bool {
+ if let Some(owner) = session_id.as_deref().and_then(session_window::lookup) {
+ let folder = path.as_deref().map(session_window::folder_name).unwrap_or_default();
+ if platform::focus_process_window(owner, folder) {
+ return true;
+ }
+ }
+ open_in_vscode(path)
+}
+
+/// The Claude Desktop pill's target: the Claude app (Windows only — it has no
+/// Linux build).
+#[tauri::command]
+fn open_claude_desktop() -> bool {
+ platform::open_claude_desktop()
+}
+
+ /// The file behind a live diff, if it may be handed to the editor: an existing
+ /// regular file given by its full path. Anything else — a relative path, a
+ /// folder, a path `code` could read as an option — goes no further.
+ fn diff_file(path: &str) -> Option<&std::path::Path> {
+ let p = std::path::Path::new(path);
+ (p.is_absolute() && p.is_file()).then_some(p)
+ }
+
+ /// The diff card's ↗: opens the edited file in VS Code when `code` is on PATH,
+ /// otherwise shows its folder. The file itself is never opened by its type —
+ /// xdg-open or Explorer would run a script that Claude just wrote.
+ #[tauri::command]
+ fn open_file_in_vscode(path: String) -> bool {
+ let Some(file) = diff_file(&path) else { return false };
+ if let Some(code) = platform::find_on_path("code") {
+ let mut cmd = Command::new(code);
+ cmd.arg(file);
+ if platform::no_console(&mut cmd).spawn().is_ok() {
+ return true;
+ }
+ }
+ if let Some(folder) = file.parent().filter(|d| d.is_dir()) {
+ platform::reveal_folder(&folder.to_string_lossy());
+ }
+ false
+ }
+
#[tauri::command]
fn quit_app(app: AppHandle) {
app.exit(0);
@@@ -521,24 -410,14 +548,25 @@@ pub fn run()
set_island_rect,
focus_window,
reposition,
+ list_monitors,
open_url,
open_in_vscode,
+ open_session,
+ open_claude_desktop,
+ open_file_in_vscode,
quit_app,
hooks_status,
+ agent_hooks_status,
hooks_preview,
hooks_apply,
+ agent_hooks_list,
+ agent_hooks_preview,
+ agent_hooks_apply,
+ status_line_preview,
+ status_line_apply,
+ codex_plan_usage,
approval_decision,
+ approval_answer,
approval_ack,
approval_decline,
log_line,
diff --cc windows/src/core/bridge.ts
index 783cf50c,1e2c298f..1abb5a29
--- a/windows/src/core/bridge.ts
+++ b/windows/src/core/bridge.ts
@@@ -58,16 -55,9 +58,19 @@@ export const Bridge =
/** "Open terminal" → opens the folder in VS Code when `code` is on PATH. */
openInVSCode: (path: string | null) => call<boolean>("open_in_vscode", { path }),
+ /**
+ * "Open terminal": the window the session runs in when Rust found it
+ * (Windows), else the folder in VS Code.
+ */
+ openSession: (sessionId: string | null, path: string | null) =>
+ call<boolean>("open_session", { sessionId, path }),
+
+ /** The Claude desktop app, for the Claude Desktop pill (Windows only). */
+ openClaudeDesktop: () => call<boolean>("open_claude_desktop"),
+
+ /** The diff card's ↗: an existing file, in VS Code; never launched by its type. */
+ openFileInVSCode: (path: string) => call<boolean>("open_file_in_vscode", { path }),
+
quit: () => call<void>("quit_app"),
openSettingsWindow: () => call<void>("open_settings_window"),
diff --cc windows/src/core/state.ts
index 52204d9b,bd801c4b..8e6897ae
--- a/windows/src/core/state.ts
+++ b/windows/src/core/state.ts
@@@ -2,12 -2,7 +2,13 @@@
import type { BotEmoteName, BotStateName, IslandMode, IslandViewName } from "./layout";
import type { EyeShape } from "../mochi/engine";
+import {
+ DEFAULT_MAIN_PILL, HOST_OS, availablePills, orderPills, pillDefinition, sanitizeDeclared,
+ toggleDeclared, type HostOs, type PillDefinition,
+} from "./pills";
+import type { CodexPlanUsage, PlanUsage } from "./plan";
+import type { ProviderId } from "./providers";
+ import type { FileDiff } from "./diff";
export type AgentSource = "claudeCode" | "n8n" | "agent";
export type PillBadge = "approval" | "finished" | "error";
@@@ -30,8 -20,8 +31,10 @@@ export interface AgentTask
miniEye?: EyeShape | null;
pillBadge?: PillBadge | null;
sessionCwd?: string | null;
+ /** Claude Code's session, so "Open terminal" can find the window it runs in. */
+ sessionId?: string | null;
+ /** Claude's final message after Stop, one line; cleared when a new turn starts. */
+ finalLine?: string | null;
}
export interface ApprovalInfo {
@@@ -178,14 -148,11 +186,19 @@@ 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;
+ /** Per-pill file diffs, in order of reception. Steps carry their ids. */
+ sessionDiffs = new Map<string, FileDiff[]>();
+ private sessionDiffTimers = new Map<string, number>();
+ /** Never reset, so an id can never point at a newer diff than the one tapped. */
+ private nextDiffId = 0;
lastActivity = performance.now();
@@@ -282,38 -213,60 +295,66 @@@
this.notify();
}
+ /** Stores a diff for a pill and returns its id (for the ticker step). */
+ appendSessionDiff(pillId: string, diff: FileDiff): number {
+ const id = this.nextDiffId++;
+ const list = this.sessionDiffs.get(pillId) ?? [];
+ list.push({ ...diff, id });
+ while (list.length > MAX_DIFFS_PER_PILL) list.shift();
+ this.sessionDiffs.set(pillId, list);
+ // One timer per pill, re-armed on every diff — nothing polls.
+ const prev = this.sessionDiffTimers.get(pillId);
+ if (prev != null) window.clearTimeout(prev);
+ this.sessionDiffTimers.set(
+ pillId,
+ window.setTimeout(() => this.clearSessionDiffs(pillId), DIFF_TTL_MS),
+ );
+ return id;
+ }
+
+ findDiff(pillId: string, id: number): FileDiff | null {
+ return this.sessionDiffs.get(pillId)?.find((d) => d.id === id) ?? null;
+ }
+
+ clearSessionDiffs(pillId: string) {
+ const timer = this.sessionDiffTimers.get(pillId);
+ if (timer != null) window.clearTimeout(timer);
+ this.sessionDiffTimers.delete(pillId);
+ this.sessionDiffs.delete(pillId);
+ }
+
- /** loadIntegrationTasks() — VS Code always on, the rest opt-in (max 4). */
+ /** The always-on workspace pill, once the setting has been checked. */
+ get mainPillId(): string {
+ return sanitizeDeclared(this.settings, this.os).mainPill;
+ }
+
+ /**
+ * True for a pill that stays when its session ends: the main pill and the
+ * declared ones go back to idle instead of going away.
+ */
+ isKept(id: string): boolean {
+ const d = sanitizeDeclared(this.settings, this.os);
+ return id === d.mainPill || d.activeIntegrations.includes(id);
+ }
+
+ /**
+ * Loads the catalog pills: the main pill always, the declared ones, and none
+ * of the others — a pill that is mid-session stays until its session ends.
+ * Safe to call any number of times. AppState.loadIntegrationTasks on macOS.
+ */
loadIntegrationTasks() {
- for (const proto of INTEGRATION_AGENTS) {
- const shouldLoad =
- proto.id === "integration_claude" || this.settings.activeIntegrations.includes(proto.id);
- const idx = this.tasks.findIndex((t) => t.id === proto.id);
- if (shouldLoad && idx < 0) this.tasks.push({ ...proto, steps: [] });
- if (!shouldLoad && idx >= 0) this.tasks.splice(idx, 1);
+ const d = sanitizeDeclared(this.settings, this.os);
+ this.settings.mainPill = d.mainPill;
+ this.settings.activeIntegrations = d.activeIntegrations;
+ for (const def of availablePills(this.os)) {
+ const shouldLoad = def.id === d.mainPill || d.activeIntegrations.includes(def.id);
+ const idx = this.tasks.findIndex((t) => t.id === def.id);
+ if (shouldLoad && idx < 0) this.tasks.push(taskFor(def));
+ const busy = idx >= 0 && (this.tasks[idx].state !== "idle" || this.tasks[idx].steps.length > 0);
+ if (!shouldLoad && idx >= 0 && !busy) this.tasks.splice(idx, 1);
}
- // Order: integration_claude first, then agent_* pills (visible in slice(0,4)),
- // then other integrations in declaration order.
- const order = INTEGRATION_AGENTS.map((t) => t.id);
- this.tasks.sort((a, b) => {
- const isAgentA = a.id.startsWith("agent_");
- const isAgentB = b.id.startsWith("agent_");
- // integration_claude always first
- if (a.id === "integration_claude") return -1;
- if (b.id === "integration_claude") return 1;
- // agent_* before other integrations; preserve insertion order among themselves
- if (isAgentA && !isAgentB) return -1;
- if (isAgentB && !isAgentA) return 1;
- if (isAgentA && isAgentB) return 0;
- // both known integrations → declaration order
- return order.indexOf(a.id) - order.indexOf(b.id);
- });
- if (!this.focusId) this.focusId = "integration_claude";
+ this.tasks = orderPills(this.tasks, d.mainPill);
+ if (!this.focusId || !this.tasks.some((t) => t.id === this.focusId)) this.focusId = d.mainPill;
this.notify();
}
@@@ -324,20 -273,9 +365,23 @@@
removeTask(id: string) {
const idx = this.tasks.findIndex((t) => t.id === id);
if (idx < 0) return;
+ if (this.isKept(id)) {
+ const t = this.tasks[idx];
+ t.state = "idle";
+ t.steps = [];
+ t.stepIndex = 0;
+ delete t.stepSeq;
+ t.pillBadge = null;
++ t.finalLine = null;
+ const def = pillDefinition(id);
+ if (def) t.name = def.name;
++ this.clearSessionDiffs(id);
+ this.notify();
+ return;
+ }
this.tasks.splice(idx, 1);
+ this.clearSessionDiffs(id);
- if (this.focusId === id) this.focusId = this.tasks[0]?.id ?? "integration_claude";
+ if (this.focusId === id) this.focusId = this.tasks[0]?.id ?? this.mainPillId;
this.notify();
}
diff --cc windows/src/island/hooks.ts
index bb71a5d0,7b471446..76f120bf
--- a/windows/src/island/hooks.ts
+++ b/windows/src/island/hooks.ts
@@@ -2,20 -2,14 +2,21 @@@
// Port of HookServer.processEvent / processPermissionRequest from the macOS app.
// Difference from macOS: no terminal filter. On Windows the hook fires from any
// terminal (Windows Terminal, VS Code, PowerShell…) and all of them are handled.
+// The relay has already mapped every agent's events and fields onto Claude
+// Code's (hook/src/normalize.rs), so one handler serves them all.
import { Bridge, onEvent } from "../core/bridge";
+ import { buildFileDiff, fileName, makeDiffStep, toOneLine } from "../core/diff";
import { Sound } from "../core/sound";
-import { State } from "../core/state";
+import { State, type AskedQuestion } from "../core/state";
+import { pillDefinition } from "../core/pills";
+import { APPROVAL_AGENTS, agentColor, agentName, validateAgent } from "./agents";
import type { Island } from "./island";
+import { parseClaudePlan, restorePlanUsage } from "../core/plan";
+import { setClaudePlanUsage, storedClaudePlanUsage } from "../views/usage";
const CLAUDE_ID = "integration_claude";
+const CURSOR_ID = "agent_cursor";
/** Clears the approval card if no decision was made before the hook gave up. */
let pendingTimeout: number | null = null;
@@@ -51,20 -31,33 +52,22 @@@ interface HookPayload
session_id?: string;
cwd?: string;
message?: string;
- /** What an agent said last, on Stop (Hermes, Codex). */
- last_assistant_message?: string;
/** UserPromptSubmit carries `prompt`; `message` belongs to Notification/Stop. */
prompt?: string;
- /** Stop: Claude's final answer of the turn (Markdown). */
++ /** Stop: the turn's final answer (Markdown) — Claude Code's, Hermes's, Codex's. */
+ last_assistant_message?: string;
tool_name?: string;
tool_input?: Record<string, unknown>;
+ /** Set by the relay when an edit was too big to forward whole (> 256 KB). */
+ coucou_diff_truncated?: boolean;
/** Optional agent tag: lowercase, digits and hyphens, ≤ 24 chars. */
coucou_agent?: string;
-}
-
-/** Same rule as HookServer.validateAgent on macOS. "claude" is reserved. */
-function validateAgent(raw: string | undefined): string | null {
- if (!raw || raw.length > 24 || raw === "claude") return null;
- if (!/^[a-z0-9-]+$/.test(raw)) return null;
- return raw;
-}
-
-const FALLBACK_COLORS = ["#22C55E", "#EAB308", "#60A5FA", "#E879F9"];
-
-function agentColor(name: string): string {
- let h = 0;
- for (let i = 0; i < name.length; i++) {
- h = (Math.imul(31, h) + name.charCodeAt(i)) | 0;
- }
- return FALLBACK_COLORS[Math.abs(h) % FALLBACK_COLORS.length];
+ /** Hermes: where the session runs (telegram, discord…; "cli" in a terminal). */
+ platform?: string;
+ /** "cursor" when Claude Code runs in Cursor's terminal (set by the relay). */
+ term_editor?: string;
+ /** StatusLine (the plan usage relay): Claude Code's 5-hour and weekly limits. */
+ rate_limits?: unknown;
}
const PROJECT_ALIASES: Record<string, string> = {
@@@ -150,49 -136,42 +153,71 @@@ function approvalTarget(tool: string, i
return tool;
}
-function upsert(projectName: string, cwd: string) {
- const t = State.tasks.find((x) => x.id === CLAUDE_ID);
- if (!t) return;
- t.name = projectName;
- if (cwd) t.sessionCwd = cwd;
+/**
+ * The questions of an AskUserQuestion call, if the island can show all of them
+ * as options to pick from. Anything it cannot is left to the terminal.
+ */
+function askedQuestions(tool: string, input: Record<string, unknown>): AskedQuestion[] | null {
+ if (tool !== "AskUserQuestion" || !Array.isArray(input.questions)) return null;
+ const out: AskedQuestion[] = [];
+ for (const raw of input.questions as Record<string, unknown>[]) {
+ const question = typeof raw?.question === "string" ? raw.question : "";
+ const options = (Array.isArray(raw?.options) ? (raw.options as Record<string, unknown>[]) : [])
+ .filter((o) => typeof o?.label === "string" && o.label)
+ .map((o) => ({
+ label: o.label as string,
+ description: typeof o.description === "string" ? o.description : "",
+ }));
+ // A question cut short by the relay would be answered under the wrong text.
+ if (!question || question.endsWith("…") || options.length < 2) return null;
+ out.push({ question, options, multiSelect: raw.multiSelect === true });
+ }
+ return out.length > 0 ? out : null;
}
-function clearSession() {
- const t = State.tasks.find((x) => x.id === CLAUDE_ID);
+/** The Claude Code session's pill, named after its project for the session. */
+function upsert(id: string, projectName: string, cwd: string, sessionId: string) {
+ const t = State.upsertWorkspacePill(id, projectName, cwd);
+ if (t && sessionId) t.sessionId = sessionId;
+}
+
+/** The session is over: the pill goes back as it was, or away if it was only there for it. */
+function clearSession(id: string) {
+ const t = State.tasks.find((x) => x.id === id);
if (!t) return;
+ if (!State.isKept(id)) {
+ State.removeTask(id);
+ return;
+ }
+ t.state = "idle";
t.steps = [];
t.stepIndex = 0;
- t.name = "VS Code";
+ delete t.stepSeq;
+ t.name = pillDefinition(id)?.name ?? t.name;
t.pillBadge = null;
+ t.sessionId = null;
+ t.finalLine = null;
+ }
+
+ /** The final message stays on the card until the next turn starts. */
+ function clearFinalLine(id: string) {
+ const t = State.tasks.find((x) => x.id === id);
+ if (t) t.finalLine = null;
+ }
+
+ /**
+ * PostToolUse of Edit / MultiEdit / Write → a diff stored for the pill and a
+ * ticker step with its +N −M counts. Nothing is kept for a pill that does not
+ * exist, so a stray event cannot grow memory. An edit the relay had to cut
+ * would give wrong counts: the PreToolUse step ("Modifie · file") stands alone.
+ */
+ function recordDiff(agentId: string, payload: HookPayload) {
+ if (payload.coucou_diff_truncated) return;
+ if (!State.tasks.some((t) => t.id === agentId)) return;
+ const diff = buildFileDiff(payload.tool_name ?? "", payload.tool_input ?? {});
+ if (!diff) return;
+ const id = State.appendSessionDiff(agentId, diff);
+ State.appendStep(agentId, makeDiffStep(fileName(diff.path), diff.added, diff.removed, id));
}
export function registerHookHandlers(island: Island) {
@@@ -287,10 -232,7 +312,11 @@@ function handleHook(island: Island, pay
switch (name) {
case "SessionStart":
ensurePill();
+ clearFinalLine(agentId);
+ // Hermes through its gateway says where the session comes from.
+ if (validAgent === "hermes" && payload.platform && payload.platform !== "cli") {
+ State.appendStep(agentId, payload.platform.charAt(0).toUpperCase() + payload.platform.slice(1));
+ }
surface("overview", false);
Sound.play("work");
break;
@@@ -318,17 -262,8 +346,18 @@@
case "PostToolUse":
supersedeStop();
+ // The question was answered in the terminal: the card would be lying.
+ if (
+ payload.tool_name === "AskUserQuestion" &&
+ State.pendingApproval?.questions &&
+ State.pendingApproval.sessionId === (payload.session_id ?? "")
+ ) {
+ if (pendingTimeout != null) window.clearTimeout(pendingTimeout);
+ pendingTimeout = null;
+ dropPendingCard(island);
+ }
State.updateTask(agentId, "working");
+ recordDiff(agentId, payload);
break;
case "PostToolUseFailure":
@@@ -354,12 -289,16 +383,19 @@@
case "Stop": {
State.updateTask(agentId, "finished");
- // Agents report their last words as `last_assistant_message` (Hermes, Codex).
- const said = payload.message ?? (isExternalAgent ? payload.last_assistant_message : undefined);
- if (said) State.appendStep(agentId, said.slice(0, 60));
+ // Claude Code puts the turn's answer in the Stop payload itself, so there is
- // no transcript to read (the relay does not even forward its path).
++ // no transcript to read (the relay does not even forward its path). Other
++ // agents report their last words the same way (Hermes, Codex) or as
++ // `message`.
+ const finalText = toOneLine(payload.last_assistant_message ?? payload.message ?? "");
+ if (finalText) {
+ State.appendStep(agentId, finalText);
+ const t = State.tasks.find((x) => x.id === agentId);
+ if (t) t.finalLine = finalText;
+ }
Sound.play("finish");
- if (focused) surface("finished", true);
+ // A card waiting for an answer is never covered by another alert.
+ if (focused && !State.pendingApproval) surface("finished", true);
else State.setPillBadge(agentId, "finished");
cancelStopTimer(agentId);
stopTimers.set(
diff --cc windows/src/views/ticker.ts
index 1d14922c,3b0bf3f2..d9436dac
--- a/windows/src/views/ticker.ts
+++ b/windows/src/views/ticker.ts
@@@ -98,20 -158,32 +158,27 @@@ export class Ticker
}
sync(task: AgentTask | null) {
- const steps = task && task.steps.length > 0 ? task.steps : ["…"];
- const idx = task ? Math.min(task.stepIndex, steps.length - 1) : -1;
+ const steps = task?.steps ?? [];
+ // Where the newest step sits in the whole session, not in `steps`: that
+ // list is capped at 20, and counting inside it made the ticker stop for
+ // good at the twentieth step of a session.
+ const newest = steps.length === 0 ? -1 : (task?.stepSeq ?? steps.length - 1);
+ const still = !!task?.finalLine;
+ if (still !== this.still) {
+ this.still = still;
+ // Mid-slide, the next frame places every row with the new look anyway.
+ if (this.startMs == null) this.rest();
+ }
+
- // First render: drop straight into place, no animation.
- if (this.displayIndex < 0) {
- this.displayIndex = idx;
- setText(this.a, idx > 0 ? steps[idx - 1] : "…");
- setText(this.b, steps[Math.max(idx, 0)]);
- this.rest();
- return;
- }
-
- // The session restarted (steps were cleared): re-seed rather than scroll.
- if (idx < this.displayIndex) {
+ // First render, or the session restarted (steps were cleared): drop
+ // straight into place rather than scroll.
+ if (this.displayIndex < 0 || newest < this.displayIndex) {
this.queue = [];
this.startMs = null;
- this.displayIndex = idx;
- setText(this.a, idx > 0 ? steps[idx - 1] : "…");
- setText(this.b, steps[Math.max(idx, 0)]);
+ this.displayIndex = newest;
+ setText(this.a, steps.at(-2) ?? "…");
+ setText(this.b, steps.at(-1) ?? "…");
this.rest();
return;
}
diff --cc windows/src/views/views.ts
index 05d0362a,96104c51..d0d660fc
--- a/windows/src/views/views.ts
+++ b/windows/src/views/views.ts
@@@ -11,10 -11,9 +11,13 @@@ import { createMiniBot, pruneMiniBots
import { buildPrompt } from "./chat";
import { buildChoose, buildUpload, buildUploading } from "./upload";
import { renderIntegrationCard, type IntegrationCardHooks } from "./integrations";
+import { pillDefinition, sessionSubtitle } from "../core/pills";
+import {
+ PlanCard, buildPlanPill, claudePillVisible, codexPillVisible, planCardOpen, refreshCodexPlanUsage,
+} from "./usage";
+ import { buildDiffCard } from "./diff";
+ import { lastTextStep } from "../core/diff";
+ import { Bridge } from "../core/bridge";
export interface ViewActions {
setView(v: IslandViewName): void;
@@@ -176,9 -152,26 +190,26 @@@ function buildOverview(actions: ViewAct
let pillIds = "";
let detailOpen = false;
let lastFocus: string | null = null;
- let mode: "ticker" | "card" | "plan" | null = null;
- let mode: "ticker" | "card" | "diff" | null = null;
++ let mode: "ticker" | "card" | "plan" | "diff" | null = null;
let cardKey = "";
+ // Leaving the overview or folding the island closes the diff, as on macOS.
+ State.subscribe(() => {
+ if (activeDiffId != null && (State.view !== "overview" || State.mode !== "expanded")) {
+ activeDiffId = null;
+ }
+ });
+ // Escape steps back out of the diff before it closes the island.
+ window.addEventListener(
+ "keydown",
+ (e) => {
+ if (e.key !== "Escape" || activeDiffId == null || State.view !== "overview") return;
+ e.stopImmediatePropagation();
+ closeDiff();
+ },
+ true,
+ );
+
const hooks: IntegrationCardHooks = {
get detailOpen() {
return detailOpen;
@@@ -226,24 -204,29 +258,42 @@@
mode = null;
}
- // VS Code with a live Claude Code session keeps the ticker; every other
- // pill shows its own card, exactly like IntegrationCardView.
- const sessionActive =
- task?.id === "integration_claude" && (task.state !== "idle" || task.steps.length > 0);
+ // A workspace or agent pill with a live session keeps the ticker; every
+ // other pill shows its own card, exactly like IntegrationCardView.
+ const sessionActive = task != null && hasSessionTicker(task);
+
+ const planOpen = planCardOpen();
+ if (mode === "plan" && !planOpen) {
+ mode = null;
+ cardKey = "";
+ }
+ syncPlanTimer(planOpen);
+ // A diff that has since been dropped (cap, expiry, session end) just closes.
+ const diff = task && activeDiffId != null ? State.findDiff(task.id, activeDiffId) : null;
+ if (!diff) activeDiffId = null;
+
- if (task && diff) {
+ if (planOpen) {
+ if (mode !== "plan") {
+ clear(leftBody);
+ leftBody.append(plan.el);
+ mode = "plan";
+ }
+ plan.sync();
++ } else if (task && diff) {
+ const key = `diff~${task.id}~${diff.id}`;
+ if (key !== cardKey) {
+ cardKey = key;
+ mode = "diff";
+ clear(leftBody);
+ leftBody.append(buildDiffCard(diff, {
+ dismiss: () => {
+ actions.blip();
+ closeDiff();
+ },
+ open: (path) => void Bridge.openFileInVSCode(path),
+ }));
+ }
} else if (task && sessionActive) {
if (mode !== "ticker") {
clear(leftBody);
@@@ -281,7 -262,7 +331,7 @@@
}
}
- jump.style.display = detailOpen || mode === "plan" ? "none" : "";
- jump.style.display = detailOpen || mode === "diff" ? "none" : "";
++ jump.style.display = detailOpen || mode === "plan" || mode === "diff" ? "none" : "";
const others = State.otherTasks.slice(0, 4);
const pillKey = others.map((t) => `${t.id}:${t.pillBadge ?? ""}`).join("|");
@@@ -461,68 -377,12 +511,69 @@@ function buildQuestion(actions: ViewAct
return {
el,
sync() {
+ const questions = State.pendingApproval?.questions;
clear(who);
- who.append(agentWho(State.focusTask, "Claude Code is asking a question"));
- const task = State.focusTask;
- title.textContent = (task && lastTextStep(task.steps)) ?? "Claude needs an answer.";
+ // Only a request that is waiting can be folded away and come back.
+ fold.style.display = State.pendingApproval ? "" : "none";
+
+ // A question that arrived as a notification has nothing to pick from.
+ if (!questions) {
+ who.append(agentWho(State.focusTask, "is asking a question"));
- title.textContent = State.focusTask?.steps.at(-1) ?? "Claude needs an answer.";
++ const task = State.focusTask;
++ title.textContent = (task && lastTextStep(task.steps)) ?? "Claude needs an answer.";
+ if (rowKey !== "terminal") {
+ rowKey = "terminal";
+ clear(row);
+ row.append(h("div", { class: "sub", text: "Answer it in your terminal." }));
+ }
+ return;
+ }
+
+ if (State.pendingApproval!.requestId !== requestId) {
+ requestId = State.pendingApproval!.requestId;
+ index = 0;
+ answers = {};
+ picked = new Set();
+ }
+ const q = questions[Math.min(index, questions.length - 1)];
+ const step = questions.length > 1 ? ` (${index + 1} of ${questions.length})` : "";
+ who.append(agentWho(State.focusTask, `is asking${step}`));
+ title.textContent = q.question;
+ title.title = q.question;
+
+ const key = `${requestId}:${index}:${[...picked].join("|")}`;
+ if (rowKey === key) return;
+ rowKey = key;
clear(row);
- row.append(h("div", { class: "sub", text: "Answer in your terminal — Coucou can't reply for you yet." }));
+ for (const option of q.options) {
+ const on = picked.has(option.label);
+ const button = btn(option.label, on ? "primary" : "secondary", () => {
+ if (!q.multiSelect) {
+ next(q.question, option.label, questions.length);
+ return;
+ }
+ if (on) picked.delete(option.label);
+ else picked.add(option.label);
+ State.notify();
+ });
+ if (option.description) button.title = option.description;
+ row.append(button);
+ }
+ if (q.multiSelect) {
+ const done = btn("Done", "primary", () => {
+ if (picked.size > 0) next(q.question, [...picked], questions.length);
+ });
+ if (picked.size === 0) done.classList.add("off");
+ row.append(done);
+ }
+ row.append(
+ h("button", {
+ class: "link-btn",
+ style: "color:#8e939c",
+ text: "Answer in terminal",
+ onclick: () => actions.answerInTerminal(),
+ }),
+ );
},
};
}
@@@ -543,11 -403,9 +594,11 @@@ function buildError(actions: ViewAction
sync() {
const task = State.focusTask;
clear(who);
- who.append(agentWho(task, task?.source === "n8n" ? "n8n" : "Claude Code"));
+ // agentWho already shows an agent's name: its label is just the kind.
+ const whoLabel = task?.source === "n8n" ? "n8n" : task?.source === "agent" ? "Agent" : "Claude Code";
+ who.append(agentWho(task, whoLabel));
title.textContent = task?.source === "n8n" ? "Workflow stopped." : "Session stopped on an error.";
- detail.textContent = task?.steps.at(-1) ?? "No detail available.";
+ detail.textContent = (task && lastTextStep(task.steps)) ?? "No detail available.";
},
};
}
@@@ -556,10 -414,9 +607,10 @@@
function buildFinished(actions: ViewActions): ViewHost {
const who = h("div");
- const title = h("div", { class: "title" });
+ const title = h("div", { class: "title one-line" });
+ const open = btn("Open terminal", "primary", () => actions.openTerminal());
const row = h("div", { class: "actions" },
- btn("Open terminal", "primary", () => actions.openTerminal()),
+ open,
btn("OK", "secondary", () => actions.collapse()),
);
const el = h("div", { class: "view" }, card("green", stack(116, 16, who, title, row)));
@@@ -567,13 -424,10 +618,15 @@@
el,
sync() {
clear(who);
- who.append(agentWho(State.focusTask, "Claude Code finished"));
- // Claude's final message, else the last step that is not a diff (FinishedView).
+ const agent = State.focusTask?.source === "agent";
+ who.append(agentWho(State.focusTask, agent ? "finished" : "Claude Code finished"));
- title.textContent = State.focusTask?.steps.at(-1) ?? "Session finished";
++ // The final message, else the last step that is not a diff (FinishedView).
+ const task = State.focusTask;
+ title.textContent = task?.finalLine || (task && lastTextStep(task.steps)) || "Session finished";
+ // Sessions from the Claude desktop app live there, not in a terminal.
- const label = State.focusTask?.id === "agent_claude-desktop" ? "Open Claude" : "Open terminal";
++ const label = task?.id === "agent_claude-desktop" ? "Open Claude" : "Open terminal";
+ const span = open.firstElementChild as HTMLElement;
+ if (span.textContent !== label) span.textContent = label;
},
};
}