diff --git a/README.md b/README.md index e8003c1..de4d2b3 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Claudiu is a native desktop app, written in Rust with [GPUI](https://gpui.rs), t ## What it does -Each session is your own `claude` process in a real pseudo-terminal, so Claude Code's keys, mouse and paste work unchanged. Claudiu has no API keys and never calls the Anthropic API. Sign-in stays with Claude Code. The first launch opens a setup window that checks for `claude` (required) and `gh` (optional), links to their install pages and installs nothing. Settings has a Check setup button to open it again. A sidebar lists your projects and sessions. Ended sessions resume through `claude --resume`, and sessions that were running come back at the next start. +Each session is your own `claude` process in a real pseudo-terminal, so Claude Code's keys, mouse and paste work unchanged. Claudiu has no API keys and never calls the Anthropic API. Sign-in stays with Claude Code. The first launch opens a setup window that checks for `claude` (required) and `gh` (optional), links to their install pages and installs nothing. It also has an optional switch that turns off six Claude Code features that add tokens to every request and that coding rarely uses, such as Artifacts and bundled skills. Settings → Claude Code tools shows each switch as high, medium or low savings. Settings has a Check setup button to open it again. A sidebar lists your projects and sessions. Ended sessions resume through `claude --resume`, and sessions that were running come back at the next start. Around the terminal, Claudiu adds an editor mode (Ctrl+Shift+E) with files, tabs, search, Git change marks and language-server diagnostics, definitions and completion. It also adds usage and context meters, a GitHub pane for issues and pull requests through your `gh` login, defaults for the model, effort and permission mode of new sessions, and extra Claude accounts that share one configuration. When a reply needs a table, chart or diagram, Claude draws it as a card inside the terminal, under the tool call, and the card scrolls with the transcript. Cards can hold buttons that send a message for you, collapsible sections, tabs and charts, and they come back when you reopen a session. A session can move between git worktrees the way it switches branches, so several agents work on separate branches at once: the worktree button in the top bar switches the shown session into another worktree, or into a new one that Claudiu makes on a branch you name, and its conversation continues there (a session that has no conversation yet starts over in the new folder). Claude can switch the session itself with the `switch_worktree` tool, after you approve it and once its turn ends. In the menu, the hover x removes a worktree, the branch button's x deletes a local branch after telling you which commits would be lost, and ending the last session in a worktree offers to remove it. Claudiu keeps the worktrees it makes in its own data folder, outside your repositories, so they never show up in `git status`; Settings has a Worktrees page that lists them to show in the file manager or remove. Settings lists the rest. diff --git a/src/app/mod.rs b/src/app/mod.rs index 02bc7e5..fe8b530 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -305,6 +305,10 @@ pub enum Modal { trimmed: Vec, /// Claudiu tools turned off (Claudiu tools page). claudiu_off: Vec, + /// Skills to turn off, separated by commas (Claude Code tools page). + skills_field: Entity, + /// Settings found at open time that make Claude Code cost more (Claude Code tools page). + costly: Vec, /// Focus of the category list, which has the keyboard when the dialog opens. list_focus: FocusHandle, }, @@ -793,10 +797,11 @@ impl Workspace { let claude = self.modal_input(&claude_t, &claude_hint, window, cx); let model = self.modal_input(defaults.model.as_deref().unwrap_or_default(), "Claude Code default", window, cx); let shell = self.modal_input(&shell_t, &platform::default_shell(None).0, window, cx); + let skills_field = self.modal_input(&self.store.data.settings.limits.text(), "none, e.g. dataviz, claude-api", window, cx); let list_focus = cx.focus_handle(); window.focus(&list_focus, cx); self.set_settings_page(self.settings_page, cx); - self.modal = Some(Modal::Settings { shell, claude, model, effort: defaults.effort, permission: defaults.permission_mode, updates, chrome, scale: crate::panels::scale::percent(), trimmed: self.store.data.settings.trimmed_tools.clone(), claudiu_off: self.store.data.settings.claudiu_tools_off.clone(), list_focus }); + self.modal = Some(Modal::Settings { shell, claude, model, effort: defaults.effort, permission: defaults.permission_mode, updates, chrome, scale: crate::panels::scale::percent(), trimmed: self.store.data.settings.trimmed_tools.clone(), claudiu_off: self.store.data.settings.claudiu_tools_off.clone(), skills_field, costly: claude::costly::scan(), list_focus }); } Act::PickEffort(choice) => { if let Some(Modal::Settings { effort, .. }) = self.modal.as_mut() { diff --git a/src/app/modal.rs b/src/app/modal.rs index e801849..68b1ce6 100644 --- a/src/app/modal.rs +++ b/src/app/modal.rs @@ -108,7 +108,7 @@ impl Workspace { } } } - Some(Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, list_focus }) => { + Some(Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, skills_field, costly, list_focus }) => { let clean = |s: &str| s.trim().trim_matches('"').to_string(); let (shell_t, claude_t) = (clean(shell.read(cx).value().as_ref()), clean(claude.read(cx).value().as_ref())); let model_name = claude::defaults::parse_model(model.read(cx).value().as_ref()); @@ -118,10 +118,12 @@ impl Workspace { .find(|(_, _, t)| !t.is_empty() && platform::resolve_program(t).is_none()) .map(|(what, field, t)| (SettingsPage::General, field.clone(), format!("{what}: “{t}” is not a file or a program on PATH"))); let bad_model = model_name.is_err().then(|| (SettingsPage::Sessions, model.clone(), "Use a model alias or id (letters, digits, . _ -).".to_string())); - if let Some((page, field, msg)) = paths.or(bad_model) { + let limits = claude::trim::Limits::parse(skills_field.read(cx).value().as_ref()); + let bad_limits = limits.as_ref().err().map(|why| (SettingsPage::ClaudeTools, skills_field.clone(), why.clone())); + if let Some((page, field, msg)) = paths.or(bad_model).or(bad_limits) { self.settings_page = page; field.update(cx, |s, cx| s.focus(window, cx)); - self.modal = Some(Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, list_focus }); + self.modal = Some(Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, skills_field, costly, list_focus }); self.toast(msg, true, cx); return; } @@ -141,20 +143,23 @@ impl Workspace { // When that fails the old trims stay, so what the page shows is what Claude Code has. let mut trim_error = None; let mut trimmed = trimmed; - if s.trimmed_tools != trimmed { + let mut limits = limits.unwrap_or_default(); + if s.trimmed_tools != trimmed || s.limits != limits { let written = claude::claude_home() .ok_or_else(|| std::io::Error::other("Claude Code's folder was not found")) - .and_then(|home| claude::trim::write_global(&home.join("settings.json"), &trimmed, &s.applied_trims)); + .and_then(|home| claude::trim::write_global(&home.join("settings.json"), &trimmed, &limits, &s.applied_trims)); match written { Ok(owned) => s.applied_trims = owned, Err(e) => { trim_error = Some(e); trimmed = s.trimmed_tools.clone(); + limits = s.limits.clone(); } } } - let tools_changed = s.trimmed_tools != trimmed || s.claudiu_tools_off != claudiu_off; + let tools_changed = s.trimmed_tools != trimmed || s.limits != limits || s.claudiu_tools_off != claudiu_off; s.trimmed_tools = trimmed; + s.limits = limits; s.claudiu_tools_off = claudiu_off; crate::panels::scale::set(scale); self.shell = platform::default_shell(s.shell.as_deref()); diff --git a/src/app/settings.rs b/src/app/settings.rs index 3fad218..568a0dd 100644 --- a/src/app/settings.rs +++ b/src/app/settings.rs @@ -46,11 +46,12 @@ impl Workspace { /// Keys for the open Settings dialog, seen before the focused control. Up and Down change the page and Enter saves /// only while the category list has focus; Tab and Shift+Tab cycle the list and the current page's text fields. pub(crate) fn settings_key(&mut self, ev: &KeyDownEvent, window: &mut Window, cx: &mut Context) { - let Some(Modal::Settings { shell, claude, model, list_focus, .. }) = &self.modal else { return }; + let Some(Modal::Settings { shell, claude, model, skills_field, list_focus, .. }) = &self.modal else { return }; let list_focus = list_focus.clone(); let fields = match self.settings_page { SettingsPage::General => vec![shell.clone(), claude.clone()], SettingsPage::Sessions => vec![model.clone()], + SettingsPage::ClaudeTools => vec![skills_field.clone()], _ => Vec::new(), }; let on_list = list_focus.is_focused(window); diff --git a/src/app/setup.rs b/src/app/setup.rs index 75acc06..6e2cf48 100644 --- a/src/app/setup.rs +++ b/src/app/setup.rs @@ -1,11 +1,12 @@ //! The setup window: a short checklist of the two tools Claudiu runs (`claude`, required; `gh`, optional). It opens //! alone on a first launch (see `main.rs`) and again from Settings or the missing-`claude` toast. It installs nothing. -//! It never owns the store: it hands the path the user typed back in `SetupEvent::Done`, and the main window applies it. +//! It never owns the store: it hands the path the user typed and the recommended-trims choice back in `SetupEvent::Done`, +//! and the main window applies them. use super::*; use gpui::{ - Bounds, ClickEvent, EventEmitter, IntoElement, ParentElement, Render, SharedString, StatefulInteractiveElement, Styled, TitlebarOptions, + Bounds, ClickEvent, EventEmitter, InteractiveElement, IntoElement, ParentElement, Render, SharedString, StatefulInteractiveElement, Styled, TitlebarOptions, WindowBounds, WindowOptions, div, prelude::FluentBuilder, px, size, }; use gpui_kit::assets::IconName; @@ -31,8 +32,9 @@ pub enum Mode { } pub enum SetupEvent { - /// The user is done. Holds the `claude` path they gave, `None` for "find it yourself". - Done(Option), + /// The user is done. `claude_path` is the path they gave, `None` for "find it yourself". `recommended_trims` asks + /// the main window to turn off `trim::RECOMMENDED` once, as if they were switched off in Settings. + Done { claude_path: Option, recommended_trims: bool }, /// Run `gh auth login` in a terminal tab of the main window (only sent in `Mode::Reopened`). SignIn, } @@ -78,6 +80,11 @@ pub struct SetupView { checks: u64, /// Reads the PATH again before each check; `platform::reload_path`, except in tests. reload_path: fn(), + /// The "recommended trims" switch; off until the user turns it on. + recommended_trims: bool, + /// The cards scroll under a fixed header and buttons: the window has one size, and UI scale or a long error can + /// make them taller than it. + body_scroll: crate::panels::glide::Smooth, done: bool, } @@ -106,7 +113,7 @@ impl SetupView { view.update(cx, |view, cx| view.close(window, cx)).is_err() }); } - let mut view = Self { mode, path_input, configured: current, path_error: None, checked: None, asked_again: false, checks: 0, reload_path, done: false }; + let mut view = Self { mode, path_input, configured: current, path_error: None, checked: None, asked_again: false, checks: 0, reload_path, recommended_trims: false, body_scroll: Default::default(), done: false }; view.run_checks(cx); view } @@ -157,7 +164,7 @@ impl SetupView { return; } self.done = true; - cx.emit(SetupEvent::Done(self.path_to_hand_back(cx))); + cx.emit(SetupEvent::Done { claude_path: self.path_to_hand_back(cx), recommended_trims: self.recommended_trims }); } /// Hand the path back and close the window. The window goes in a deferred step: the main window listens through a @@ -219,6 +226,26 @@ impl SetupView { button(id, label, true).on_click(cx.listener(move |_, _: &ClickEvent, _, cx| cx.open_url(url))) } + fn trims_row(&self, cx: &mut Context) -> impl IntoElement { + let on = self.recommended_trims; + card() + .id("setup-recommended-trims") + .cursor_pointer() + .child( + div() + .flex() + .items_center() + .justify_between() + .child(tool_title("Recommended trims", "OPTIONAL")) + .child(div().text_size(crate::panels::scale::px(13.0)).text_color(hsla(if on { theme::ACCENT } else { theme::TEXT_FAINT })).child(if on { "On" } else { "Off" })), + ) + .child(faint("Fewer tokens in every request. Change it later in Settings → Claude Code tools.")) + .on_click(cx.listener(|view, _: &ClickEvent, _, cx| { + view.recommended_trims = !view.recommended_trims; + cx.notify(); + })) + } + fn claude_row(&self, cx: &mut Context) -> impl IntoElement { let found = self.checked.as_ref().map(|found| &found.claude); let state = match found { @@ -272,7 +299,7 @@ impl SetupView { } impl Render for SetupView { - fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let primary = if self.mode == Mode::Reopened { button("setup-done", "Close", true).on_click(cx.listener(|view, _: &ClickEvent, window, cx| view.close(window, cx))) } else if self.can_continue() { @@ -302,10 +329,18 @@ impl Render for SetupView { .child("Claudiu runs your own claude and reaches GitHub through your own gh. It installs nothing; this page only checks that they are there."), ), ) - .child(self.claude_row(cx)) - .child(self.gh_row(cx)) - .children(self.needs_restart_hint().then(|| faint(STILL_MISSING))) - .child(div().flex_1()) + .child( + self.body_scroll.wire(div().id("setup-body").flex_1().min_h_0(), window).child( + div() + .flex() + .flex_col() + .gap(px(14.0)) + .child(self.claude_row(cx)) + .child(self.gh_row(cx)) + .children(self.needs_restart_hint().then(|| faint(STILL_MISSING))) + .child(self.trims_row(cx)), + ), + ) .child( div() .flex() @@ -336,9 +371,9 @@ impl Workspace { }; self.setup_window = Some(handle); cx.subscribe_in(&view, window, |ws: &mut Workspace, _, ev: &SetupEvent, window, cx| match ev { - SetupEvent::Done(path) => { + SetupEvent::Done { claude_path, recommended_trims } => { ws.setup_window = None; - ws.apply_setup(path.clone(), cx); + ws.apply_setup(claude_path.clone(), *recommended_trims, cx); } SetupEvent::SignIn => { window.activate_window(); @@ -348,15 +383,38 @@ impl Workspace { .detach(); } - /// Use what the setup window ended with: its `claude` path (`None` clears it), looked for again, and saved. On a - /// first launch the save also creates the state file. - pub fn apply_setup(&mut self, claude_path: Option, cx: &mut Context) { + /// Use what the setup window ended with: its `claude` path (`None` clears it), looked for again, and saved, and + /// the recommended trims when asked for. On a first launch the save also creates the state file. + pub fn apply_setup(&mut self, claude_path: Option, recommended_trims: bool, cx: &mut Context) { self.store.data.settings.claude_path = claude_path; self.claude_exe = claude::discover(self.store.data.settings.claude_path.as_deref()); + if recommended_trims { + self.add_recommended_trims(cx); + } self.store.mark_dirty(); self.store.save(); cx.notify(); } + + /// Write the recommended trims into Claude Code's settings.json, as saving them in Settings would. When the file + /// can't be changed the trims stay as they were, so Settings shows what Claude Code has. + fn add_recommended_trims(&mut self, cx: &mut Context) { + let s = &mut self.store.data.settings; + let trimmed = claude::trim::with_recommended(&s.trimmed_tools); + if trimmed == s.trimmed_tools { + return; + } + let written = claude::claude_home() + .ok_or_else(|| std::io::Error::other("Claude Code's folder was not found")) + .and_then(|home| claude::trim::write_global(&home.join("settings.json"), &trimmed, &s.limits, &s.applied_trims)); + match written { + Ok(owned) => { + s.applied_trims = owned; + s.trimmed_tools = trimmed; + } + Err(e) => self.toast(format!("Claude Code's settings.json could not be changed ({e}), so the recommended trims are not on."), true, cx), + } + } } #[cfg(test)] @@ -385,8 +443,8 @@ mod tests { let log = handed_back.clone(); let _watch = cx.update(|app| { app.subscribe(&view, move |_, ev: &SetupEvent, _| { - if let SetupEvent::Done(path) = ev { - log.borrow_mut().push(path.clone()); + if let SetupEvent::Done { claude_path, .. } = ev { + log.borrow_mut().push(claude_path.clone()); } }) }); @@ -417,8 +475,8 @@ mod tests { let log = handed_back.clone(); let _watch = cx.update(|app| { app.subscribe(&view, move |_, ev: &SetupEvent, _| { - if let SetupEvent::Done(path) = ev { - log.borrow_mut().push(path.clone()); + if let SetupEvent::Done { claude_path, .. } = ev { + log.borrow_mut().push(claude_path.clone()); } }) }); @@ -451,6 +509,33 @@ mod tests { } } + #[test] + fn the_recommended_trims_are_off_unless_the_user_turns_them_on() { + let mut cx = TestAppContext::single(); + cx.update(gpui_kit::init); + let choices: Rc>> = Rc::default(); + for turn_on in [false, true] { + let (_, view) = cx + .update(|app| gpui_kit::open_window(Default::default(), app, |window, app| app.new(|cx| SetupView::with_reload(Mode::Reopened, None, || {}, window, cx)))) + .unwrap(); + let log = choices.clone(); + let _watch = cx.update(|app| { + app.subscribe(&view, move |_, ev: &SetupEvent, _| { + if let SetupEvent::Done { recommended_trims, .. } = ev { + log.borrow_mut().push(*recommended_trims); + } + }) + }); + view.update(&mut cx, |view, cx| { + if turn_on { + view.recommended_trims = !view.recommended_trims; + } + view.finish(cx); + }); + } + assert_eq!(*choices.borrow(), [false, true]); + } + #[test] fn the_claude_path_field_is_empty_a_real_program_or_an_error() { let tmp = tempfile::tempdir().unwrap(); diff --git a/src/claude/costly.rs b/src/claude/costly.rs new file mode 100644 index 0000000..9186f0e --- /dev/null +++ b/src/claude/costly.rs @@ -0,0 +1,125 @@ +//! Settings that make Claude Code cost more, found in Claudiu's own environment and in Claude Code's `settings.json` +//! `env` block. Each one changed a real request in a measured run on Claude Code 2.1.319: with prompt caching off +//! nothing was read from the cache, and with tool search off the first request grew from 18k to 26k tokens. + +use std::path::Path; + +use serde_json::{Map, Value}; + +/// One variable that raises cost, and where it was found. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Finding { + pub name: &'static str, + pub source: &'static str, + pub effect: &'static str, +} + +const NO_CACHE: &str = "Turns prompt caching off, so every request pays full price for the whole conversation."; +const NO_TOOL_SEARCH: &str = "Sends every tool definition in each request (about 8,000 more tokens in a measured run)."; + +/// A variable and the effect of having it on. Caching variables are on when truthy, tool search is off when falsy. +const CACHING: [(&str, &str); 6] = [ + ("DISABLE_PROMPT_CACHING", NO_CACHE), + ("DISABLE_PROMPT_CACHING_FABLE", NO_CACHE), + ("DISABLE_PROMPT_CACHING_HAIKU", NO_CACHE), + ("DISABLE_PROMPT_CACHING_MYTHOS", NO_CACHE), + ("DISABLE_PROMPT_CACHING_OPUS", NO_CACHE), + ("DISABLE_PROMPT_CACHING_SONNET", NO_CACHE), +]; + +fn truthy(value: &str) -> bool { + matches!(value.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on") +} + +fn falsy(value: &str) -> bool { + matches!(value.trim().to_ascii_lowercase().as_str(), "0" | "false" | "no" | "off") +} + +/// What raises cost in `process_env` (Claudiu's environment, which the sessions it starts inherit) and `file_env` (the +/// `env` block of `settings.json`). A variable set in both places is reported for the process environment. +pub fn find(process_env: &dyn Fn(&str) -> Option, file_env: &Map) -> Vec { + let look = |name: &str| -> Option<(&'static str, String)> { + if let Some(v) = process_env(name) { + return Some(("Claudiu's environment", v)); + } + file_env.get(name).and_then(Value::as_str).map(|v| ("Claude Code's settings.json", v.to_string())) + }; + let mut found = vec![]; + for (name, effect) in CACHING { + if let Some((source, _)) = look(name).filter(|(_, v)| truthy(v)) { + found.push(Finding { name, source, effect }); + } + } + if let Some((source, _)) = look("ENABLE_TOOL_SEARCH").filter(|(_, v)| falsy(v)) { + found.push(Finding { name: "ENABLE_TOOL_SEARCH", source, effect: NO_TOOL_SEARCH }); + } + found +} + +/// The `env` block of the `settings.json` at `path`; empty when the file is missing or is not a JSON object. +pub fn read_file_env(path: &Path) -> Map { + let Ok(text) = std::fs::read_to_string(path) else { return Map::new() }; + let Ok(Value::Object(settings)) = serde_json::from_str(&text) else { return Map::new() }; + settings.get("env").and_then(Value::as_object).cloned().unwrap_or_default() +} + +/// `find` on the real environment and Claude Code's own `settings.json`. +pub fn scan() -> Vec { + let file_env = crate::claude::claude_home().map(|home| read_file_env(&home.join("settings.json"))).unwrap_or_default(); + find(&|name| std::env::var(name).ok(), &file_env) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn none(_: &str) -> Option { + None + } + + fn names(found: &[Finding]) -> Vec<&'static str> { + found.iter().map(|f| f.name).collect() + } + + #[test] + fn a_clean_setup_has_no_findings() { + assert!(find(&none, &Map::new()).is_empty()); + } + + #[test] + fn caching_off_is_found_in_the_environment_and_says_where() { + let env = |name: &str| (name == "DISABLE_PROMPT_CACHING_HAIKU").then(|| "1".to_string()); + let found = find(&env, &Map::new()); + assert_eq!(found, [Finding { name: "DISABLE_PROMPT_CACHING_HAIKU", source: "Claudiu's environment", effect: NO_CACHE }]); + } + + #[test] + fn the_settings_file_env_block_is_read_too() { + let file = json!({ "DISABLE_PROMPT_CACHING": "true", "ENABLE_TOOL_SEARCH": "false" }).as_object().unwrap().clone(); + let found = find(&none, &file); + assert_eq!(names(&found), ["DISABLE_PROMPT_CACHING", "ENABLE_TOOL_SEARCH"]); + assert!(found.iter().all(|f| f.source == "Claude Code's settings.json")); + } + + #[test] + fn a_variable_set_to_off_is_not_a_finding() { + let file = json!({ "DISABLE_PROMPT_CACHING": "0", "ENABLE_TOOL_SEARCH": "true" }).as_object().unwrap().clone(); + assert!(find(&none, &file).is_empty()); + } + + #[test] + fn the_process_environment_wins_over_the_file() { + let env = |name: &str| (name == "DISABLE_PROMPT_CACHING").then(|| "1".to_string()); + let file = json!({ "DISABLE_PROMPT_CACHING": "1" }).as_object().unwrap().clone(); + assert_eq!(find(&env, &file)[0].source, "Claudiu's environment"); + } + + #[test] + fn a_missing_or_broken_settings_file_gives_an_empty_env_block() { + let tmp = tempfile::tempdir().unwrap(); + assert!(read_file_env(&tmp.path().join("missing.json")).is_empty()); + std::fs::write(tmp.path().join("bad.json"), "{ nope").unwrap(); + assert!(read_file_env(&tmp.path().join("bad.json")).is_empty()); + } +} diff --git a/src/claude/mod.rs b/src/claude/mod.rs index bd0ed83..394edeb 100644 --- a/src/claude/mod.rs +++ b/src/claude/mod.rs @@ -12,6 +12,7 @@ pub mod accounts; pub mod ask; pub mod bridge; pub mod config_sync; +pub mod costly; pub mod defaults; pub mod mcp; pub mod plugin; diff --git a/src/claude/trim.rs b/src/claude/trim.rs index c007f7b..22c4a8c 100644 --- a/src/claude/trim.rs +++ b/src/claude/trim.rs @@ -29,24 +29,63 @@ pub enum Trim { DesignSync, NotebookEdit, ReportFindings, + GitInstructions, + ClaudeApiSkill, + ExplorePlanAgents, + AdvisorTool, + BackgroundTasks, } /// What turning an item off does in the settings file. enum Effect { /// Settings keys set to the given values. Keys(&'static [(&'static str, bool)]), + /// Variables set in the `env` block, which Claude Code applies to the session. + Env(&'static [(&'static str, &'static str)]), /// Tool names added to `permissions.deny`. Deny(&'static [&'static str]), } +/// How much a trim saves; shown beside each switch (see `Trim::saving`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Saving { + High, + Medium, + Low, +} + +impl Saving { + pub fn label(self) -> &'static str { + match self { + Saving::High => "high savings", + Saving::Medium => "medium savings", + Saving::Low => "low savings", + } + } +} + +/// What the setup window's "recommended trims" switch turns off: the high and medium savers that take nothing away +/// from how Claude works. The Advisor tool, Git instructions, background tasks and the Explore and Plan agents save +/// tokens too, but a new user has not chosen to lose them. +pub const RECOMMENDED: [Trim; 6] = [Trim::Artifacts, Trim::BundledSkills, Trim::ClaudeApiSkill, Trim::ClaudeAiConnectors, Trim::ScheduleWakeup, Trim::ReportFindings]; + +/// `trimmed` with the recommended trims added; what the user had turned off stays off. +pub fn with_recommended(trimmed: &[Trim]) -> Vec { + normalized(&[trimmed, &RECOMMENDED[..]].concat()) +} + impl Trim { /// In the order the page lists them, grouped (see `GROUPS`). - pub const ALL: [Trim; 15] = [ + pub const ALL: [Trim; 20] = [ + Self::Artifacts, Self::BundledSkills, + Self::ClaudeApiSkill, Self::Workflows, Self::RemoteControl, Self::ClaudeAiConnectors, - Self::Artifacts, + Self::ExplorePlanAgents, + Self::AdvisorTool, + Self::BackgroundTasks, Self::PlanMode, Self::AskUserQuestion, Self::ScheduledTasks, @@ -57,15 +96,17 @@ impl Trim { Self::DesignSync, Self::NotebookEdit, Self::ReportFindings, + Self::GitInstructions, ]; /// The page's groups: a heading and the items under it. - pub const GROUPS: [(&'static str, &'static [Trim]); 5] = [ - ("FEATURES", &[Self::BundledSkills, Self::Workflows, Self::RemoteControl, Self::ClaudeAiConnectors, Self::Artifacts]), + pub const GROUPS: [(&'static str, &'static [Trim]); 6] = [ + ("FEATURES", &[Self::Artifacts, Self::BundledSkills, Self::ClaudeApiSkill, Self::Workflows, Self::RemoteControl, Self::ClaudeAiConnectors]), + ("AGENTS AND TASKS", &[Self::ExplorePlanAgents, Self::AdvisorTool, Self::BackgroundTasks]), ("PLANNING", &[Self::PlanMode, Self::AskUserQuestion]), ("SCHEDULING", &[Self::ScheduledTasks, Self::ScheduleWakeup, Self::RemoteTrigger]), ("MESSAGING", &[Self::SendMessage, Self::PushNotification]), - ("OTHER", &[Self::DesignSync, Self::NotebookEdit, Self::ReportFindings]), + ("OTHER", &[Self::DesignSync, Self::NotebookEdit, Self::ReportFindings, Self::GitInstructions]), ]; pub fn label(self) -> &'static str { @@ -85,6 +126,31 @@ impl Trim { Self::DesignSync => "DesignSync", Self::NotebookEdit => "NotebookEdit", Self::ReportFindings => "ReportFindings", + Self::GitInstructions => "Git instructions", + Self::ClaudeApiSkill => "Claude API skill", + Self::ExplorePlanAgents => "Explore and Plan agents", + Self::AdvisorTool => "Advisor tool", + Self::BackgroundTasks => "Background tasks", + } + } + + /// How many tokens turning it off saved per request in a measured run on Claude Code 2.1.319 (first request, + /// alone against no trims): high is 1,300 to 13,400, medium 330 to 830, low under 100. Low ones are tools that load + /// only when Claude searches for them. The Advisor tool is high only when an advisor model is set, and 0 otherwise. + pub fn saving(self) -> Saving { + match self { + Self::Artifacts | Self::BundledSkills | Self::ClaudeAiConnectors | Self::ScheduleWakeup | Self::AdvisorTool => Saving::High, + Self::GitInstructions | Self::ReportFindings | Self::ClaudeApiSkill | Self::BackgroundTasks | Self::ExplorePlanAgents => Saving::Medium, + Self::Workflows + | Self::RemoteControl + | Self::PlanMode + | Self::AskUserQuestion + | Self::ScheduledTasks + | Self::RemoteTrigger + | Self::SendMessage + | Self::PushNotification + | Self::DesignSync + | Self::NotebookEdit => Saving::Low, } } @@ -105,6 +171,11 @@ impl Trim { Self::DesignSync => Effect::Deny(&["DesignSync"]), Self::NotebookEdit => Effect::Deny(&["NotebookEdit"]), Self::ReportFindings => Effect::Deny(&["ReportFindings"]), + Self::GitInstructions => Effect::Keys(&[("includeGitInstructions", false)]), + Self::ClaudeApiSkill => Effect::Env(&[("CLAUDE_CODE_DISABLE_CLAUDE_API_SKILL", "1")]), + Self::ExplorePlanAgents => Effect::Env(&[("CLAUDE_CODE_DISABLE_EXPLORE_PLAN_AGENTS", "1")]), + Self::AdvisorTool => Effect::Env(&[("CLAUDE_CODE_DISABLE_ADVISOR_TOOL", "1")]), + Self::BackgroundTasks => Effect::Env(&[("CLAUDE_CODE_DISABLE_BACKGROUND_TASKS", "1")]), } } } @@ -114,67 +185,97 @@ pub fn normalized(trimmed: &[Trim]) -> Vec { Trim::ALL.into_iter().filter(|t| trimmed.contains(t)).collect() } -/// One line Claudiu adds to `settings.json` for a trim. -#[derive(Clone, Copy, PartialEq)] +/// One line Claudiu adds to `settings.json`. +#[derive(Clone, PartialEq)] enum Entry { Key(&'static str, bool), Deny(&'static str), + Env(&'static str, &'static str), + /// A skill turned off in `skillOverrides`. + Skill(String), } impl Entry { /// How `applied` remembers it. - fn id(self) -> String { + fn id(&self) -> String { match self { Entry::Key(key, _) => key.to_string(), Entry::Deny(name) => format!("deny:{name}"), + Entry::Env(name, value) => format!("env:{name}={value}"), + Entry::Skill(name) => format!("skill:{name}"), } } + + /// The entry an earlier `id` stood for, so it can be taken out again. + fn from_id(id: &str) -> Option { + if let Some(name) = id.strip_prefix("skill:") { + return Some(Entry::Skill(name.into())); + } + Trim::ALL.into_iter().flat_map(entries).find(|entry| entry.id() == id) + } } fn entries(trim: Trim) -> Vec { match trim.effect() { Effect::Keys(keys) => keys.iter().map(|(key, value)| Entry::Key(key, *value)).collect(), Effect::Deny(names) => names.iter().map(|name| Entry::Deny(name)).collect(), + Effect::Env(vars) => vars.iter().map(|(name, value)| Entry::Env(name, value)).collect(), } } -fn present(settings: &Map, entry: Entry) -> bool { +fn present(settings: &Map, entry: &Entry) -> bool { match entry { - Entry::Key(key, value) => settings.get(key) == Some(&Value::Bool(value)), + Entry::Key(key, value) => settings.get(*key) == Some(&Value::Bool(*value)), Entry::Deny(name) => { let list = settings.get("permissions").and_then(|p| p.get("deny")).and_then(Value::as_array); list.is_some_and(|list| list.iter().any(|v| v.as_str() == Some(name))) } + Entry::Env(name, value) => settings.get("env").and_then(|e| e.get(*name)).and_then(Value::as_str) == Some(*value), + Entry::Skill(name) => settings.get("skillOverrides").and_then(|o| o.get(name)).and_then(Value::as_str) == Some("off"), } } -fn add(settings: &mut Map, entry: Entry) { +/// Add `entry`. A value the user set differently for the same env variable or skill stays; `apply` notices that the +/// entry is not present afterwards and does not claim it. +fn add(settings: &mut Map, entry: &Entry) { match entry { Entry::Key(key, value) => { - settings.insert(key.into(), Value::Bool(value)); + settings.insert((*key).into(), Value::Bool(*value)); } Entry::Deny(name) => { let permissions = settings.entry("permissions").or_insert_with(|| json!({})); if let Some(permissions) = permissions.as_object_mut() && let Some(list) = permissions.entry("deny").or_insert_with(|| json!([])).as_array_mut() { - list.push(Value::String(name.into())); + list.push(Value::String((*name).into())); + } + } + Entry::Env(name, value) => { + let env = settings.entry("env").or_insert_with(|| json!({})); + if let Some(env) = env.as_object_mut() { + env.entry(*name).or_insert_with(|| Value::String((*value).into())); + } + } + Entry::Skill(name) => { + let overrides = settings.entry("skillOverrides").or_insert_with(|| json!({})); + if let Some(overrides) = overrides.as_object_mut() { + overrides.entry(name.clone()).or_insert_with(|| Value::String("off".into())); } } } } -fn remove(settings: &mut Map, entry: Entry) { +fn remove(settings: &mut Map, entry: &Entry) { match entry { Entry::Key(key, value) => { - if settings.get(key) == Some(&Value::Bool(value)) { - settings.remove(key); + if settings.get(*key) == Some(&Value::Bool(*value)) { + settings.remove(*key); } } Entry::Deny(name) => { let Some(permissions) = settings.get_mut("permissions").and_then(Value::as_object_mut) else { return }; if let Some(list) = permissions.get_mut("deny").and_then(Value::as_array_mut) { - list.retain(|v| v.as_str() != Some(name)); + list.retain(|v| v.as_str() != Some(*name)); if list.is_empty() { permissions.remove("deny"); } @@ -183,24 +284,84 @@ fn remove(settings: &mut Map, entry: Entry) { settings.remove("permissions"); } } + Entry::Env(name, value) => { + let Some(env) = settings.get_mut("env").and_then(Value::as_object_mut) else { return }; + if env.get(*name).and_then(Value::as_str) == Some(*value) { + env.remove(*name); + } + if env.is_empty() { + settings.remove("env"); + } + } + Entry::Skill(name) => { + let Some(overrides) = settings.get_mut("skillOverrides").and_then(Value::as_object_mut) else { return }; + if overrides.get(name).and_then(Value::as_str) == Some("off") { + overrides.remove(name); + } + if overrides.is_empty() { + settings.remove("skillOverrides"); + } + } + } +} + +/// The skills the user turned off on the Claude Code tools page. Empty leaves Claude Code's own behavior. +/// +/// There are no output caps (`BASH_MAX_OUTPUT_LENGTH`, `CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS`): in measured runs on +/// Claude Code 2.1.319, even a 10,000-character Bash cap cut Claude's normal batched reads, so it re-read them in +/// smaller calls and used twice the tokens. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Limits { + /// Skills Claude no longer sees (`skillOverrides` set to `off`); the user can still type them. + #[serde(default)] + pub skills_off: Vec, +} + +impl Limits { + /// The page's skills field: names separated by commas or spaces. + pub fn parse(skills: &str) -> Result { + let mut skills_off: Vec = vec![]; + for name in skills.split([',', ' ', '\n']).map(str::trim).filter(|n| !n.is_empty()) { + let valid = name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | ':' | '.')); + if !valid { + return Err(format!("Skills: “{name}” is not a skill name (letters, digits, - _ : .).")); + } + if !skills_off.iter().any(|s| s == name) { + skills_off.push(name.to_string()); + } + } + Ok(Limits { skills_off }) + } + + /// The skills field as text, for the page. + pub fn text(&self) -> String { + self.skills_off.join(", ") + } + + fn entries(&self) -> Vec { + self.skills_off.iter().map(|name| Entry::Skill(name.clone())).collect() } } -/// Put the trimmed items into `settings` and take out the ones Claudiu added earlier (`applied`) that are no longer -/// trimmed. A line the user had before Claudiu (a tool they denied themselves) is never recorded, so turning the trim -/// off leaves it. Returns what Claudiu now owns, to pass back next time. -pub fn apply(settings: &mut Map, trimmed: &[Trim], applied: &[String]) -> Vec { - let wanted: Vec = normalized(trimmed).into_iter().flat_map(entries).collect(); - let known: Vec = Trim::ALL.into_iter().flat_map(entries).collect(); - for entry in known.iter().filter(|e| applied.contains(&e.id()) && !wanted.contains(e)) { - remove(settings, *entry); +/// Put the trimmed items and limits into `settings` and take out the ones Claudiu added earlier (`applied`) that are +/// no longer wanted. A line the user had before Claudiu (a tool they denied themselves, a skill they set) is never +/// recorded, so turning the trim off leaves it. Returns what Claudiu now owns, to pass back next time. +pub fn apply(settings: &mut Map, trimmed: &[Trim], limits: &Limits, applied: &[String]) -> Vec { + let wanted: Vec = normalized(trimmed).into_iter().flat_map(entries).chain(limits.entries()).collect(); + let wanted_ids: Vec = wanted.iter().map(Entry::id).collect(); + for id in applied.iter().filter(|id| !wanted_ids.contains(id)) { + if let Some(entry) = Entry::from_id(id) { + remove(settings, &entry); + } } let mut owned = vec![]; for entry in wanted { let was_ours = applied.contains(&entry.id()); - if !present(settings, entry) { - add(settings, entry); - owned.push(entry.id()); + if !present(settings, &entry) { + add(settings, &entry); + if present(settings, &entry) { + owned.push(entry.id()); + } } else if was_ours { owned.push(entry.id()); } @@ -210,7 +371,7 @@ pub fn apply(settings: &mut Map, trimmed: &[Trim], applied: &[Str /// `apply` to the `settings.json` at `path`, written only when something changed. A file that is not a JSON object is /// never overwritten. -pub fn write_global(path: &std::path::Path, trimmed: &[Trim], applied: &[String]) -> std::io::Result> { +pub fn write_global(path: &std::path::Path, trimmed: &[Trim], limits: &Limits, applied: &[String]) -> std::io::Result> { let text = match std::fs::read_to_string(path) { Ok(text) => text, Err(e) if e.kind() == std::io::ErrorKind::NotFound => "{}".into(), @@ -220,7 +381,7 @@ pub fn write_global(path: &std::path::Path, trimmed: &[Trim], applied: &[String] return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "settings.json is not a JSON object")); }; let before = settings.clone(); - let owned = apply(&mut settings, trimmed, applied); + let owned = apply(&mut settings, trimmed, limits, applied); if settings != before { crate::datadir::write_atomic(path, &serde_json::to_string_pretty(&settings).map_err(std::io::Error::other)?)?; } @@ -244,7 +405,7 @@ mod tests { #[test] fn a_flag_and_a_tool_group_give_the_flag_and_exactly_their_denies() { let mut s = object(json!({ "model": "sonnet" })); - let owned = apply(&mut s, &[PlanMode, Workflows], &[]); + let owned = apply(&mut s, &[PlanMode, Workflows], &Limits::default(), &[]); assert_eq!(Value::Object(s), json!({ "model": "sonnet", "disableWorkflows": true, "permissions": { "deny": ["EnterPlanMode", "ExitPlanMode"] } })); assert_eq!(owned, ["disableWorkflows", "deny:EnterPlanMode", "deny:ExitPlanMode"]); } @@ -252,7 +413,7 @@ mod tests { #[test] fn artifacts_are_turned_off_with_the_current_key_and_the_deprecated_one() { let mut s = Map::new(); - apply(&mut s, &[Artifacts], &[]); + apply(&mut s, &[Artifacts], &Limits::default(), &[]); assert_eq!(Value::Object(s), json!({ "enableArtifact": false, "disableArtifact": true })); } @@ -260,9 +421,9 @@ mod tests { fn turning_a_trim_off_takes_out_only_what_claudiu_added() { let mut s = object(json!({ "permissions": { "deny": ["NotebookEdit"], "defaultMode": "auto" } })); // The user already denied NotebookEdit; Claudiu adds the other two. - let owned = apply(&mut s, &[NotebookEdit, ScheduledTasks, Workflows], &[]); + let owned = apply(&mut s, &[NotebookEdit, ScheduledTasks, Workflows], &Limits::default(), &[]); assert_eq!(owned, ["disableWorkflows", "deny:CronCreate", "deny:CronDelete", "deny:CronList"], "the user's own deny is not recorded"); - let owned = apply(&mut s, &[], &owned); + let owned = apply(&mut s, &[], &Limits::default(), &owned); assert!(owned.is_empty()); assert_eq!(Value::Object(s), json!({ "permissions": { "deny": ["NotebookEdit"], "defaultMode": "auto" } })); } @@ -270,18 +431,18 @@ mod tests { #[test] fn an_empty_deny_list_and_permissions_object_are_cleaned_up() { let mut s = Map::new(); - let owned = apply(&mut s, &[SendMessage], &[]); + let owned = apply(&mut s, &[SendMessage], &Limits::default(), &[]); assert!(s.contains_key("permissions")); - apply(&mut s, &[], &owned); + apply(&mut s, &[], &Limits::default(), &owned); assert!(s.is_empty()); } #[test] fn trimming_again_changes_nothing_and_keeps_ownership() { let mut s = Map::new(); - let owned = apply(&mut s, &[BundledSkills], &[]); + let owned = apply(&mut s, &[BundledSkills], &Limits::default(), &[]); let before = s.clone(); - assert_eq!(apply(&mut s, &[BundledSkills], &owned), owned); + assert_eq!(apply(&mut s, &[BundledSkills], &Limits::default(), &owned), owned); assert_eq!(s, before); } @@ -290,12 +451,12 @@ mod tests { let tmp = tempfile::tempdir().unwrap(); let path = tmp.path().join("settings.json"); std::fs::write(&path, "{\n \"zeta\": 1,\n \"alpha\": 2\n}").unwrap(); - let owned = write_global(&path, &[Workflows], &[]).unwrap(); + let owned = write_global(&path, &[Workflows], &Limits::default(), &[]).unwrap(); let text = std::fs::read_to_string(&path).unwrap(); assert!(text.find("zeta").unwrap() < text.find("alpha").unwrap(), "keys keep their order: {text}"); assert!(text.contains("disableWorkflows")); let stamp = std::fs::metadata(&path).unwrap().modified().unwrap(); - write_global(&path, &[Workflows], &owned).unwrap(); + write_global(&path, &[Workflows], &Limits::default(), &owned).unwrap(); assert_eq!(std::fs::metadata(&path).unwrap().modified().unwrap(), stamp, "nothing to change, nothing written"); } @@ -304,10 +465,101 @@ mod tests { let tmp = tempfile::tempdir().unwrap(); let path = tmp.path().join("settings.json"); std::fs::write(&path, "{ not json").unwrap(); - assert!(write_global(&path, &[Workflows], &[]).is_err()); + assert!(write_global(&path, &[Workflows], &Limits::default(), &[]).is_err()); assert_eq!(std::fs::read_to_string(&path).unwrap(), "{ not json"); } + #[test] + fn env_trims_go_in_the_env_block_beside_the_users_own_variables() { + let mut s = object(json!({ "env": { "FOO": "1" } })); + let owned = apply(&mut s, &[AdvisorTool, BackgroundTasks], &Limits::default(), &[]); + assert_eq!( + Value::Object(s.clone()), + json!({ "env": { "FOO": "1", "CLAUDE_CODE_DISABLE_ADVISOR_TOOL": "1", "CLAUDE_CODE_DISABLE_BACKGROUND_TASKS": "1" } }) + ); + apply(&mut s, &[], &Limits::default(), &owned); + assert_eq!(Value::Object(s), json!({ "env": { "FOO": "1" } })); + } + + #[test] + fn an_env_block_that_claudiu_created_is_removed_when_it_ends_up_empty() { + let mut s = Map::new(); + let owned = apply(&mut s, &[ExplorePlanAgents], &Limits::default(), &[]); + apply(&mut s, &[], &Limits::default(), &owned); + assert!(s.is_empty()); + } + + #[test] + fn git_instructions_are_turned_off_with_a_false_value_that_is_removed_again() { + let mut s = object(json!({ "model": "sonnet" })); + let owned = apply(&mut s, &[GitInstructions], &Limits::default(), &[]); + assert_eq!(Value::Object(s.clone()), json!({ "model": "sonnet", "includeGitInstructions": false })); + apply(&mut s, &[], &Limits::default(), &owned); + assert_eq!(Value::Object(s), json!({ "model": "sonnet" })); + } + + fn skills(names: &[&str]) -> Limits { + Limits { skills_off: names.iter().map(|s| s.to_string()).collect() } + } + + #[test] + fn skills_turned_off_go_where_claude_code_reads_them() { + let mut s = object(json!({ "skillOverrides": { "loop": "user-invocable-only" } })); + apply(&mut s, &[], &skills(&["dataviz", "m4:do"]), &[]); + assert_eq!(Value::Object(s), json!({ "skillOverrides": { "loop": "user-invocable-only", "dataviz": "off", "m4:do": "off" } })); + } + + #[test] + fn a_skill_the_user_set_differently_is_kept_and_never_removed() { + let mut s = object(json!({ "skillOverrides": { "dataviz": "user-invocable-only" } })); + let owned = apply(&mut s, &[], &skills(&["dataviz"]), &[]); + assert!(owned.is_empty(), "nothing was added, so nothing is claimed"); + apply(&mut s, &[], &Limits::default(), &owned); + assert_eq!(Value::Object(s), json!({ "skillOverrides": { "dataviz": "user-invocable-only" } })); + } + + #[test] + fn turning_a_skill_back_on_removes_the_override_and_an_empty_block() { + let mut s = Map::new(); + let owned = apply(&mut s, &[], &skills(&["dataviz"]), &[]); + apply(&mut s, &[], &skills(&[]), &owned); + assert!(s.is_empty()); + } + + #[test] + fn the_skills_field_is_parsed_with_empty_meaning_none() { + assert_eq!(Limits::parse(" ").unwrap(), Limits::default()); + assert_eq!(Limits::parse("dataviz, m4:do dataviz").unwrap(), skills(&["dataviz", "m4:do"])); + assert!(Limits::parse("a/b").unwrap_err().starts_with("Skills")); + } + + #[test] + fn the_field_shows_the_saved_skills_as_text() { + assert_eq!(skills(&["a", "b"]).text(), "a, b"); + } + + #[test] + fn each_switch_shows_the_saving_band_it_was_measured_in() { + let band = |saving: Saving| -> Vec { Trim::ALL.into_iter().filter(|t| t.saving() == saving).collect() }; + assert_eq!(band(Saving::High), [Artifacts, BundledSkills, ClaudeAiConnectors, AdvisorTool, ScheduleWakeup]); + assert_eq!(band(Saving::Medium), [ClaudeApiSkill, ExplorePlanAgents, BackgroundTasks, ReportFindings, GitInstructions]); + assert_eq!( + band(Saving::Low), + [Workflows, RemoteControl, PlanMode, AskUserQuestion, ScheduledTasks, RemoteTrigger, SendMessage, PushNotification, DesignSync, NotebookEdit] + ); + assert_eq!(Saving::Medium.label(), "medium savings"); + } + + #[test] + fn the_recommended_trims_are_added_to_what_the_user_already_turned_off() { + assert_eq!(with_recommended(&[]), [Artifacts, BundledSkills, ClaudeApiSkill, ClaudeAiConnectors, ScheduleWakeup, ReportFindings]); + assert_eq!( + with_recommended(&[PlanMode, Artifacts]), + [Artifacts, BundledSkills, ClaudeApiSkill, ClaudeAiConnectors, PlanMode, ScheduleWakeup, ReportFindings], + "the user's own trim stays, and nothing is listed twice" + ); + } + #[test] fn every_item_is_listed_once_in_the_page_groups() { let listed: Vec = Trim::GROUPS.iter().flat_map(|(_, items)| items.iter().copied()).collect(); diff --git a/src/main.rs b/src/main.rs index c7eb116..19bfd8b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -252,10 +252,10 @@ fn main() { }) .expect("open setup window"); cx.subscribe(&setup, move |_, ev: &app::SetupEvent, cx| { - let app::SetupEvent::Done(claude_path) = ev else { return }; + let app::SetupEvent::Done { claude_path, recommended_trims } = ev else { return }; // The main window opens before the setup window closes: closing the last window quits the app. let (window, workspace) = open_main_window(initial.clone(), cx); - workspace.update(cx, |ws, cx| ws.apply_setup(claude_path.clone(), cx)); + workspace.update(cx, |ws, cx| ws.apply_setup(claude_path.clone(), *recommended_trims, cx)); *main.borrow_mut() = Some((window, workspace)); setup_window.update(cx, |_, window, _| window.remove_window()).ok(); }) diff --git a/src/panels/workspace_view.rs b/src/panels/workspace_view.rs index d7e1854..e3d6c2a 100644 --- a/src/panels/workspace_view.rs +++ b/src/panels/workspace_view.rs @@ -822,7 +822,7 @@ impl Render for Workspace { /// The Settings dialog's body: the category list on the left and the chosen page on the right. fn settings_body(page: SettingsPage, modal: &Modal, worktrees: &crate::app::WorktreesPage, scroll: &crate::panels::glide::Smooth, window: &mut Window, cx: &mut Context) -> AnyElement { - let Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, list_focus } = modal else { + let Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, skills_field, costly, list_focus } = modal else { return div().into_any_element(); }; let (updates, chrome, scale) = (*updates, *chrome, *scale); @@ -884,6 +884,14 @@ fn settings_body(page: SettingsPage, modal: &Modal, worktrees: &crate::app::Work SettingsPage::ClaudeTools => { let plan_trimmed = trimmed.contains(&Trim::PlanMode); let mut list = div().flex().flex_col().gap(px(8.0)); + for found in costly { + list = list.child( + div() + .text_size(scaled(11.0)) + .text_color(hsla(theme::WARN)) + .child(format!("{} is set in {}. {}", found.name, found.source, found.effect)), + ); + } list = list.child(faint( "Applies to new sessions. Running sessions keep their tools. Resumed sessions get the new tools, and the old instructions stay until their next compaction. These switches edit Claude Code's own settings.json, for every account and for Claude Code outside Claudiu. Claudiu only turns things off; anything you turned off yourself stays off." .to_string(), @@ -891,7 +899,8 @@ fn settings_body(page: SettingsPage, modal: &Modal, worktrees: &crate::app::Work for (heading, items) in Trim::GROUPS { list = list.child(div().mt(px(4.0)).child(section_label(heading.to_string()))); for &item in items { - list = list.child(switch_row(("settings-trim", item as usize), item.label(), !trimmed.contains(&item), move |ws| { + let tag = Some(item.saving().label()); + list = list.child(switch_row(("settings-trim", item as usize), item.label(), tag, !trimmed.contains(&item), move |ws| { if let Some(Modal::Settings { trimmed, .. }) = ws.modal.as_mut() { flip(trimmed, item); } @@ -901,7 +910,9 @@ fn settings_body(page: SettingsPage, modal: &Modal, worktrees: &crate::app::Work if plan_trimmed { list = list.child(faint("With Plan mode off, Claude can't leave plan mode itself; press Shift+Tab.".to_string())); } - list + list.child(div().mt(px(4.0)).child(section_label("SKILLS".to_string()))) + .child(faint("Claude no longer sees these skills, but you can still type them. A setting you already have for a skill in Claude Code's settings.json wins.".to_string())) + .child(field("SKILLS TO TURN OFF, SEPARATED BY COMMAS", skills_field)) } SettingsPage::ClaudiuTools => { let mut list = div().flex().flex_col().gap(px(8.0)).child(faint( @@ -909,7 +920,7 @@ fn settings_body(page: SettingsPage, modal: &Modal, worktrees: &crate::app::Work .to_string(), )); for feature in Feature::ALL { - list = list.child(switch_row(("settings-claudiu", feature as usize), feature.label(), !claudiu_off.contains(&feature), move |ws| { + list = list.child(switch_row(("settings-claudiu", feature as usize), feature.label(), None, !claudiu_off.contains(&feature), move |ws| { if let Some(Modal::Settings { claudiu_off, .. }) = ws.modal.as_mut() { flip(claudiu_off, feature); } @@ -1044,7 +1055,7 @@ fn worktrees_page(page: &crate::app::WorktreesPage, cx: &mut Context) /// An On/Off row in the Settings modal; `field` picks the flag it flips. fn settings_toggle(id: &'static str, label: &'static str, on: bool, field: fn(&mut Modal) -> Option<&mut bool>, cx: &mut Context) -> impl IntoElement { - switch_row(id, label, on, move |ws| { + switch_row(id, label, None, on, move |ws| { if let Some(flag) = ws.modal.as_mut().and_then(field) { *flag = !*flag; } @@ -1095,10 +1106,11 @@ fn flip(items: &mut Vec, item: T) { } } -/// An On/Off row that runs `flip` on the workspace when clicked. +/// An On/Off row that runs `flip` on the workspace when clicked, with an optional faint `tag` after the label. fn switch_row( id: impl Into, label: &'static str, + tag: Option<&'static str>, on: bool, flip: impl Fn(&mut Workspace) + 'static, cx: &mut Context, @@ -1116,7 +1128,9 @@ fn switch_row( .border_color(hsla(0x242424)) .text_size(crate::panels::scale::px(13.0)) .cursor_pointer() - .child(label) + .child(div().flex().items_center().gap(px(8.0)).child(label).children(tag.map(|tag| { + div().text_size(crate::panels::scale::px(11.0)).text_color(hsla(theme::TEXT_FAINT)).child(tag) + }))) .child(div().text_color(hsla(if on { theme::ACCENT } else { theme::TEXT_FAINT })).child(if on { "On" } else { "Off" })) .on_click(cx.listener(move |ws, _: &ClickEvent, _w, cx| { flip(ws); diff --git a/src/store.rs b/src/store.rs index 6f5819d..fd61bee 100644 --- a/src/store.rs +++ b/src/store.rs @@ -285,6 +285,9 @@ pub struct Settings { /// The lines Claudiu added to Claude Code's `settings.json` for those trims, so turning one off removes only them. #[serde(default)] pub applied_trims: Vec, + /// Output caps and turned-off skills for Claude Code (`claude/trim.rs`); empty leaves Claude Code's own behavior. + #[serde(default)] + pub limits: crate::claude::trim::Limits, } #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] diff --git a/web/src/pages/index.astro b/web/src/pages/index.astro index 20f36ef..be6a9c8 100644 --- a/web/src/pages/index.astro +++ b/web/src/pages/index.astro @@ -52,6 +52,7 @@ const calls = [ @@ -150,26 +151,63 @@ const calls = [ -
-
Claudiu · runningFig. 4 · under load
- -
-

Scrolling that keeps up.

-

Wheel and trackpad glide in the terminal, sidebars and editor, and the editor no longer overshoots its ends.

- -
- -
-

Quiet when nothing happens.

-

The list draws only the rows in view, an idle window doesn't redraw, and saves happen in the background. On Windows, claude runs at above-normal priority.

- -
+
+
Claudiu · token optimizationFig. 4 · one request, drawn to scale
+ +
+
+

−21,300 tokens. Every request.

+

+ Claude Code sends its tools and instructions again with every call. The nine switches that measured + highest cut a first request from 34.3k tokens to 13.0k. Over a 14-call task that works out to about + 300,000 tokens never sent, and the work came out just as correct. +

+ + + + + + +
Hidden tests30 of 30 passed, before and after
Tool calls13–14 before, 14 after
Measured onClaude Code 2.1.319, Sonnet 5.5, one change across 7 files
+
-
-

Settings, by category.

-

Defaults for new sessions, 15 switches for Claude Code's bundled tools, one for each Claudiu feature.

-
- Claudiu's settings dialog on the Claude Code tools page, listing switches for bundled skills, workflows, remote control, claude.ai connectors, artifacts and plan mode +
+ + A first request drawn to scale: 34.3k tokens with no trims, 13.0k with them; the 21,300 tokens cut are hatched, and the same cut repeats on each of 14 calls + + + + + + + + + + No trims + + + 34.3k tokens + + Savers off + + + 13.0k + + + + + + + + + −21,300 per request + + Each of 14 calls + + + ≈ 300,000 never sent + +

Fig. 4Hatched: what the trims remove from every request.

diff --git a/web/src/styles/global.css b/web/src/styles/global.css index 79bc783..e6b7a61 100644 --- a/web/src/styles/global.css +++ b/web/src/styles/global.css @@ -440,10 +440,6 @@ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); grid-template-areas: "tb tb" "e1 e1" "l1 a1"; } - .win.run { - grid-template-columns: minmax(0, 1fr) minmax(0, 1.5fr); - grid-template-areas: "tb tb" "r1 r3" "r2 r3"; - } .win.ed .l1 figure { margin-top: 0; } @@ -451,12 +447,83 @@ grid-template-columns: minmax(0, 1fr); grid-template-areas: "tb" "sp"; } + .win.tok { + grid-template-columns: minmax(0, 1fr); + grid-template-areas: "tb" "tk"; + } + .win .tk { + grid-area: tk; + display: grid; + grid-template-columns: minmax(0, 4fr) minmax(0, 7fr); + column-gap: 56px; + align-items: center; + padding-block: 40px; + } + .tk-copy { + display: flex; + flex-direction: column; + gap: 22px; + } + .win .tk h2 { + font-size: clamp(40px, 5.2vw, 76px); + line-height: 0.95; + letter-spacing: -0.04em; + } + .tk-num { + display: block; + color: var(--color-orange); + } + .tk-fig svg { + display: block; + width: 100%; + height: auto; + } + .tk-fig .t-lbl { + font: 600 20px var(--font-sans); + letter-spacing: 0.08em; + text-transform: uppercase; + fill: var(--color-dim); + } + .tk-fig .t-in { + font: 700 26px var(--font-sans); + fill: var(--color-ink); + } + .tk-fig .t-in.dark { + fill: var(--color-paper); + } + @media (max-width: 640px) { + .tk-fig .t-lbl { + font-size: 36px; + } + .tk-fig .t-in { + font-size: 38px; + } + .tk-fig .t-cut { + font-size: 46px; + } + } + .tk-fig .t-cut { + font: 800 34px var(--font-sans); + letter-spacing: -0.02em; + fill: var(--color-orange); + } + @media (prefers-reduced-motion: no-preference) { + @supports (animation-timeline: view()) { + .tk-fig .cut { + animation: tk-cut linear both; + animation-timeline: view(); + animation-range: entry 20% cover 45%; + } + @keyframes tk-cut { + from { + clip-path: inset(0 100% 0 0); + } + } + } + } .win .e1 { grid-area: e1; } .win .l1 { grid-area: l1; } .win .a1 { grid-area: a1; } - .win .r1 { grid-area: r1; } - .win .r2 { grid-area: r2; } - .win .r3 { grid-area: r3; } .win .sp { grid-area: sp; display: grid; @@ -483,9 +550,10 @@ grid-template-columns: minmax(0, 1fr); grid-template-areas: "tb" "e1" "l1" "a1"; } - .win.run { + .win .tk { grid-template-columns: minmax(0, 1fr); - grid-template-areas: "tb" "r1" "r2" "r3"; + row-gap: 36px; + padding-block: 28px; } .win .sp { grid-template-columns: minmax(0, 1fr);