Initial public release

Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
Evan Whittaker
2026-10-17 12:08:30 -05:00
commit 09a7de2520
1730 changed files with 412952 additions and 0 deletions

View File

@@ -0,0 +1,320 @@
//! Behavior settings — the agent, the gate, plan mode, the reviewer, compaction and tools.
use serde::{Deserialize, Serialize};
/// Tool enablement preferences.
///
/// A deny-list: every built-in tool is enabled unless named here, so a new release's tools stay
/// on by default. The truly essential tools (`read`/`write`/`edit`/`bash`) are never disabled even
/// if listed — the agent can't function without them. Written by `luxe init`; example:
/// `{ "disabled": ["screenshot", "web_search"] }`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct ToolsConfig {
/// Names of built-in tools to leave unregistered.
pub disabled: Vec<String>,
/// Whether an edited file goes through its formatter. On when absent.
pub format_on_save: Option<bool>,
/// Whether `web_fetch` clones a GitHub repository URL into `.luxe/gh-cache/` rather than
/// reading it as a page. On when absent.
pub clone_repositories: Option<bool>,
}
/// Built-in tools that can never be disabled — the agent's irreducible core.
pub const ESSENTIAL_TOOLS: [&str; 4] = ["read", "write", "edit", "bash"];
impl ToolsConfig {
/// Whether `web_fetch` clones a GitHub repository URL (default: yes).
pub fn clone_repositories(&self) -> bool {
self.clone_repositories.unwrap_or(true)
}
/// Whether a tool is enabled (not on the deny-list, or essential regardless).
pub fn is_enabled(&self, name: &str) -> bool {
ESSENTIAL_TOOLS.contains(&name) || !self.disabled.iter().any(|d| d == name)
}
/// The deny-list for one run: config, plus `disable`, minus `enable`.
///
/// Config is the standing preference and the flags are this session's exception, which is why
/// `enable` can lift a config entry — someone who disabled `screenshot` on principle still
/// needs it on the afternoon they are doing UI work, and editing a file to get through the
/// afternoon is how a standing preference stops being one.
///
/// Essential tools are not filtered here: the caller reports each refusal by name, and a
/// silent drop is how a user comes to believe `--no-tool read` worked.
pub fn effective_disabled(&self, disable: &[String], enable: &[String]) -> Vec<String> {
let mut out: Vec<String> = self.disabled.clone();
for name in disable {
if !out.iter().any(|existing| existing == name) {
out.push(name.clone());
}
}
out.retain(|name| !enable.iter().any(|lifted| lifted == name));
out
}
}
/// How a session behaves when it starts to fill the model's context window.
///
/// Four questions a real user asks — stop doing this automatically, do it sooner, keep more of the
/// recent conversation, and use a cheaper model to write the summary — plus the one switch that
/// turns off eliding stale tool output. The tuning constants behind those stay internal: they are
/// answers to questions nobody has, and every one of them is a way to make caching worse.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
#[serde(default)]
pub struct CompactionConfig {
/// Summarize automatically once the window fills. `None` = on. `false` leaves it to `/compact`,
/// and a session that overflows will fail its next request rather than shorten itself.
pub auto: Option<bool>,
/// Share of the usable window (0.0–1.0) at which that happens. `None` = 0.9.
pub at: Option<f64>,
/// Tokens of the newest conversation kept verbatim rather than summarized. `None` = 20000.
/// Capped at half the usable window, so a figure larger than the model cannot stall compaction
/// on the sessions that need it most.
pub keep_recent: Option<u32>,
/// Tokens held back for the reply when deciding whether the window is full. `None` = 20000.
pub reserve: Option<u32>,
/// Elide stale tool output as a last step before summarizing. `None` = on. Off goes straight to
/// a summary, which keeps less detail but never rewrites history mid-session.
pub prune: Option<bool>,
/// Model that writes the summary, as `provider/id`. `None` = whichever model is active. A
/// smaller one here is usually the single best value in this file: summarizing is the most
/// expensive call a long session makes and the least demanding.
pub summarizer: Option<String>,
}
/// How far ahead of the summarize threshold eliding starts.
///
/// Not a knob, because the two are not independent: eliding is the last cheap thing tried *before*
/// summarizing, so a pair a user could set in either order is a pair they could set backwards — at
/// which point eliding never fires and the setting that switched it off is invisible.
const PRUNE_LEAD: f64 = 0.1;
impl CompactionConfig {
/// The engine's settings, with every unset field left at its default.
///
/// `summarizer` is parsed as `provider/id`; anything else is ignored rather than fatal, on the
/// same rule as the rest of this file — one typo must not cost someone their session. It
/// carries only the id: the front-end fills in its window and price from the model catalog.
pub fn settings(&self) -> crate::compaction::CompactionSettings {
let defaults = crate::compaction::CompactionSettings::default();
let compact_at = self.at.filter(|at| *at > 0.0).unwrap_or(defaults.compact_at_fraction);
crate::compaction::CompactionSettings {
enabled: self.auto.unwrap_or(defaults.enabled),
reserve_tokens: self.reserve.unwrap_or(defaults.reserve_tokens),
keep_recent_tokens: self.keep_recent.unwrap_or(defaults.keep_recent_tokens),
compact_at_fraction: compact_at,
// Off is expressed as a threshold nothing reaches, so the one gate in `prune_tool_outputs`
// stays the only place that decides.
prune_at_fraction: match self.prune {
Some(false) => f64::INFINITY,
_ => (compact_at - PRUNE_LEAD).max(0.0),
},
prune_protect_tokens: defaults.prune_protect_tokens,
prune_min_tokens: defaults.prune_min_tokens,
summarizer: self
.summarizer
.as_deref()
.and_then(parse_model_ref)
.map(|r#ref| crate::provider::ModelInfo { r#ref, ..Default::default() }),
}
}
}
/// `provider/id`, or `None` for anything that isn't.
fn parse_model_ref(raw: &str) -> Option<crate::provider::ModelRef> {
let (provider, id) = raw.trim().split_once('/')?;
let (provider, id) = (provider.trim(), id.trim());
(!provider.is_empty() && !id.is_empty()).then(|| crate::provider::ModelRef::new(provider, id))
}
/// What a claimed phase has to clear.
///
/// The loop's gate has two stages: these commands, then a reviewer. Both are opt-in, and with
/// neither configured a claim is taken at its word — which is what a loop that has not been told how
/// to check itself deserves.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct GateConfig {
/// Commands that must succeed, each as `["program", "arg", …]`.
///
/// No shell is interposed — same rule as `hooks.json`, and for the same reason: a string that
/// gets word-split is a string that breaks on the first path with a space in it. Use
/// `["sh", "-c", "…"]` when you want shell features, and remember that spells a platform.
pub commands: Vec<Vec<String>>,
/// How long any one command may run, in seconds. Defaults to ten minutes.
pub timeout_secs: Option<u64>,
/// Whether a reviewer reads each claimed phase after the commands pass.
///
/// The reviewer runs in a fresh context, on `reviewer.model` when one is named and on the run's
/// own model otherwise. Unset means on exactly when `reviewer.model` is named, which is what
/// naming a reviewer has always meant.
pub review: Option<bool>,
}
impl GateConfig {
/// Whether a claimed phase is read by a reviewer, given the reviewer settings.
pub fn reviews(&self, reviewer: &ReviewerConfig) -> bool {
self.review.unwrap_or_else(|| reviewer.model_ref().is_some())
}
/// The per-command deadline.
pub fn timeout(&self) -> std::time::Duration {
std::time::Duration::from_secs(self.timeout_secs.unwrap_or(600))
}
/// Commands with anything unusable dropped, and a reason logged for each.
///
/// An empty entry would spawn nothing and be reported as a failed command, which reads as "the
/// gate refused" rather than "your config has a stray comma".
pub fn commands(&self) -> Vec<Vec<String>> {
self.commands
.iter()
.filter(|command| {
if command.iter().any(|part| !part.trim().is_empty()) {
true
} else {
tracing::warn!("ignoring an empty acceptance command");
false
}
})
.cloned()
.collect()
}
}
/// Agent-loop preferences.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct AgentConfig {
/// Cap on tool-call round-trips within one turn. Omitted (the default) means no cap: a turn
/// runs until the model stops calling tools or you cancel it. Set a number to bound cost;
/// the final round-trip then runs without tools so the model wraps up in prose.
pub max_tool_iterations: Option<usize>,
/// Whether an in-session model / thinking choice becomes the next launch's default.
///
/// On unless set to `false`. Re-picking a model you already chose is a tax on the person who
/// already decided; anyone who wants a fixed default sets `default_model` and turns this off.
pub remember_model: Option<bool>,
/// What an `ask` resolves to where nobody can answer it.
///
/// Headless, `luxe loop` and a review agent have no human to prompt, so every `ask` rule — the
/// built-in guardrails on out-of-project work and a force push, a hook's escalation, anything
/// `permissions.json` marks — collapses to one answer. `allow` unless set, because that is
/// what an unattended run has always done and nobody should find their automation stopped by
/// an upgrade.
///
/// A project may set `deny` and may not set `allow`: tighten-only, the same rule as its
/// `permissions.json`, because a repository you cloned does not get to widen what its own code
/// may do. Interactive runs ignore it — there the answer is the reader's.
pub on_ask: Option<OnAsk>,
/// When the prompt cache is kept warm through a long wait; `streaming` unless set.
///
/// A project may turn it down and may not turn it up, since warming spends the user's money.
pub cache_warming: Option<crate::cache_warming::CacheWarming>,
/// The mode a session starts in: `build` unless set. `--plan` overrides it for one run.
pub default_mode: Option<String>,
}
/// What an `ask` resolves to in a run with nobody to ask (`agent.on_ask`, `--on-ask`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OnAsk {
/// Let it through, which is what an unattended run has always done (default).
#[default]
Allow,
/// Refuse it, and tell the model the run is unattended so it takes another route.
Deny,
/// Unknown values fall back to `allow`.
#[serde(other)]
Unknown,
}
impl OnAsk {
/// The spelling this parses from, for a flag and for a message that quotes one.
pub fn parse(raw: &str) -> Option<Self> {
match raw.trim().to_ascii_lowercase().as_str() {
"allow" => Some(Self::Allow),
"deny" => Some(Self::Deny),
_ => None,
}
}
/// How an unattended run resolves an `ask` under this setting.
pub fn resolution(self) -> crate::permission::AskResolution {
match self {
Self::Deny => crate::permission::AskResolution::AutoDeny,
Self::Allow | Self::Unknown => crate::permission::AskResolution::AutoAllow,
}
}
}
/// Plan mode: which files it may write, and what it runs on.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(default)]
pub struct PlanConfig {
/// Project-relative files, or globs, plan mode may write. `PLAN.md` when empty.
///
/// The first plain file is where the agent is told to put the plan, so a list that starts with
/// a glob still names a file to write. A list of globs alone asks for a file matching the first.
pub files: Vec<String>,
/// Model plan mode runs on, as `provider/id`. `None` keeps the session's.
///
/// Each model keeps its own prompt cache, so switching to plan mode on another model reads the
/// whole conversation again at full price. Worth it for a long plan on a stronger model, not
/// for a quick question.
pub model: Option<String>,
/// Reasoning level in plan mode, clamped to what its model supports.
pub thinking: Option<crate::provider::ThinkingLevel>,
}
impl PlanConfig {
/// `model` split into its parts, ignoring a spelling that is not `provider/id`.
pub fn model_ref(&self) -> Option<(&str, &str)> {
split_model(self.model.as_deref()?)
}
}
/// The reviewer: a second opinion in a fresh context, for `/review` and the loop's gate.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(default)]
pub struct ReviewerConfig {
/// Model the reviewer runs on, as `provider/id`. `None` uses the session's own model.
///
/// The fresh context is most of a review's value, so the session's model is a real reviewer.
/// A different vendor's adds a second set of blind spots, which is worth it when you have one.
pub model: Option<String>,
/// Reasoning level for a review, clamped to what its model supports.
pub thinking: Option<crate::provider::ThinkingLevel>,
/// Tools a review may call, all of them read-only. Absent or empty means the built-in list.
pub tools: Option<Vec<String>>,
}
impl ReviewerConfig {
/// `model` split into its parts, ignoring a spelling that is not `provider/id`.
pub fn model_ref(&self) -> Option<(&str, &str)> {
split_model(self.model.as_deref()?)
}
}
/// `provider/id` split at its first slash, so an id that contains one keeps it.
///
/// A bare `gpt-5.6` has no provider, and guessing one would silently send the call to whichever
/// provider happened to be configured. `None` lets the caller say so instead.
fn split_model(raw: &str) -> Option<(&str, &str)> {
let (provider, id) = raw.trim().split_once('/')?;
(!provider.is_empty() && !id.is_empty()).then_some((provider, id))
}
impl AgentConfig {
/// Whether the last in-session model / thinking choice is remembered (default: yes).
pub fn remember_model(&self) -> bool {
self.remember_model.unwrap_or(true)
}
/// When the prompt cache is kept warm (default: while a turn runs).
pub fn cache_warming(&self) -> crate::cache_warming::CacheWarming {
self.cache_warming.unwrap_or_default().resolved()
}
}

View File

@@ -0,0 +1,529 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Luxe config",
"type": "object",
"properties": {
"$schema": {
"type": "string",
"description": "Path or URL of this configuration schema."
},
"theme": {
"type": "string",
"description": "Theme name: a built-in (luxe, catppuccin, nord, tokyo-night, and more — /theme lists them all), the name of a file in themes/, or omarchy to follow the Omarchy desktop's theme. When omitted, Luxe follows Omarchy when it is running there, and uses luxe otherwise."
},
"colors": {
"type": "object",
"description": "Per-token color overrides layered over the active theme. Keys are theme tokens (e.g. diffAddBg, diffDelBg, accent, selectedBg); values are #rrggbb, an ANSI index 0-255, or an empty string for the terminal default. Unknown or unparseable entries are ignored.",
"additionalProperties": { "type": "string" }
},
"show_key_hints": {
"type": "boolean",
"default": true,
"description": "Show the key hint beside messages waiting for a turn, such as alt+up to edit them. Default: true."
},
"mouse": {
"type": "boolean",
"default": true,
"description": "Capture the mouse for wheel scroll and clicks (default true). Capturing suppresses the terminal's native click-drag text selection while active — hold Shift to bypass it, or toggle at runtime with /mouse. Set false to start with capture off."
},
"dashboard": {
"oneOf": [
{ "type": "boolean" },
{
"type": "object",
"properties": {
"style": {
"type": "string",
"enum": ["launcher", "minimal"],
"default": "launcher",
"description": "launcher (default) lists your sessions and commands under the prompt; minimal shows the prompt alone, and the list waits for the down arrow."
}
},
"additionalProperties": false
}
],
"default": true,
"description": "The start screen: a prompt that is also a search over your sessions and commands. true (default) shows it, false opens straight into a conversation, and { \"style\": \"minimal\" } shows the prompt alone."
},
"banner_animation": {
"type": "boolean",
"default": true,
"description": "Animate the dashboard wordmark: a shine crosses the letters every few seconds. Default: true. Set to false for a still logotype (it costs no frames either way while resting)."
},
"glyphs": {
"type": "string",
"enum": ["auto", "nerd", "nerd_wide", "unicode", "ascii"],
"default": "auto",
"description": "How much glyph fidelity the TUI asks for. Icons are decoration \u2014 the words beside them carry the meaning \u2014 so every setting is fully usable. nerd draws Material Design icons from a Nerd Font (the look Luxe ships with); nerd_wide draws the same icons with a second cell of clearance, for a Nerd Font's non-Mono cut, whose icons carry two cells of ink behind a one-cell advance and so paint over the space after them; unicode uses Geometric Shapes and Arrows only, so no patched font is needed; ascii reduces to plain punctuation for a minimal or non-UTF-8 terminal. auto (default) picks nerd where those glyphs can actually be drawn \u2014 kitty bundles its own symbol font, and elsewhere fontconfig is asked whether any installed font provides them \u2014 and unicode otherwise. auto never picks nerd_wide: both cuts of a face report the same advance, so there is nothing to measure."
},
"images": {
"type": "string",
"enum": ["auto", "pixels", "blocks", "off"],
"default": "auto",
"description": "How an inline image is drawn. pixels uses the kitty graphics protocol; blocks uses half-block cells, which are coarse but need no protocol; off prints a line naming the image and its size. auto (default) picks pixels where the terminal is known to draw them and blocks everywhere else."
},
"tools": {
"type": "object",
"description": "Which built-in tools the model is offered. A deny-list, because the useful question is which one to take away.",
"properties": {
"disabled": {
"type": "array",
"items": { "type": "string" },
"description": "Tools to leave unregistered, by name. read, write, edit and bash are the agent's irreducible core and stay registered whatever this says."
},
"format_on_save": {
"type": "boolean",
"description": "Run the formatter on each file the agent writes or edits. On by default. rustfmt and gofmt always apply; biome, ruff and taplo only where the project has their config."
},
"clone_repositories": {
"type": "boolean",
"description": "Let web_fetch clone a GitHub repository URL into the project's .luxe/gh-cache/ so the agent can search the real files. On by default. Off, the repository is read as a web page instead."
}
},
"additionalProperties": false
},
"notifications": {
"oneOf": [
{ "type": "boolean" },
{
"type": "array",
"items": { "type": "string", "enum": ["turn", "permission", "question", "review"] },
"uniqueItems": true
}
],
"default": false,
"description": "Send a desktop notification while the terminal is in the background: true for every moment below, or a list of them. turn: a turn finished or failed. permission: a tool call is waiting for your approval. question: the agent asked you something. review: a Guided Review finished writing its guide. It goes through the terminal as an escape sequence, so the terminal has to show them: Ghostty, iTerm2, kitty, WezTerm, Warp and foot do. Inside tmux it needs `set -g allow-passthrough on`; inside herdr, herdr shows its own instead."
},
"notification_method": {
"type": "string",
"enum": ["auto", "osc9", "osc777"],
"default": "auto",
"description": "Which escape sequence a notification is sent as. auto (default) picks OSC 9 for Ghostty, iTerm2, kitty, WezTerm and Warp, OSC 777 for foot, and sends nothing to a terminal it does not know. osc9 or osc777 sends that sequence regardless, for a terminal auto does not recognize."
},
"bell": {
"type": "boolean",
"default": false,
"description": "Ring the terminal bell when a turn finishes or fails, or a permission prompt or question waits on you. Off by default: terminals turn a bell into an attention request, and a window manager that honors one takes focus away from whatever you walked off to do."
},
"herdr": {
"type": "boolean",
"default": true,
"description": "When Luxe runs in a herdr pane, report whether it is working, idle or waiting on you, so herdr's sidebar, notifications and `herdr agent wait` follow it. On by default; nothing is sent outside herdr."
},
"diff": {
"type": "object",
"description": "How every surface draws a diff: the edit/write tool card, the preview beside the conversation, and Guided Review. One setting, because the three differ only in how much room they have.",
"properties": {
"layout": {
"type": "string",
"enum": ["auto", "unified", "split"],
"default": "auto",
"description": "One column or two. 'auto' (default) draws two wherever the surface can give each column 44 cells of code after its line-number gutter, and one below that — so the same rule lands differently on a tool card, the preview and a full-screen review, because each has different chrome around it. 'unified' always stacks one column. 'split' draws two wherever two can be laid out at all, including for an all-additions change that auto would leave unified. ctrl+b flips it for the session."
},
"word_wrap": {
"type": "boolean",
"default": false,
"description": "Soft-wrap long lines (with a continuation glyph) instead of scrolling them sideways. Only Guided Review has the choice — a tool card and the preview cannot scroll sideways, so they always wrap rather than putting content out of reach. Toggle at runtime with w; works in both layouts."
}
},
"additionalProperties": false
},
"review": {
"type": "object",
"description": "Guided Review preferences. How its diffs are drawn is under `diff`, with every other surface's.",
"properties": {
"context_files": {
"type": "array",
"items": { "type": "string" },
"default": [],
"description": "Extra project-relative planning files a review reads for context, on top of PLAN.md and AGENTS.md. Each must resolve inside the opened project."
},
"exclude": {
"type": "array",
"items": { "type": "string" },
"default": [],
"description": "Project-relative globs a review leaves out, e.g. [\"PROGRESS.md\", \"docs/design/**\"]. Luxe's own .luxe/ directory is always excluded and needs no entry. Supports *, ** and ?; a trailing / matches a directory and everything under it. Excluded files are counted and named in the Brief, never silently dropped."
}
},
"additionalProperties": false
},
"dock": {
"type": "object",
"description": "Context Dock (full-height sidebar) preferences.",
"properties": {
"mode": {
"type": "string",
"enum": ["auto", "shown", "hidden"],
"default": "auto",
"description": "Show the Context Dock automatically on wide terminals, always, or never."
},
"position": {
"type": "string",
"enum": ["left", "right"],
"default": "left",
"description": "Which side the full-height sidebar occupies."
}
},
"additionalProperties": false
},
"agent": {
"type": "object",
"description": "Agent-loop behavior.",
"properties": {
"max_tool_iterations": {
"type": "integer",
"minimum": 1,
"description": "Cap on tool-call round-trips within a single turn. Omit for no cap (the default): a turn runs until the model stops calling tools or you cancel it. When set, the final round-trip runs without tools so the model wraps up with a summary instead of being cut off. LUXE_MAX_TOOL_ITERATIONS overrides this (use 0/off/none to lift a configured cap for one run)."
},
"remember_model": {
"type": "boolean",
"default": true,
"description": "Remember the model and thinking level picked in a session and use them next launch. Precedence: --model/--thinking flag, then LUXE_MODEL/LUXE_PROVIDER, then what you last picked, then default_model in models.json — and nothing under that, because Luxe never picks a model for you. Set false to always start from the configured default."
},
"on_ask": {
"type": "string",
"enum": ["allow", "deny"],
"default": "allow",
"description": "What an `ask` resolves to in a run with nobody to ask — headless, `luxe loop`, and a review agent. Those runs cannot prompt, so every ask rule (the built-in guardrails on out-of-project work and a force push, a hook's escalation, anything permissions.json marks `ask`) collapses to one answer. allow is the default; deny refuses the call and tells the model the run is unattended, so it takes another route rather than retrying. --on-ask overrides this for one run. A project's config may set deny and may not set allow — tighten-only, the same rule as its permissions.json. Interactive runs ignore it: there the answer is yours."
},
"cache_warming": {
"type": "string",
"enum": ["off", "streaming", "idle"],
"default": "streaming",
"description": "When Luxe keeps a conversation's prompt cache alive through a long wait, by re-sending the last request with a one-token cap just before the cache entry expires (five minutes on Anthropic, unless supports_long_cache_retention asks for an hour). A refresh is a cache read of the prompt; the write it saves is usually ten times that. streaming (the default) does it while a turn is running — a slow tool, a permission prompt, a question — where the next request is certain. idle also does it for up to 30 minutes after a turn ends, where a reply is a guess, so a refresh is sent only on a conversation large enough to make the guess pay. off never does. Either way nothing is sent unless it is expected to save at least $0.05, never on a subscription plan, and its cost shows on /cost as cache warming. A project's config may turn this down and may not turn it up."
},
"default_mode": {
"type": "string",
"enum": ["build", "plan"],
"default": "build",
"description": "The mode a session starts in. build changes files and runs commands; plan reads, asks and writes only plan.files. --plan starts one session in plan mode, and shift+tab switches during a session."
}
},
"additionalProperties": false
},
"gate": {
"type": "object",
"description": "What a claimed phase has to clear in a continuous loop. Stage one is these acceptance commands; stage two is a reviewer in a fresh context (gate.review, configured under reviewer). Both are opt-in \u2014 with neither set, a claim is taken at its word. A project's commands replace the global list rather than appending to it.",
"properties": {
"commands": {
"type": "array",
"description": "Commands that must all succeed before a phase advances, each as [\"program\", \"arg\", \u2026]. No shell is interposed, so use [\"sh\", \"-c\", \"\u2026\"] for shell features \u2014 which names a platform.",
"items": {
"type": "array",
"items": { "type": "string" },
"minItems": 1
}
},
"timeout_secs": {
"type": "integer",
"minimum": 1,
"default": 600,
"description": "How long any one acceptance command may run before it is killed as a group."
},
"review": {
"type": "boolean",
"description": "Whether a reviewer reads each claimed phase once the commands pass. It runs in a fresh context, on reviewer.model when that is set and on the run's own model otherwise. Unset means on exactly when reviewer.model is set."
}
},
"additionalProperties": false
},
"plan": {
"type": "object",
"description": "Plan mode: reads, asks, and writes only the plan.",
"properties": {
"files": {
"type": "array",
"items": { "type": "string" },
"default": ["PLAN.md"],
"description": "Project-relative files or globs plan mode may write. The first plain file is where the plan goes, or a file matching the first glob when there is none. PLAN.md when empty."
},
"model": { "$ref": "#/definitions/model" },
"thinking": { "$ref": "#/definitions/thinking" }
},
"additionalProperties": false
},
"reviewer": {
"type": "object",
"description": "The reviewer /review and the loop's gate ask: a second opinion in a fresh context that changes nothing. Its model defaults to the session's.",
"properties": {
"model": { "$ref": "#/definitions/model" },
"thinking": { "$ref": "#/definitions/thinking" },
"tools": {
"type": "array",
"items": { "type": "string" },
"uniqueItems": true,
"description": "Tools a review may call. Absent or empty means the built-in read-only list. Whatever is named, a review changes nothing: its mode refuses every write."
}
},
"additionalProperties": false
},
"lsp": {
"type": "object",
"description": "Language-server behavior. Read from the global config only — a project does not get a say in whether its own binaries may run.",
"properties": {
"project_servers": {
"type": "string",
"enum": ["auto", "always", "never"],
"default": "auto",
"description": "Whether to run a program the project installed for itself — a language server in node_modules/.bin, or the formatter in its virtualenv — which is often the only copy that matches the project. auto uses it with a human at the keyboard and refuses when nobody is there (headless, the loop, the review agent) unless --trust-project says otherwise; always includes those; never uses only programs found on PATH and in the usual install directories. Format-on-save reads the same answer."
}
},
"additionalProperties": false
},
"worktree": {
"type": "object",
"description": "Whether sessions work in a checkout of their own.",
"properties": {
"always": {
"type": "boolean",
"default": false,
"description": "Give every new session its own git worktree under .luxe/worktrees/, on a branch of its own, as --worktree does: the agent's edits never land in your checkout, and abandoning the work is removing the worktree. Sessions, reviews and logs stay with the project. A resumed session re-enters the worktree it had."
}
},
"additionalProperties": false
},
"launchers": {
"type": "array",
"description": "Programs a key hands the terminal to — gh-dash, lazygit, anything that takes over a terminal and gives it back. Luxe keeps running underneath, a turn included, and redraws when the program exits; text the program writes to the file named by $LUXE_HANDOFF lands in the composer. Read from the global config only: a key that runs a program a repository named is arbitrary execution.",
"items": {
"type": "object",
"properties": {
"key": { "type": "string", "description": "The chord that starts it, like alt+l." },
"command": { "type": "string", "description": "The program, looked up on PATH." },
"args": { "type": "array", "items": { "type": "string" }, "description": "Its arguments." }
},
"required": ["key", "command"],
"additionalProperties": false
}
},
"mentions": {
"type": "array",
"description": "Programs the @ picker lists as sources of their own, each a tab after Files and GitHub: Jira issues, Asana tasks, anything a script can reach. The program prints one JSON object a line — {\"id\", \"label\", \"detail\", \"text\"} — a picked row inserts @[kind:id], and its text is what the model is sent. Read from the global config only: a source runs a program.",
"items": {
"type": "object",
"properties": {
"name": { "type": "string", "description": "The tab's name, like Jira." },
"kind": { "type": "string", "description": "The reference's kind, as in @[jira:PROJ-12]; the name in lowercase when unset. Not file, skill, github or mcp." },
"command": { "type": "string", "description": "The program, looked up on PATH." },
"args": { "type": "array", "items": { "type": "string" }, "description": "Its arguments." },
"icon": { "type": "string", "description": "A glyph drawn beside the tab's name, like a Nerd Font's md-jira (U+F0303). Drawn where the Nerd Font icons are; a tag otherwise, and when unset." }
},
"required": ["name", "command"],
"additionalProperties": false
}
},
"github": {
"type": "object",
"description": "How Luxe keeps up with GitHub: the checked-out branch's pull request, and what /github lists. The refresh interval is read from the global config only — how often Luxe calls out on a timer is not a decision a repository you cloned makes; a project may add its own /github sections.",
"properties": {
"refresh_secs": {
"type": "integer",
"minimum": 0,
"default": 60,
"description": "Seconds between background checks of the branch's pull request once nothing is in flight. While checks run, or for ten minutes after a push, it looks every 15 seconds, or at this interval if that is shorter; after two minutes out of focus, every five minutes. 0 turns background checks off; checks that follow something you did, like a push or /pr, still happen. Each check is one GraphQL query against the hourly budget your gh shares with other tools."
},
"sections": {
"type": "array",
"description": "The sections /github lists, each a GitHub search as the site's search box takes it; {repo} stands for the checkout's repository. Replaces the defaults: review requested, mine, assigned issues, every pull request and every issue, all in this repository.",
"items": {
"type": "object",
"properties": {
"name": { "type": "string", "description": "What the section's tab says." },
"query": { "type": "string", "description": "The GitHub search that fills it, e.g. is:open is:pr label:needs-review repo:{repo}." }
},
"required": ["name", "query"],
"additionalProperties": false
}
}
},
"additionalProperties": false
},
"update": {
"type": "object",
"description": "Whether Luxe checks for a newer release. Read from the global config only — whether Luxe reaches the network on your behalf is not a decision a repository you cloned makes.",
"properties": {
"check": {
"type": "boolean",
"default": true,
"description": "Look for a newer release, at most once a day, and mention it under the dashboard's footer. Luxe never updates itself; the notice names the command that matches how you installed it. The request sends nothing about you — no version, no platform, no identifier — and every failure is silent. Set false, or LUXE_UPDATE_CHECK=0, to turn it off."
}
},
"additionalProperties": false
},
"compaction": {
"type": "object",
"description": "When a long conversation gets summarized, and what survives it.",
"properties": {
"auto": {
"type": "boolean",
"default": true,
"description": "Summarize automatically once the window fills. Off leaves it to /compact, and a session that overflows fails its next request rather than shortening itself."
},
"at": {
"type": "number",
"exclusiveMinimum": 0,
"maximum": 1,
"default": 0.9,
"description": "Share of the usable window at which that happens. Eliding stale tool output starts one tenth earlier."
},
"keep_recent": {
"type": "integer",
"minimum": 1,
"default": 20000,
"description": "Tokens of the newest conversation kept verbatim rather than summarized. Capped at half the usable window, so a figure larger than the model cannot stall compaction on the sessions that need it most."
},
"reserve": {
"type": "integer",
"minimum": 1,
"default": 20000,
"description": "Tokens held back for the reply when deciding whether the window is full."
},
"prune": {
"type": "boolean",
"default": true,
"description": "Elide stale tool output as a last step before summarizing. Off goes straight to a summary, which keeps less detail but never rewrites history mid-session."
},
"summarizer": {
"type": "string",
"pattern": "^[^/]+/.+$",
"description": "Model that writes the summary, as provider/id. Defaults to whichever model is active; a smaller one here is usually the best value in this file, since summarizing is the most expensive call a long session makes and the least demanding."
}
},
"additionalProperties": false
},
"conversation": {
"type": "object",
"description": "Conversation canvas width and tool detail defaults.",
"properties": {
"prose_max_width": {
"type": "integer",
"minimum": 72,
"maximum": 120,
"default": 120,
"description": "Maximum prose width in terminal cells. Read only under alignment 'left' or 'center' \u2014 the default 'full' fills the pane and ignores both caps. Invalid values fall back to 120."
},
"wide_block_max_width": {
"type": "integer",
"minimum": 72,
"maximum": 140,
"default": 140,
"description": "Maximum width for code, tables, and tool details in terminal cells. Read only under alignment 'left' or 'center', like prose_max_width. Invalid values fall back to 140."
},
"tool_details": {
"type": "string",
"enum": ["errors", "all", "collapsed"],
"default": "errors",
"description": "Whether failed calls, all calls, or no calls start with details expanded."
},
"alignment": {
"type": "string",
"enum": ["left", "center", "full"],
"default": "full",
"description": "Horizontal placement of conversation content. 'full' (default) fills the whole width, ignoring the prose cap; 'left' anchors content to the left with readable width caps; 'center' centers it within those caps."
},
"growth": {
"type": "string",
"enum": ["top", "bottom"],
"default": "bottom",
"description": "Vertical growth of the transcript when content is shorter than the viewport. 'bottom' (default) anchors messages just above the input and grows upward (chat-style); 'top' anchors them under the header and grows downward."
},
"thinking": {
"type": "string",
"enum": ["shown", "collapsed", "hidden"],
"default": "shown",
"description": "How model reasoning (thinking) is displayed. 'shown' (default) renders it inline in muted italic; 'collapsed' shows a one-line peek you can expand with enter/space (like a tool card); 'hidden' omits it. Reasoning is always recorded on the session regardless of this setting."
},
"scroll_lines": {
"type": "integer",
"minimum": 1,
"maximum": 20,
"default": 3,
"description": "Lines one mouse-wheel notch scrolls the conversation. Values outside 1-20 fall back to 3. The scrollbar thumb can also be dragged, and PageUp/PageDown move a full viewport."
},
"activity_bar": {
"type": "string",
"enum": ["bars", "dots", "off"],
"default": "bars",
"description": "The indicator above the composer while a turn runs: a comet shaded in the theme accent that sweeps the rail, runs off the end, waits a beat, and returns the way it came. Its cells dim and thin as they trail away, so the far tail converges on the rail and disappears, and the rail is lit by the comet rather than drawn at a fixed weight, so the bar's ends melt into the canvas. 'bars' (default) uses block-element segments, which every terminal font draws at exact cell fractions; 'dots' is softer and lighter; 'off' keeps the elapsed time and interrupt hint without the motion. The slanted, upright and braille rails are retired \u2014 whether a font draws those at one cell wide is unmeasurable, so the setting was a coin toss; a config naming one falls back to 'bars'."
},
"image_max_rows": {
"type": "integer",
"minimum": 3,
"maximum": 200,
"default": 24,
"description": "Rows an inline image may occupy before it is scaled down to fit. Values outside 3-200 fall back to 24. Capped again at half the transcript's height, so one tall screenshot cannot swallow the window."
},
"tool_runs": {
"type": "string",
"enum": ["fold", "cards"],
"default": "fold",
"description": "How a run of lookups one message asked for is drawn. 'fold' (default) collapses the run into one line that names the lookup happening now and settles into a count; select it or click it to see every card it stands for. 'cards' keeps each call on its own card. Only lookups fold, and a failure never does."
},
"stream_reveal": {
"type": "string",
"enum": ["smooth", "off"],
"default": "smooth",
"description": "How streamed reasoning and prose land on screen. 'smooth' (default) paces them at the rate the model is actually producing, with the newest characters fading up out of the background, because a provider's delivery is nothing like its production: one measured at a single ~75-character delta every ~470 ms, which paints as two visible jumps a second. Tool cards, your own messages and everything else appear immediately either way, and anything that needs you \u2014 a permission prompt, a question, an error, a keystroke \u2014 shows the rest at once. 'off' paints each arrival the instant it lands."
}
},
"additionalProperties": false
},
"statusline": {
"type": "object",
"description": "Statusline visibility, module order, and appearance.",
"properties": {
"visibility": {
"type": "string",
"enum": ["auto", "shown", "hidden"],
"default": "auto",
"description": "Show the bottom statusline always, never, or automatically (auto = shown unless the full-height sidebar sits beside the conversation). Toggle at runtime via the command palette, /statusline, or the bound key."
},
"style": {
"type": "string",
"enum": ["slab", "flat"],
"default": "slab",
"description": "How modules are drawn: 'slab' gives each one a half-capped block colored off the theme accent, receding into the background; 'flat' draws tinted text straight on the bar. The Context Dock's section headings follow the same setting. Neither needs a patched font."
},
"left": {
"type": "array",
"items": {
"type": "string",
"enum": ["project", "branch", "pr", "todo", "changes", "cwd", "activity"]
},
"uniqueItems": true,
"default": ["project", "branch", "pr", "todo", "changes"],
"description": "Left-side modules in rendered order from the outer edge toward the center. Default: project, branch, pr, todo, changes. 'pr' is the branch's pull request on GitHub — its number, failing or running checks, a request for changes, unresolved threads — and renders nothing when the branch has none or GitHub cannot be asked. 'todo' leads with the checklist ratio and renders nothing at all when the session has no plan. 'changes' says how many files this session has touched and which key opens them, and renders nothing when the worktree is clean. 'cwd' is opt-in now that the project name says where you are, and 'activity' because a running turn already announces itself above the composer. Project and branch stay shown even when the Context Dock also shows them; omit a module from an explicit list to hide it."
},
"right": {
"type": "array",
"items": {
"type": "string",
"enum": ["context", "cost", "tokens", "thinking", "model"]
},
"uniqueItems": true,
"default": ["context", "cost", "tokens", "thinking", "model"],
"description": "Right-side modules in rendered left-to-right order, from the center toward the outer edge. 'context' leads because it rides bare on the bar, where its fill coloring reads without a surface competing with it. Omit a module to hide it."
},
"thinking_colors": {
"type": "boolean",
"default": false,
"description": "Color the thinking module by level: muted off, text minimal, yellow low, green medium, blue high, purple xhigh, magenta ultra."
}
},
"additionalProperties": false
}
},
"definitions": {
"model": {
"type": "string",
"pattern": "^[^/]+/.+$",
"description": "Model as provider/id, e.g. anthropic/claude-sonnet-4-20250514. Only the first slash separates them, so a namespaced id keeps its own (openrouter/anthropic/claude-sonnet-4). An id no catalog knows still works, on provider-aware defaults. Each model keeps its own prompt cache, so a switch reads the conversation again at full price."
},
"thinking": {
"type": "string",
"enum": ["off", "minimal", "low", "medium", "high", "xhigh", "ultra"],
"description": "Reasoning level, clamped to what the model supports."
}
},
"additionalProperties": false
}

View File

@@ -0,0 +1,450 @@
//! Display settings — how the TUI looks: statusline, start screen, glyphs, images, notifications
//! and the Context Dock.
use serde::{Deserialize, Serialize};
mod conversation;
mod diff;
pub use conversation::*;
pub use diff::*;
/// A setting read leniently: a value this build does not know deserializes to [`Lenient::UNKNOWN`],
/// and resolving it gives the default, with a warning, so one typo never costs the whole file.
pub(crate) trait Lenient: Copy + PartialEq {
/// What a value this build does not know deserializes to
const UNKNOWN: Self;
/// What applies when nobody set it
const DEFAULT: Self;
/// [`Self::DEFAULT`] as a config file spells it, for the settings surface and the warning
const DEFAULT_NAME: &'static str;
/// The setting, as the warning names it
const NAME: &'static str;
}
/// The value in force: the one set, or the default when it is unset or unknown.
pub(crate) fn known_or<T: Lenient>(value: Option<T>) -> T {
match value {
Some(value) if value == T::UNKNOWN => {
tracing::warn!("unknown {}; falling back to {}", T::NAME, T::DEFAULT_NAME);
T::DEFAULT
}
Some(value) => value,
None => T::DEFAULT,
}
}
/// Configurable modules for either half of the TUI statusline.
///
/// The left half favors workspace/interaction state; the right half favors model/runtime
/// telemetry. A module only renders on the side that knows how to build it, so listing a
/// right-only module on the left (or vice versa) is a harmless no-op.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StatuslineModule {
// === Left half ===
/// Project name, as the bar's left anchor
Project,
/// Git branch with a dirty-worktree indicator
Branch,
/// The branch's pull request on GitHub, drawn only when it has one
Pr,
/// How far the agent's checklist has got, and what it is pointing at
Todo,
/// How many files have changed, and the key that shows them
Changes,
/// Compact working-directory path
Cwd,
/// Turn activity: spinner, active tool, elapsed time
Activity,
// === Right half ===
/// Estimated turn cost
Cost,
/// Prompt and completion token counts
Tokens,
/// Context usage and context-window size
Context,
/// Active thinking level
Thinking,
/// Active model name
Model,
/// Unknown module names are ignored for forward compatibility. Retired names land here too, so
/// an older config keeps loading — `mode` was one, from an experiment in emulating a modal
/// editor's statusline, and `lsp` another, which only ever read back a setting.
#[serde(other)]
Unknown,
}
/// How the statusline draws its modules.
///
/// Shape only — which modules appear and in what order is [`StatuslineConfig::left`] and
/// [`StatuslineConfig::right`], and both styles honor them identically.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StatuslineStyle {
/// Each module a diagonal-capped parallelogram floating on the bar, colored off one accent
/// receding into the background (default).
#[default]
Slab,
/// Tinted text on the bar background, with no surface behind it.
Flat,
/// Unknown values fall back to slabs.
#[serde(other)]
Unknown,
}
impl Lenient for StatuslineStyle {
const UNKNOWN: Self = Self::Unknown;
const DEFAULT: Self = Self::Slab;
const DEFAULT_NAME: &'static str = "slab";
const NAME: &'static str = "statusline style";
}
/// The start screen's shape.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DashboardStyle {
/// The prompt, with sessions and commands listed under it (default)
#[default]
Launcher,
/// The prompt alone; the list waits for `↓`
Minimal,
/// Unknown values fall back to the launcher.
#[serde(other)]
Unknown,
}
/// `dashboard` in `config.json`: a switch, or a style.
///
/// `"dashboard": false` was shipped and is in people's files, so the key takes either shape — the
/// way `permissions.json` takes a bare action or a keyed table — and no file has to change.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DashboardSetting {
/// `true` for the default start screen, `false` for none
Enabled(bool),
/// `{ "style": "minimal" }`
Styled {
/// Which start screen
#[serde(default)]
style: DashboardStyle,
},
}
/// Bottom statusline visibility.
///
/// The statusline and the full-height Context Dock are two forms of the same workspace context.
/// `Auto` shows the statusline as a compact fallback whenever the dock is not sitting beside the
/// conversation, so wide terminals get the rich sidebar and narrower ones keep a glanceable bar.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StatuslineVisibility {
/// Show the statusline unless the dock is presented side-by-side.
Auto,
/// Always show the statusline.
Shown,
/// Never show the statusline.
Hidden,
/// Unknown values safely fall back to automatic behavior.
#[serde(other)]
Unknown,
}
impl Lenient for StatuslineVisibility {
const UNKNOWN: Self = Self::Unknown;
const DEFAULT: Self = Self::Auto;
const DEFAULT_NAME: &'static str = "auto";
const NAME: &'static str = "statusline visibility";
}
/// User overrides for statusline composition.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct StatuslineConfig {
/// Visibility mode; omitted values follow the automatic dock-aware behavior.
pub visibility: Option<StatuslineVisibility>,
/// Left-side modules ordered from the outer edge toward the center. `None` keeps the
/// default composition with Context-Dock-aware de-duplication; an explicit list is
/// honored verbatim (so `branch`/`cwd` can stay visible even when the dock shows them).
pub left: Option<Vec<StatuslineModule>>,
/// Right-side modules ordered from the center toward the outer edge
pub right: Option<Vec<StatuslineModule>>,
/// Color the thinking module by level; `None` keeps the neutral default
pub thinking_colors: Option<bool>,
/// How modules are drawn; `None` keeps the slabs
pub style: Option<StatuslineStyle>,
}
impl StatuslineConfig {
/// Resolves the configured visibility, safely defaulting unknown values to automatic.
pub fn visibility(&self) -> StatuslineVisibility {
known_or(self.visibility)
}
/// Resolves the configured style, safely defaulting unknown values to slabs.
pub fn style(&self) -> StatuslineStyle {
known_or(self.style)
}
}
/// How much glyph fidelity the TUI asks the terminal for.
///
/// Icons are decoration: the words beside them carry the meaning, so every tier is fully usable and the
/// difference is polish. The nerd tier needs a patched font, which is why it is not simply assumed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GlyphStyle {
/// Use the Material icons where they can be drawn, plain shapes otherwise (default).
#[default]
Auto,
/// Material Design icons from a Nerd Font.
Nerd,
/// The same icons, given a second cell to be drawn in.
///
/// A Nerd Font ships in two cuts of every face. The `Mono` one rescales the icons to a single
/// cell; the other draws them at their natural size — roughly two cells of ink behind a
/// one-cell advance — so on that cut an icon paints straight over the space after it and butts
/// against the word it labels. Nothing can measure which cut is loaded: both report one cell.
/// This is the lever for anyone whose font is the wide one and who prefers the bigger icons to
/// swapping the face.
NerdWide,
/// Geometric Shapes and Arrows; no private-use codepoints, so no patched font needed.
Unicode,
/// Plain ASCII punctuation, for a minimal or non-UTF-8 terminal.
Ascii,
/// Unknown values fall back to `auto`.
#[serde(other)]
Unknown,
}
impl Lenient for GlyphStyle {
const UNKNOWN: Self = Self::Unknown;
const DEFAULT: Self = Self::Auto;
const DEFAULT_NAME: &'static str = "auto";
const NAME: &'static str = "glyph style";
}
/// How much image fidelity the TUI asks the terminal for.
///
/// The tiers mirror [`GlyphStyle`], for the same reason: a terminal that cannot do the beautiful
/// thing should lose shine, not information. `pixels` needs the kitty graphics protocol *with*
/// Unicode placeholders, a narrower set than "speaks kitty graphics" (WezTerm draws the
/// placeholders as tofu), so `auto` picks it only for terminals measured to handle it and `pixels`
/// is the override for one `auto` does not know yet.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ImageStyle {
/// Real pixels where the terminal is known to draw them, a line naming the image otherwise.
///
/// Never `blocks`: a screenshot is mostly text, and two scanlines per cell turn text into a
/// smear that reads as a broken image, so the imitation is opt-in.
#[default]
Auto,
/// Kitty graphics protocol with Unicode placeholders.
Pixels,
/// Half-block cells: coarse, but no protocol and nothing to be incompatible with.
Blocks,
/// A text line naming the image and its size.
Off,
/// Unknown values fall back to `auto`.
#[serde(other)]
Unknown,
}
impl Lenient for ImageStyle {
const UNKNOWN: Self = Self::Unknown;
const DEFAULT: Self = Self::Auto;
const DEFAULT_NAME: &'static str = "auto";
const NAME: &'static str = "image style";
}
/// How a desktop notification reaches the desktop: an escape sequence the terminal turns into one.
///
/// Through the terminal rather than a desktop library, so it needs no D-Bus, works over ssh, and
/// lands wherever the terminal sends its own notifications. Terminals disagree on the sequence and
/// none can be asked, so `auto` picks from the ones known to show it, and the rest is this lever.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NotificationMethod {
/// The sequence the terminal is known to show, or none for a terminal that is not known.
#[default]
Auto,
/// `OSC 9`, iTerm2's: Ghostty, iTerm2, kitty, WezTerm and Warp show it.
Osc9,
/// `OSC 777`, rxvt-unicode's, with a separate title: foot and some VTE builds show it.
Osc777,
/// Unknown values fall back to `auto`.
#[serde(other)]
Unknown,
}
/// The moments that send a desktop notification: all of them, none, or a list.
///
/// Read leniently, like every other key: a value that is neither a boolean nor a list is treated as
/// unset and a name Luxe does not know is skipped, so one typo never takes the whole config with it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(untagged)]
pub enum Notifications {
/// Every moment, or none
All(bool),
/// Only these
Only(Vec<NotificationEvent>),
}
impl Notifications {
/// Whether `event` sends a notification under this setting.
pub fn includes(&self, event: NotificationEvent) -> bool {
match self {
Self::All(enabled) => *enabled,
Self::Only(events) => events.contains(&event),
}
}
/// Whether any moment sends one at all.
pub fn any(&self) -> bool {
match self {
Self::All(enabled) => *enabled,
Self::Only(events) => !events.is_empty(),
}
}
}
impl<'de> Deserialize<'de> for Notifications {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(match serde_json::Value::deserialize(deserializer)? {
serde_json::Value::Bool(enabled) => Self::All(enabled),
serde_json::Value::Array(names) => Self::Only(
names
.iter()
.filter_map(serde_json::Value::as_str)
.filter_map(NotificationEvent::named)
.collect(),
),
_ => Self::All(false),
})
}
}
/// A moment worth telling a reader who has looked away.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NotificationEvent {
/// A turn finished, or failed
Turn,
/// A tool call is waiting for your approval
Permission,
/// The agent asked you a question
Question,
/// A Guided Review finished writing its guide
Review,
}
impl NotificationEvent {
/// The event a config names, or `None` for a name this build does not know.
fn named(name: &str) -> Option<Self> {
match name.trim().to_ascii_lowercase().as_str() {
"turn" => Some(Self::Turn),
"permission" => Some(Self::Permission),
"question" => Some(Self::Question),
"review" => Some(Self::Review),
_ => None,
}
}
}
/// The look of the activity bar that runs above the composer while a turn is in flight.
///
/// Two shapes and an off switch. The retired `progress`, `rect` and `braille` shapes drew
/// glyphs that only some fonts keep to one cell, and a setting whose result depends on a font
/// substitution nobody can measure is a coin toss with a name. A config still naming one falls
/// back to `bars`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ActivityBarStyle {
/// `▌▍▎▏` — block-element segments with a gap inside each cell (default).
///
/// The default because block elements are the one glyph family every terminal font draws
/// itself, at exact cell fractions.
#[default]
Bars,
/// `●•·` — round marks over a dotted rail; softer and lighter than `bars`.
Dots,
/// No indicator; the elapsed time and interrupt hint remain.
Off,
/// Unknown values fall back to the default.
#[serde(other)]
Unknown,
}
impl Lenient for ActivityBarStyle {
const UNKNOWN: Self = Self::Unknown;
const DEFAULT: Self = Self::Bars;
const DEFAULT_NAME: &'static str = "bars";
const NAME: &'static str = "activity bar";
}
/// Context Dock visibility preference.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DockMode {
/// Follow the responsive workspace layout.
Auto,
/// Always show the Context Dock.
Shown,
/// Keep the Context Dock closed.
Hidden,
/// Unknown values safely follow the automatic layout.
#[serde(other)]
Unknown,
}
impl Lenient for DockMode {
const UNKNOWN: Self = Self::Unknown;
const DEFAULT: Self = Self::Auto;
const DEFAULT_NAME: &'static str = "auto";
const NAME: &'static str = "dock mode";
}
/// Which side of the terminal the full-height Context Dock occupies.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DockPosition {
/// Anchor the dock to the left edge.
Left,
/// Anchor the dock to the right edge.
Right,
/// Unknown values safely fall back to the left edge.
#[serde(other)]
Unknown,
}
impl Lenient for DockPosition {
const UNKNOWN: Self = Self::Unknown;
const DEFAULT: Self = Self::Left;
const DEFAULT_NAME: &'static str = "left";
const NAME: &'static str = "dock position";
}
/// Persisted Context Dock preferences.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct DockConfig {
/// Visibility mode; omitted values follow the automatic layout.
pub mode: Option<DockMode>,
/// Which side the dock occupies; omitted values anchor it to the left.
pub position: Option<DockPosition>,
}
impl DockConfig {
/// Resolves the configured mode, safely defaulting unknown values to automatic behavior.
pub fn mode(&self) -> DockMode {
known_or(self.mode)
}
/// Resolves the configured side, safely defaulting unknown/omitted values to the left.
pub fn position(&self) -> DockPosition {
known_or(self.position)
}
}

View File

@@ -0,0 +1,235 @@
//! Conversation settings — how the transcript is laid out and what it shows.
use super::ActivityBarStyle;
use super::{known_or, Lenient};
use serde::{Deserialize, Serialize};
/// How model reasoning ("thinking") output is presented in the transcript.
///
/// Reasoning is always recorded on the session; this only controls display. `Collapsed` blocks
/// stay expandable at runtime with the same key that expands a tool card.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ThinkingDisplay {
/// Show reasoning inline, in full (muted italic).
Shown,
/// Show a one-line peek that can be expanded on demand.
Collapsed,
/// Don't render reasoning at all.
Hidden,
/// Unknown values fall back to shown.
#[serde(other)]
Unknown,
}
impl Lenient for ThinkingDisplay {
const UNKNOWN: Self = Self::Unknown;
const DEFAULT: Self = Self::Shown;
const DEFAULT_NAME: &'static str = "shown";
const NAME: &'static str = "conversation thinking display";
}
/// Default behavior for collapsed tool activity details.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolDetailsPreference {
/// Expand failed tool calls only.
Errors,
/// Expand every tool call.
All,
/// Start every tool call collapsed.
Collapsed,
/// Unknown values fall back to failed calls only.
#[serde(other)]
Unknown,
}
impl Lenient for ToolDetailsPreference {
const UNKNOWN: Self = Self::Unknown;
const DEFAULT: Self = Self::Errors;
const DEFAULT_NAME: &'static str = "errors";
const NAME: &'static str = "conversation tool_details";
}
/// Horizontal placement of conversation content within the available width.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConversationAlignment {
/// Anchor content to the left; readable width caps still apply.
Left,
/// Center content within the available width.
Center,
/// Fill the full available width, ignoring the readable prose cap.
Full,
/// Unknown values fall back to full width.
#[serde(other)]
Unknown,
}
impl Lenient for ConversationAlignment {
const UNKNOWN: Self = Self::Unknown;
const DEFAULT: Self = Self::Full;
const DEFAULT_NAME: &'static str = "full";
const NAME: &'static str = "conversation alignment";
}
/// How streamed reasoning and prose reach the screen.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StreamReveal {
/// Paced against the model's measured rate, with the newest characters fading in.
Smooth,
/// Painted the instant it arrives, in whatever lumps the provider sends.
Off,
/// Unknown values fall back to smooth.
#[serde(other)]
Unknown,
}
impl Lenient for StreamReveal {
const UNKNOWN: Self = Self::Unknown;
const DEFAULT: Self = Self::Smooth;
const DEFAULT_NAME: &'static str = "smooth";
const NAME: &'static str = "conversation stream_reveal";
}
/// How a run of lookups one message asked for is drawn.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolRuns {
/// One line for the whole run, opened with a click.
Fold,
/// A card per call, however many the message asked for.
Cards,
/// Unknown values fall back to folding.
#[serde(other)]
Unknown,
}
impl Lenient for ToolRuns {
const UNKNOWN: Self = Self::Unknown;
const DEFAULT: Self = Self::Fold;
const DEFAULT_NAME: &'static str = "fold";
const NAME: &'static str = "conversation tool_runs";
}
/// Vertical growth direction of the transcript when content is shorter than the viewport.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConversationGrowth {
/// Anchor content to the top, under the header, growing downward.
Top,
/// Anchor content to the bottom, just above the input, growing upward (chat-style default).
Bottom,
/// Unknown values fall back to bottom.
#[serde(other)]
Unknown,
}
impl Lenient for ConversationGrowth {
const UNKNOWN: Self = Self::Unknown;
const DEFAULT: Self = Self::Bottom;
const DEFAULT_NAME: &'static str = "bottom";
const NAME: &'static str = "conversation growth";
}
/// Conversation width and tool-detail preferences.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct ConversationConfig {
/// Maximum prose width in terminal cells. Only consulted under a capped [`alignment`].
///
/// [`alignment`]: ConversationAlignment
pub prose_max_width: Option<u16>,
/// Maximum wide-block width in terminal cells. Only consulted under a capped alignment.
pub wide_block_max_width: Option<u16>,
/// Default expansion behavior for tool details.
pub tool_details: Option<ToolDetailsPreference>,
/// Horizontal placement of conversation content; omitted values fill the full width.
pub alignment: Option<ConversationAlignment>,
/// Vertical growth when content is shorter than the viewport; omitted values anchor bottom.
pub growth: Option<ConversationGrowth>,
/// How model reasoning is displayed; omitted values show reasoning inline in full.
pub thinking: Option<ThinkingDisplay>,
/// Lines one wheel notch scrolls the transcript; omitted values scroll three.
pub scroll_lines: Option<u16>,
/// The activity bar's look; omitted values use `bars`.
pub activity_bar: Option<ActivityBarStyle>,
/// Rows an inline image may occupy before it is scaled down to fit. Omitted = 24.
pub image_max_rows: Option<u16>,
/// How streamed reasoning and prose land on screen. Omitted = `smooth`.
pub stream_reveal: Option<StreamReveal>,
/// How a run of lookups one message asked for is drawn. Omitted = `fold`.
pub tool_runs: Option<ToolRuns>,
}
impl ConversationConfig {
/// Resolves the prose width, using 120 cells outside the supported 72–120 range.
pub fn prose_max_width(&self) -> u16 {
self.prose_max_width.filter(|width| (72..=120).contains(width)).unwrap_or(120)
}
/// Resolves the wide-block width, using 140 cells outside the supported 72–140 range.
pub fn wide_block_max_width(&self) -> u16 {
self.wide_block_max_width.filter(|width| (72..=140).contains(width)).unwrap_or(140)
}
/// Lines one wheel notch moves the transcript.
///
/// Three by default: one line per notch makes paging a long conversation a chore, and terminals
/// send one notch per physical click. Capped at 20 so a bad value can't teleport the view.
pub fn scroll_lines(&self) -> usize {
usize::from(self.scroll_lines.filter(|lines| (1..=20).contains(lines)).unwrap_or(3))
}
/// Rows an inline image may occupy in the transcript.
///
/// Twenty-four by default: tall enough to read a dev-server screenshot at a glance, short
/// enough that a burst of them still leaves conversation on screen. The floor of 3 keeps a
/// misconfiguration from producing a one-row smear, and the ceiling is the protocol's own.
pub fn image_max_rows(&self) -> u16 {
self.image_max_rows.filter(|rows| (3..=200).contains(rows)).unwrap_or(24)
}
/// Resolves the content alignment.
///
/// Defaults to `full`: capping prose at 120 cells left ultrawide terminals mostly empty, and
/// the people running them chose that width on purpose. `left`/`center` keep the readable cap
/// for anyone who prefers it.
pub fn alignment(&self) -> ConversationAlignment {
known_or(self.alignment)
}
/// Resolves the growth direction, safely defaulting unknown/omitted values to bottom-up.
pub fn growth(&self) -> ConversationGrowth {
known_or(self.growth)
}
/// Resolves how reasoning is displayed, safely defaulting unknown/omitted values to shown.
pub fn thinking(&self) -> ThinkingDisplay {
known_or(self.thinking)
}
/// Whether streamed reasoning and prose are paced onto the screen.
///
/// On by default: a provider's delivery is nothing like its production — one measured at ~75
/// characters every ~470 ms — so painting each arrival as it lands is what makes a fast model
/// look choppy. `off` restores exactly that, for anyone who wants the raw wire.
pub fn stream_reveal(&self) -> StreamReveal {
known_or(self.stream_reveal)
}
/// Whether a run of lookups collapses into the one line that stands for it.
///
/// Folded by default: a message asking for seven `read` calls fills the screen with headers in
/// half a second, and the conversation they belonged to goes off the top. `cards` keeps every
/// call on its own card for anyone who would rather watch each one land.
pub fn tool_runs(&self) -> ToolRuns {
known_or(self.tool_runs)
}
/// Resolves the default tool-detail behavior, safely falling back for unknown values.
pub fn tool_details(&self) -> ToolDetailsPreference {
known_or(self.tool_details)
}
}

View File

@@ -0,0 +1,97 @@
//! Diff settings — one layout rule for every surface that draws a diff.
use super::{known_or, Lenient};
use serde::{Deserialize, Serialize};
/// How a diff is drawn, wherever Luxe draws one.
///
/// One setting for three surfaces — the `edit`/`write` tool card, the peeked file beside the
/// conversation, and Guided Review. They differ only in how much room they have, and
/// [`DiffLayout::splits`] is handed that room rather than each surface keeping an opinion.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DiffLayout {
/// Side by side where the surface can give each column a readable width, unified below that.
Auto,
/// Always one column.
Unified,
/// Side by side down to a cramped column, for a reader who would rather have the pairing.
Split,
/// Unknown values fall back to automatic behavior.
#[serde(other)]
Unknown,
}
impl Lenient for DiffLayout {
const UNKNOWN: Self = Self::Unknown;
const DEFAULT: Self = Self::Auto;
const DEFAULT_NAME: &'static str = "auto";
const NAME: &'static str = "diff layout";
}
/// Cells of code a column needs before [`DiffLayout::Auto`] prefers two of them to one.
///
/// Measured after the column's own line-number gutter, so it is the same quantity on a tool card,
/// a peeked file and a full-screen review. Each converts it using the chrome it knows about, so
/// each reaches the figure at a different terminal width: a review spends a third of a wide
/// terminal on its guide pane and a peeked file shares its column with the conversation, so they
/// are legitimately later to split than a card that has the whole width.
///
/// Chosen by measuring all three: at 44 a terminal of 160 columns pairs the sides everywhere and
/// one of 100 pairs them nowhere. Below it a line of ordinary source wraps more than once and the
/// row stops reading as a row, though it is never *lost*, since every surface wraps rather than
/// clips.
pub const MIN_SPLIT_COLUMN: usize = 44;
/// Cells of code a column needs before [`DiffLayout::Split`] will draw two of them.
///
/// Cramped, and deliberately reachable: someone who set `split` would rather read a wrapped pairing
/// than a unified list, and the only thing left to protect them from is a column too narrow to be
/// a column.
pub const SPLIT_FLOOR_COLUMN: usize = 28;
impl DiffLayout {
/// Whether a surface offering `column_cells` of code per side draws two columns.
///
/// The three settings differ on exactly one axis — how much width they demand before pairing
/// the sides up: never, [`MIN_SPLIT_COLUMN`], or down to [`SPLIT_FLOOR_COLUMN`].
///
/// `two_sided` is whether the change has both a removal and an addition to pair. An
/// all-additions block has nothing for the left column, so it stays unified on every setting.
pub fn splits(self, column_cells: usize, two_sided: bool) -> bool {
if !two_sided {
return false;
}
match self {
Self::Unified => false,
Self::Split => column_cells >= SPLIT_FLOOR_COLUMN,
Self::Auto | Self::Unknown => column_cells >= MIN_SPLIT_COLUMN,
}
}
}
/// How every diff is drawn.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct DiffConfig {
/// One column or two. Omitted = [`DiffLayout::Auto`].
pub layout: Option<DiffLayout>,
/// Soft-wrap long lines rather than scrolling them sideways. Omitted = scroll.
///
/// Only two of the three surfaces have a choice here: a tool card and a peeked file cannot
/// scroll sideways, so they always wrap — clipping there would put content out of reach rather
/// than one keystroke away. Guided Review can, so this is its default, and `w` flips it live.
pub word_wrap: Option<bool>,
}
impl DiffConfig {
/// Resolves the layout, safely defaulting unknown values to automatic.
pub fn layout(&self) -> DiffLayout {
known_or(self.layout)
}
/// Whether long lines soft-wrap where the surface could have scrolled them instead.
pub fn word_wrap(&self) -> bool {
self.word_wrap.unwrap_or(false)
}
}

View File

@@ -0,0 +1,77 @@
//! Config files — where they live, how one is read, and how the user's is first written.
use super::Config;
use crate::user_dirs::luxe_config_dir;
use std::io::Write;
use std::path::{Path, PathBuf};
impl Config {
/// The user-level `config.json`.
pub fn global_path() -> PathBuf {
luxe_config_dir().join("config.json")
}
/// Path to the optional custom debug-adapter registry (`debug-adapters.json`).
pub fn debug_adapters_path() -> PathBuf {
luxe_config_dir().join("debug-adapters.json")
}
/// Path to the optional custom LSP-server registry (`lsp-servers.json`).
pub fn lsp_servers_path() -> PathBuf {
luxe_config_dir().join("lsp-servers.json")
}
/// Creates the user config and its JSON schema when missing.
///
/// Existing config is never overwritten. The generated schema is refreshed so opening
/// the file after an upgrade immediately exposes new settings to editor completion.
pub fn ensure_global_file() -> std::io::Result<PathBuf> {
let path = Self::global_path();
let directory = path.parent().unwrap_or_else(|| Path::new("."));
ensure_config_file(directory)
}
}
/// Load the global config from `~/.config/luxe/config.json`.
pub(super) fn load_global_config() -> Option<Config> {
read_config_file(&Config::global_path())
}
/// Load the project config from `<repo>/.luxe/config.json`.
pub(super) fn load_project_config(repo_root: &Path) -> Option<Config> {
let path = repo_root.join(".luxe").join("config.json");
read_config_file(&path)
}
/// Read and parse a config file, returning `None` on any error (with a warning).
pub(super) fn read_config_file(path: &Path) -> Option<Config> {
if !path.exists() {
return None;
}
match std::fs::read_to_string(path) {
Ok(contents) => match serde_json::from_str(&contents) {
Ok(config) => Some(config),
Err(e) => {
tracing::warn!(path = %path.display(), error = %e, "malformed UI config; using defaults");
None
}
},
Err(e) => {
tracing::warn!(path = %path.display(), error = %e, "failed to read UI config; using defaults");
None
}
}
}
pub(super) fn ensure_config_file(directory: &Path) -> std::io::Result<PathBuf> {
std::fs::create_dir_all(directory)?;
std::fs::write(directory.join("config.schema.json"), Config::schema_json())?;
let path = directory.join("config.json");
match std::fs::OpenOptions::new().write(true).create_new(true).open(&path) {
Ok(mut file) => file.write_all(b"{\n \"$schema\": \"./config.schema.json\"\n}\n")?,
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(error) => return Err(error),
}
Ok(path)
}

View File

@@ -0,0 +1,233 @@
//! Integration settings — launchers, `@` sources, worktrees, GitHub, updates, language servers
//! and Guided Review.
use serde::{Deserialize, Serialize};
/// A program a key hands the terminal to: gh-dash, lazygit, anything that takes over a terminal
/// and gives it back.
///
/// Read from the global config only, like command hooks: a key that runs a program a repository
/// named is the same arbitrary execution a project's hooks would be.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Launcher {
/// The chord that starts it, like `alt+l`
pub key: String,
/// The program, looked up on `PATH`
pub command: String,
/// Its arguments
#[serde(default)]
pub args: Vec<String>,
}
/// A program the `@` picker runs to list references of a kind of its own — Jira issues, Asana
/// tasks, anything a script can reach — each row inserted as `@[kind:id]`.
///
/// Read from the global config only, like launchers and command hooks: a source runs a program,
/// and a program a repository named is arbitrary execution.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MentionSource {
/// The tab's name, like `Jira`
pub name: String,
/// The reference's kind, as in `@[jira:PROJ-12]`; the name in lowercase when unset
#[serde(default)]
pub kind: Option<String>,
/// The program, looked up on `PATH`
pub command: String,
/// Its arguments
#[serde(default)]
pub args: Vec<String>,
/// A glyph drawn beside the tab's name, like a Nerd Font's `md-jira`; a tag when unset
#[serde(default)]
pub icon: Option<String>,
}
impl MentionSource {
/// The glyph it asked for, when that is one: a character or two — a mark and its variation
/// selector — with nothing that moves the cursor. Anything else is ignored for the default,
/// since a tab row is not the place to find out a config value was a sentence.
pub fn icon(&self) -> Option<&str> {
let icon = self.icon.as_deref()?.trim();
let count = icon.chars().count();
let clean = icon.chars().all(|c| !c.is_whitespace() && !c.is_control());
((1..=2).contains(&count) && clean).then_some(icon)
}
/// The kind its references carry: the one set, or the name folded to lowercase letters, digits
/// and dashes.
pub fn kind(&self) -> String {
let named = self.kind.as_deref().unwrap_or(&self.name);
let folded: String = named
.trim()
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '-' })
.collect();
folded.trim_matches('-').to_string()
}
/// Whether it can stand beside files, skills, GitHub and MCP: it has a kind, and not one of
/// theirs.
pub fn usable(&self) -> bool {
let kind = self.kind();
!kind.is_empty() && !self.reserved() && !self.command.trim().is_empty()
}
/// Whether its kind is one Luxe's own tabs use, which leaves it without a tab of its own.
///
/// Worth telling the reader rather than only skipping: `mcp` joined the list after sources
/// could be named anything, so a source that worked yesterday can be the one it displaced.
pub fn reserved(&self) -> bool {
RESERVED_MENTION_KINDS.contains(&self.kind().as_str())
}
}
/// The reference kinds Luxe's own `@` tabs use: `@[file:…]`, `@[skill:…]`, `@[github:…]`,
/// `@[mcp:…]`.
pub const RESERVED_MENTION_KINDS: [&str; 4] = ["file", "skill", "github", "mcp"];
/// Session worktree preferences.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
#[serde(default)]
pub struct WorktreeConfig {
/// Give every new session a worktree of its own, as `--worktree` does. `None` — the default —
/// means no.
pub always: Option<bool>,
}
impl WorktreeConfig {
/// Whether a new session gets a worktree without being asked.
pub fn always(&self) -> bool {
self.always.unwrap_or(false)
}
}
/// GitHub preferences.
///
/// Read from the global config only, like [`UpdateConfig`]: how often Luxe calls out on a timer is
/// the reader's decision, not one a repository they cloned gets to make.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
#[serde(default)]
pub struct GithubConfig {
/// Seconds between background checks of the branch's pull request once nothing is in flight.
/// `None` — the default — means 60; `0` turns background checks off.
pub refresh_secs: Option<u64>,
/// The sections `/github` lists, each a GitHub search; `None` means review requested, mine,
/// assigned issues, and every open pull request and issue, in this repository.
pub sections: Option<Vec<GithubSection>>,
}
/// One section of `/github`: a name, and the GitHub search that fills it. `{repo}` in the query
/// stands for the checkout's repository, `owner/name`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct GithubSection {
/// What the tab says
pub name: String,
/// A GitHub search, as the site's search box takes it
pub query: String,
}
impl GithubConfig {
/// The sections `/github` lists: the configured ones, or the defaults — what is addressed to
/// you first, then everything open, most recently active first. All in this repository, since
/// that is where each row's action works.
pub fn sections(&self) -> Vec<GithubSection> {
self.sections.clone().unwrap_or_else(|| {
[
("Review requested", "is:open is:pr review-requested:@me repo:{repo}"),
("Mine", "is:open is:pr author:@me repo:{repo}"),
("Assigned issues", "is:open is:issue assignee:@me repo:{repo}"),
("Pull requests", "is:open is:pr sort:updated-desc repo:{repo}"),
("Issues", "is:open is:issue sort:updated-desc repo:{repo}"),
]
.into_iter()
.map(|(name, query)| GithubSection { name: name.into(), query: query.into() })
.collect()
})
}
/// The settled interval, in seconds; `0` means no background checks.
pub fn refresh_secs(&self) -> u64 {
self.refresh_secs.unwrap_or(crate::github::refresh::DEFAULT_REFRESH_SECS)
}
}
/// Update-notice preferences.
///
/// Luxe never updates itself; the only question here is whether it may *notice* that it is behind.
/// The check fetches a public manifest and sends nothing about you — see `luxe_core::update` — but
/// it is still an outbound request, so it gets a switch like every other one.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
#[serde(default)]
pub struct UpdateConfig {
/// Look for a newer release. `None` — the default — means yes.
pub check: Option<bool>,
}
impl UpdateConfig {
/// Whether the check may run.
pub fn enabled(&self) -> bool {
self.check.unwrap_or(true)
}
}
/// Language-server preferences.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
#[serde(default)]
pub struct LspConfig {
/// Whether a server the *project* installed may be launched. `None` = [`ProjectServers::Auto`].
///
/// **Read from the global config only.** A project that could set this would be granting
/// itself permission to run its own binaries, which is the whole thing being decided — the same
/// reason `.luxe/hooks.json` is ignored without `--trust-project`.
///
/// Format-on-save reads the same answer, because it is the same question: a `.venv/bin/ruff`
/// came from the repository exactly as a `node_modules/.bin` server did. It lives under `lsp`
/// because language servers asked first — a user who said "do not run this project's binaries"
/// did not mean only those.
pub project_servers: Option<ProjectServers>,
}
/// Whether Luxe may launch a language server out of the project's `node_modules/.bin`.
///
/// npm puts a dev dependency there rather than on `PATH`, so for the JavaScript servers it is
/// routinely the only copy that matches the project — `svelteserver` has to agree with the Svelte
/// major, a TypeScript server with the `typescript` the build uses. Every editor prefers it.
///
/// It is also a binary the repository supplied, so the default asks who is watching rather than
/// answering the same way everywhere. See [`ProjectServers::Auto`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum ProjectServers {
/// Use them with a human at the keyboard; refuse when nobody is there (default).
///
/// An interactive session is someone who opened this repository in their coding agent on
/// purpose, and a populated `node_modules/.bin` means `npm install` already ran this project's
/// install scripts — arbitrary code, with more privilege than one language server. Refusing
/// there protects nothing and costs the correct server.
///
/// Unattended is the opposite: `--headless`, the loop and the review agent can be pointed at a
/// tree nobody has read, and there is no one to notice. Those refuse unless `--trust-project`
/// says otherwise, which is the same flag that lets a repository's hooks run.
#[default]
Auto,
/// Always, including unattended. For a loop over repositories you own.
Always,
/// Never; only servers found on `PATH` and in the usual install directories.
Never,
}
/// Guided Review preferences.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct ReviewConfig {
/// Extra project-relative planning files a review reads for context, on top of the built-in
/// `PLAN.md`/`AGENTS.md`. Each must resolve inside the opened project.
#[serde(default)]
pub context_files: Vec<String>,
/// Project-relative globs a review leaves out, on top of Luxe's own `.luxe/` directory.
///
/// For bookkeeping a repo carries but nobody reviews — a loop's `PROGRESS.md`, a planning
/// directory, another agent's memory. Excluded files are *counted and named*, never silently
/// dropped: the Brief says how many and the review is honest that it is not the whole diff.
#[serde(default)]
pub exclude: Vec<String>,
}

View File

@@ -0,0 +1,313 @@
//! Merging — how a project's config layers over the user's, one block at a time.
//!
//! The project wins a key it sets, except where a block says otherwise, and each block's
//! exceptions sit in its own impl: what a cloned repository may not grant itself, may only turn
//! down, or replaces whole rather than appending to.
use super::{
AgentConfig, CompactionConfig, Config, ConversationConfig, DiffConfig, DockConfig, GateConfig,
GithubConfig, LspConfig, OnAsk, PlanConfig, ReviewConfig, ReviewerConfig, StatuslineConfig,
ToolsConfig, UpdateConfig, WorktreeConfig,
};
use std::collections::HashMap;
/// A config block that knows how a project's copy layers over the user's.
///
/// Every impl takes the project's copy apart field by field, so a field added to a block does not
/// compile until someone has decided how it layers.
pub(super) trait Layered {
fn layered(global: Self, project: Self) -> Self;
}
impl Layered for Config {
fn layered(global: Self, project: Self) -> Self {
let Self {
theme,
colors,
show_key_hints,
mouse,
dashboard,
banner_animation,
glyphs,
images,
notifications,
notification_method,
bell,
herdr,
statusline,
conversation,
dock,
diff,
review,
tools,
agent,
gate,
plan,
reviewer,
compaction,
lsp,
update,
github,
worktree,
launchers: _,
mentions: _,
} = project;
Self {
theme: theme.or(global.theme),
colors: merge_color_overrides(global.colors, colors),
show_key_hints: show_key_hints.or(global.show_key_hints),
mouse: mouse.or(global.mouse),
dashboard: dashboard.or(global.dashboard),
banner_animation: banner_animation.or(global.banner_animation),
glyphs: glyphs.or(global.glyphs),
images: images.or(global.images),
notifications: notifications.or(global.notifications),
notification_method: notification_method.or(global.notification_method),
bell: bell.or(global.bell),
herdr: herdr.or(global.herdr),
statusline: Layered::layered(global.statusline, statusline),
conversation: Layered::layered(global.conversation, conversation),
dock: Layered::layered(global.dock, dock),
diff: Layered::layered(global.diff, diff),
review: Layered::layered(global.review, review),
tools: Layered::layered(global.tools, tools),
agent: Layered::layered(global.agent, agent),
gate: Layered::layered(global.gate, gate),
plan: Layered::layered(global.plan, plan),
reviewer: Layered::layered(global.reviewer, reviewer),
compaction: Layered::layered(global.compaction, compaction),
lsp: Layered::layered(global.lsp, lsp),
update: Layered::layered(global.update, update),
github: Layered::layered(global.github, github),
worktree: Layered::layered(global.worktree, worktree),
// `global` only: a key that runs a program a cloned repository named is its hooks by
// another door
launchers: global.launchers,
// `global` only, for the same reason: a source runs a program
mentions: global.mentions,
}
}
}
impl Layered for StatuslineConfig {
fn layered(global: Self, project: Self) -> Self {
let Self { visibility, left, right, thinking_colors, style } = project;
Self {
visibility: visibility.or(global.visibility),
left: left.or(global.left),
right: right.or(global.right),
thinking_colors: thinking_colors.or(global.thinking_colors),
style: style.or(global.style),
}
}
}
impl Layered for ConversationConfig {
fn layered(global: Self, project: Self) -> Self {
let Self {
prose_max_width,
wide_block_max_width,
tool_details,
alignment,
growth,
thinking,
scroll_lines,
activity_bar,
image_max_rows,
stream_reveal,
tool_runs,
} = project;
Self {
prose_max_width: prose_max_width.or(global.prose_max_width),
wide_block_max_width: wide_block_max_width.or(global.wide_block_max_width),
tool_details: tool_details.or(global.tool_details),
alignment: alignment.or(global.alignment),
growth: growth.or(global.growth),
thinking: thinking.or(global.thinking),
scroll_lines: scroll_lines.or(global.scroll_lines),
activity_bar: activity_bar.or(global.activity_bar),
image_max_rows: image_max_rows.or(global.image_max_rows),
stream_reveal: stream_reveal.or(global.stream_reveal),
tool_runs: tool_runs.or(global.tool_runs),
}
}
}
impl Layered for DockConfig {
fn layered(global: Self, project: Self) -> Self {
let Self { mode, position } = project;
Self { mode: mode.or(global.mode), position: position.or(global.position) }
}
}
impl Layered for DiffConfig {
fn layered(global: Self, project: Self) -> Self {
let Self { layout, word_wrap } = project;
Self { layout: layout.or(global.layout), word_wrap: word_wrap.or(global.word_wrap) }
}
}
impl Layered for ReviewConfig {
fn layered(global: Self, project: Self) -> Self {
let Self { context_files, exclude } = project;
Self {
exclude: replaced(global.exclude, exclude),
context_files: replaced(global.context_files, context_files),
}
}
}
impl Layered for ToolsConfig {
fn layered(global: Self, project: Self) -> Self {
let Self { disabled, format_on_save, clone_repositories } = project;
Self {
disabled: merge_disabled(global.disabled, disabled),
format_on_save: format_on_save.or(global.format_on_save),
clone_repositories: clone_repositories.or(global.clone_repositories),
}
}
}
impl Layered for AgentConfig {
fn layered(global: Self, project: Self) -> Self {
let Self { max_tool_iterations, remember_model, on_ask, cache_warming, default_mode } =
project;
let warming_ceiling = global.cache_warming();
Self {
max_tool_iterations: max_tool_iterations.or(global.max_tool_iterations),
remember_model: remember_model.or(global.remember_model),
// Tighten-only, the same rule as a project's `permissions.json`: a repository may
// refuse what its own code is allowed to do and may not grant it. A project asking for
// `allow` is therefore ignored rather than honored — it is the one direction that
// would let a clone widen policy.
on_ask: match on_ask {
Some(OnAsk::Deny) => Some(OnAsk::Deny),
_ => global.on_ask,
},
// Down-only, for the same reason: warming spends the user's money, and a cloned
// repository may decline to but may not volunteer more of it.
cache_warming: cache_warming
.map(|mode| mode.min(warming_ceiling))
.or(global.cache_warming),
default_mode: default_mode.or(global.default_mode),
}
}
}
impl Layered for GateConfig {
fn layered(global: Self, project: Self) -> Self {
let Self { commands, timeout_secs, review } = project;
Self {
// A trusted project's commands replace rather than append another repo's suite
commands: replaced(global.commands, commands),
timeout_secs: timeout_secs.or(global.timeout_secs),
review: review.or(global.review),
}
}
}
impl Layered for PlanConfig {
// Field by field, so a project that names only plan files keeps your model
fn layered(global: Self, project: Self) -> Self {
let Self { files, model, thinking } = project;
Self {
files: replaced(global.files, files),
model: model.or(global.model),
thinking: thinking.or(global.thinking),
}
}
}
impl Layered for ReviewerConfig {
fn layered(global: Self, project: Self) -> Self {
let Self { model, thinking, tools } = project;
Self {
model: model.or(global.model),
thinking: thinking.or(global.thinking),
tools: tools.or(global.tools),
}
}
}
impl Layered for CompactionConfig {
fn layered(global: Self, project: Self) -> Self {
let Self { auto, at, keep_recent, reserve, prune, summarizer } = project;
Self {
auto: auto.or(global.auto),
at: at.or(global.at),
keep_recent: keep_recent.or(global.keep_recent),
reserve: reserve.or(global.reserve),
prune: prune.or(global.prune),
summarizer: summarizer.or(global.summarizer),
}
}
}
impl Layered for LspConfig {
// `global` only, deliberately: the project does not get a say in whether its own binaries may
// run. See [`LspConfig::project_servers`].
fn layered(global: Self, project: Self) -> Self {
let Self { project_servers: _ } = project;
Self { project_servers: global.project_servers }
}
}
impl Layered for UpdateConfig {
// `global` only, same reasoning in a lower key: whether Luxe reaches the network on your
// behalf is your decision, not a decision a repository you cloned makes.
fn layered(global: Self, project: Self) -> Self {
let Self { check: _ } = project;
Self { check: global.check }
}
}
impl Layered for GithubConfig {
// The interval is the user's alone; a project's sections are searches run only when someone
// opens `/github`, so the project may add its own
fn layered(global: Self, project: Self) -> Self {
let Self { refresh_secs: _, sections } = project;
Self { refresh_secs: global.refresh_secs, sections: sections.or(global.sections) }
}
}
impl Layered for WorktreeConfig {
fn layered(global: Self, project: Self) -> Self {
let Self { always } = project;
Self { always: always.or(global.always) }
}
}
/// Merges per-token color overrides, project entries winning key-by-key over global ones, so a
/// project can tweak one color without dropping the user's other global overrides.
pub(super) fn merge_color_overrides(
global: Option<HashMap<String, String>>,
project: Option<HashMap<String, String>>,
) -> Option<HashMap<String, String>> {
match (global, project) {
(Some(mut merged), Some(project)) => {
merged.extend(project);
Some(merged)
}
(global, project) => project.or(global),
}
}
/// Union of two tool deny-lists (global + project), de-duplicated and order-preserving.
pub(super) fn merge_disabled(global: Vec<String>, project: Vec<String>) -> Vec<String> {
let mut merged = global;
for name in project {
if !merged.contains(&name) {
merged.push(name);
}
}
merged
}
/// A list the project replaces whole when it sets one, rather than appending to the user's.
fn replaced<T>(global: Vec<T>, project: Vec<T>) -> Vec<T> {
if project.is_empty() {
global
} else {
project
}
}

View File

@@ -0,0 +1,743 @@
use super::*;
use crate::theme::Theme;
mod gate_trust;
mod merge;
mod schema;
#[test]
fn the_notification_method_defaults_to_auto_and_an_unknown_value_falls_back_to_it() {
assert_eq!(Config::default().notification_method(), NotificationMethod::Auto);
let parse = |json: &str| serde_json::from_str::<Config>(json).expect("parses");
let osc777 = parse(r#"{ "notification_method": "osc777" }"#);
assert_eq!(osc777.notification_method(), NotificationMethod::Osc777);
let typo = parse(r#"{ "notification_method": "osc-nine" }"#);
assert_eq!(typo.notification_method(), NotificationMethod::Auto);
}
#[test]
fn cloning_repositories_is_on_unless_config_says_otherwise() {
assert!(ToolsConfig::default().clone_repositories());
let off: ToolsConfig =
serde_json::from_str(r#"{ "clone_repositories": false }"#).expect("parses");
assert!(!off.clone_repositories());
}
/// The per-run flags layer over config in both directions.
#[test]
fn a_run_can_disable_more_tools_than_config_does() {
let tools = ToolsConfig { disabled: vec!["screenshot".into()], ..Default::default() };
let effective = tools.effective_disabled(&["web_search".into()], &[]);
assert_eq!(effective, vec!["screenshot".to_string(), "web_search".to_string()]);
}
/// A standing preference must be liftable for one session, or it stops being a preference and
/// becomes a file you edit twice a day.
#[test]
fn a_run_can_lift_a_tool_its_config_disabled() {
let tools = ToolsConfig {
disabled: vec!["screenshot".into(), "web_search".into()],
..Default::default()
};
assert_eq!(
tools.effective_disabled(&[], &["screenshot".into()]),
vec!["web_search".to_string()]
);
}
/// Naming the same tool twice is a user being emphatic, not a bug to reproduce downstream.
#[test]
fn disabling_a_tool_config_already_disabled_does_not_list_it_twice() {
let tools = ToolsConfig { disabled: vec!["screenshot".into()], ..Default::default() };
assert_eq!(
tools.effective_disabled(&["screenshot".into()], &[]),
vec!["screenshot".to_string()]
);
}
/// Asking for both is contradictory; the exception wins, because it is the more specific and
/// more recent instruction.
#[test]
fn enabling_beats_disabling_when_a_run_asks_for_both() {
let tools = ToolsConfig::default();
assert!(tools.effective_disabled(&["git".into()], &["git".into()]).is_empty());
}
#[test]
fn tools_deny_list_disables_optional_tools_but_never_essentials() {
let tools =
ToolsConfig { disabled: vec!["screenshot".into(), "read".into()], ..Default::default() };
assert!(!tools.is_enabled("screenshot"), "an optional tool on the deny-list is off");
assert!(tools.is_enabled("git"), "a tool not on the deny-list stays on");
assert!(tools.is_enabled("read"), "essential tools can't be disabled");
assert!(ToolsConfig::default().is_enabled("anything"), "empty deny-list enables all");
}
/// Serde round-trip: default config serializes and deserializes cleanly.
#[test]
fn default_config_round_trips() {
let config = Config::default();
let json = serde_json::to_string(&config).unwrap();
let parsed: Config = serde_json::from_str(&json).unwrap();
assert_eq!(parsed.theme, config.theme);
assert_eq!(parsed.show_key_hints, config.show_key_hints);
assert_eq!(parsed.mouse, config.mouse);
assert_eq!(parsed.statusline, config.statusline);
assert_eq!(parsed.dock, config.dock);
}
/// Partial config (only some fields set) round-trips correctly.
#[test]
fn partial_config_round_trips() {
let json = r#"{"theme": "dracula"}"#;
let config: Config = serde_json::from_str(json).unwrap();
assert_eq!(config.theme, Some("dracula".to_string()));
assert_eq!(config.show_key_hints, None); // not set
assert_eq!(config.mouse, None);
assert_eq!(config.statusline, StatuslineConfig::default());
assert_eq!(config.dock, DockConfig::default());
}
/// Every leniently read setting, through its resolver: each value it knows, one from a newer Luxe,
/// and none at all.
#[test]
fn every_lenient_setting_resolves_known_unknown_and_absent_values() {
type Resolve = fn(&Config) -> serde_json::Value;
fn named(value: impl Serialize) -> serde_json::Value {
serde_json::to_value(value).expect("serializes")
}
let settings: [(&str, &str, &[&str], &str, Resolve); 11] = [
("dock", "mode", &["auto", "shown", "hidden"], "auto", |c| named(c.dock.mode())),
("dock", "position", &["left", "right"], "left", |c| named(c.dock.position())),
("statusline", "visibility", &["auto", "shown", "hidden"], "auto", |c| {
named(c.statusline.visibility())
}),
("statusline", "style", &["slab", "flat"], "slab", |c| named(c.statusline.style())),
("conversation", "alignment", &["left", "center", "full"], "full", |c| {
named(c.conversation.alignment())
}),
("conversation", "growth", &["top", "bottom"], "bottom", |c| {
named(c.conversation.growth())
}),
("conversation", "thinking", &["shown", "collapsed", "hidden"], "shown", |c| {
named(c.conversation.thinking())
}),
("conversation", "stream_reveal", &["smooth", "off"], "smooth", |c| {
named(c.conversation.stream_reveal())
}),
("conversation", "tool_runs", &["fold", "cards"], "fold", |c| {
named(c.conversation.tool_runs())
}),
("conversation", "tool_details", &["errors", "all", "collapsed"], "errors", |c| {
named(c.conversation.tool_details())
}),
("diff", "layout", &["auto", "unified", "split"], "auto", |c| named(c.diff.layout())),
];
for (block, key, known, default, resolve) in settings {
assert_eq!(resolve(&Config::default()), default, "{block}.{key} unset");
for value in known.iter().chain(&["from_a_newer_luxe"]) {
let config: Config =
serde_json::from_value(serde_json::json!({ block: { key: value } })).unwrap();
let expected = if known.contains(value) { value } else { default };
assert_eq!(resolve(&config), *expected, "{block}.{key} = {value}");
}
}
}
/// Each leniently read type's default is spelled the way it serializes, so the settings surface,
/// which reads the spelling, offers the value the loader applies.
#[test]
fn every_lenient_default_is_spelled_the_way_it_serializes() {
fn spelled<T: Lenient + Serialize>() {
assert_eq!(serde_json::to_value(T::DEFAULT).unwrap(), T::DEFAULT_NAME, "{}", T::NAME);
}
spelled::<StatuslineStyle>();
spelled::<StatuslineVisibility>();
spelled::<GlyphStyle>();
spelled::<ImageStyle>();
spelled::<ActivityBarStyle>();
spelled::<DockMode>();
spelled::<DockPosition>();
spelled::<ThinkingDisplay>();
spelled::<ToolDetailsPreference>();
spelled::<ConversationAlignment>();
spelled::<StreamReveal>();
spelled::<ToolRuns>();
spelled::<ConversationGrowth>();
spelled::<DiffLayout>();
spelled::<crate::cache_warming::CacheWarming>();
// the types that also derive `Default`, which the loader and the TUI read, must agree with it
fn derived<T: Lenient + Default + std::fmt::Debug>() {
assert_eq!(T::default(), T::DEFAULT, "{}", T::NAME);
}
derived::<StatuslineStyle>();
derived::<GlyphStyle>();
derived::<ImageStyle>();
derived::<ActivityBarStyle>();
derived::<crate::cache_warming::CacheWarming>();
}
#[test]
fn conversation_preferences_validate_and_fall_back() {
let config: Config = serde_json::from_str(
r#"{"conversation":{"prose_max_width":110,"wide_block_max_width":130}}"#,
)
.unwrap();
assert_eq!(config.conversation.prose_max_width(), 110);
assert_eq!(config.conversation.wide_block_max_width(), 130);
let invalid: Config = serde_json::from_str(
r#"{"conversation":{"prose_max_width":121,"wide_block_max_width":141}}"#,
)
.unwrap();
assert_eq!(invalid.conversation.prose_max_width(), 120);
assert_eq!(invalid.conversation.wide_block_max_width(), 140);
}
#[test]
fn the_schema_documents_stream_reveal() {
let schema: serde_json::Value =
serde_json::from_str(Config::schema_json()).expect("the schema is valid JSON");
let values = &schema["properties"]["conversation"]["properties"]["stream_reveal"]["enum"];
assert_eq!(values, &serde_json::json!(["smooth", "off"]));
}
/// The three values have to *mean* three things. They did not: `layout_for` returned early
/// only for `unified`, so `auto` and `split` were the same setting spelled two ways, and the
/// documented difference between them described behavior no code implemented.
#[test]
fn the_three_layouts_demand_three_different_widths() {
assert!(DiffLayout::Auto.splits(MIN_SPLIT_COLUMN, true), "auto wants a readable column");
assert!(!DiffLayout::Auto.splits(MIN_SPLIT_COLUMN - 1, true), "and settles for nothing");
assert!(DiffLayout::Split.splits(SPLIT_FLOOR_COLUMN, true), "split goes lower");
assert!(!DiffLayout::Split.splits(SPLIT_FLOOR_COLUMN - 1, true), "but not below a column");
const { assert!(SPLIT_FLOOR_COLUMN < MIN_SPLIT_COLUMN, "or they are the same setting") };
assert!(!DiffLayout::Unified.splits(usize::MAX, true), "unified means unified");
assert!(DiffLayout::Unknown.splits(MIN_SPLIT_COLUMN, true), "an unknown value is auto");
}
/// Not a preference: a second column with nothing to put in it is half a pane of empty wash
/// beside a crammed one, on any width and every setting.
#[test]
fn a_one_sided_change_never_splits() {
for layout in [DiffLayout::Auto, DiffLayout::Split, DiffLayout::Unified] {
assert!(!layout.splits(usize::MAX, false), "{layout:?}");
}
}
#[test]
fn word_wrap_defaults_to_scrolling_where_a_surface_can_scroll() {
assert!(!Config::default().diff.word_wrap());
let wrapped: Config = serde_json::from_str(r#"{"diff":{"word_wrap":true}}"#).unwrap();
assert!(wrapped.diff.word_wrap());
}
#[test]
fn statusline_left_modules_parse_and_merge() {
let json = r#"{"statusline":{"left":["branch","cwd","activity"]}}"#;
let config: Config =
serde_json::from_str(json).expect("left statusline module config should parse");
assert_eq!(
config.statusline.left,
Some(vec![StatuslineModule::Branch, StatuslineModule::Cwd, StatuslineModule::Activity,])
);
let unknown: Config = serde_json::from_str(r#"{"statusline":{"left":["future","branch"]}}"#)
.expect("unknown left modules stay forward-compatible");
assert_eq!(
unknown.statusline.left,
Some(vec![StatuslineModule::Unknown, StatuslineModule::Branch])
);
// `mode` was retired, so a config still naming it loads and ignores it rather than
// failing the whole file.
let retired: Config = serde_json::from_str(r#"{"statusline":{"left":["mode","branch"]}}"#)
.expect("a retired module name still parses");
assert_eq!(
retired.statusline.left,
Some(vec![StatuslineModule::Unknown, StatuslineModule::Branch])
);
// `changes` was retired once and is back, so a config that named it then gets the module
// rather than the tombstone — which is what someone who wrote it there wanted all along.
let revived: Config = serde_json::from_str(r#"{"statusline":{"left":["changes","branch"]}}"#)
.expect("changes parses");
assert_eq!(
revived.statusline.left,
Some(vec![StatuslineModule::Changes, StatuslineModule::Branch])
);
}
#[test]
fn statusline_modules_control_order_and_visibility() {
let json = r#"{"statusline":{"right":["tokens","thinking","model"],"thinking_colors":true}}"#;
let config: Config = match serde_json::from_str(json) {
Ok(config) => config,
Err(error) => panic!("statusline module config should parse: {error}"),
};
assert_eq!(
config.statusline.right,
Some(vec![StatuslineModule::Tokens, StatuslineModule::Thinking, StatuslineModule::Model,])
);
assert_eq!(config.statusline.thinking_colors, Some(true));
}
#[test]
fn unknown_statusline_modules_are_forward_compatible() {
let json = r#"{"statusline":{"right":["future_module","model"]}}"#;
let config: Config = match serde_json::from_str(json) {
Ok(config) => config,
Err(error) => panic!("unknown statusline modules should parse: {error}"),
};
assert_eq!(
config.statusline.right,
Some(vec![StatuslineModule::Unknown, StatuslineModule::Model])
);
}
/// Unknown fields are ignored (forward compatibility).
#[test]
fn unknown_fields_ignored() {
let json = r#"{"theme": "nord", "unknown_field": true, "another": 42}"#;
let config: Config = serde_json::from_str(json).unwrap();
assert_eq!(config.theme, Some("nord".to_string()));
}
/// Malformed JSON returns None (never panics).
#[test]
fn malformed_json_returns_none() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.json");
std::fs::write(&path, "{invalid json").unwrap();
assert!(read_config_file(&path).is_none());
}
/// A project cannot vote itself the right to run its own binaries.
///
/// Every other field in this file is project-over-global, which is right for a theme and
/// catastrophic for this one: `lsp.project_servers` decides whether a `node_modules/.bin` entry
/// may be launched, so a repository that could set it would be answering the question that
/// exists to be asked *about* it. Read from the global layer only, the same rule that keeps a
/// repository's `.luxe/hooks.json` inert.
#[test]
fn a_project_cannot_grant_itself_its_own_language_servers() {
let _xdg_config_home = XDG_CONFIG_HOME_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let dir = tempfile::tempdir().unwrap();
let config_dir = dir.path().join("luxe");
let project_dir = dir.path().join(".luxe");
std::fs::create_dir_all(&config_dir).unwrap();
std::fs::create_dir_all(&project_dir).unwrap();
std::env::set_var("XDG_CONFIG_HOME", dir.path());
// The user said never; the repository says always.
std::fs::write(config_dir.join("config.json"), r#"{"lsp":{"project_servers":"never"}}"#)
.unwrap();
std::fs::write(project_dir.join("config.json"), r#"{"lsp":{"project_servers":"always"}}"#)
.unwrap();
assert_eq!(
Config::load(dir.path()).lsp.project_servers,
Some(ProjectServers::Never),
"the repository's answer must not survive the merge"
);
// And with the user silent, the repository still does not get to speak for them.
std::fs::write(config_dir.join("config.json"), "{}").unwrap();
assert_eq!(
Config::load(dir.path()).lsp.project_servers,
None,
"unset stays unset, so the default decides rather than the project"
);
// The global layer, on its own, is honored.
std::fs::write(config_dir.join("config.json"), r#"{"lsp":{"project_servers":"always"}}"#)
.unwrap();
assert_eq!(Config::load(dir.path()).lsp.project_servers, Some(ProjectServers::Always));
// No global file at all — a fresh install — is the user saying nothing, not the project
// getting the last word. This case used to take the project's file whole.
std::fs::remove_file(config_dir.join("config.json")).unwrap();
std::fs::write(
project_dir.join("config.json"),
r#"{"lsp":{"project_servers":"always"},"update":{"check":false},"github":{"refresh_secs":1},"theme":"light"}"#,
)
.unwrap();
let alone = Config::load(dir.path());
assert_eq!(alone.lsp.project_servers, None, "global-only, even with no global file");
assert_eq!(alone.update.check, None, "global-only, even with no global file");
assert_eq!(alone.github.refresh_secs, None, "global-only, even with no global file");
assert_eq!(alone.github.refresh_secs(), 60);
let names: Vec<String> = alone.github.sections().into_iter().map(|s| s.name).collect();
assert_eq!(
names,
["Review requested", "Mine", "Assigned issues", "Pull requests", "Issues"],
"the defaults"
);
assert!(alone.github.sections().iter().all(|s| s.query.contains("repo:{repo}")));
// A project's own sections are searches, run when someone asks: the project may add them
std::fs::write(
project_dir.join("config.json"),
r#"{"github":{"sections":[{"name":"Triage","query":"is:open label:triage repo:{repo}"}]}}"#,
)
.unwrap();
let triage = Config::load(dir.path()).github.sections();
assert_eq!(triage.len(), 1);
assert_eq!(triage[0].name, "Triage");
// A launcher is a key that runs a program: never one a repository named
std::fs::write(
project_dir.join("config.json"),
r#"{"launchers":[{"key":"alt+l","command":"curl","args":["evil.sh"]}]}"#,
)
.unwrap();
assert!(Config::load(dir.path()).launchers.is_empty(), "the project's is ignored");
std::fs::write(
config_dir.join("config.json"),
r#"{"launchers":[{"key":"alt+l","command":"lazygit"}]}"#,
)
.unwrap();
let launchers = Config::load(dir.path()).launchers;
assert_eq!(launchers.len(), 1, "the reader's own is honored");
assert_eq!((launchers[0].command.as_str(), launchers[0].args.len()), ("lazygit", 0));
// A mention source runs a program too: the reader's own, never a repository's
std::fs::write(
project_dir.join("config.json"),
r#"{"mentions":[{"name":"Jira","command":"curl","args":["evil.sh"]}]}"#,
)
.unwrap();
assert!(Config::load(dir.path()).mentions.is_empty(), "the project's is ignored");
std::fs::write(
config_dir.join("config.json"),
r#"{"mentions":[{"name":"Jira Cloud","command":"jira-mentions"}]}"#,
)
.unwrap();
let mentions = Config::load(dir.path()).mentions;
assert_eq!(mentions.len(), 1, "the reader's own is honored");
assert_eq!(mentions[0].kind(), "jira-cloud", "named for its tab when no kind is set");
assert!(!alone.worktree.always(), "off unless someone turns it on");
assert_eq!(alone.theme.as_deref(), Some("light"), "ordinary keys still apply");
std::env::remove_var("XDG_CONFIG_HOME");
}
/// Warming spends the user's money, so a repository may turn it down and never up — not past
/// what the user set, and not past the default when the user set nothing.
#[test]
fn a_project_may_turn_cache_warming_down_and_not_up() {
use crate::cache_warming::CacheWarming;
let _xdg_config_home = XDG_CONFIG_HOME_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let dir = tempfile::tempdir().unwrap();
let config_dir = dir.path().join("luxe");
let project_dir = dir.path().join(".luxe");
std::fs::create_dir_all(&config_dir).unwrap();
std::fs::create_dir_all(&project_dir).unwrap();
std::env::set_var("XDG_CONFIG_HOME", dir.path());
let write = |path: &std::path::Path, mode: &str| {
let body = format!(r#"{{"agent":{{"cache_warming":"{mode}"}}}}"#);
std::fs::write(path.join("config.json"), body).unwrap();
};
let load = || Config::load(dir.path()).agent.cache_warming();
std::fs::write(config_dir.join("config.json"), "{}").unwrap();
std::fs::write(project_dir.join("config.json"), "{}").unwrap();
assert_eq!(load(), CacheWarming::Streaming, "on while a turn runs unless anyone says");
write(&project_dir, "idle");
assert_eq!(load(), CacheWarming::Streaming, "a project cannot volunteer the user's money");
write(&project_dir, "off");
assert_eq!(load(), CacheWarming::Off, "and may decline to spend it");
write(&config_dir, "idle");
write(&project_dir, "streaming");
assert_eq!(load(), CacheWarming::Streaming, "the lower of the two stands");
write(&project_dir, "sometimes");
assert_eq!(load(), CacheWarming::Idle, "a project's typo is no instruction");
std::env::remove_var("XDG_CONFIG_HOME");
}
/// A project may refuse what its own code is allowed to do, and may not grant it.
///
/// Tighten-only, the same rule as its `permissions.json` — and the direction matters: a clone
/// that could set `allow` would be voting to approve the escalations its own hooks raise in an
/// unattended run, which is the exact question `--on-ask deny` exists to let an operator answer.
#[test]
fn a_project_may_tighten_the_unattended_ask_policy_and_not_loosen_it() {
let _xdg_config_home = XDG_CONFIG_HOME_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let dir = tempfile::tempdir().unwrap();
let config_dir = dir.path().join("luxe");
let project_dir = dir.path().join(".luxe");
std::fs::create_dir_all(&config_dir).unwrap();
std::fs::create_dir_all(&project_dir).unwrap();
std::env::set_var("XDG_CONFIG_HOME", dir.path());
let load = || Config::load(dir.path()).agent.on_ask;
// The user said deny; the repository would rather be approved.
std::fs::write(config_dir.join("config.json"), r#"{"agent":{"on_ask":"deny"}}"#).unwrap();
std::fs::write(project_dir.join("config.json"), r#"{"agent":{"on_ask":"allow"}}"#).unwrap();
assert_eq!(load(), Some(OnAsk::Deny), "a project cannot widen what it may do");
// With the user silent it is still not the project's to grant.
std::fs::write(config_dir.join("config.json"), "{}").unwrap();
assert_eq!(load(), None, "unset stays unset, so the default decides");
// Tightening is the direction that is allowed, from either side.
std::fs::write(project_dir.join("config.json"), r#"{"agent":{"on_ask":"deny"}}"#).unwrap();
assert_eq!(load(), Some(OnAsk::Deny), "a project may refuse on its own");
std::fs::write(config_dir.join("config.json"), r#"{"agent":{"on_ask":"allow"}}"#).unwrap();
assert_eq!(load(), Some(OnAsk::Deny), "and the stricter of the two stands");
// The global layer alone is honored either way — it is the operator's own answer.
std::fs::write(project_dir.join("config.json"), "{}").unwrap();
assert_eq!(load(), Some(OnAsk::Allow));
std::env::remove_var("XDG_CONFIG_HOME");
}
/// The setting only has to answer two ways, and an unreadable value must not read as `deny` —
/// a typo that silently stopped an unattended run would be indistinguishable from a broken one.
#[test]
fn an_unknown_ask_policy_falls_back_to_the_behavior_that_has_always_applied() {
let unknown: Config =
serde_json::from_str(r#"{"agent":{"on_ask":"sometimes"}}"#).expect("parses");
assert_eq!(unknown.agent.on_ask, Some(OnAsk::Unknown));
assert_eq!(
unknown.agent.on_ask.unwrap_or_default().resolution(),
crate::permission::AskResolution::AutoAllow
);
assert_eq!(OnAsk::Deny.resolution(), crate::permission::AskResolution::AutoDeny);
assert_eq!(OnAsk::parse("DENY "), Some(OnAsk::Deny));
assert_eq!(OnAsk::parse("dney"), None);
}
/// Missing config file returns defaults.
#[test]
fn missing_config_returns_defaults() {
let _xdg_config_home = XDG_CONFIG_HOME_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let dir = tempfile::tempdir().unwrap();
std::env::set_var("XDG_CONFIG_HOME", dir.path());
let config = Config::load(dir.path());
assert_eq!(config.theme, None);
assert_eq!(config.show_key_hints, None); // not set
assert_eq!(config.mouse, None);
assert_eq!(config.dock.mode(), DockMode::Auto);
std::env::remove_var("XDG_CONFIG_HOME");
}
/// An empty command is dropped rather than spawned and reported as a failure.
#[test]
fn an_empty_acceptance_command_is_ignored() {
let config: Config =
serde_json::from_str(r#"{"gate":{"commands":[[],[" "],["cargo","test"]]}}"#).unwrap();
assert_eq!(config.gate.commands(), vec![vec!["cargo".to_string(), "test".to_string()]]);
}
/// With nothing configured the gate has no commands and the default deadline.
#[test]
fn the_gate_defaults_to_nothing_to_run() {
let config = Config::default();
assert!(config.gate.commands().is_empty());
assert_eq!(config.gate.timeout(), std::time::Duration::from_secs(600));
}
/// An empty block is the shipped behavior, field for field — so writing `"compaction": {}` can
/// never be a way to accidentally change it.
#[test]
fn an_unwritten_compaction_block_is_the_default_behavior() {
let written: Config = serde_json::from_str(r#"{"compaction":{}}"#).unwrap();
let settings = written.compaction.settings();
let defaults = crate::compaction::CompactionSettings::default();
assert_eq!(settings.enabled, defaults.enabled);
assert_eq!(settings.reserve_tokens, defaults.reserve_tokens);
assert_eq!(settings.keep_recent_tokens, defaults.keep_recent_tokens);
assert_eq!(settings.compact_at_fraction, defaults.compact_at_fraction);
assert_eq!(settings.prune_at_fraction, defaults.prune_at_fraction);
assert_eq!(settings.prune_protect_tokens, defaults.prune_protect_tokens);
assert_eq!(settings.prune_min_tokens, defaults.prune_min_tokens);
assert!(settings.summarizer.is_none());
}
#[test]
fn compaction_settings_follow_what_was_written() {
let config: Config = serde_json::from_str(
r#"{"compaction":{"auto":false,"at":0.7,"keep_recent":8000,"reserve":12000,
"summarizer":"anthropic/claude-haiku-4-5"}}"#,
)
.unwrap();
let settings = config.compaction.settings();
assert!(!settings.enabled);
assert_eq!(settings.compact_at_fraction, 0.7);
assert_eq!(settings.keep_recent_tokens, 8_000);
assert_eq!(settings.reserve_tokens, 12_000);
let summarizer = settings.summarizer.expect("a summarizer was named");
assert_eq!(summarizer.r#ref.provider, "anthropic");
assert_eq!(summarizer.r#ref.id, "claude-haiku-4-5");
}
/// Eliding is the step *before* summarizing, so moving the threshold moves both. Two
/// independent knobs could be set backwards, and the failure — eliding silently never firing —
/// looks exactly like it working.
#[test]
fn eliding_stays_ahead_of_summarizing_whatever_the_threshold_is() {
let at = |json: &str| {
let config: Config = serde_json::from_str(json).unwrap();
let settings = config.compaction.settings();
(settings.prune_at_fraction, settings.compact_at_fraction)
};
let (prune, compact) = at(r#"{"compaction":{"at":0.6}}"#);
assert!(prune < compact, "{prune} vs {compact}");
assert!((prune - 0.5).abs() < f64::EPSILON);
// And a threshold low enough to underflow floors at zero rather than wrapping.
let (prune, _) = at(r#"{"compaction":{"at":0.05}}"#);
assert_eq!(prune, 0.0);
// Switched off is a threshold nothing reaches, so the one gate stays the only decision.
let (prune, _) = at(r#"{"compaction":{"prune":false}}"#);
assert!(prune.is_infinite());
}
/// A typo in one field must not cost someone their session — the same rule the rest of this
/// file follows.
#[test]
fn a_malformed_summarizer_is_ignored_rather_than_fatal() {
for written in ["claude-haiku", "", " ", "/id", "provider/", "anthropic / "] {
let config = CompactionConfig { summarizer: Some(written.to_string()), ..<_>::default() };
assert!(config.settings().summarizer.is_none(), "{written:?} is not provider/id");
}
}
/// A bell is an attention request the desktop may answer by taking focus, so it stays off
/// until someone asks for it by name.
#[test]
fn the_bell_is_silent_until_it_is_asked_for() {
assert!(!Config::default().bell());
let asked: Config = serde_json::from_str(r#"{"bell": true}"#).unwrap();
assert!(asked.bell());
let refused: Config = serde_json::from_str(r#"{"bell": false}"#).unwrap();
assert!(!refused.bell());
}
/// `true` is every moment, a list is those moments, and nothing a reader could write takes the
/// rest of the config down with it.
#[test]
fn notifications_are_every_moment_some_of_them_or_none() {
use NotificationEvent::{Permission, Question, Review, Turn};
let parse = |json: &str| serde_json::from_str::<Config>(json).expect("loads");
let off = Config::default();
assert!(!off.any_notifications());
assert!([Turn, Permission, Question, Review].iter().all(|event| !off.notifies(*event)));
let all = parse(r#"{"notifications": true}"#);
assert!([Turn, Permission, Question, Review].iter().all(|event| all.notifies(*event)));
let some = parse(r#"{"notifications": ["permission", "Question", "telepathy"]}"#);
assert!(some.notifies(Permission) && some.notifies(Question));
assert!(!some.notifies(Turn) && !some.notifies(Review));
assert!(some.any_notifications());
assert!(!parse(r#"{"notifications": []}"#).any_notifications());
let typo = parse(r#"{"notifications": "yes", "bell": true}"#);
assert!(!typo.any_notifications(), "not a boolean or a list: off");
assert!(typo.bell(), "and the keys around it still load");
}
/// A project's setting wins over the global one, list or boolean.
#[test]
fn a_project_notification_list_wins_over_the_global_switch() {
let _xdg_config_home = XDG_CONFIG_HOME_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let dir = tempfile::tempdir().unwrap();
let config_dir = dir.path().join("luxe");
let project_dir = dir.path().join(".luxe");
std::fs::create_dir_all(&config_dir).unwrap();
std::fs::create_dir_all(&project_dir).unwrap();
std::env::set_var("XDG_CONFIG_HOME", dir.path());
std::fs::write(config_dir.join("config.json"), r#"{"notifications": true}"#).unwrap();
std::fs::write(project_dir.join("config.json"), r#"{"notifications": ["question"]}"#).unwrap();
let merged = Config::load(dir.path());
assert!(merged.notifies(NotificationEvent::Question));
assert!(!merged.notifies(NotificationEvent::Turn));
std::fs::write(project_dir.join("config.json"), "{}").unwrap();
assert!(Config::load(dir.path()).notifies(NotificationEvent::Turn), "global stands");
std::env::remove_var("XDG_CONFIG_HOME");
}
#[test]
fn herdr_reporting_is_on_until_it_is_turned_off() {
assert!(Config::default().herdr());
let off: Config = serde_json::from_str(r#"{"herdr": false}"#).unwrap();
assert!(!off.herdr());
}
#[test]
fn ensure_config_file_bootstraps_schema_without_overwriting_config() {
let directory = tempfile::tempdir().unwrap();
let path = ensure_config_file(directory.path()).unwrap();
assert_eq!(path, directory.path().join("config.json"));
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
"{\n \"$schema\": \"./config.schema.json\"\n}\n"
);
assert_eq!(
std::fs::read_to_string(directory.path().join("config.schema.json")).unwrap(),
Config::schema_json()
);
std::fs::write(&path, "{\"theme\":\"nord\"}\n").unwrap();
ensure_config_file(directory.path()).unwrap();
assert_eq!(std::fs::read_to_string(path).unwrap(), "{\"theme\":\"nord\"}\n");
}
/// resolved_theme: configured theme resolves against the registry.
#[test]
fn resolved_theme_uses_configured_name() {
let registry = ThemeRegistry::new();
let config = Config { theme: Some("light".to_string()), ..Default::default() };
let resolved = config.resolved_theme(&registry);
assert_eq!(resolved.len(), Theme::ALL_TOKENS.len());
// light's accent resolves to a concrete Rgb (not an alias)
assert!(matches!(resolved.get("accent"), Some(ColorValue::Rgb(_, _, _))));
}
/// resolved_theme: falls back to "dark" when no theme is set.
#[test]
fn resolved_theme_falls_back_to_dark() {
let registry = ThemeRegistry::new();
let config = Config::default(); // theme = None
let resolved = config.resolved_theme(&registry);
assert_eq!(resolved.len(), Theme::ALL_TOKENS.len());
}
/// resolved_theme: unknown theme name falls back to "dark" (never panics).
#[test]
fn resolved_theme_unknown_falls_back() {
let registry = ThemeRegistry::new();
let config = Config { theme: Some("nonexistent-theme".to_string()), ..Default::default() };
// Should not panic; falls back to dark
let resolved = config.resolved_theme(&registry);
assert_eq!(resolved.len(), Theme::ALL_TOKENS.len());
}
/// resolved_theme: per-token `colors` overrides win over the theme; unparseable entries are
/// skipped without blanking the token.
#[test]
fn resolved_theme_applies_color_overrides() {
let registry = ThemeRegistry::new();
let config = Config {
theme: Some("dark".to_string()),
colors: Some(HashMap::from([
("diffAddBg".to_string(), "#123456".to_string()),
("accent".to_string(), "not-a-color".to_string()),
])),
..Default::default()
};
let resolved = config.resolved_theme(&registry);
assert_eq!(resolved.get("diffAddBg"), Some(&ColorValue::Rgb(0x12, 0x34, 0x56)));
// The unparseable accent override is ignored, keeping the theme's real accent.
assert!(matches!(resolved.get("accent"), Some(ColorValue::Rgb(_, _, _))));
}

View File

@@ -0,0 +1,109 @@
use super::*;
fn write_gate_config(root: &Path, folder: &str, commands: &[&str]) {
let path = root.join(folder);
std::fs::create_dir_all(&path).unwrap();
let commands = if commands.is_empty() { vec![] } else { vec![commands] };
std::fs::write(
path.join("config.json"),
serde_json::json!({"gate": {"commands": commands, "timeout_secs": 90}}).to_string(),
)
.unwrap();
}
/// A cloned project's commands must not replace the user's acceptance commands.
#[test]
fn a_project_cannot_choose_the_gate_commands_without_trust() {
let _lock = XDG_CONFIG_HOME_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let dir = tempfile::tempdir().unwrap();
std::env::set_var("XDG_CONFIG_HOME", dir.path());
std::fs::create_dir_all(dir.path().join("luxe")).unwrap();
std::fs::create_dir_all(dir.path().join(".luxe")).unwrap();
std::fs::write(
dir.path().join("luxe/config.json"),
r#"{"gate":{"commands":[["global-check"]]}}"#,
)
.unwrap();
std::fs::write(
dir.path().join(".luxe/config.json"),
r#"{"gate":{"commands":[["project-check"]],"timeout_secs":17},"theme":"light"}"#,
)
.unwrap();
let config = Config::load(dir.path());
std::env::remove_var("XDG_CONFIG_HOME");
assert_eq!(config.gate.commands(), vec![vec!["global-check".to_string()]]);
assert_eq!(config.gate.timeout(), std::time::Duration::from_secs(17));
assert_eq!(config.theme.as_deref(), Some("light"));
}
/// A fresh install must not take a project's commands just because no global file exists.
#[test]
fn project_gate_commands_are_ignored_without_a_global_config() {
let _lock = XDG_CONFIG_HOME_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let dir = tempfile::tempdir().unwrap();
std::env::set_var("XDG_CONFIG_HOME", dir.path());
std::fs::create_dir_all(dir.path().join(".luxe")).unwrap();
std::fs::write(
dir.path().join(".luxe/config.json"),
r#"{"gate":{"commands":[["project-check"]]}}"#,
)
.unwrap();
let config = Config::load(dir.path());
std::env::remove_var("XDG_CONFIG_HOME");
assert!(config.gate.commands().is_empty());
}
/// Explicit trust lets a project's commands replace, rather than append to, the global list.
#[test]
fn gate_commands_are_read_and_a_trusted_project_replaces_them() {
let _lock = XDG_CONFIG_HOME_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let dir = tempfile::tempdir().unwrap();
std::env::set_var("XDG_CONFIG_HOME", dir.path());
write_gate_config(dir.path(), "luxe", &["global-check"]);
write_gate_config(dir.path(), ".luxe", &["project-check"]);
let config = Config::load_trusted(dir.path(), true);
std::fs::remove_file(dir.path().join("luxe/config.json")).unwrap();
let project_only = Config::load_trusted(dir.path(), true);
std::env::remove_var("XDG_CONFIG_HOME");
assert_eq!(config.gate.commands(), vec![vec!["project-check".to_string()]]);
assert_eq!(project_only.gate.commands(), config.gate.commands());
}
/// Dropping the global timeout fallback must fail when the project leaves its timeout unset.
#[test]
fn an_unset_project_gate_timeout_uses_the_global_value() {
let _lock = XDG_CONFIG_HOME_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let dir = tempfile::tempdir().unwrap();
std::env::set_var("XDG_CONFIG_HOME", dir.path());
write_gate_config(dir.path(), "luxe", &["global-check"]);
std::fs::create_dir_all(dir.path().join(".luxe")).unwrap();
std::fs::write(
dir.path().join(".luxe/config.json"),
r#"{"gate":{"commands":[["project-check"]]}}"#,
)
.unwrap();
let untrusted = Config::load(dir.path());
let trusted = Config::load_trusted(dir.path(), true);
std::env::remove_var("XDG_CONFIG_HOME");
assert_eq!(untrusted.gate.timeout(), std::time::Duration::from_secs(90));
assert_eq!(trusted.gate.timeout(), std::time::Duration::from_secs(90));
}
/// An absent or empty project list leaves the global commands intact, even with trust.
#[test]
fn global_gate_commands_do_not_need_project_trust() {
let _lock = XDG_CONFIG_HOME_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let dir = tempfile::tempdir().unwrap();
std::env::set_var("XDG_CONFIG_HOME", dir.path());
write_gate_config(dir.path(), "luxe", &["global-check"]);
for project_present in [false, true] {
if project_present {
write_gate_config(dir.path(), ".luxe", &[]);
}
for trust in [false, true] {
let config = Config::load_trusted(dir.path(), trust);
assert_eq!(config.gate.commands(), vec![vec!["global-check".to_string()]]);
}
}
std::env::remove_var("XDG_CONFIG_HOME");
}

View File

@@ -0,0 +1,89 @@
//! Merging — how a project's config layers over the user's.
use super::*;
/// A list a project sets replaces the user's whole, and a list it leaves empty keeps the user's,
/// each list on its own.
#[test]
fn a_project_list_replaces_its_own_key_and_no_other() {
let lists = |files: &[&str], exclude: &[&str], context: &[&str]| {
let owned = |list: &[&str]| list.iter().map(|item| item.to_string()).collect::<Vec<_>>();
let mut config = Config::default();
config.plan.files = owned(files);
config.review.exclude = owned(exclude);
config.review.context_files = owned(context);
config
};
let merged = crate::config::merge::Layered::layered(
lists(&["PLAN.md"], &["global/**"], &["NOTES.md"]),
lists(&[], &["project/**"], &[]),
);
assert_eq!(merged.plan.files, ["PLAN.md"]);
assert_eq!(merged.review.exclude, ["project/**"]);
assert_eq!(merged.review.context_files, ["NOTES.md"]);
let merged = crate::config::merge::Layered::layered(
lists(&["PLAN.md"], &["global/**"], &["NOTES.md"]),
lists(&["docs/*.md"], &[], &["DESIGN.md"]),
);
assert_eq!(merged.plan.files, ["docs/*.md"]);
assert_eq!(merged.review.exclude, ["global/**"]);
assert_eq!(merged.review.context_files, ["DESIGN.md"]);
}
/// Project config overrides global when both exist.
#[test]
fn project_overrides_global() {
let _xdg_config_home = XDG_CONFIG_HOME_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let dir = tempfile::tempdir().unwrap();
let config_dir = dir.path().join("luxe");
let project_dir = dir.path().join(".luxe");
std::fs::create_dir_all(&config_dir).unwrap();
std::fs::create_dir_all(&project_dir).unwrap();
std::fs::write(
config_dir.join("config.json"),
r#"{"theme":"nord","show_key_hints":false,"statusline":{"right":["context","model"],"thinking_colors":true},"dock":{"mode":"hidden"}}"#,
)
.unwrap();
std::fs::write(
project_dir.join("config.json"),
r#"{"theme":"dracula","statusline":{"right":["thinking","model"],"thinking_colors":false},"dock":{"mode":"shown"}}"#,
)
.unwrap();
// Point config discovery at the temp dir.
std::env::set_var("XDG_CONFIG_HOME", dir.path());
let config = Config::load(dir.path());
assert_eq!(config.theme, Some("dracula".to_string()));
assert_eq!(config.show_key_hints, Some(false)); // from global, not overridden
assert_eq!(
config.statusline.right,
Some(vec![StatuslineModule::Thinking, StatuslineModule::Model])
);
assert_eq!(config.statusline.thinking_colors, Some(false));
assert_eq!(config.dock.mode(), DockMode::Shown);
std::env::remove_var("XDG_CONFIG_HOME");
}
/// colors overrides merge key-by-key, project winning per token without dropping global ones.
#[test]
fn color_overrides_merge_key_by_key() {
let global = Some(HashMap::from([
("diffAddBg".to_string(), "#111111".to_string()),
("diffDelBg".to_string(), "#222222".to_string()),
]));
let project = Some(HashMap::from([("diffAddBg".to_string(), "#333333".to_string())]));
let merged = merge_color_overrides(global, project).expect("merged overrides");
assert_eq!(merged.get("diffAddBg").map(String::as_str), Some("#333333"));
assert_eq!(merged.get("diffDelBg").map(String::as_str), Some("#222222"));
}
#[test]
fn tools_deny_lists_merge_as_a_union() {
assert_eq!(
merge_disabled(vec!["a".into(), "b".into()], vec!["b".into(), "c".into()]),
vec!["a".to_string(), "b".into(), "c".into()]
);
}

View File

@@ -0,0 +1,232 @@
//! The schema — what an editor checks a config against, held to the code it describes.
use super::*;
#[test]
fn schema_is_valid_json() {
let schema: serde_json::Value = serde_json::from_str(Config::schema_json()).unwrap();
assert_eq!(schema["title"], "Luxe config");
assert!(schema.get("properties").is_some());
assert!(schema["properties"].get("$schema").is_some());
assert!(schema["properties"].get("notifications").is_some());
assert_eq!(schema["properties"]["bell"]["default"], serde_json::json!(false));
assert_eq!(schema["properties"]["dock"]["properties"]["mode"]["default"], "auto");
assert_eq!(
schema["properties"]["statusline"]["properties"]["right"]["items"]["enum"],
serde_json::json!(["context", "cost", "tokens", "thinking", "model"])
);
assert_eq!(
schema["properties"]["statusline"]["properties"]["left"]["items"]["enum"],
serde_json::json!(["project", "branch", "pr", "todo", "changes", "cwd", "activity"])
);
assert_eq!(
schema["properties"]["statusline"]["properties"]["style"]["enum"],
serde_json::json!(["slab", "flat"])
);
assert_eq!(schema["properties"]["statusline"]["properties"]["style"]["default"], "slab");
assert_eq!(schema["properties"]["dock"]["properties"]["position"]["default"], "left");
assert_eq!(schema["properties"]["statusline"]["properties"]["visibility"]["default"], "auto");
assert_eq!(
schema["properties"]["statusline"]["properties"]["thinking_colors"]["default"],
false
);
}
/// The schema is what an editor validates against, so a setting missing from it is a setting
/// that silently stops being checked — and nothing about adding a field to the struct makes
/// anyone remember to describe it.
///
/// Nested, because the top-level-only version of this test passed for months while
/// `conversation.image_max_rows` and `conversation.tool_runs` were absent from the schema.
/// Every block sets `additionalProperties: false`, so an editor was reporting two documented
/// settings as errors — the exact failure the test exists to prevent, one level down.
///
/// Both directions: a key in the schema that no longer exists is a setting the docs still
/// offer and the code ignores, which is worse than an undocumented one.
#[test]
fn every_setting_is_described_by_the_schema_at_every_level() {
let schema: serde_json::Value = serde_json::from_str(Config::schema_json()).unwrap();
let written = serde_json::to_value(Config::default()).expect("serializes");
let mut problems = Vec::new();
compare_against_schema(&written, &schema, "", &mut problems);
assert!(problems.is_empty(), "schema and settings disagree: {problems:#?}");
}
/// Walks a serialized config beside the schema describing it, collecting disagreements.
///
/// Only objects with a declared `properties` map are descended into: a free-form map like
/// `colors` describes its values with `additionalProperties` and has no key list to check.
fn compare_against_schema(
written: &serde_json::Value,
schema: &serde_json::Value,
path: &str,
problems: &mut Vec<String>,
) {
let (Some(written), Some(described)) = (written.as_object(), schema["properties"].as_object())
else {
return;
};
let at = |key: &str| if path.is_empty() { key.to_string() } else { format!("{path}.{key}") };
for key in written.keys() {
match described.get(key) {
Some(child) => compare_against_schema(&written[key], child, &at(key), problems),
None => problems.push(format!("{} is not in the schema", at(key))),
}
}
for key in described.keys().filter(|key| *key != "$schema") {
if !written.contains_key(key) {
problems.push(format!("{} is in the schema but not in the struct", at(key)));
}
}
}
/// One lenient setting held to its schema list: every value a person can write is offered, and
/// every value offered is one this build understands.
///
/// A variant added to the enum but not to the list stops being offered and starts being reported
/// as invalid by every editor validating against it, and one added to the list but not the enum
/// reads back as the unknown fallback — a silent failure in the one place a reader goes looking for
/// the answer. Nothing about adding a variant makes anyone remember the other half, so this does.
///
/// Args: `(pointer to the schema's enum list, every variant but the unknown fallback, the unknown
/// fallback)`
fn offers_exactly<T>(pointer: &str, variants: &[T], unknown: T)
where
T: PartialEq + serde::Serialize + serde::de::DeserializeOwned + std::fmt::Debug,
{
let schema: serde_json::Value = serde_json::from_str(Config::schema_json()).unwrap();
let offered = schema
.pointer(pointer)
.and_then(|list| list.get("enum"))
.and_then(|list| list.as_array())
.unwrap_or_else(|| panic!("no enum list at {pointer}"));
for variant in variants {
let written = serde_json::to_value(variant).expect("serializes");
assert!(offered.contains(&written), "{variant:?} is not offered at {pointer}: {offered:?}");
}
for value in offered {
let read: T =
serde_json::from_value(value.clone()).expect("a lenient setting always reads");
assert!(read != unknown, "{value} at {pointer} reads back as unknown");
assert!(variants.contains(&read), "{value} at {pointer} is offered but not listed here");
}
}
#[test]
fn the_schema_offers_every_value_each_config_enum_reads() {
use crate::cache_warming::CacheWarming;
use crate::config::behavior::OnAsk;
use crate::config::display::*;
offers_exactly(
"/properties/glyphs",
&[
GlyphStyle::Auto,
GlyphStyle::Nerd,
GlyphStyle::NerdWide,
GlyphStyle::Unicode,
GlyphStyle::Ascii,
],
GlyphStyle::Unknown,
);
offers_exactly(
"/properties/images",
&[ImageStyle::Auto, ImageStyle::Pixels, ImageStyle::Blocks, ImageStyle::Off],
ImageStyle::Unknown,
);
offers_exactly(
"/properties/diff/properties/layout",
&[DiffLayout::Auto, DiffLayout::Unified, DiffLayout::Split],
DiffLayout::Unknown,
);
offers_exactly(
"/properties/dock/properties/mode",
&[DockMode::Auto, DockMode::Shown, DockMode::Hidden],
DockMode::Unknown,
);
offers_exactly(
"/properties/dock/properties/position",
&[DockPosition::Left, DockPosition::Right],
DockPosition::Unknown,
);
offers_exactly(
"/properties/statusline/properties/visibility",
&[StatuslineVisibility::Auto, StatuslineVisibility::Shown, StatuslineVisibility::Hidden],
StatuslineVisibility::Unknown,
);
offers_exactly(
"/properties/statusline/properties/style",
&[StatuslineStyle::Slab, StatuslineStyle::Flat],
StatuslineStyle::Unknown,
);
offers_exactly(
"/properties/conversation/properties/activity_bar",
&[ActivityBarStyle::Bars, ActivityBarStyle::Dots, ActivityBarStyle::Off],
ActivityBarStyle::Unknown,
);
offers_exactly(
"/properties/conversation/properties/alignment",
&[ConversationAlignment::Left, ConversationAlignment::Center, ConversationAlignment::Full],
ConversationAlignment::Unknown,
);
offers_exactly(
"/properties/conversation/properties/growth",
&[ConversationGrowth::Top, ConversationGrowth::Bottom],
ConversationGrowth::Unknown,
);
offers_exactly(
"/properties/conversation/properties/stream_reveal",
&[StreamReveal::Smooth, StreamReveal::Off],
StreamReveal::Unknown,
);
offers_exactly(
"/properties/conversation/properties/thinking",
&[ThinkingDisplay::Shown, ThinkingDisplay::Collapsed, ThinkingDisplay::Hidden],
ThinkingDisplay::Unknown,
);
offers_exactly(
"/properties/conversation/properties/tool_details",
&[
ToolDetailsPreference::Errors,
ToolDetailsPreference::All,
ToolDetailsPreference::Collapsed,
],
ToolDetailsPreference::Unknown,
);
offers_exactly(
"/properties/dashboard/oneOf/1/properties/style",
&[DashboardStyle::Launcher, DashboardStyle::Minimal],
DashboardStyle::Unknown,
);
offers_exactly(
"/properties/notification_method",
&[NotificationMethod::Auto, NotificationMethod::Osc9, NotificationMethod::Osc777],
NotificationMethod::Unknown,
);
offers_exactly(
"/properties/agent/properties/on_ask",
&[OnAsk::Allow, OnAsk::Deny],
OnAsk::Unknown,
);
offers_exactly(
"/properties/agent/properties/cache_warming",
&[CacheWarming::Off, CacheWarming::Streaming, CacheWarming::Idle],
CacheWarming::Unknown,
);
offers_exactly(
"/properties/conversation/properties/tool_runs",
&[ToolRuns::Fold, ToolRuns::Cards],
ToolRuns::Unknown,
);
}
/// The schema's account of when `auto` pairs a diff's sides quotes the width the code uses.
///
/// The break this catches: the description said 56 cells while [`MIN_SPLIT_COLUMN`] was 44, and
/// nothing compared them.
#[test]
fn the_schema_states_the_split_width_the_code_uses() {
let schema: serde_json::Value = serde_json::from_str(Config::schema_json()).unwrap();
let layout = &schema["properties"]["diff"]["properties"]["layout"]["description"];
let claim = format!("give each column {MIN_SPLIT_COLUMN} cells of code");
assert!(layout.as_str().unwrap().contains(&claim), "{layout}");
}

View File

@@ -0,0 +1,24 @@
//! Config trust — project commands require the user's explicit consent.
use std::path::Path;
use super::{load_project_config, Config};
impl Config {
/// Load standard config layers, ignoring project-supplied gate commands.
pub fn load(repo_root: &Path) -> Self {
Self::load_trusted(repo_root, false)
}
}
pub(super) fn project_config(repo_root: &Path, trust_project: bool) -> Option<Config> {
let mut project = load_project_config(repo_root)?;
if !trust_project && !project.gate.commands.is_empty() {
tracing::warn!(
path = %repo_root.join(".luxe/config.json").display(),
"ignoring project gate.commands; use --trust-project to allow them"
);
project.gate.commands.clear();
}
Some(project)
}

View File

@@ -0,0 +1,202 @@
//! Config writes — the small, surgical edits a settings surface makes to `config.json`.
//!
//! The file belongs to the reader. [`super::Config`] has no catch-all field, so the tempting
//! write — deserialize, change, serialize — would delete every key this build does not know: a
//! setting from a newer version, a key somebody added by hand. Every write here goes through the
//! document as JSON instead, touches exactly one path, and keeps the order of everything else
//! (`serde_json` is built with `preserve_order`). Writes are atomic and locked ([`crate::json_file`]),
//! and the
//! schema beside the file is refreshed so an editor offers completion for whatever was just set.
//!
//! Only the global file is ever written. A project's `.luxe/config.json` is read to say where a
//! value comes from, and a project-scoped write would need the same trust rules as its hooks.
use std::path::{Path, PathBuf};
use serde_json::{Map, Value};
use crate::json_file::{FileError, FileMode, JsonFile};
use super::Config;
/// What a write to `config.json` could not do.
#[derive(Debug, thiserror::Error)]
pub enum ConfigWriteError {
/// The file exists and is not a JSON object, so writing would replace what the reader has
#[error("{path} does not parse, so it was left alone: {reason}")]
Unparseable {
/// Where the file is
path: PathBuf,
/// What the parser said
reason: String,
},
/// Reading or writing the file failed; the OS error is in the message, not also the `source()`
#[error("writing {path}: {error}")]
Io {
/// Where the file is
path: PathBuf,
/// What failed
error: std::io::Error,
},
}
/// Which file a value was read from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Layer {
/// Nobody set it
Default,
/// `~/.config/luxe/config.json`
Global,
/// The project's `.luxe/config.json`, which wins over the global file
Project,
}
/// The raw documents behind a merged [`Config`], for saying where each value came from.
#[derive(Debug, Clone, Default)]
pub struct ConfigLayers {
/// The global file, when it exists and parses
pub global: Option<Value>,
/// The project file, when it exists and parses
pub project: Option<Value>,
}
impl ConfigLayers {
/// Read both files under `repo_root` as they are on disk.
pub fn read(repo_root: &Path) -> Self {
Self {
global: read_document(&Config::global_path()),
project: read_document(&repo_root.join(".luxe").join("config.json")),
}
}
/// The value at `path` and the layer it came from — the project's when it sets one, or the
/// global file's, or `None` for the built-in default.
///
/// The precedence of a plain setting. A few keys merge instead (`tools.disabled` is a union,
/// `agent.on_ask` is tighten-only), and a surface showing one of those reads both documents.
pub fn lookup(&self, path: &[&str]) -> (Layer, Option<&Value>) {
if let Some(value) = self.project.as_ref().and_then(|doc| value_at(doc, path)) {
return (Layer::Project, Some(value));
}
match self.global.as_ref().and_then(|doc| value_at(doc, path)) {
Some(value) => (Layer::Global, Some(value)),
None => (Layer::Default, None),
}
}
}
/// The value at `path` inside `document`.
pub fn value_at<'a>(document: &'a Value, path: &[&str]) -> Option<&'a Value> {
path.iter().try_fold(document, |node, key| node.get(key)).filter(|value| !value.is_null())
}
fn read_document(path: &Path) -> Option<Value> {
let text = std::fs::read_to_string(path).ok()?;
serde_json::from_str::<Value>(&text).ok().filter(Value::is_object)
}
impl Config {
/// Sets `path` to `value` in the global config, leaving every other key exactly as it was.
///
/// Creates the file (pointing at its schema) when there is none. Refuses, rather than
/// overwrites, a file that does not parse: the reader may be halfway through editing it.
pub fn set_global(path: &[&str], value: Value) -> Result<PathBuf, ConfigWriteError> {
edit_global(|document| set(document, path, value))
}
/// Removes `path` from the global config, so the built-in default applies again, and drops any
/// object the removal leaves empty.
pub fn unset_global(path: &[&str]) -> Result<PathBuf, ConfigWriteError> {
edit_global(|document| unset(document, path))
}
/// Turns one tool on or off in the global `tools.disabled`, keeping the rest of the list in its
/// order and removing the key once nothing is left in it.
///
/// A project's own list is a union on top of this one, so turning a tool on here does not
/// override a project that turned it off; a surface says so beside the toggle.
pub fn set_tool_enabled_globally(
name: &str,
enabled: bool,
) -> Result<PathBuf, ConfigWriteError> {
edit_global(|document| {
let mut disabled: Vec<Value> =
match value_at(&Value::Object(document.clone()), &["tools", "disabled"]) {
Some(Value::Array(list)) => list.clone(),
_ => Vec::new(),
};
disabled.retain(|entry| entry.as_str() != Some(name));
if !enabled {
disabled.push(Value::String(name.to_string()));
}
match disabled.is_empty() {
true => unset(document, &["tools", "disabled"]),
false => set(document, &["tools", "disabled"], Value::Array(disabled)),
}
})
}
}
/// Edit the global config under [`JsonFile`]'s lock. Called from the UI thread; the wait for the
/// lock is bounded (a few seconds), and only another Luxe writing the same file at that moment, or
/// one that crashed holding the lock, makes it wait at all.
fn edit_global(edit: impl FnOnce(&mut Map<String, Value>)) -> Result<PathBuf, ConfigWriteError> {
let path = Config::global_path();
let file = JsonFile::new(path.clone(), FileMode::PreserveExisting);
file.modify(|document| {
if document.is_empty() {
*document = fresh();
}
edit(document);
Ok(())
})
.map_err(|error| match error {
FileError::Unparseable { reason, .. } => {
ConfigWriteError::Unparseable { path: path.clone(), reason }
}
FileError::Io { error, .. } => ConfigWriteError::Io { path: path.clone(), error },
other => ConfigWriteError::Io { path: path.clone(), error: std::io::Error::other(other) },
})?;
let schema = path.with_file_name("config.schema.json");
crate::fs_atomic::replace(&schema, Config::schema_json().as_bytes())
.map_err(|error| ConfigWriteError::Io { path: schema, error })?;
Ok(path)
}
/// A new file: nothing in it but the pointer to its schema.
fn fresh() -> Map<String, Value> {
let mut map = Map::new();
map.insert("$schema".into(), Value::String("./config.schema.json".into()));
map
}
fn set(document: &mut Map<String, Value>, path: &[&str], value: Value) {
let Some((last, parents)) = path.split_last() else { return };
let mut node = document;
for key in parents {
let entry = node.entry((*key).to_string()).or_insert_with(|| Value::Object(Map::new()));
// A scalar where an object belongs is replaced: the path names an object
if !entry.is_object() {
*entry = Value::Object(Map::new());
}
node = entry.as_object_mut().expect("just made an object");
}
node.insert((*last).to_string(), value);
}
fn unset(document: &mut Map<String, Value>, path: &[&str]) {
let Some((first, rest)) = path.split_first() else { return };
if rest.is_empty() {
document.remove(*first);
return;
}
if let Some(Value::Object(child)) = document.get_mut(*first) {
unset(child, rest);
if child.is_empty() {
document.remove(*first);
}
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,149 @@
use super::*;
/// The OS error is said once, whether a caller prints the message alone or walks the chain.
#[test]
fn a_failed_write_names_its_cause_once() {
let path = PathBuf::from("config.json");
let error = ConfigWriteError::Io { path, error: std::io::Error::other("disk on fire") };
assert_eq!(error.to_string(), "writing config.json: disk on fire");
let chain = crate::error_cause::chain(&error);
assert_eq!(chain.matches("disk on fire").count(), 1, "{chain}");
}
fn with_home(test: impl FnOnce(&Path)) {
let _guard =
super::super::XDG_CONFIG_HOME_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let home = tempfile::tempdir().expect("temp dir");
std::env::set_var("XDG_CONFIG_HOME", home.path());
test(home.path());
std::env::remove_var("XDG_CONFIG_HOME");
}
fn seed(text: &str) -> PathBuf {
let path = Config::global_path();
std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
std::fs::write(&path, text).expect("seed");
path
}
/// The literal a reader would have: keys this build knows, one it does not, and an order of
/// their own. Setting one value must change that one line and nothing else.
#[test]
fn a_write_changes_one_value_and_keeps_the_rest_byte_for_byte() {
with_home(|_| {
let path = seed(
r#"{
"$schema": "./config.schema.json",
"theme": "nord",
"a_key_from_a_newer_build": {
"nested": [
1,
2
]
},
"tools": {
"disabled": [
"screenshot"
]
}
}
"#,
);
Config::set_global(&["tools", "disabled"], serde_json::json!(["screenshot", "debug"]))
.expect("write");
assert_eq!(
std::fs::read_to_string(&path).expect("read"),
r#"{
"$schema": "./config.schema.json",
"theme": "nord",
"a_key_from_a_newer_build": {
"nested": [
1,
2
]
},
"tools": {
"disabled": [
"screenshot",
"debug"
]
}
}
"#
);
});
}
#[test]
fn a_first_write_creates_the_file_and_its_schema() {
with_home(|_| {
let path = Config::set_global(&["conversation", "growth"], "fill".into()).expect("write");
assert_eq!(
std::fs::read_to_string(&path).expect("read"),
"{\n \"$schema\": \"./config.schema.json\",\n \"conversation\": {\n \"growth\": \"fill\"\n }\n}\n"
);
let schema = path.parent().expect("dir").join("config.schema.json");
assert!(schema.exists(), "an editor can complete what was just written");
});
}
/// A settings surface writing into a file the reader is halfway through editing would throw
/// their edit away. It says so instead, and the file is untouched.
#[test]
fn a_file_that_will_not_parse_is_refused_rather_than_replaced() {
with_home(|_| {
for bad in ["{ \"theme\": ", "[1, 2]"] {
let path = seed(bad);
let error = Config::set_global(&["mouse"], false.into()).expect_err(bad);
assert!(matches!(error, ConfigWriteError::Unparseable { .. }), "{error}");
assert_eq!(std::fs::read_to_string(&path).expect("read"), bad, "left alone");
}
});
}
/// Resetting a setting puts the default back by removing the key, and an object left empty by
/// that goes too rather than lingering as `"tools": {}`.
#[test]
fn unsetting_removes_the_key_and_any_object_it_empties() {
with_home(|_| {
let path = seed(
"{\"theme\":\"nord\",\"tools\":{\"disabled\":[\"debug\"]},\"dock\":{\"mode\":\"auto\",\"position\":\"left\"}}",
);
Config::unset_global(&["tools", "disabled"]).expect("unset");
Config::unset_global(&["dock", "mode"]).expect("unset");
Config::unset_global(&["not", "there"]).expect("a missing key is not an error");
let written: Value =
serde_json::from_str(&std::fs::read_to_string(&path).expect("read")).expect("json");
assert_eq!(written, serde_json::json!({ "theme": "nord", "dock": { "position": "left" } }));
});
}
#[test]
fn a_tool_is_turned_off_and_back_on_without_disturbing_its_neighbors() {
with_home(|_| {
let path = seed("{\"tools\":{\"disabled\":[\"screenshot\"],\"format_on_save\":false}}");
Config::set_tool_enabled_globally("debug", false).expect("off");
Config::set_tool_enabled_globally("debug", false).expect("off twice is still once");
let read = || -> Value {
serde_json::from_str(&std::fs::read_to_string(&path).expect("read")).expect("json")
};
assert_eq!(read()["tools"]["disabled"], serde_json::json!(["screenshot", "debug"]));
Config::set_tool_enabled_globally("screenshot", true).expect("on");
Config::set_tool_enabled_globally("debug", true).expect("on");
assert_eq!(read(), serde_json::json!({ "tools": { "format_on_save": false } }));
});
}
/// A value set by the project wins over the global one, and says so; a value nobody set is the
/// default.
#[test]
fn a_lookup_names_the_layer_that_won() {
let layers = ConfigLayers {
global: Some(serde_json::json!({ "mouse": false, "dock": { "mode": "auto" } })),
project: Some(serde_json::json!({ "dock": { "mode": "hidden" }, "bell": null })),
};
assert_eq!(layers.lookup(&["mouse"]), (Layer::Global, Some(&Value::Bool(false))));
assert_eq!(layers.lookup(&["dock", "mode"]), (Layer::Project, Some(&"hidden".into())));
assert_eq!(layers.lookup(&["bell"]), (Layer::Default, None), "null is not a value");
assert_eq!(layers.lookup(&["glyphs"]), (Layer::Default, None));
}