feat: add command scope support and reload functionality

- Introduced command scope types (user and project) to manage command configurations at different levels.
- Enhanced command management functions to check and create commands based on their scope.
- Updated the API to handle command creation, updates, and deletions with respect to their scope.
- Added a reload button in the AboutSettings component to refresh OpenCode configuration.
- Improved command source retrieval to prioritize project-level commands over user-level commands.
- Refactored related functions to ensure proper handling of command paths and configurations based on scope.
This commit is contained in:
Bohdan Triapitsyn
2025-12-29 17:48:06 +02:00
parent 66351bea6c
commit 0adcba854b
12 changed files with 1008 additions and 268 deletions
+1 -1
View File
@@ -10,7 +10,7 @@ All notable changes to this project will be documented in this file.
- Added queued message mode with chips, batching, and idle autosend (including attachments).
- Added queue mode toggle to OpenChamber settings (chat section) with persistence across runtimes.
- Fixed scroll position persistence for active conversation turns across session switches.
- Refactored command management with ability to configure project/user scoped commands.
## [1.3.7] - 2025-12-28
+9 -7
View File
@@ -74,7 +74,7 @@
},
"packages/desktop": {
"name": "@openchamber/desktop",
"version": "1.3.5",
"version": "1.3.7",
"dependencies": {
"@openchamber/ui": "workspace:*",
"@tauri-apps/plugin-notification": "^2.3.3",
@@ -97,7 +97,7 @@
},
"packages/ui": {
"name": "@openchamber/ui",
"version": "1.3.5",
"version": "1.3.7",
"dependencies": {
"@fontsource/ibm-plex-mono": "^5.2.7",
"@fontsource/ibm-plex-sans": "^5.1.1",
@@ -165,7 +165,7 @@
},
"packages/vscode": {
"name": "openchamber",
"version": "1.3.5",
"version": "1.3.7",
"dependencies": {
"@openchamber/ui": "workspace:*",
"@opencode-ai/sdk": "^1.0.185",
@@ -184,7 +184,7 @@
},
"packages/web": {
"name": "@openchamber/web",
"version": "1.3.5",
"version": "1.3.7",
"bin": {
"openchamber": "./bin/cli.js",
},
@@ -517,7 +517,7 @@
"@openchamber/web": ["@openchamber/web@workspace:packages/web"],
"@opencode-ai/sdk": ["@opencode-ai/sdk@1.0.203", "", {}, "sha512-Chr/eWlb5jB+aluf70t9H0zv0tkb+otVnnkZQg3xrB7dtHJc6SxqsixAjTGnND6v3mURwchYb0UdcnGM7dOcng=="],
"@opencode-ai/sdk": ["@opencode-ai/sdk@1.0.207", "", {}, "sha512-/t4C3+PXZ5NpN7+HwKZmVwJsJmQ1eyub0eQcV8GZh7fuPo2wCxKHCD/lzk82CobW+3jVp2TSBKeDBBTtVvEFeQ=="],
"@pierre/diffs": ["@pierre/diffs@1.0.2", "", { "dependencies": { "@shikijs/core": "^3.0.0", "@shikijs/engine-javascript": "3.19.0", "@shikijs/transformers": "3.19.0", "diff": "8.0.2", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "3.19.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-RkFSDD5X/U+8QjyilPViYGJfmJNWXR17zTL8zw48+DcVC1Ujbh6I1edyuRnFfgRzpft05x2DSCkz2cjoIAxPvQ=="],
@@ -1627,7 +1627,7 @@
"inline-style-parser": ["inline-style-parser@0.2.7", "", {}, "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA=="],
"internmap": ["internmap@1.0.1", "", {}, "sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw=="],
"internmap": ["internmap@2.0.3", "", {}, "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg=="],
"intl-messageformat": ["intl-messageformat@10.7.18", "", { "dependencies": { "@formatjs/ecma402-abstract": "2.3.6", "@formatjs/fast-memoize": "2.2.7", "@formatjs/icu-messageformat-parser": "2.11.4", "tslib": "^2.8.0" } }, "sha512-m3Ofv/X/tV8Y3tHXLohcuVuhWKo7BBq62cqY15etqmLxg2DZ34AGGgQDeR+SCta2+zICb1NX83af0GJmbQ1++g=="],
@@ -2369,7 +2369,7 @@
"truncate-utf8-bytes": ["truncate-utf8-bytes@1.0.2", "", { "dependencies": { "utf8-byte-length": "^1.0.1" } }, "sha512-95Pu1QXQvruGEhv62XCMO3Mm90GscOCClvrIUwCM0PYOXK3kaF3l3sIHxx71ThJfcbM2O5Au6SO3AWCSEfW4mQ=="],
"ts-api-utils": ["ts-api-utils@2.1.0", "", { "peerDependencies": { "typescript": ">=4.8.4" } }, "sha512-CUgTZL1irw8u29bzrOD/nH85jqyc74D6SshFgujOIA7osm2Rz7dYH77agkx7H4FBNxDq7Cjf+IjaX/8zwFW+ZQ=="],
"ts-api-utils": ["ts-api-utils@2.3.0", "", { "peerDependencies": { "typescript": ">=4.8.4" } }, "sha512-6eg3Y9SF7SsAvGzRHQvvc1skDAhwI4YQ32ui1scxD1Ccr0G5qIIbUBT3pFTKX8kmWIQClHobtUdNuaBgwdfdWg=="],
"ts-dedent": ["ts-dedent@2.2.0", "", {}, "sha512-q5W7tVM71e2xjHZTlgfTDoPF/SmqKG5hddq9SzR49CH2hayqRKJtQ4mtRlSxKaJlR/+9rEM+mnBHf7I2/BQcpQ=="],
@@ -2819,6 +2819,8 @@
"cytoscape-fcose/cose-base/layout-base": ["layout-base@2.0.1", "", {}, "sha512-dp3s92+uNI1hWIpPGH3jK2kxE2lMjdXdr+DH8ynZHpd6PUlH6x6cbuXnoMmiNumznqaNO31xu9e79F0uuZ0JFg=="],
"d3-sankey/d3-array/internmap": ["internmap@1.0.1", "", {}, "sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw=="],
"d3-sankey/d3-shape/d3-path": ["d3-path@1.0.9", "", {}, "sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg=="],
"electron/@types/node/undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
+30 -12
View File
@@ -236,6 +236,7 @@ struct ConfigErrorResponse {
struct ConfigMetadataResponse {
name: String,
sources: opencode_config::ConfigSources,
scope: Option<opencode_config::CommandScope>,
is_built_in: bool,
}
@@ -1197,6 +1198,7 @@ async fn handle_agent_route(
ConfigMetadataResponse {
name,
is_built_in: !sources.md.exists && !sources.json.exists,
scope: None,
sources,
},
)),
@@ -1320,17 +1322,24 @@ async fn handle_command_route(
req: Request<Body>,
name: String,
) -> Result<Response<Body>, StatusCode> {
// Get working directory for project-level command detection
let working_directory = state.opencode.get_working_directory();
match method {
Method::GET => {
match opencode_config::get_command_sources(&name).await {
Ok(sources) => Ok(json_response(
StatusCode::OK,
ConfigMetadataResponse {
name,
is_built_in: !sources.md.exists && !sources.json.exists,
sources,
},
)),
match opencode_config::get_command_sources(&name, Some(&working_directory)).await {
Ok(sources) => {
let scope = sources.md.scope.clone();
Ok(json_response(
StatusCode::OK,
ConfigMetadataResponse {
name,
is_built_in: !sources.md.exists && !sources.json.exists,
scope,
sources,
},
))
}
Err(err) => {
error!("[desktop:config] Failed to read command sources: {}", err);
Ok(config_error_response(
@@ -1345,8 +1354,17 @@ async fn handle_command_route(
Ok(data) => data,
Err(resp) => return Ok(resp),
};
// Extract scope from payload if present
let scope = payload.get("scope")
.and_then(|v| v.as_str())
.and_then(|s| match s {
"project" => Some(opencode_config::CommandScope::Project),
"user" => Some(opencode_config::CommandScope::User),
_ => None,
});
match opencode_config::create_command(&name, &payload).await {
match opencode_config::create_command(&name, &payload, Some(&working_directory), scope).await {
Ok(()) => {
if let Err(resp) =
refresh_opencode_after_config_change(state, "command creation").await
@@ -1382,7 +1400,7 @@ async fn handle_command_route(
Err(resp) => return Ok(resp),
};
match opencode_config::update_command(&name, &payload).await {
match opencode_config::update_command(&name, &payload, Some(&working_directory)).await {
Ok(()) => {
if let Err(resp) =
refresh_opencode_after_config_change(state, "command update").await
@@ -1412,7 +1430,7 @@ async fn handle_command_route(
}
}
}
Method::DELETE => match opencode_config::delete_command(&name).await {
Method::DELETE => match opencode_config::delete_command(&name, Some(&working_directory)).await {
Ok(()) => {
if let Err(resp) =
refresh_opencode_after_config_change(state, "command deletion").await
+205 -46
View File
@@ -11,12 +11,29 @@ use tokio::fs;
static PROMPT_FILE_PATTERN: Lazy<Regex> =
Lazy::new(|| Regex::new(r"(?i)^\{file:(.+)\}$").expect("valid regex"));
/// Command scope types
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum CommandScope {
User,
Project,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SourceInfo {
pub exists: bool,
pub path: Option<String>,
pub fields: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub scope: Option<CommandScope>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MdLocationInfo {
pub exists: bool,
pub path: Option<String>,
}
#[derive(Debug, Serialize)]
@@ -24,6 +41,10 @@ pub struct SourceInfo {
pub struct ConfigSources {
pub md: SourceInfo,
pub json: SourceInfo,
#[serde(skip_serializing_if = "Option::is_none")]
pub project_md: Option<MdLocationInfo>,
#[serde(skip_serializing_if = "Option::is_none")]
pub user_md: Option<MdLocationInfo>,
}
/// Get OpenCode config directory path
@@ -39,7 +60,7 @@ fn get_agent_dir() -> PathBuf {
get_config_dir().join("agent")
}
/// Get command directory path
/// Get user-level command directory path
fn get_command_dir() -> PathBuf {
get_config_dir().join("command")
}
@@ -49,6 +70,64 @@ fn get_config_file() -> PathBuf {
get_config_dir().join("opencode.json")
}
/// Get project-level command directory path
fn get_project_command_dir(working_directory: &Path) -> PathBuf {
working_directory.join(".opencode").join("command")
}
/// Get project-level command path
fn get_project_command_path(working_directory: &Path, command_name: &str) -> PathBuf {
get_project_command_dir(working_directory).join(format!("{}.md", command_name))
}
/// Get user-level command path
fn get_user_command_path(command_name: &str) -> PathBuf {
get_command_dir().join(format!("{}.md", command_name))
}
/// Ensure project command directory exists
async fn ensure_project_command_dir(working_directory: &Path) -> Result<PathBuf> {
let project_command_dir = get_project_command_dir(working_directory);
fs::create_dir_all(&project_command_dir).await?;
Ok(project_command_dir)
}
/// Determine command scope based on where the .md file exists
pub fn get_command_scope(command_name: &str, working_directory: Option<&Path>) -> (Option<CommandScope>, Option<PathBuf>) {
if let Some(wd) = working_directory {
let project_path = get_project_command_path(wd, command_name);
if project_path.exists() {
return (Some(CommandScope::Project), Some(project_path));
}
}
let user_path = get_user_command_path(command_name);
if user_path.exists() {
return (Some(CommandScope::User), Some(user_path));
}
(None, None)
}
/// Get the path where a command should be written based on scope
fn get_command_write_path(command_name: &str, working_directory: Option<&Path>, requested_scope: Option<CommandScope>) -> (CommandScope, PathBuf) {
// For updates: check existing location first (project takes precedence)
let (existing_scope, existing_path) = get_command_scope(command_name, working_directory);
if let Some(path) = existing_path {
return (existing_scope.unwrap(), path);
}
// For new commands or built-in overrides: use requested scope or default to user
let scope = requested_scope.unwrap_or(CommandScope::User);
if scope == CommandScope::Project {
if let Some(wd) = working_directory {
return (CommandScope::Project, get_project_command_path(wd, command_name));
}
}
(CommandScope::User, get_user_command_path(command_name))
}
/// Ensure required directories exist
async fn ensure_dirs() -> Result<()> {
let config_dir = get_config_dir();
@@ -240,7 +319,13 @@ async fn write_md_file(
frontmatter: &HashMap<String, Value>,
body: &str,
) -> Result<()> {
let yaml_str = serde_yaml::to_string(frontmatter)?;
// Filter out null values - OpenCode expects keys to be omitted rather than set to null
let cleaned_frontmatter: HashMap<String, Value> = frontmatter
.iter()
.filter(|(_, v)| !v.is_null())
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
let yaml_str = serde_yaml::to_string(&cleaned_frontmatter)?;
let content = format!("---\n{}---\n\n{}", yaml_str, body);
fs::write(file_path, content).await?;
@@ -281,12 +366,16 @@ pub async fn get_agent_sources(agent_name: &str) -> Result<ConfigSources> {
exists: md_exists,
path: md_exists.then(|| md_path.display().to_string()),
fields: md_fields,
scope: None, // Agents don't have project/user scope distinction yet
},
json: SourceInfo {
exists: json_section.is_some(),
path: Some(get_config_file().display().to_string()),
fields: json_fields,
scope: None,
},
project_md: None,
user_md: None,
};
Ok(sources)
@@ -528,18 +617,34 @@ pub async fn delete_agent(agent_name: &str) -> Result<()> {
}
/// Get information about where command configuration is stored
pub async fn get_command_sources(command_name: &str) -> Result<ConfigSources> {
pub async fn get_command_sources(command_name: &str, working_directory: Option<&Path>) -> Result<ConfigSources> {
ensure_dirs().await?;
let md_path = get_command_dir().join(format!("{}.md", command_name));
let md_exists = md_path.exists();
// Check project level first (takes precedence)
let project_path = working_directory.map(|wd| get_project_command_path(wd, command_name));
let project_exists = project_path.as_ref().map(|p| p.exists()).unwrap_or(false);
// Then check user level
let user_path = get_user_command_path(command_name);
let user_exists = user_path.exists();
// Determine which md file to use (project takes precedence)
let (md_path, md_exists, md_scope) = if project_exists {
(project_path.clone(), true, Some(CommandScope::Project))
} else if user_exists {
(Some(user_path.clone()), true, Some(CommandScope::User))
} else {
(None, false, None)
};
let mut md_fields = Vec::new();
if md_exists {
let md_data = parse_md_file(&md_path).await?;
md_fields.extend(md_data.frontmatter.keys().cloned());
if !md_data.body.trim().is_empty() {
md_fields.push("template".to_string());
if let Some(ref path) = md_path {
let md_data = parse_md_file(path).await?;
md_fields.extend(md_data.frontmatter.keys().cloned());
if !md_data.body.trim().is_empty() {
md_fields.push("template".to_string());
}
}
}
@@ -557,29 +662,53 @@ pub async fn get_command_sources(command_name: &str) -> Result<ConfigSources> {
let sources = ConfigSources {
md: SourceInfo {
exists: md_exists,
path: md_exists.then(|| md_path.display().to_string()),
path: md_path.map(|p| p.display().to_string()),
fields: md_fields,
scope: md_scope,
},
json: SourceInfo {
exists: json_section.is_some(),
path: Some(get_config_file().display().to_string()),
fields: json_fields,
scope: None,
},
project_md: Some(MdLocationInfo {
exists: project_exists,
path: project_path.map(|p| p.display().to_string()),
}),
user_md: Some(MdLocationInfo {
exists: user_exists,
path: Some(user_path.display().to_string()),
}),
};
Ok(sources)
}
/// Create new command as .md file
pub async fn create_command(command_name: &str, config: &HashMap<String, Value>) -> Result<()> {
pub async fn create_command(
command_name: &str,
config: &HashMap<String, Value>,
working_directory: Option<&Path>,
scope: Option<CommandScope>
) -> Result<()> {
ensure_dirs().await?;
let md_path = get_command_dir().join(format!("{}.md", command_name));
// Check if command already exists
if md_path.exists() {
// Check if command already exists at either level
if let Some(wd) = working_directory {
let project_path = get_project_command_path(wd, command_name);
if project_path.exists() {
return Err(anyhow!(
"Command {} already exists as project-level .md file",
command_name
));
}
}
let user_path = get_user_command_path(command_name);
if user_path.exists() {
return Err(anyhow!(
"Command {} already exists as .md file",
"Command {} already exists as user-level .md file",
command_name
));
}
@@ -594,16 +723,29 @@ pub async fn create_command(command_name: &str, config: &HashMap<String, Value>)
}
}
// Extract template from config
// Determine target path based on requested scope
let (target_scope, target_path) = if scope == Some(CommandScope::Project) {
if let Some(wd) = working_directory {
ensure_project_command_dir(wd).await?;
(CommandScope::Project, get_project_command_path(wd, command_name))
} else {
(CommandScope::User, user_path)
}
} else {
(CommandScope::User, user_path)
};
// Extract template and scope from config - scope is only used for path determination, not written to file
let mut frontmatter = config.clone();
let template = frontmatter
.remove("template")
.and_then(|v| v.as_str().map(|s| s.to_string()))
.unwrap_or_default();
frontmatter.remove("scope"); // Remove scope - it's not a valid command field
// Write .md file
write_md_file(&md_path, &frontmatter, &template).await?;
info!("Created new command: {}", command_name);
write_md_file(&target_path, &frontmatter, &template).await?;
info!("Created new command: {} (scope: {:?}, path: {})", command_name, target_scope, target_path.display());
Ok(())
}
@@ -612,17 +754,29 @@ pub async fn create_command(command_name: &str, config: &HashMap<String, Value>)
pub async fn update_command(
command_name: &str,
updates: &HashMap<String, Value>,
working_directory: Option<&Path>,
) -> Result<()> {
ensure_dirs().await?;
let md_path = get_command_dir().join(format!("{}.md", command_name));
// Determine correct path: project level takes precedence
let (scope, md_path) = get_command_write_path(command_name, working_directory, None);
let md_exists = md_path.exists();
// If no existing md file, we need to create one (for built-in command overrides)
let target_path = if !md_exists {
// No existing md file - this is a built-in override, create at user level
get_user_command_path(command_name)
} else {
md_path.clone()
};
let mut md_data = if md_exists {
Some(parse_md_file(&md_path).await?)
} else {
None
Some(MdData { frontmatter: HashMap::new(), body: String::new() })
};
let creating_new_md = !md_exists;
let mut config = read_config().await?;
let mut existing_command = config
@@ -657,7 +811,7 @@ pub async fn update_command(
if field == "template" {
let normalized_value = value.as_str().unwrap_or("").to_string();
if md_exists {
if md_exists || creating_new_md {
if let Some(ref mut data) = md_data {
data.body = normalized_value.clone();
md_modified = true;
@@ -677,10 +831,11 @@ pub async fn update_command(
}
}
// Write template directly to JSON entry (file ref or inline string)
existing_command.insert("template".to_string(), Value::String(normalized_value));
json_modified = true;
// Create new md file for the update
if let Some(ref mut data) = md_data {
data.body = normalized_value;
md_modified = true;
}
continue;
}
@@ -691,7 +846,7 @@ pub async fn update_command(
.unwrap_or(false);
let in_json = existing_command.contains_key(field);
if in_md {
if in_md || creating_new_md {
// Update in .md frontmatter
if let Some(ref mut data) = md_data {
data.frontmatter.insert(field.clone(), value.clone());
@@ -702,19 +857,13 @@ pub async fn update_command(
existing_command.insert(field.clone(), value.clone());
json_modified = true;
} else {
// Field not defined - apply priority rules
if md_exists && !existing_command.is_empty() {
// Both exist → add to opencode.json (higher priority)
existing_command.insert(field.clone(), value.clone());
json_modified = true;
} else if md_exists {
// Only .md exists → add to frontmatter
// New field - add to md if it exists or we're creating one
if md_exists || creating_new_md {
if let Some(ref mut data) = md_data {
data.frontmatter.insert(field.clone(), value.clone());
md_modified = true;
}
} else {
// Only JSON or built-in → add/create section in opencode.json
existing_command.insert(field.clone(), value.clone());
json_modified = true;
}
@@ -724,7 +873,7 @@ pub async fn update_command(
// Write changes
if md_modified {
if let Some(data) = md_data {
write_md_file(&md_path, &data.frontmatter, &data.body).await?;
write_md_file(&target_path, &data.frontmatter, &data.body).await?;
}
}
@@ -756,26 +905,36 @@ pub async fn update_command(
}
info!(
"Updated command: {} (md: {}, json: {})",
command_name, md_modified, json_modified
"Updated command: {} (scope: {:?}, md: {}, json: {})",
command_name, scope, md_modified, json_modified
);
Ok(())
}
/// Delete command configuration
pub async fn delete_command(command_name: &str) -> Result<()> {
let md_path = get_command_dir().join(format!("{}.md", command_name));
pub async fn delete_command(command_name: &str, working_directory: Option<&Path>) -> Result<()> {
let mut deleted = false;
// 1. Delete .md file if exists
if md_path.exists() {
fs::remove_file(&md_path).await?;
info!("Deleted command .md file: {}", md_path.display());
// 1. Check project level first (takes precedence)
if let Some(wd) = working_directory {
let project_path = get_project_command_path(wd, command_name);
if project_path.exists() {
fs::remove_file(&project_path).await?;
info!("Deleted project-level command .md file: {}", project_path.display());
deleted = true;
}
}
// 2. Check user level
let user_path = get_user_command_path(command_name);
if user_path.exists() {
fs::remove_file(&user_path).await?;
info!("Deleted user-level command .md file: {}", user_path.display());
deleted = true;
}
// 2. Remove section from opencode.json if exists
// 3. Remove section from opencode.json if exists
let mut config = read_config().await?;
if let Some(commands) = config.get_mut("command").and_then(|v| v.as_object_mut()) {
if commands.remove(command_name).is_some() {
@@ -785,7 +944,7 @@ pub async fn delete_command(command_name: &str) -> Result<()> {
}
}
// 3. If nothing was deleted, throw error
// 4. If nothing was deleted, throw error
if !deleted {
return Err(anyhow!("Command \"{}\" not found", command_name));
}
@@ -3,21 +3,28 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { toast } from 'sonner';
import { useCommandsStore, type CommandConfig } from '@/stores/useCommandsStore';
import { RiCheckLine, RiInformationLine, RiSaveLine, RiTerminalBoxLine } from '@remixicon/react';
import { useCommandsStore, type CommandConfig, type CommandScope } from '@/stores/useCommandsStore';
import { RiCheckLine, RiInformationLine, RiSaveLine, RiTerminalBoxLine, RiUser3Line, RiFolderLine } from '@remixicon/react';
import { cn } from '@/lib/utils';
import { ModelSelector } from '../agents/ModelSelector';
import { AgentSelector } from './AgentSelector';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
} from '@/components/ui/select';
export const CommandsPage: React.FC = () => {
const { selectedCommandName, getCommandByName, createCommand, updateCommand, commands } = useCommandsStore();
const { selectedCommandName, getCommandByName, createCommand, updateCommand, commands, commandDraft, setCommandDraft } = useCommandsStore();
const selectedCommand = selectedCommandName ? getCommandByName(selectedCommandName) : null;
const isNewCommand = selectedCommandName && !selectedCommand;
const isNewCommand = Boolean(commandDraft && commandDraft.name === selectedCommandName && !selectedCommand);
const [name, setName] = React.useState('');
const [draftName, setDraftName] = React.useState('');
const [draftScope, setDraftScope] = React.useState<CommandScope>('user');
const [description, setDescription] = React.useState('');
const [agent, setAgent] = React.useState('');
const [model, setModel] = React.useState('');
@@ -26,27 +33,28 @@ export const CommandsPage: React.FC = () => {
const [isSaving, setIsSaving] = React.useState(false);
React.useEffect(() => {
if (isNewCommand) {
setName(selectedCommandName || '');
setDescription('');
setAgent('');
setModel('');
setTemplate('');
setSubtask(false);
if (isNewCommand && commandDraft) {
// Prefill from draft (for new or duplicated commands)
setDraftName(commandDraft.name || '');
setDraftScope(commandDraft.scope || 'user');
setDescription(commandDraft.description || '');
setAgent(commandDraft.agent || '');
setModel(commandDraft.model || '');
setTemplate(commandDraft.template || '');
setSubtask(commandDraft.subtask || false);
} else if (selectedCommand) {
setName(selectedCommand.name);
setDescription(selectedCommand.description || '');
setAgent(selectedCommand.agent || '');
setModel(selectedCommand.model || '');
setTemplate(selectedCommand.template || '');
setSubtask(selectedCommand.subtask || false);
}
}, [selectedCommand, isNewCommand, selectedCommandName, commands]);
}, [selectedCommand, isNewCommand, selectedCommandName, commands, commandDraft]);
const handleSave = async () => {
if (!name.trim()) {
const commandName = isNewCommand ? draftName.trim().replace(/\s+/g, '-') : selectedCommandName?.trim();
if (!commandName) {
toast.error('Command name is required');
return;
}
@@ -56,6 +64,12 @@ export const CommandsPage: React.FC = () => {
return;
}
// Check for duplicate name when creating new command
if (isNewCommand && commands.some((cmd) => cmd.name === commandName)) {
toast.error('A command with this name already exists');
return;
}
setIsSaving(true);
try {
@@ -63,19 +77,23 @@ export const CommandsPage: React.FC = () => {
const trimmedModel = model.trim();
const trimmedTemplate = template.trim();
const config: CommandConfig = {
name: name.trim(),
name: commandName,
description: description.trim() || undefined,
agent: trimmedAgent === '' ? null : trimmedAgent,
model: trimmedModel === '' ? null : trimmedModel,
template: trimmedTemplate,
subtask,
scope: isNewCommand ? draftScope : undefined,
};
let success: boolean;
if (isNewCommand) {
success = await createCommand(config);
if (success) {
setCommandDraft(null); // Clear draft after successful creation
}
} else {
success = await updateCommand(name, config);
success = await updateCommand(commandName, config);
}
if (success) {
@@ -108,7 +126,7 @@ export const CommandsPage: React.FC = () => {
{}
<div className="space-y-1">
<h1 className="typography-ui-header font-semibold text-lg">
{isNewCommand ? 'New Command' : name}
{isNewCommand ? 'New Command' : `/${selectedCommandName}`}
</h1>
</div>
@@ -121,20 +139,54 @@ export const CommandsPage: React.FC = () => {
</p>
</div>
<div className="space-y-2">
<label className="typography-ui-label font-medium text-foreground">
Command Name
</label>
<Input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="my-command"
disabled={!isNewCommand}
/>
<p className="typography-meta text-muted-foreground">
Used with slash (/) prefix in chat
</p>
</div>
{isNewCommand && (
<div className="space-y-2">
<label className="typography-ui-label font-medium text-foreground">
Command Name & Scope
</label>
<div className="flex items-center gap-2">
<div className="flex items-center flex-1">
<span className="typography-ui-label text-muted-foreground mr-1">/</span>
<Input
value={draftName}
onChange={(e) => setDraftName(e.target.value)}
placeholder="command-name"
className="flex-1 text-foreground placeholder:text-muted-foreground"
/>
</div>
<Select value={draftScope} onValueChange={(v) => setDraftScope(v as CommandScope)}>
<SelectTrigger className="!h-9 w-auto gap-1.5">
{draftScope === 'user' ? (
<RiUser3Line className="h-4 w-4" />
) : (
<RiFolderLine className="h-4 w-4" />
)}
<span className="capitalize">{draftScope}</span>
</SelectTrigger>
<SelectContent align="end">
<SelectItem value="user" className="pr-2 [&>span:first-child]:hidden">
<div className="flex flex-col gap-0.5">
<div className="flex items-center gap-2">
<RiUser3Line className="h-4 w-4" />
<span>User</span>
</div>
<span className="typography-micro text-muted-foreground ml-6">Available in all projects</span>
</div>
</SelectItem>
<SelectItem value="project" className="pr-2 [&>span:first-child]:hidden">
<div className="flex flex-col gap-0.5">
<div className="flex items-center gap-2">
<RiFolderLine className="h-4 w-4" />
<span>Project</span>
</div>
<span className="typography-micro text-muted-foreground ml-6">Only in current project</span>
</div>
</SelectItem>
</SelectContent>
</Select>
</div>
</div>
)}
<div className="space-y-2">
<label className="typography-ui-label font-medium text-foreground">
@@ -10,7 +10,6 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import {
DropdownMenu,
@@ -18,8 +17,8 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { RiAddLine, RiTerminalBoxLine, RiMore2Line, RiDeleteBinLine, RiFileCopyLine } from '@remixicon/react';
import { useCommandsStore, type Command } from '@/stores/useCommandsStore';
import { RiAddLine, RiTerminalBoxLine, RiMore2Line, RiDeleteBinLine, RiFileCopyLine, RiRestartLine, RiEditLine } from '@remixicon/react';
import { useCommandsStore, isCommandBuiltIn, type Command } from '@/stores/useCommandsStore';
import { useUIStore } from '@/stores/useUIStore';
import { useDeviceInfo } from '@/lib/device';
import { isVSCodeRuntime } from '@/lib/desktop';
@@ -31,13 +30,15 @@ interface CommandsSidebarProps {
}
export const CommandsSidebar: React.FC<CommandsSidebarProps> = ({ onItemSelect }) => {
const [newCommandName, setNewCommandName] = React.useState('');
const [isCreateDialogOpen, setIsCreateDialogOpen] = React.useState(false);
const [renameDialogCommand, setRenameDialogCommand] = React.useState<Command | null>(null);
const [renameNewName, setRenameNewName] = React.useState('');
const {
selectedCommandName,
commands,
setSelectedCommand,
setCommandDraft,
createCommand,
deleteCommand,
loadCommands,
} = useCommandsStore();
@@ -67,22 +68,19 @@ export const CommandsSidebar: React.FC<CommandsSidebarProps> = ({ onItemSelect }
? 'bg-background'
: 'bg-sidebar';
const handleCreateCommand = () => {
if (!newCommandName.trim()) {
toast.error('Command name is required');
return;
const handleCreateNew = () => {
// Generate unique name
const baseName = 'new-command';
let newName = baseName;
let counter = 1;
while (commands.some((c) => c.name === newName)) {
newName = `${baseName}-${counter}`;
counter++;
}
const sanitizedName = newCommandName.trim().replace(/\s+/g, '-');
if (commands.some((cmd) => cmd.name === sanitizedName)) {
toast.error('A command with this name already exists');
return;
}
setSelectedCommand(sanitizedName);
setNewCommandName('');
setIsCreateDialogOpen(false);
// Set draft and open the page for editing
setCommandDraft({ name: newName, scope: 'user' });
setSelectedCommand(newName);
if (isMobile) {
setSidebarOpen(false);
@@ -90,6 +88,11 @@ export const CommandsSidebar: React.FC<CommandsSidebarProps> = ({ onItemSelect }
};
const handleDeleteCommand = async (command: Command) => {
if (isCommandBuiltIn(command)) {
toast.error('Built-in commands cannot be deleted');
return;
}
if (window.confirm(`Are you sure you want to delete command "${command.name}"?`)) {
const success = await deleteCommand(command.name);
if (success) {
@@ -100,6 +103,21 @@ export const CommandsSidebar: React.FC<CommandsSidebarProps> = ({ onItemSelect }
}
};
const handleResetCommand = async (command: Command) => {
if (!isCommandBuiltIn(command)) {
return;
}
if (window.confirm(`Are you sure you want to reset command "${command.name}" to its default configuration?`)) {
const success = await deleteCommand(command.name);
if (success) {
toast.success(`Command "${command.name}" reset to default`);
} else {
toast.error('Failed to reset command');
}
}
};
const handleDuplicateCommand = (command: Command) => {
const baseName = command.name;
let copyNumber = 1;
@@ -110,85 +128,185 @@ export const CommandsSidebar: React.FC<CommandsSidebarProps> = ({ onItemSelect }
newName = `${baseName}-copy-${copyNumber}`;
}
// Set draft with prefilled values from source command
setCommandDraft({
name: newName,
scope: command.scope || 'user',
description: command.description,
template: command.template,
agent: command.agent,
model: command.model,
subtask: command.subtask,
});
setSelectedCommand(newName);
setIsCreateDialogOpen(false);
if (isMobile) {
setSidebarOpen(false);
}
};
const handleOpenRenameDialog = (command: Command) => {
setRenameNewName(command.name);
setRenameDialogCommand(command);
};
const handleRenameCommand = async () => {
if (!renameDialogCommand) return;
const sanitizedName = renameNewName.trim().replace(/\s+/g, '-');
if (!sanitizedName) {
toast.error('Command name is required');
return;
}
if (sanitizedName === renameDialogCommand.name) {
setRenameDialogCommand(null);
return;
}
if (commands.some((cmd) => cmd.name === sanitizedName)) {
toast.error('A command with this name already exists');
return;
}
// Create new command with new name and all existing config
const success = await createCommand({
name: sanitizedName,
description: renameDialogCommand.description,
template: renameDialogCommand.template,
agent: renameDialogCommand.agent,
model: renameDialogCommand.model,
subtask: renameDialogCommand.subtask,
});
if (success) {
// Delete old command
const deleteSuccess = await deleteCommand(renameDialogCommand.name);
if (deleteSuccess) {
toast.success(`Command renamed to "${sanitizedName}"`);
setSelectedCommand(sanitizedName);
} else {
toast.error('Failed to remove old command after rename');
}
} else {
toast.error('Failed to rename command');
}
setRenameDialogCommand(null);
};
const builtInCommands = commands.filter(isCommandBuiltIn);
const customCommands = commands.filter((cmd) => !isCommandBuiltIn(cmd));
return (
<div className={cn('flex h-full flex-col', bgClass)}>
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
<div className={cn('border-b px-3', isMobile ? 'mt-2 py-3' : 'py-3')}>
<div className="flex items-center justify-between gap-2">
<span className="typography-meta text-muted-foreground">Total {commands.length}</span>
<DialogTrigger asChild>
<Button type="button" variant="ghost" size="icon" className="h-7 w-7 -my-1 text-muted-foreground">
<RiAddLine className="size-4" />
</Button>
</DialogTrigger>
</div>
<div className={cn('border-b px-3', isMobile ? 'mt-2 py-3' : 'py-3')}>
<div className="flex items-center justify-between gap-2">
<span className="typography-meta text-muted-foreground">Total {commands.length}</span>
<Button
type="button"
variant="ghost"
size="icon"
className="h-7 w-7 -my-1 text-muted-foreground"
onClick={handleCreateNew}
>
<RiAddLine className="size-4" />
</Button>
</div>
</div>
<ScrollableOverlay outerClassName="flex-1 min-h-0" className="space-y-1 px-3 py-2">
{commands.length === 0 ? (
<div className="py-12 px-4 text-center text-muted-foreground">
<RiTerminalBoxLine className="mx-auto mb-3 h-10 w-10 opacity-50" />
<p className="typography-ui-label font-medium">No commands configured</p>
<p className="typography-meta mt-1 opacity-75">Use the + button above to create one</p>
</div>
) : (
<ScrollableOverlay outerClassName="flex-1 min-h-0" className="space-y-1 px-3 py-2">
{commands.length === 0 ? (
<div className="py-12 px-4 text-center text-muted-foreground">
<RiTerminalBoxLine className="mx-auto mb-3 h-10 w-10 opacity-50" />
<p className="typography-ui-label font-medium">No commands configured</p>
<p className="typography-meta mt-1 opacity-75">Use the + button above to create one</p>
</div>
) : (
<>
{builtInCommands.length > 0 && (
<>
{[...commands].sort((a, b) => a.name.localeCompare(b.name)).map((command) => (
<CommandListItem
key={command.name}
command={command}
isSelected={selectedCommandName === command.name}
onSelect={() => {
setSelectedCommand(command.name);
onItemSelect?.();
if (isMobile) {
setSidebarOpen(false);
}
}}
onDelete={() => handleDeleteCommand(command)}
onDuplicate={() => handleDuplicateCommand(command)}
/>
))}
<div className="px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
Built-in Commands
</div>
{[...builtInCommands].sort((a, b) => a.name.localeCompare(b.name)).map((command) => (
<CommandListItem
key={command.name}
command={command}
isSelected={selectedCommandName === command.name}
onSelect={() => {
setSelectedCommand(command.name);
onItemSelect?.();
if (isMobile) {
setSidebarOpen(false);
}
}}
onReset={() => handleResetCommand(command)}
onDuplicate={() => handleDuplicateCommand(command)}
/>
))}
</>
)}
</ScrollableOverlay>
{customCommands.length > 0 && (
<>
<div className="px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
Custom Commands
</div>
{[...customCommands].sort((a, b) => a.name.localeCompare(b.name)).map((command) => (
<CommandListItem
key={command.name}
command={command}
isSelected={selectedCommandName === command.name}
onSelect={() => {
setSelectedCommand(command.name);
onItemSelect?.();
if (isMobile) {
setSidebarOpen(false);
}
}}
onRename={() => handleOpenRenameDialog(command)}
onDelete={() => handleDeleteCommand(command)}
onDuplicate={() => handleDuplicateCommand(command)}
/>
))}
</>
)}
</>
)}
</ScrollableOverlay>
{/* Rename Dialog */}
<Dialog open={renameDialogCommand !== null} onOpenChange={(open) => !open && setRenameDialogCommand(null)}>
<DialogContent>
<DialogHeader>
<DialogTitle>Create New Command</DialogTitle>
<DialogTitle>Rename Command</DialogTitle>
<DialogDescription>
Enter a unique name for your new slash command
Enter a new name for the command "/{renameDialogCommand?.name}"
</DialogDescription>
</DialogHeader>
<Input
value={newCommandName}
onChange={(e) => setNewCommandName(e.target.value)}
placeholder="Command name..."
value={renameNewName}
onChange={(e) => setRenameNewName(e.target.value)}
placeholder="New command name..."
className="text-foreground placeholder:text-muted-foreground"
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleCreateCommand();
handleRenameCommand();
}
}}
/>
<DialogFooter>
<Button
variant="ghost"
onClick={() => setIsCreateDialogOpen(false)}
onClick={() => setRenameDialogCommand(null)}
className="text-foreground hover:bg-muted hover:text-foreground"
>
Cancel
</Button>
<ButtonLarge onClick={handleCreateCommand}>
Create
<ButtonLarge onClick={handleRenameCommand}>
Rename
</ButtonLarge>
</DialogFooter>
</DialogContent>
@@ -201,7 +319,9 @@ interface CommandListItemProps {
command: Command;
isSelected: boolean;
onSelect: () => void;
onDelete: () => void;
onDelete?: () => void;
onReset?: () => void;
onRename?: () => void;
onDuplicate: () => void;
}
@@ -210,6 +330,8 @@ const CommandListItem: React.FC<CommandListItemProps> = ({
isSelected,
onSelect,
onDelete,
onReset,
onRename,
onDuplicate,
}) => {
return (
@@ -229,6 +351,11 @@ const CommandListItem: React.FC<CommandListItemProps> = ({
<span className="typography-ui-label font-normal truncate text-foreground">
/{command.name}
</span>
{(command.scope || isCommandBuiltIn(command)) && (
<span className="typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50">
{isCommandBuiltIn(command) ? 'system' : command.scope}
</span>
)}
</div>
{command.description && (
@@ -249,6 +376,18 @@ const CommandListItem: React.FC<CommandListItemProps> = ({
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-fit min-w-20">
{onRename && (
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
onRename();
}}
>
<RiEditLine className="h-4 w-4 mr-px" />
Rename
</DropdownMenuItem>
)}
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
@@ -259,16 +398,30 @@ const CommandListItem: React.FC<CommandListItemProps> = ({
Duplicate
</DropdownMenuItem>
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
onDelete();
}}
className="text-destructive focus:text-destructive"
>
<RiDeleteBinLine className="h-4 w-4 mr-px" />
Delete
</DropdownMenuItem>
{onReset && (
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
onReset();
}}
>
<RiRestartLine className="h-4 w-4 mr-px" />
Reset
</DropdownMenuItem>
)}
{onDelete && (
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
onDelete();
}}
className="text-destructive focus:text-destructive"
>
<RiDeleteBinLine className="h-4 w-4 mr-px" />
Delete
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
@@ -1,10 +1,11 @@
import React from 'react';
import { RiDiscordFill, RiDownloadLine, RiGithubFill, RiLoaderLine, RiTwitterXFill } from '@remixicon/react';
import { RiDiscordFill, RiDownloadLine, RiGithubFill, RiLoaderLine, RiRestartLine, RiTwitterXFill } from '@remixicon/react';
import { useUpdateStore } from '@/stores/useUpdateStore';
import { UpdateDialog } from '@/components/ui/UpdateDialog';
import { useDeviceInfo } from '@/lib/device';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';
import { reloadOpenCodeConfiguration } from '@/stores/useAgentsStore';
const GITHUB_URL = 'https://github.com/btriapitsyn/openchamber';
@@ -45,6 +46,15 @@ export const AboutSettings: React.FC = () => {
if (isMobile) {
return (
<div className="w-full space-y-2">
{/* Reload OpenCode Configuration */}
<button
onClick={() => reloadOpenCodeConfiguration()}
className="flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors"
>
<RiRestartLine className="h-3.5 w-3.5" />
<span>Reload OpenCode Configuration</span>
</button>
{/* Version row with update status */}
<div className="flex items-center justify-between">
<span className="typography-meta text-muted-foreground">
+67 -4
View File
@@ -10,6 +10,9 @@ import {
import { emitConfigChange, scopeMatches, subscribeToConfigChanges } from "@/lib/configSync";
import { getSafeStorage } from "./utils/safeStorage";
import { useConfigStore } from "@/stores/useConfigStore";
import { useDirectoryStore } from "@/stores/useDirectoryStore";
export type CommandScope = 'user' | 'project';
export interface CommandConfig {
name: string;
@@ -18,12 +21,20 @@ export interface CommandConfig {
model?: string | null;
template?: string;
subtask?: boolean;
scope?: CommandScope;
}
export interface Command extends CommandConfig {
isBuiltIn?: boolean;
}
// Built-in commands provided by OpenCode (not defined in user config directories)
const BUILTIN_COMMAND_NAMES = new Set(['init', 'review']);
export const isCommandBuiltIn = (command: Command): boolean => {
return BUILTIN_COMMAND_NAMES.has(command.name);
};
const CONFIG_EVENT_SOURCE = "useCommandsStore";
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const MAX_HEALTH_WAIT_MS = 20000;
@@ -33,13 +44,25 @@ const SLOW_HEALTH_POLL_BASE_MS = 800;
const SLOW_HEALTH_POLL_INCREMENT_MS = 200;
const SLOW_HEALTH_POLL_MAX_MS = 2000;
export interface CommandDraft {
name: string;
scope: CommandScope;
description?: string;
agent?: string | null;
model?: string | null;
template?: string;
subtask?: boolean;
}
interface CommandsStore {
selectedCommandName: string | null;
commands: Command[];
isLoading: boolean;
commandDraft: CommandDraft | null;
setSelectedCommand: (name: string | null) => void;
setCommandDraft: (draft: CommandDraft | null) => void;
loadCommands: () => Promise<boolean>;
createCommand: (config: CommandConfig) => Promise<boolean>;
updateCommand: (name: string, config: Partial<CommandConfig>) => Promise<boolean>;
@@ -61,11 +84,16 @@ export const useCommandsStore = create<CommandsStore>()(
selectedCommandName: null,
commands: [],
isLoading: false,
commandDraft: null,
setSelectedCommand: (name: string | null) => {
set({ selectedCommandName: name });
},
setCommandDraft: (draft: CommandDraft | null) => {
set({ commandDraft: draft });
},
loadCommands: async () => {
set({ isLoading: true });
const previousCommands = get().commands;
@@ -74,7 +102,29 @@ export const useCommandsStore = create<CommandsStore>()(
for (let attempt = 0; attempt < 3; attempt++) {
try {
const commands = await opencodeClient.listCommandsWithDetails();
set({ commands, isLoading: false });
// Fetch scope info for each command
const currentDirectory = useDirectoryStore.getState().currentDirectory;
const queryParams = currentDirectory ? `?directory=${encodeURIComponent(currentDirectory)}` : '';
const commandsWithScope = await Promise.all(
commands.map(async (cmd) => {
try {
const response = await fetch(`/api/config/commands/${encodeURIComponent(cmd.name)}${queryParams}`);
if (response.ok) {
const data = await response.json();
// Handle both web (data.scope) and desktop (data.sources.md.scope) response formats
const scope = data.scope ?? data.sources?.md?.scope;
return { ...cmd, scope: scope as CommandScope | undefined };
}
} catch {
// Ignore errors fetching scope
}
return cmd;
})
);
set({ commands: commandsWithScope, isLoading: false });
return true;
} catch (error) {
lastError = error;
@@ -102,10 +152,15 @@ export const useCommandsStore = create<CommandsStore>()(
if (config.agent) commandConfig.agent = config.agent;
if (config.model) commandConfig.model = config.model;
if (config.subtask !== undefined) commandConfig.subtask = config.subtask;
if (config.scope) commandConfig.scope = config.scope;
console.log('[CommandsStore] Command config to save:', commandConfig);
const response = await fetch(`/api/config/commands/${encodeURIComponent(config.name)}`, {
// Get current directory for project-level command support
const currentDirectory = useDirectoryStore.getState().currentDirectory;
const queryParams = currentDirectory ? `?directory=${encodeURIComponent(currentDirectory)}` : '';
const response = await fetch(`/api/config/commands/${encodeURIComponent(config.name)}${queryParams}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(commandConfig)
@@ -161,7 +216,11 @@ export const useCommandsStore = create<CommandsStore>()(
console.log('[CommandsStore] Command config to update:', commandConfig);
const response = await fetch(`/api/config/commands/${encodeURIComponent(name)}`, {
// Get current directory for project-level command support
const currentDirectory = useDirectoryStore.getState().currentDirectory;
const queryParams = currentDirectory ? `?directory=${encodeURIComponent(currentDirectory)}` : '';
const response = await fetch(`/api/config/commands/${encodeURIComponent(name)}${queryParams}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(commandConfig)
@@ -204,7 +263,11 @@ export const useCommandsStore = create<CommandsStore>()(
startConfigUpdate("Deleting command configuration…");
let requiresReload = false;
try {
const response = await fetch(`/api/config/commands/${encodeURIComponent(name)}`, {
// Get current directory for project-level command support
const currentDirectory = useDirectoryStore.getState().currentDirectory;
const queryParams = currentDirectory ? `?directory=${encodeURIComponent(currentDirectory)}` : '';
const response = await fetch(`/api/config/commands/${encodeURIComponent(name)}${queryParams}`, {
method: 'DELETE'
});
+12 -6
View File
@@ -2,7 +2,7 @@ import * as vscode from 'vscode';
import * as os from 'os';
import * as path from 'path';
import type { OpenCodeManager } from './opencode';
import { createAgent, createCommand, deleteAgent, deleteCommand, getAgentSources, getCommandSources, updateAgent, updateCommand } from './opencodeConfig';
import { createAgent, createCommand, deleteAgent, deleteCommand, getAgentSources, getCommandSources, updateAgent, updateCommand, type CommandScope, COMMAND_SCOPE } from './opencodeConfig';
import { removeProviderAuth } from './opencodeAuth';
export interface BridgeRequest {
@@ -686,19 +686,25 @@ export async function handleBridgeMessage(message: BridgeRequest, ctx?: BridgeCo
return { id, type, success: false, error: 'Command name is required' };
}
// Get working directory for project-level command support
const workingDirectory = ctx?.manager?.getWorkingDirectory() || vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
const normalizedMethod = typeof method === 'string' && method.trim() ? method.trim().toUpperCase() : 'GET';
if (normalizedMethod === 'GET') {
const sources = getCommandSources(commandName);
const sources = getCommandSources(commandName, workingDirectory);
return {
id,
type,
success: true,
data: { name: commandName, sources, isBuiltIn: !sources.md.exists && !sources.json.exists },
data: { name: commandName, sources, scope: sources.md.scope, isBuiltIn: !sources.md.exists && !sources.json.exists },
};
}
if (normalizedMethod === 'POST') {
createCommand(commandName, (body || {}) as Record<string, unknown>);
// Extract scope from body if present
const scopeValue = body?.scope as string | undefined;
const scope: CommandScope | undefined = scopeValue === 'project' ? COMMAND_SCOPE.PROJECT : scopeValue === 'user' ? COMMAND_SCOPE.USER : undefined;
createCommand(commandName, (body || {}) as Record<string, unknown>, workingDirectory, scope);
await ctx?.manager?.restart();
return {
id,
@@ -714,7 +720,7 @@ export async function handleBridgeMessage(message: BridgeRequest, ctx?: BridgeCo
}
if (normalizedMethod === 'PATCH') {
updateCommand(commandName, (body || {}) as Record<string, unknown>);
updateCommand(commandName, (body || {}) as Record<string, unknown>, workingDirectory);
await ctx?.manager?.restart();
return {
id,
@@ -730,7 +736,7 @@ export async function handleBridgeMessage(message: BridgeRequest, ctx?: BridgeCo
}
if (normalizedMethod === 'DELETE') {
deleteCommand(commandName);
deleteCommand(commandName, workingDirectory);
await ctx?.manager?.restart();
return {
id,
+163 -33
View File
@@ -10,9 +10,19 @@ const COMMAND_DIR = path.join(OPENCODE_CONFIG_DIR, 'command');
const CONFIG_FILE = path.join(OPENCODE_CONFIG_DIR, 'opencode.json');
const PROMPT_FILE_PATTERN = /^\{file:(.+)\}$/i;
// Command scope types
export const COMMAND_SCOPE = {
USER: 'user',
PROJECT: 'project'
} as const;
export type CommandScope = typeof COMMAND_SCOPE[keyof typeof COMMAND_SCOPE];
export type ConfigSources = {
md: { exists: boolean; path: string | null; fields: string[] };
md: { exists: boolean; path: string | null; fields: string[]; scope?: CommandScope | null };
json: { exists: boolean; path: string; fields: string[] };
projectMd?: { exists: boolean; path: string | null };
userMd?: { exists: boolean; path: string | null };
};
const ensureDirs = () => {
@@ -21,6 +31,58 @@ const ensureDirs = () => {
if (!fs.existsSync(COMMAND_DIR)) fs.mkdirSync(COMMAND_DIR, { recursive: true });
};
const ensureProjectCommandDir = (workingDirectory: string): string => {
const projectCommandDir = path.join(workingDirectory, '.opencode', 'command');
if (!fs.existsSync(projectCommandDir)) {
fs.mkdirSync(projectCommandDir, { recursive: true });
}
return projectCommandDir;
};
const getProjectCommandPath = (workingDirectory: string, commandName: string): string => {
return path.join(workingDirectory, '.opencode', 'command', `${commandName}.md`);
};
const getUserCommandPath = (commandName: string): string => {
return path.join(COMMAND_DIR, `${commandName}.md`);
};
export const getCommandScope = (commandName: string, workingDirectory?: string): { scope: CommandScope | null; path: string | null } => {
if (workingDirectory) {
const projectPath = getProjectCommandPath(workingDirectory, commandName);
if (fs.existsSync(projectPath)) {
return { scope: COMMAND_SCOPE.PROJECT, path: projectPath };
}
}
const userPath = getUserCommandPath(commandName);
if (fs.existsSync(userPath)) {
return { scope: COMMAND_SCOPE.USER, path: userPath };
}
return { scope: null, path: null };
};
const getCommandWritePath = (commandName: string, workingDirectory?: string, requestedScope?: CommandScope): { scope: CommandScope; path: string } => {
const existing = getCommandScope(commandName, workingDirectory);
if (existing.path) {
return { scope: existing.scope!, path: existing.path };
}
const scope = requestedScope || COMMAND_SCOPE.USER;
if (scope === COMMAND_SCOPE.PROJECT && workingDirectory) {
return {
scope: COMMAND_SCOPE.PROJECT,
path: getProjectCommandPath(workingDirectory, commandName)
};
}
return {
scope: COMMAND_SCOPE.USER,
path: getUserCommandPath(commandName)
};
};
const isPromptFileReference = (value: unknown): value is string => {
return typeof value === 'string' && PROMPT_FILE_PATTERN.test(value.trim());
};
@@ -73,7 +135,11 @@ const parseMdFile = (filePath: string): { frontmatter: Record<string, unknown>;
};
const writeMdFile = (filePath: string, frontmatter: Record<string, unknown>, body: string) => {
const yamlStr = yaml.stringify(frontmatter ?? {});
// Filter out null/undefined values - OpenCode expects keys to be omitted rather than set to null
const cleanedFrontmatter = Object.fromEntries(
Object.entries(frontmatter ?? {}).filter(([, value]) => value != null)
);
const yamlStr = yaml.stringify(cleanedFrontmatter);
const content = `---\n${yamlStr}---\n\n${body ?? ''}`.trimEnd();
fs.writeFileSync(filePath, content, 'utf8');
};
@@ -208,19 +274,31 @@ export const deleteAgent = (agentName: string) => {
}
};
export const getCommandSources = (commandName: string): ConfigSources => {
const mdPath = path.join(COMMAND_DIR, `${commandName}.md`);
const mdExists = fs.existsSync(mdPath);
export const getCommandSources = (commandName: string, workingDirectory?: string): ConfigSources => {
// Check project level first (takes precedence)
const projectPath = workingDirectory ? getProjectCommandPath(workingDirectory, commandName) : null;
const projectExists = projectPath ? fs.existsSync(projectPath) : false;
// Then check user level
const userPath = getUserCommandPath(commandName);
const userExists = fs.existsSync(userPath);
// Determine which md file to use (project takes precedence)
const mdPath = projectExists ? projectPath : (userExists ? userPath : null);
const mdExists = !!mdPath;
const mdScope = projectExists ? COMMAND_SCOPE.PROJECT : (userExists ? COMMAND_SCOPE.USER : null);
const config = readConfig();
const commandSection = (config.command as Record<string, unknown> | undefined)?.[commandName] as Record<string, unknown> | undefined;
const sources: ConfigSources = {
md: { exists: mdExists, path: mdExists ? mdPath : null, fields: [] },
md: { exists: mdExists, path: mdPath, scope: mdScope, fields: [] },
json: { exists: Boolean(commandSection), path: CONFIG_FILE, fields: [] },
projectMd: { exists: projectExists, path: projectPath },
userMd: { exists: userExists, path: userPath }
};
if (mdExists) {
if (mdExists && mdPath) {
const { frontmatter, body } = parseMdFile(mdPath);
sources.md.fields = Object.keys(frontmatter);
if (body) sources.md.fields.push('template');
@@ -233,39 +311,70 @@ export const getCommandSources = (commandName: string): ConfigSources => {
return sources;
};
export const createCommand = (commandName: string, config: Record<string, unknown>) => {
export const createCommand = (commandName: string, config: Record<string, unknown>, workingDirectory?: string, scope?: CommandScope) => {
ensureDirs();
const mdPath = path.join(COMMAND_DIR, `${commandName}.md`);
if (fs.existsSync(mdPath)) throw new Error(`Command ${commandName} already exists as .md file`);
// Check if command already exists at either level
const projectPath = workingDirectory ? getProjectCommandPath(workingDirectory, commandName) : null;
const userPath = getUserCommandPath(commandName);
if (projectPath && fs.existsSync(projectPath)) {
throw new Error(`Command ${commandName} already exists as project-level .md file`);
}
if (fs.existsSync(userPath)) {
throw new Error(`Command ${commandName} already exists as user-level .md file`);
}
const existingConfig = readConfig();
const commandMap = existingConfig.command as Record<string, unknown> | undefined;
if (commandMap?.[commandName]) throw new Error(`Command ${commandName} already exists in opencode.json`);
const { template, ...frontmatter } = config as Record<string, unknown> & { template?: unknown };
writeMdFile(mdPath, frontmatter, typeof template === 'string' ? template : '');
// Determine target path based on requested scope
let targetPath: string;
if (scope === COMMAND_SCOPE.PROJECT && workingDirectory) {
ensureProjectCommandDir(workingDirectory);
targetPath = projectPath!;
} else {
targetPath = userPath;
}
// Extract scope from config - it's only used for path determination, not written to file
const { template, scope: _ignored, ...frontmatter } = config as Record<string, unknown> & { template?: unknown; scope?: unknown };
void _ignored; // Scope is only used for path determination
writeMdFile(targetPath, frontmatter, typeof template === 'string' ? template : '');
};
export const updateCommand = (commandName: string, updates: Record<string, unknown>) => {
export const updateCommand = (commandName: string, updates: Record<string, unknown>, workingDirectory?: string) => {
ensureDirs();
const mdPath = path.join(COMMAND_DIR, `${commandName}.md`);
const mdExists = fs.existsSync(mdPath);
// Determine correct path: project level takes precedence
const { path: mdPath } = getCommandWritePath(commandName, workingDirectory);
const mdExists = mdPath ? fs.existsSync(mdPath) : false;
// If no existing md file, we need to create one (for built-in command overrides)
let targetPath = mdPath;
if (!mdExists) {
// No existing md file - this is a built-in override, create at user level
targetPath = getUserCommandPath(commandName);
}
const mdData = mdExists ? parseMdFile(mdPath) : null;
const mdData = mdExists && mdPath ? parseMdFile(mdPath) : { frontmatter: {} as Record<string, unknown>, body: '' };
const config = readConfig();
const commandMap = (config.command as Record<string, unknown> | undefined) ?? {};
const jsonSection = commandMap[commandName] as Record<string, unknown> | undefined;
let mdModified = false;
let jsonModified = false;
let creatingNewMd = !mdExists;
for (const [field, value] of Object.entries(updates || {})) {
if (field === 'template') {
const normalizedValue = typeof value === 'string' ? value : value == null ? '' : String(value);
if (mdExists && mdData) {
if (mdExists || creatingNewMd) {
mdData.body = normalizedValue;
mdModified = true;
continue;
@@ -278,34 +387,44 @@ export const updateCommand = (commandName: string, updates: Record<string, unkno
continue;
}
if (!config.command) config.command = {};
const target = (config.command as Record<string, unknown>)[commandName] as Record<string, unknown> | undefined;
(config.command as Record<string, unknown>)[commandName] = { ...(target || {}), template: normalizedValue };
jsonModified = true;
// Create new md file for the update
mdData.body = normalizedValue;
mdModified = true;
creatingNewMd = true;
continue;
}
const hasMdField = Boolean(mdData?.frontmatter?.[field] !== undefined);
const hasJsonField = Boolean(jsonSection?.[field] !== undefined);
if (hasMdField && mdData) {
if (hasMdField || creatingNewMd) {
mdData.frontmatter[field] = value;
mdModified = true;
continue;
}
if (!config.command) config.command = {};
const current = ((config.command as Record<string, unknown>)[commandName] as Record<string, unknown> | undefined) ?? {};
(config.command as Record<string, unknown>)[commandName] = { ...current, [field]: value };
jsonModified = true;
if (hasJsonField) {
if (!config.command) config.command = {};
const current = ((config.command as Record<string, unknown>)[commandName] as Record<string, unknown> | undefined) ?? {};
(config.command as Record<string, unknown>)[commandName] = { ...current, [field]: value };
jsonModified = true;
continue;
}
// New field - add to md if it exists or we're creating one
if (mdExists || creatingNewMd) {
mdData.frontmatter[field] = value;
mdModified = true;
} else {
if (!config.command) config.command = {};
const current = ((config.command as Record<string, unknown>)[commandName] as Record<string, unknown> | undefined) ?? {};
(config.command as Record<string, unknown>)[commandName] = { ...current, [field]: value };
jsonModified = true;
}
}
if (mdModified && mdData) {
writeMdFile(mdPath, mdData.frontmatter, mdData.body);
if (mdModified && targetPath) {
writeMdFile(targetPath, mdData.frontmatter, mdData.body);
}
if (jsonModified) {
@@ -313,15 +432,26 @@ export const updateCommand = (commandName: string, updates: Record<string, unkno
}
};
export const deleteCommand = (commandName: string) => {
const mdPath = path.join(COMMAND_DIR, `${commandName}.md`);
export const deleteCommand = (commandName: string, workingDirectory?: string) => {
let deleted = false;
if (fs.existsSync(mdPath)) {
fs.unlinkSync(mdPath);
// Check project level first (takes precedence)
if (workingDirectory) {
const projectPath = getProjectCommandPath(workingDirectory, commandName);
if (fs.existsSync(projectPath)) {
fs.unlinkSync(projectPath);
deleted = true;
}
}
// Then check user level
const userPath = getUserCommandPath(commandName);
if (fs.existsSync(userPath)) {
fs.unlinkSync(userPath);
deleted = true;
}
// Also check json config
const config = readConfig();
const commandMap = (config.command as Record<string, unknown> | undefined) ?? {};
if (commandMap[commandName] !== undefined) {
+16 -6
View File
@@ -1630,6 +1630,7 @@ function setupProxy(app) {
req.path.startsWith('/themes/custom') ||
req.path.startsWith('/config/agents') ||
req.path.startsWith('/config/settings') ||
req.path === '/config/reload' ||
req.path === '/health'
) {
return next();
@@ -2168,9 +2169,11 @@ async function main(options = {}) {
updateAgent,
deleteAgent,
getCommandSources,
getCommandScope,
createCommand,
updateCommand,
deleteCommand
deleteCommand,
COMMAND_SCOPE
} = await import('./lib/opencode-config.js');
app.get('/api/config/agents/:name', (req, res) => {
@@ -2259,11 +2262,13 @@ async function main(options = {}) {
app.get('/api/config/commands/:name', (req, res) => {
try {
const commandName = req.params.name;
const sources = getCommandSources(commandName);
const workingDirectory = req.query.directory || openCodeWorkingDirectory;
const sources = getCommandSources(commandName, workingDirectory);
res.json({
name: commandName,
sources: sources,
scope: sources.md.scope,
isBuiltIn: !sources.md.exists && !sources.json.exists
});
} catch (error) {
@@ -2275,12 +2280,14 @@ async function main(options = {}) {
app.post('/api/config/commands/:name', async (req, res) => {
try {
const commandName = req.params.name;
const config = req.body;
const { scope, ...config } = req.body;
const workingDirectory = req.query.directory || openCodeWorkingDirectory;
console.log('[Server] Creating command:', commandName);
console.log('[Server] Config received:', JSON.stringify(config, null, 2));
console.log('[Server] Scope:', scope, 'Working directory:', workingDirectory);
createCommand(commandName, config);
createCommand(commandName, config, workingDirectory, scope);
await refreshOpenCodeAfterConfigChange('command creation', {
commandName
});
@@ -2301,11 +2308,13 @@ async function main(options = {}) {
try {
const commandName = req.params.name;
const updates = req.body;
const workingDirectory = req.query.directory || openCodeWorkingDirectory;
console.log(`[Server] Updating command: ${commandName}`);
console.log('[Server] Updates:', JSON.stringify(updates, null, 2));
console.log('[Server] Working directory:', workingDirectory);
updateCommand(commandName, updates);
updateCommand(commandName, updates, workingDirectory);
await refreshOpenCodeAfterConfigChange('command update');
console.log(`[Server] Command ${commandName} updated successfully`);
@@ -2326,8 +2335,9 @@ async function main(options = {}) {
app.delete('/api/config/commands/:name', async (req, res) => {
try {
const commandName = req.params.name;
const workingDirectory = req.query.directory || openCodeWorkingDirectory;
deleteCommand(commandName);
deleteCommand(commandName, workingDirectory);
await refreshOpenCodeAfterConfigChange('command deletion');
res.json({
+180 -43
View File
@@ -10,6 +10,12 @@ const COMMAND_DIR = path.join(OPENCODE_CONFIG_DIR, 'command');
const CONFIG_FILE = path.join(OPENCODE_CONFIG_DIR, 'opencode.json');
const PROMPT_FILE_PATTERN = /^\{file:(.+)\}$/i;
// Command scope types
const COMMAND_SCOPE = {
USER: 'user',
PROJECT: 'project'
};
function ensureDirs() {
if (!fs.existsSync(OPENCODE_CONFIG_DIR)) {
fs.mkdirSync(OPENCODE_CONFIG_DIR, { recursive: true });
@@ -22,6 +28,76 @@ function ensureDirs() {
}
}
/**
* Ensure project-level command directory exists
*/
function ensureProjectCommandDir(workingDirectory) {
const projectCommandDir = path.join(workingDirectory, '.opencode', 'command');
if (!fs.existsSync(projectCommandDir)) {
fs.mkdirSync(projectCommandDir, { recursive: true });
}
return projectCommandDir;
}
/**
* Get project-level command path
*/
function getProjectCommandPath(workingDirectory, commandName) {
return path.join(workingDirectory, '.opencode', 'command', `${commandName}.md`);
}
/**
* Get user-level command path
*/
function getUserCommandPath(commandName) {
return path.join(COMMAND_DIR, `${commandName}.md`);
}
/**
* Determine command scope based on where the .md file exists
* Priority: project level > user level > null (built-in only)
*/
function getCommandScope(commandName, workingDirectory) {
if (workingDirectory) {
const projectPath = getProjectCommandPath(workingDirectory, commandName);
if (fs.existsSync(projectPath)) {
return { scope: COMMAND_SCOPE.PROJECT, path: projectPath };
}
}
const userPath = getUserCommandPath(commandName);
if (fs.existsSync(userPath)) {
return { scope: COMMAND_SCOPE.USER, path: userPath };
}
return { scope: null, path: null };
}
/**
* Get the path where a command should be written based on scope
*/
function getCommandWritePath(commandName, workingDirectory, requestedScope) {
// For updates: check existing location first (project takes precedence)
const existing = getCommandScope(commandName, workingDirectory);
if (existing.path) {
return existing;
}
// For new commands or built-in overrides: use requested scope or default to user
const scope = requestedScope || COMMAND_SCOPE.USER;
if (scope === COMMAND_SCOPE.PROJECT && workingDirectory) {
return {
scope: COMMAND_SCOPE.PROJECT,
path: getProjectCommandPath(workingDirectory, commandName)
};
}
return {
scope: COMMAND_SCOPE.USER,
path: getUserCommandPath(commandName)
};
}
function isPromptFileReference(value) {
if (typeof value !== 'string') {
return false;
@@ -111,7 +187,11 @@ function parseMdFile(filePath) {
function writeMdFile(filePath, frontmatter, body) {
try {
const yamlStr = yaml.stringify(frontmatter);
// Filter out null/undefined values - OpenCode expects keys to be omitted rather than set to null
const cleanedFrontmatter = Object.fromEntries(
Object.entries(frontmatter).filter(([, value]) => value != null)
);
const yamlStr = yaml.stringify(cleanedFrontmatter);
const content = `---\n${yamlStr}---\n\n${body}`;
fs.writeFileSync(filePath, content, 'utf8');
console.log(`Successfully wrote markdown file: ${filePath}`);
@@ -289,9 +369,19 @@ function deleteAgent(agentName) {
}
}
function getCommandSources(commandName) {
const mdPath = path.join(COMMAND_DIR, `${commandName}.md`);
const mdExists = fs.existsSync(mdPath);
function getCommandSources(commandName, workingDirectory) {
// Check project level first (takes precedence)
const projectPath = workingDirectory ? getProjectCommandPath(workingDirectory, commandName) : null;
const projectExists = projectPath && fs.existsSync(projectPath);
// Then check user level
const userPath = getUserCommandPath(commandName);
const userExists = fs.existsSync(userPath);
// Determine which md file to use (project takes precedence)
const mdPath = projectExists ? projectPath : (userExists ? userPath : null);
const mdExists = !!mdPath;
const mdScope = projectExists ? COMMAND_SCOPE.PROJECT : (userExists ? COMMAND_SCOPE.USER : null);
const config = readConfig();
const jsonSection = config.command?.[commandName];
@@ -299,13 +389,23 @@ function getCommandSources(commandName) {
const sources = {
md: {
exists: mdExists,
path: mdExists ? mdPath : null,
path: mdPath,
scope: mdScope,
fields: []
},
json: {
exists: !!jsonSection,
path: CONFIG_FILE,
fields: []
},
// Additional info about both levels
projectMd: {
exists: projectExists,
path: projectPath
},
userMd: {
exists: userExists,
path: userPath
}
};
@@ -324,13 +424,19 @@ function getCommandSources(commandName) {
return sources;
}
function createCommand(commandName, config) {
function createCommand(commandName, config, workingDirectory, scope) {
ensureDirs();
const mdPath = path.join(COMMAND_DIR, `${commandName}.md`);
if (fs.existsSync(mdPath)) {
throw new Error(`Command ${commandName} already exists as .md file`);
// Check if command already exists at either level
const projectPath = workingDirectory ? getProjectCommandPath(workingDirectory, commandName) : null;
const userPath = getUserCommandPath(commandName);
if (projectPath && fs.existsSync(projectPath)) {
throw new Error(`Command ${commandName} already exists as project-level .md file`);
}
if (fs.existsSync(userPath)) {
throw new Error(`Command ${commandName} already exists as user-level .md file`);
}
const existingConfig = readConfig();
@@ -338,31 +444,58 @@ function createCommand(commandName, config) {
throw new Error(`Command ${commandName} already exists in opencode.json`);
}
const { template, ...frontmatter } = config;
// Determine target path based on requested scope
let targetPath;
let targetScope;
if (scope === COMMAND_SCOPE.PROJECT && workingDirectory) {
ensureProjectCommandDir(workingDirectory);
targetPath = projectPath;
targetScope = COMMAND_SCOPE.PROJECT;
} else {
targetPath = userPath;
targetScope = COMMAND_SCOPE.USER;
}
writeMdFile(mdPath, frontmatter, template || '');
console.log(`Created new command: ${commandName}`);
// Extract scope from config - it's only used for path determination, not written to file
const { template, scope: _scopeFromConfig, ...frontmatter } = config;
writeMdFile(targetPath, frontmatter, template || '');
console.log(`Created new command: ${commandName} (scope: ${targetScope}, path: ${targetPath})`);
}
function updateCommand(commandName, updates) {
function updateCommand(commandName, updates, workingDirectory) {
ensureDirs();
const mdPath = path.join(COMMAND_DIR, `${commandName}.md`);
const mdExists = fs.existsSync(mdPath);
// Determine correct path: project level takes precedence
const { scope, path: mdPath } = getCommandWritePath(commandName, workingDirectory);
const mdExists = mdPath && fs.existsSync(mdPath);
// If no existing md file, we need to create one (for built-in command overrides)
// Default to user level for built-in overrides
let targetPath = mdPath;
let targetScope = scope;
if (!mdExists) {
// No existing md file - this is a built-in override, create at user level
targetPath = getUserCommandPath(commandName);
targetScope = COMMAND_SCOPE.USER;
}
let mdData = mdExists ? parseMdFile(mdPath) : null;
let mdData = mdExists ? parseMdFile(mdPath) : { frontmatter: {}, body: '' };
let config = readConfig();
const jsonSection = config.command?.[commandName];
let mdModified = false;
let jsonModified = false;
let creatingNewMd = !mdExists;
for (const [field, value] of Object.entries(updates)) {
if (field === 'template') {
const normalizedValue = typeof value === 'string' ? value : (value == null ? '' : String(value));
if (mdExists) {
if (mdExists || creatingNewMd) {
mdData.body = normalizedValue;
mdModified = true;
} else if (isPromptFileReference(jsonSection?.template)) {
@@ -377,10 +510,10 @@ function updateCommand(commandName, updates) {
config.command[commandName].template = normalizedValue;
jsonModified = true;
} else {
if (!config.command) config.command = {};
if (!config.command[commandName]) config.command[commandName] = {};
config.command[commandName].template = normalizedValue;
jsonModified = true;
// Create new md file for the update
mdData.body = normalizedValue;
mdModified = true;
creatingNewMd = true;
}
continue;
}
@@ -388,30 +521,20 @@ function updateCommand(commandName, updates) {
const inMd = mdData?.frontmatter?.[field] !== undefined;
const inJson = jsonSection?.[field] !== undefined;
if (inMd) {
if (inMd || creatingNewMd) {
mdData.frontmatter[field] = value;
mdModified = true;
} else if (inJson) {
if (!config.command) config.command = {};
if (!config.command[commandName]) config.command[commandName] = {};
config.command[commandName][field] = value;
jsonModified = true;
} else {
if (mdExists && jsonSection) {
if (!config.command) config.command = {};
if (!config.command[commandName]) config.command[commandName] = {};
config.command[commandName][field] = value;
jsonModified = true;
} else if (mdExists) {
// New field - add to md if it exists or we're creating one
if (mdExists || creatingNewMd) {
mdData.frontmatter[field] = value;
mdModified = true;
} else {
if (!config.command) config.command = {};
if (!config.command[commandName]) config.command[commandName] = {};
config.command[commandName][field] = value;
@@ -421,26 +544,38 @@ function updateCommand(commandName, updates) {
}
if (mdModified) {
writeMdFile(mdPath, mdData.frontmatter, mdData.body);
writeMdFile(targetPath, mdData.frontmatter, mdData.body);
}
if (jsonModified) {
writeConfig(config);
}
console.log(`Updated command: ${commandName} (md: ${mdModified}, json: ${jsonModified})`);
console.log(`Updated command: ${commandName} (scope: ${targetScope}, md: ${mdModified}, json: ${jsonModified})`);
}
function deleteCommand(commandName) {
const mdPath = path.join(COMMAND_DIR, `${commandName}.md`);
function deleteCommand(commandName, workingDirectory) {
let deleted = false;
if (fs.existsSync(mdPath)) {
fs.unlinkSync(mdPath);
console.log(`Deleted command .md file: ${mdPath}`);
// Check project level first (takes precedence)
if (workingDirectory) {
const projectPath = getProjectCommandPath(workingDirectory, commandName);
if (fs.existsSync(projectPath)) {
fs.unlinkSync(projectPath);
console.log(`Deleted project-level command .md file: ${projectPath}`);
deleted = true;
}
}
// Then check user level
const userPath = getUserCommandPath(commandName);
if (fs.existsSync(userPath)) {
fs.unlinkSync(userPath);
console.log(`Deleted user-level command .md file: ${userPath}`);
deleted = true;
}
// Also check json config
const config = readConfig();
if (config.command?.[commandName]) {
delete config.command[commandName];
@@ -460,6 +595,7 @@ export {
updateAgent,
deleteAgent,
getCommandSources,
getCommandScope,
createCommand,
updateCommand,
deleteCommand,
@@ -467,5 +603,6 @@ export {
writeConfig,
AGENT_DIR,
COMMAND_DIR,
CONFIG_FILE
CONFIG_FILE,
COMMAND_SCOPE
};