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:
+1
-1
@@ -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 auto‑send (including attachments).
|
- Added queued message mode with chips, batching, and idle auto‑send (including attachments).
|
||||||
- Added queue mode toggle to OpenChamber settings (chat section) with persistence across runtimes.
|
- Added queue mode toggle to OpenChamber settings (chat section) with persistence across runtimes.
|
||||||
- Fixed scroll position persistence for active conversation turns across session switches.
|
- 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
|
## [1.3.7] - 2025-12-28
|
||||||
|
|||||||
@@ -74,7 +74,7 @@
|
|||||||
},
|
},
|
||||||
"packages/desktop": {
|
"packages/desktop": {
|
||||||
"name": "@openchamber/desktop",
|
"name": "@openchamber/desktop",
|
||||||
"version": "1.3.5",
|
"version": "1.3.7",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@openchamber/ui": "workspace:*",
|
"@openchamber/ui": "workspace:*",
|
||||||
"@tauri-apps/plugin-notification": "^2.3.3",
|
"@tauri-apps/plugin-notification": "^2.3.3",
|
||||||
@@ -97,7 +97,7 @@
|
|||||||
},
|
},
|
||||||
"packages/ui": {
|
"packages/ui": {
|
||||||
"name": "@openchamber/ui",
|
"name": "@openchamber/ui",
|
||||||
"version": "1.3.5",
|
"version": "1.3.7",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@fontsource/ibm-plex-mono": "^5.2.7",
|
"@fontsource/ibm-plex-mono": "^5.2.7",
|
||||||
"@fontsource/ibm-plex-sans": "^5.1.1",
|
"@fontsource/ibm-plex-sans": "^5.1.1",
|
||||||
@@ -165,7 +165,7 @@
|
|||||||
},
|
},
|
||||||
"packages/vscode": {
|
"packages/vscode": {
|
||||||
"name": "openchamber",
|
"name": "openchamber",
|
||||||
"version": "1.3.5",
|
"version": "1.3.7",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@openchamber/ui": "workspace:*",
|
"@openchamber/ui": "workspace:*",
|
||||||
"@opencode-ai/sdk": "^1.0.185",
|
"@opencode-ai/sdk": "^1.0.185",
|
||||||
@@ -184,7 +184,7 @@
|
|||||||
},
|
},
|
||||||
"packages/web": {
|
"packages/web": {
|
||||||
"name": "@openchamber/web",
|
"name": "@openchamber/web",
|
||||||
"version": "1.3.5",
|
"version": "1.3.7",
|
||||||
"bin": {
|
"bin": {
|
||||||
"openchamber": "./bin/cli.js",
|
"openchamber": "./bin/cli.js",
|
||||||
},
|
},
|
||||||
@@ -517,7 +517,7 @@
|
|||||||
|
|
||||||
"@openchamber/web": ["@openchamber/web@workspace:packages/web"],
|
"@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=="],
|
"@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=="],
|
"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=="],
|
"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=="],
|
"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=="],
|
"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=="],
|
"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=="],
|
"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=="],
|
"electron/@types/node/undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||||
|
|||||||
@@ -236,6 +236,7 @@ struct ConfigErrorResponse {
|
|||||||
struct ConfigMetadataResponse {
|
struct ConfigMetadataResponse {
|
||||||
name: String,
|
name: String,
|
||||||
sources: opencode_config::ConfigSources,
|
sources: opencode_config::ConfigSources,
|
||||||
|
scope: Option<opencode_config::CommandScope>,
|
||||||
is_built_in: bool,
|
is_built_in: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1197,6 +1198,7 @@ async fn handle_agent_route(
|
|||||||
ConfigMetadataResponse {
|
ConfigMetadataResponse {
|
||||||
name,
|
name,
|
||||||
is_built_in: !sources.md.exists && !sources.json.exists,
|
is_built_in: !sources.md.exists && !sources.json.exists,
|
||||||
|
scope: None,
|
||||||
sources,
|
sources,
|
||||||
},
|
},
|
||||||
)),
|
)),
|
||||||
@@ -1320,17 +1322,24 @@ async fn handle_command_route(
|
|||||||
req: Request<Body>,
|
req: Request<Body>,
|
||||||
name: String,
|
name: String,
|
||||||
) -> Result<Response<Body>, StatusCode> {
|
) -> Result<Response<Body>, StatusCode> {
|
||||||
|
// Get working directory for project-level command detection
|
||||||
|
let working_directory = state.opencode.get_working_directory();
|
||||||
|
|
||||||
match method {
|
match method {
|
||||||
Method::GET => {
|
Method::GET => {
|
||||||
match opencode_config::get_command_sources(&name).await {
|
match opencode_config::get_command_sources(&name, Some(&working_directory)).await {
|
||||||
Ok(sources) => Ok(json_response(
|
Ok(sources) => {
|
||||||
StatusCode::OK,
|
let scope = sources.md.scope.clone();
|
||||||
ConfigMetadataResponse {
|
Ok(json_response(
|
||||||
name,
|
StatusCode::OK,
|
||||||
is_built_in: !sources.md.exists && !sources.json.exists,
|
ConfigMetadataResponse {
|
||||||
sources,
|
name,
|
||||||
},
|
is_built_in: !sources.md.exists && !sources.json.exists,
|
||||||
)),
|
scope,
|
||||||
|
sources,
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
error!("[desktop:config] Failed to read command sources: {}", err);
|
error!("[desktop:config] Failed to read command sources: {}", err);
|
||||||
Ok(config_error_response(
|
Ok(config_error_response(
|
||||||
@@ -1345,8 +1354,17 @@ async fn handle_command_route(
|
|||||||
Ok(data) => data,
|
Ok(data) => data,
|
||||||
Err(resp) => return Ok(resp),
|
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(()) => {
|
Ok(()) => {
|
||||||
if let Err(resp) =
|
if let Err(resp) =
|
||||||
refresh_opencode_after_config_change(state, "command creation").await
|
refresh_opencode_after_config_change(state, "command creation").await
|
||||||
@@ -1382,7 +1400,7 @@ async fn handle_command_route(
|
|||||||
Err(resp) => return Ok(resp),
|
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(()) => {
|
Ok(()) => {
|
||||||
if let Err(resp) =
|
if let Err(resp) =
|
||||||
refresh_opencode_after_config_change(state, "command update").await
|
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(()) => {
|
Ok(()) => {
|
||||||
if let Err(resp) =
|
if let Err(resp) =
|
||||||
refresh_opencode_after_config_change(state, "command deletion").await
|
refresh_opencode_after_config_change(state, "command deletion").await
|
||||||
|
|||||||
@@ -11,12 +11,29 @@ use tokio::fs;
|
|||||||
static PROMPT_FILE_PATTERN: Lazy<Regex> =
|
static PROMPT_FILE_PATTERN: Lazy<Regex> =
|
||||||
Lazy::new(|| Regex::new(r"(?i)^\{file:(.+)\}$").expect("valid 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)]
|
#[derive(Debug, Serialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct SourceInfo {
|
pub struct SourceInfo {
|
||||||
pub exists: bool,
|
pub exists: bool,
|
||||||
pub path: Option<String>,
|
pub path: Option<String>,
|
||||||
pub fields: Vec<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)]
|
#[derive(Debug, Serialize)]
|
||||||
@@ -24,6 +41,10 @@ pub struct SourceInfo {
|
|||||||
pub struct ConfigSources {
|
pub struct ConfigSources {
|
||||||
pub md: SourceInfo,
|
pub md: SourceInfo,
|
||||||
pub json: 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
|
/// Get OpenCode config directory path
|
||||||
@@ -39,7 +60,7 @@ fn get_agent_dir() -> PathBuf {
|
|||||||
get_config_dir().join("agent")
|
get_config_dir().join("agent")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get command directory path
|
/// Get user-level command directory path
|
||||||
fn get_command_dir() -> PathBuf {
|
fn get_command_dir() -> PathBuf {
|
||||||
get_config_dir().join("command")
|
get_config_dir().join("command")
|
||||||
}
|
}
|
||||||
@@ -49,6 +70,64 @@ fn get_config_file() -> PathBuf {
|
|||||||
get_config_dir().join("opencode.json")
|
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
|
/// Ensure required directories exist
|
||||||
async fn ensure_dirs() -> Result<()> {
|
async fn ensure_dirs() -> Result<()> {
|
||||||
let config_dir = get_config_dir();
|
let config_dir = get_config_dir();
|
||||||
@@ -240,7 +319,13 @@ async fn write_md_file(
|
|||||||
frontmatter: &HashMap<String, Value>,
|
frontmatter: &HashMap<String, Value>,
|
||||||
body: &str,
|
body: &str,
|
||||||
) -> Result<()> {
|
) -> 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);
|
let content = format!("---\n{}---\n\n{}", yaml_str, body);
|
||||||
|
|
||||||
fs::write(file_path, content).await?;
|
fs::write(file_path, content).await?;
|
||||||
@@ -281,12 +366,16 @@ pub async fn get_agent_sources(agent_name: &str) -> Result<ConfigSources> {
|
|||||||
exists: md_exists,
|
exists: md_exists,
|
||||||
path: md_exists.then(|| md_path.display().to_string()),
|
path: md_exists.then(|| md_path.display().to_string()),
|
||||||
fields: md_fields,
|
fields: md_fields,
|
||||||
|
scope: None, // Agents don't have project/user scope distinction yet
|
||||||
},
|
},
|
||||||
json: SourceInfo {
|
json: SourceInfo {
|
||||||
exists: json_section.is_some(),
|
exists: json_section.is_some(),
|
||||||
path: Some(get_config_file().display().to_string()),
|
path: Some(get_config_file().display().to_string()),
|
||||||
fields: json_fields,
|
fields: json_fields,
|
||||||
|
scope: None,
|
||||||
},
|
},
|
||||||
|
project_md: None,
|
||||||
|
user_md: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(sources)
|
Ok(sources)
|
||||||
@@ -528,18 +617,34 @@ pub async fn delete_agent(agent_name: &str) -> Result<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Get information about where command configuration is stored
|
/// 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?;
|
ensure_dirs().await?;
|
||||||
|
|
||||||
let md_path = get_command_dir().join(format!("{}.md", command_name));
|
// Check project level first (takes precedence)
|
||||||
let md_exists = md_path.exists();
|
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();
|
let mut md_fields = Vec::new();
|
||||||
if md_exists {
|
if md_exists {
|
||||||
let md_data = parse_md_file(&md_path).await?;
|
if let Some(ref path) = md_path {
|
||||||
md_fields.extend(md_data.frontmatter.keys().cloned());
|
let md_data = parse_md_file(path).await?;
|
||||||
if !md_data.body.trim().is_empty() {
|
md_fields.extend(md_data.frontmatter.keys().cloned());
|
||||||
md_fields.push("template".to_string());
|
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 {
|
let sources = ConfigSources {
|
||||||
md: SourceInfo {
|
md: SourceInfo {
|
||||||
exists: md_exists,
|
exists: md_exists,
|
||||||
path: md_exists.then(|| md_path.display().to_string()),
|
path: md_path.map(|p| p.display().to_string()),
|
||||||
fields: md_fields,
|
fields: md_fields,
|
||||||
|
scope: md_scope,
|
||||||
},
|
},
|
||||||
json: SourceInfo {
|
json: SourceInfo {
|
||||||
exists: json_section.is_some(),
|
exists: json_section.is_some(),
|
||||||
path: Some(get_config_file().display().to_string()),
|
path: Some(get_config_file().display().to_string()),
|
||||||
fields: json_fields,
|
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)
|
Ok(sources)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create new command as .md file
|
/// 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?;
|
ensure_dirs().await?;
|
||||||
|
|
||||||
let md_path = get_command_dir().join(format!("{}.md", command_name));
|
// Check if command already exists at either level
|
||||||
|
if let Some(wd) = working_directory {
|
||||||
// Check if command already exists
|
let project_path = get_project_command_path(wd, command_name);
|
||||||
if md_path.exists() {
|
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!(
|
return Err(anyhow!(
|
||||||
"Command {} already exists as .md file",
|
"Command {} already exists as user-level .md file",
|
||||||
command_name
|
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 mut frontmatter = config.clone();
|
||||||
let template = frontmatter
|
let template = frontmatter
|
||||||
.remove("template")
|
.remove("template")
|
||||||
.and_then(|v| v.as_str().map(|s| s.to_string()))
|
.and_then(|v| v.as_str().map(|s| s.to_string()))
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
|
frontmatter.remove("scope"); // Remove scope - it's not a valid command field
|
||||||
|
|
||||||
// Write .md file
|
// Write .md file
|
||||||
write_md_file(&md_path, &frontmatter, &template).await?;
|
write_md_file(&target_path, &frontmatter, &template).await?;
|
||||||
info!("Created new command: {}", command_name);
|
info!("Created new command: {} (scope: {:?}, path: {})", command_name, target_scope, target_path.display());
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -612,17 +754,29 @@ pub async fn create_command(command_name: &str, config: &HashMap<String, Value>)
|
|||||||
pub async fn update_command(
|
pub async fn update_command(
|
||||||
command_name: &str,
|
command_name: &str,
|
||||||
updates: &HashMap<String, Value>,
|
updates: &HashMap<String, Value>,
|
||||||
|
working_directory: Option<&Path>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
ensure_dirs().await?;
|
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();
|
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 {
|
let mut md_data = if md_exists {
|
||||||
Some(parse_md_file(&md_path).await?)
|
Some(parse_md_file(&md_path).await?)
|
||||||
} else {
|
} else {
|
||||||
None
|
Some(MdData { frontmatter: HashMap::new(), body: String::new() })
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let creating_new_md = !md_exists;
|
||||||
|
|
||||||
let mut config = read_config().await?;
|
let mut config = read_config().await?;
|
||||||
let mut existing_command = config
|
let mut existing_command = config
|
||||||
@@ -657,7 +811,7 @@ pub async fn update_command(
|
|||||||
if field == "template" {
|
if field == "template" {
|
||||||
let normalized_value = value.as_str().unwrap_or("").to_string();
|
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 {
|
if let Some(ref mut data) = md_data {
|
||||||
data.body = normalized_value.clone();
|
data.body = normalized_value.clone();
|
||||||
md_modified = true;
|
md_modified = true;
|
||||||
@@ -677,10 +831,11 @@ pub async fn update_command(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Write template directly to JSON entry (file ref or inline string)
|
// Create new md file for the update
|
||||||
existing_command.insert("template".to_string(), Value::String(normalized_value));
|
if let Some(ref mut data) = md_data {
|
||||||
json_modified = true;
|
data.body = normalized_value;
|
||||||
|
md_modified = true;
|
||||||
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -691,7 +846,7 @@ pub async fn update_command(
|
|||||||
.unwrap_or(false);
|
.unwrap_or(false);
|
||||||
let in_json = existing_command.contains_key(field);
|
let in_json = existing_command.contains_key(field);
|
||||||
|
|
||||||
if in_md {
|
if in_md || creating_new_md {
|
||||||
// Update in .md frontmatter
|
// Update in .md frontmatter
|
||||||
if let Some(ref mut data) = md_data {
|
if let Some(ref mut data) = md_data {
|
||||||
data.frontmatter.insert(field.clone(), value.clone());
|
data.frontmatter.insert(field.clone(), value.clone());
|
||||||
@@ -702,19 +857,13 @@ pub async fn update_command(
|
|||||||
existing_command.insert(field.clone(), value.clone());
|
existing_command.insert(field.clone(), value.clone());
|
||||||
json_modified = true;
|
json_modified = true;
|
||||||
} else {
|
} else {
|
||||||
// Field not defined - apply priority rules
|
// New field - add to md if it exists or we're creating one
|
||||||
if md_exists && !existing_command.is_empty() {
|
if md_exists || creating_new_md {
|
||||||
// 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
|
|
||||||
if let Some(ref mut data) = md_data {
|
if let Some(ref mut data) = md_data {
|
||||||
data.frontmatter.insert(field.clone(), value.clone());
|
data.frontmatter.insert(field.clone(), value.clone());
|
||||||
md_modified = true;
|
md_modified = true;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Only JSON or built-in → add/create section in opencode.json
|
|
||||||
existing_command.insert(field.clone(), value.clone());
|
existing_command.insert(field.clone(), value.clone());
|
||||||
json_modified = true;
|
json_modified = true;
|
||||||
}
|
}
|
||||||
@@ -724,7 +873,7 @@ pub async fn update_command(
|
|||||||
// Write changes
|
// Write changes
|
||||||
if md_modified {
|
if md_modified {
|
||||||
if let Some(data) = md_data {
|
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!(
|
info!(
|
||||||
"Updated command: {} (md: {}, json: {})",
|
"Updated command: {} (scope: {:?}, md: {}, json: {})",
|
||||||
command_name, md_modified, json_modified
|
command_name, scope, md_modified, json_modified
|
||||||
);
|
);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Delete command configuration
|
/// Delete command configuration
|
||||||
pub async fn delete_command(command_name: &str) -> Result<()> {
|
pub async fn delete_command(command_name: &str, working_directory: Option<&Path>) -> Result<()> {
|
||||||
let md_path = get_command_dir().join(format!("{}.md", command_name));
|
|
||||||
let mut deleted = false;
|
let mut deleted = false;
|
||||||
|
|
||||||
// 1. Delete .md file if exists
|
// 1. Check project level first (takes precedence)
|
||||||
if md_path.exists() {
|
if let Some(wd) = working_directory {
|
||||||
fs::remove_file(&md_path).await?;
|
let project_path = get_project_command_path(wd, command_name);
|
||||||
info!("Deleted command .md file: {}", md_path.display());
|
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;
|
deleted = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Remove section from opencode.json if exists
|
// 3. Remove section from opencode.json if exists
|
||||||
let mut config = read_config().await?;
|
let mut config = read_config().await?;
|
||||||
if let Some(commands) = config.get_mut("command").and_then(|v| v.as_object_mut()) {
|
if let Some(commands) = config.get_mut("command").and_then(|v| v.as_object_mut()) {
|
||||||
if commands.remove(command_name).is_some() {
|
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 {
|
if !deleted {
|
||||||
return Err(anyhow!("Command \"{}\" not found", command_name));
|
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 { Input } from '@/components/ui/input';
|
||||||
import { Textarea } from '@/components/ui/textarea';
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { useCommandsStore, type CommandConfig } from '@/stores/useCommandsStore';
|
import { useCommandsStore, type CommandConfig, type CommandScope } from '@/stores/useCommandsStore';
|
||||||
import { RiCheckLine, RiInformationLine, RiSaveLine, RiTerminalBoxLine } from '@remixicon/react';
|
import { RiCheckLine, RiInformationLine, RiSaveLine, RiTerminalBoxLine, RiUser3Line, RiFolderLine } from '@remixicon/react';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { ModelSelector } from '../agents/ModelSelector';
|
import { ModelSelector } from '../agents/ModelSelector';
|
||||||
import { AgentSelector } from './AgentSelector';
|
import { AgentSelector } from './AgentSelector';
|
||||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
|
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
|
||||||
import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay';
|
import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay';
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
} from '@/components/ui/select';
|
||||||
|
|
||||||
export const CommandsPage: React.FC = () => {
|
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 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 [description, setDescription] = React.useState('');
|
||||||
const [agent, setAgent] = React.useState('');
|
const [agent, setAgent] = React.useState('');
|
||||||
const [model, setModel] = React.useState('');
|
const [model, setModel] = React.useState('');
|
||||||
@@ -26,27 +33,28 @@ export const CommandsPage: React.FC = () => {
|
|||||||
const [isSaving, setIsSaving] = React.useState(false);
|
const [isSaving, setIsSaving] = React.useState(false);
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
if (isNewCommand) {
|
if (isNewCommand && commandDraft) {
|
||||||
|
// Prefill from draft (for new or duplicated commands)
|
||||||
setName(selectedCommandName || '');
|
setDraftName(commandDraft.name || '');
|
||||||
setDescription('');
|
setDraftScope(commandDraft.scope || 'user');
|
||||||
setAgent('');
|
setDescription(commandDraft.description || '');
|
||||||
setModel('');
|
setAgent(commandDraft.agent || '');
|
||||||
setTemplate('');
|
setModel(commandDraft.model || '');
|
||||||
setSubtask(false);
|
setTemplate(commandDraft.template || '');
|
||||||
|
setSubtask(commandDraft.subtask || false);
|
||||||
} else if (selectedCommand) {
|
} else if (selectedCommand) {
|
||||||
|
|
||||||
setName(selectedCommand.name);
|
|
||||||
setDescription(selectedCommand.description || '');
|
setDescription(selectedCommand.description || '');
|
||||||
setAgent(selectedCommand.agent || '');
|
setAgent(selectedCommand.agent || '');
|
||||||
setModel(selectedCommand.model || '');
|
setModel(selectedCommand.model || '');
|
||||||
setTemplate(selectedCommand.template || '');
|
setTemplate(selectedCommand.template || '');
|
||||||
setSubtask(selectedCommand.subtask || false);
|
setSubtask(selectedCommand.subtask || false);
|
||||||
}
|
}
|
||||||
}, [selectedCommand, isNewCommand, selectedCommandName, commands]);
|
}, [selectedCommand, isNewCommand, selectedCommandName, commands, commandDraft]);
|
||||||
|
|
||||||
const handleSave = async () => {
|
const handleSave = async () => {
|
||||||
if (!name.trim()) {
|
const commandName = isNewCommand ? draftName.trim().replace(/\s+/g, '-') : selectedCommandName?.trim();
|
||||||
|
|
||||||
|
if (!commandName) {
|
||||||
toast.error('Command name is required');
|
toast.error('Command name is required');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -56,6 +64,12 @@ export const CommandsPage: React.FC = () => {
|
|||||||
return;
|
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);
|
setIsSaving(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -63,19 +77,23 @@ export const CommandsPage: React.FC = () => {
|
|||||||
const trimmedModel = model.trim();
|
const trimmedModel = model.trim();
|
||||||
const trimmedTemplate = template.trim();
|
const trimmedTemplate = template.trim();
|
||||||
const config: CommandConfig = {
|
const config: CommandConfig = {
|
||||||
name: name.trim(),
|
name: commandName,
|
||||||
description: description.trim() || undefined,
|
description: description.trim() || undefined,
|
||||||
agent: trimmedAgent === '' ? null : trimmedAgent,
|
agent: trimmedAgent === '' ? null : trimmedAgent,
|
||||||
model: trimmedModel === '' ? null : trimmedModel,
|
model: trimmedModel === '' ? null : trimmedModel,
|
||||||
template: trimmedTemplate,
|
template: trimmedTemplate,
|
||||||
subtask,
|
subtask,
|
||||||
|
scope: isNewCommand ? draftScope : undefined,
|
||||||
};
|
};
|
||||||
|
|
||||||
let success: boolean;
|
let success: boolean;
|
||||||
if (isNewCommand) {
|
if (isNewCommand) {
|
||||||
success = await createCommand(config);
|
success = await createCommand(config);
|
||||||
|
if (success) {
|
||||||
|
setCommandDraft(null); // Clear draft after successful creation
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
success = await updateCommand(name, config);
|
success = await updateCommand(commandName, config);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (success) {
|
if (success) {
|
||||||
@@ -108,7 +126,7 @@ export const CommandsPage: React.FC = () => {
|
|||||||
{}
|
{}
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<h1 className="typography-ui-header font-semibold text-lg">
|
<h1 className="typography-ui-header font-semibold text-lg">
|
||||||
{isNewCommand ? 'New Command' : name}
|
{isNewCommand ? 'New Command' : `/${selectedCommandName}`}
|
||||||
</h1>
|
</h1>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -121,20 +139,54 @@ export const CommandsPage: React.FC = () => {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
{isNewCommand && (
|
||||||
<label className="typography-ui-label font-medium text-foreground">
|
<div className="space-y-2">
|
||||||
Command Name
|
<label className="typography-ui-label font-medium text-foreground">
|
||||||
</label>
|
Command Name & Scope
|
||||||
<Input
|
</label>
|
||||||
value={name}
|
<div className="flex items-center gap-2">
|
||||||
onChange={(e) => setName(e.target.value)}
|
<div className="flex items-center flex-1">
|
||||||
placeholder="my-command"
|
<span className="typography-ui-label text-muted-foreground mr-1">/</span>
|
||||||
disabled={!isNewCommand}
|
<Input
|
||||||
/>
|
value={draftName}
|
||||||
<p className="typography-meta text-muted-foreground">
|
onChange={(e) => setDraftName(e.target.value)}
|
||||||
Used with slash (/) prefix in chat
|
placeholder="command-name"
|
||||||
</p>
|
className="flex-1 text-foreground placeholder:text-muted-foreground"
|
||||||
</div>
|
/>
|
||||||
|
</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">
|
<div className="space-y-2">
|
||||||
<label className="typography-ui-label font-medium text-foreground">
|
<label className="typography-ui-label font-medium text-foreground">
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import {
|
|||||||
DialogFooter,
|
DialogFooter,
|
||||||
DialogHeader,
|
DialogHeader,
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
DialogTrigger,
|
|
||||||
} from '@/components/ui/dialog';
|
} from '@/components/ui/dialog';
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
@@ -18,8 +17,8 @@ import {
|
|||||||
DropdownMenuItem,
|
DropdownMenuItem,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from '@/components/ui/dropdown-menu';
|
} from '@/components/ui/dropdown-menu';
|
||||||
import { RiAddLine, RiTerminalBoxLine, RiMore2Line, RiDeleteBinLine, RiFileCopyLine } from '@remixicon/react';
|
import { RiAddLine, RiTerminalBoxLine, RiMore2Line, RiDeleteBinLine, RiFileCopyLine, RiRestartLine, RiEditLine } from '@remixicon/react';
|
||||||
import { useCommandsStore, type Command } from '@/stores/useCommandsStore';
|
import { useCommandsStore, isCommandBuiltIn, type Command } from '@/stores/useCommandsStore';
|
||||||
import { useUIStore } from '@/stores/useUIStore';
|
import { useUIStore } from '@/stores/useUIStore';
|
||||||
import { useDeviceInfo } from '@/lib/device';
|
import { useDeviceInfo } from '@/lib/device';
|
||||||
import { isVSCodeRuntime } from '@/lib/desktop';
|
import { isVSCodeRuntime } from '@/lib/desktop';
|
||||||
@@ -31,13 +30,15 @@ interface CommandsSidebarProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const CommandsSidebar: React.FC<CommandsSidebarProps> = ({ onItemSelect }) => {
|
export const CommandsSidebar: React.FC<CommandsSidebarProps> = ({ onItemSelect }) => {
|
||||||
const [newCommandName, setNewCommandName] = React.useState('');
|
const [renameDialogCommand, setRenameDialogCommand] = React.useState<Command | null>(null);
|
||||||
const [isCreateDialogOpen, setIsCreateDialogOpen] = React.useState(false);
|
const [renameNewName, setRenameNewName] = React.useState('');
|
||||||
|
|
||||||
const {
|
const {
|
||||||
selectedCommandName,
|
selectedCommandName,
|
||||||
commands,
|
commands,
|
||||||
setSelectedCommand,
|
setSelectedCommand,
|
||||||
|
setCommandDraft,
|
||||||
|
createCommand,
|
||||||
deleteCommand,
|
deleteCommand,
|
||||||
loadCommands,
|
loadCommands,
|
||||||
} = useCommandsStore();
|
} = useCommandsStore();
|
||||||
@@ -67,22 +68,19 @@ export const CommandsSidebar: React.FC<CommandsSidebarProps> = ({ onItemSelect }
|
|||||||
? 'bg-background'
|
? 'bg-background'
|
||||||
: 'bg-sidebar';
|
: 'bg-sidebar';
|
||||||
|
|
||||||
const handleCreateCommand = () => {
|
const handleCreateNew = () => {
|
||||||
if (!newCommandName.trim()) {
|
// Generate unique name
|
||||||
toast.error('Command name is required');
|
const baseName = 'new-command';
|
||||||
return;
|
let newName = baseName;
|
||||||
|
let counter = 1;
|
||||||
|
while (commands.some((c) => c.name === newName)) {
|
||||||
|
newName = `${baseName}-${counter}`;
|
||||||
|
counter++;
|
||||||
}
|
}
|
||||||
|
|
||||||
const sanitizedName = newCommandName.trim().replace(/\s+/g, '-');
|
// Set draft and open the page for editing
|
||||||
|
setCommandDraft({ name: newName, scope: 'user' });
|
||||||
if (commands.some((cmd) => cmd.name === sanitizedName)) {
|
setSelectedCommand(newName);
|
||||||
toast.error('A command with this name already exists');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setSelectedCommand(sanitizedName);
|
|
||||||
setNewCommandName('');
|
|
||||||
setIsCreateDialogOpen(false);
|
|
||||||
|
|
||||||
if (isMobile) {
|
if (isMobile) {
|
||||||
setSidebarOpen(false);
|
setSidebarOpen(false);
|
||||||
@@ -90,6 +88,11 @@ export const CommandsSidebar: React.FC<CommandsSidebarProps> = ({ onItemSelect }
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleDeleteCommand = async (command: Command) => {
|
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}"?`)) {
|
if (window.confirm(`Are you sure you want to delete command "${command.name}"?`)) {
|
||||||
const success = await deleteCommand(command.name);
|
const success = await deleteCommand(command.name);
|
||||||
if (success) {
|
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 handleDuplicateCommand = (command: Command) => {
|
||||||
const baseName = command.name;
|
const baseName = command.name;
|
||||||
let copyNumber = 1;
|
let copyNumber = 1;
|
||||||
@@ -110,85 +128,185 @@ export const CommandsSidebar: React.FC<CommandsSidebarProps> = ({ onItemSelect }
|
|||||||
newName = `${baseName}-copy-${copyNumber}`;
|
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);
|
setSelectedCommand(newName);
|
||||||
setIsCreateDialogOpen(false);
|
|
||||||
|
|
||||||
if (isMobile) {
|
if (isMobile) {
|
||||||
setSidebarOpen(false);
|
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 (
|
return (
|
||||||
<div className={cn('flex h-full flex-col', bgClass)}>
|
<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={cn('border-b px-3', isMobile ? 'mt-2 py-3' : 'py-3')}>
|
<div className="flex items-center justify-between gap-2">
|
||||||
<div className="flex items-center justify-between gap-2">
|
<span className="typography-meta text-muted-foreground">Total {commands.length}</span>
|
||||||
<span className="typography-meta text-muted-foreground">Total {commands.length}</span>
|
<Button
|
||||||
<DialogTrigger asChild>
|
type="button"
|
||||||
<Button type="button" variant="ghost" size="icon" className="h-7 w-7 -my-1 text-muted-foreground">
|
variant="ghost"
|
||||||
<RiAddLine className="size-4" />
|
size="icon"
|
||||||
</Button>
|
className="h-7 w-7 -my-1 text-muted-foreground"
|
||||||
</DialogTrigger>
|
onClick={handleCreateNew}
|
||||||
</div>
|
>
|
||||||
|
<RiAddLine className="size-4" />
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<ScrollableOverlay outerClassName="flex-1 min-h-0" className="space-y-1 px-3 py-2">
|
<ScrollableOverlay outerClassName="flex-1 min-h-0" className="space-y-1 px-3 py-2">
|
||||||
{commands.length === 0 ? (
|
{commands.length === 0 ? (
|
||||||
<div className="py-12 px-4 text-center text-muted-foreground">
|
<div className="py-12 px-4 text-center text-muted-foreground">
|
||||||
<RiTerminalBoxLine className="mx-auto mb-3 h-10 w-10 opacity-50" />
|
<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-ui-label font-medium">No commands configured</p>
|
||||||
<p className="typography-meta mt-1 opacity-75">Use the + button above to create one</p>
|
<p className="typography-meta mt-1 opacity-75">Use the + button above to create one</p>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
|
<>
|
||||||
|
{builtInCommands.length > 0 && (
|
||||||
<>
|
<>
|
||||||
{[...commands].sort((a, b) => a.name.localeCompare(b.name)).map((command) => (
|
<div className="px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
|
||||||
<CommandListItem
|
Built-in Commands
|
||||||
key={command.name}
|
</div>
|
||||||
command={command}
|
{[...builtInCommands].sort((a, b) => a.name.localeCompare(b.name)).map((command) => (
|
||||||
isSelected={selectedCommandName === command.name}
|
<CommandListItem
|
||||||
onSelect={() => {
|
key={command.name}
|
||||||
setSelectedCommand(command.name);
|
command={command}
|
||||||
onItemSelect?.();
|
isSelected={selectedCommandName === command.name}
|
||||||
if (isMobile) {
|
onSelect={() => {
|
||||||
setSidebarOpen(false);
|
setSelectedCommand(command.name);
|
||||||
}
|
onItemSelect?.();
|
||||||
}}
|
if (isMobile) {
|
||||||
onDelete={() => handleDeleteCommand(command)}
|
setSidebarOpen(false);
|
||||||
onDuplicate={() => handleDuplicateCommand(command)}
|
}
|
||||||
/>
|
}}
|
||||||
))}
|
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>
|
<DialogContent>
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>Create New Command</DialogTitle>
|
<DialogTitle>Rename Command</DialogTitle>
|
||||||
<DialogDescription>
|
<DialogDescription>
|
||||||
Enter a unique name for your new slash command
|
Enter a new name for the command "/{renameDialogCommand?.name}"
|
||||||
</DialogDescription>
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<Input
|
<Input
|
||||||
value={newCommandName}
|
value={renameNewName}
|
||||||
onChange={(e) => setNewCommandName(e.target.value)}
|
onChange={(e) => setRenameNewName(e.target.value)}
|
||||||
placeholder="Command name..."
|
placeholder="New command name..."
|
||||||
className="text-foreground placeholder:text-muted-foreground"
|
className="text-foreground placeholder:text-muted-foreground"
|
||||||
onKeyDown={(e) => {
|
onKeyDown={(e) => {
|
||||||
if (e.key === 'Enter') {
|
if (e.key === 'Enter') {
|
||||||
handleCreateCommand();
|
handleRenameCommand();
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
onClick={() => setIsCreateDialogOpen(false)}
|
onClick={() => setRenameDialogCommand(null)}
|
||||||
className="text-foreground hover:bg-muted hover:text-foreground"
|
className="text-foreground hover:bg-muted hover:text-foreground"
|
||||||
>
|
>
|
||||||
Cancel
|
Cancel
|
||||||
</Button>
|
</Button>
|
||||||
<ButtonLarge onClick={handleCreateCommand}>
|
<ButtonLarge onClick={handleRenameCommand}>
|
||||||
Create
|
Rename
|
||||||
</ButtonLarge>
|
</ButtonLarge>
|
||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
@@ -201,7 +319,9 @@ interface CommandListItemProps {
|
|||||||
command: Command;
|
command: Command;
|
||||||
isSelected: boolean;
|
isSelected: boolean;
|
||||||
onSelect: () => void;
|
onSelect: () => void;
|
||||||
onDelete: () => void;
|
onDelete?: () => void;
|
||||||
|
onReset?: () => void;
|
||||||
|
onRename?: () => void;
|
||||||
onDuplicate: () => void;
|
onDuplicate: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -210,6 +330,8 @@ const CommandListItem: React.FC<CommandListItemProps> = ({
|
|||||||
isSelected,
|
isSelected,
|
||||||
onSelect,
|
onSelect,
|
||||||
onDelete,
|
onDelete,
|
||||||
|
onReset,
|
||||||
|
onRename,
|
||||||
onDuplicate,
|
onDuplicate,
|
||||||
}) => {
|
}) => {
|
||||||
return (
|
return (
|
||||||
@@ -229,6 +351,11 @@ const CommandListItem: React.FC<CommandListItemProps> = ({
|
|||||||
<span className="typography-ui-label font-normal truncate text-foreground">
|
<span className="typography-ui-label font-normal truncate text-foreground">
|
||||||
/{command.name}
|
/{command.name}
|
||||||
</span>
|
</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>
|
</div>
|
||||||
|
|
||||||
{command.description && (
|
{command.description && (
|
||||||
@@ -249,6 +376,18 @@ const CommandListItem: React.FC<CommandListItemProps> = ({
|
|||||||
</Button>
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end" className="w-fit min-w-20">
|
<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
|
<DropdownMenuItem
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
@@ -259,16 +398,30 @@ const CommandListItem: React.FC<CommandListItemProps> = ({
|
|||||||
Duplicate
|
Duplicate
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
|
||||||
<DropdownMenuItem
|
{onReset && (
|
||||||
onClick={(e) => {
|
<DropdownMenuItem
|
||||||
e.stopPropagation();
|
onClick={(e) => {
|
||||||
onDelete();
|
e.stopPropagation();
|
||||||
}}
|
onReset();
|
||||||
className="text-destructive focus:text-destructive"
|
}}
|
||||||
>
|
>
|
||||||
<RiDeleteBinLine className="h-4 w-4 mr-px" />
|
<RiRestartLine className="h-4 w-4 mr-px" />
|
||||||
Delete
|
Reset
|
||||||
</DropdownMenuItem>
|
</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>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
import React from 'react';
|
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 { useUpdateStore } from '@/stores/useUpdateStore';
|
||||||
import { UpdateDialog } from '@/components/ui/UpdateDialog';
|
import { UpdateDialog } from '@/components/ui/UpdateDialog';
|
||||||
import { useDeviceInfo } from '@/lib/device';
|
import { useDeviceInfo } from '@/lib/device';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
import { reloadOpenCodeConfiguration } from '@/stores/useAgentsStore';
|
||||||
|
|
||||||
const GITHUB_URL = 'https://github.com/btriapitsyn/openchamber';
|
const GITHUB_URL = 'https://github.com/btriapitsyn/openchamber';
|
||||||
|
|
||||||
@@ -45,6 +46,15 @@ export const AboutSettings: React.FC = () => {
|
|||||||
if (isMobile) {
|
if (isMobile) {
|
||||||
return (
|
return (
|
||||||
<div className="w-full space-y-2">
|
<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 */}
|
{/* Version row with update status */}
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<span className="typography-meta text-muted-foreground">
|
<span className="typography-meta text-muted-foreground">
|
||||||
|
|||||||
@@ -10,6 +10,9 @@ import {
|
|||||||
import { emitConfigChange, scopeMatches, subscribeToConfigChanges } from "@/lib/configSync";
|
import { emitConfigChange, scopeMatches, subscribeToConfigChanges } from "@/lib/configSync";
|
||||||
import { getSafeStorage } from "./utils/safeStorage";
|
import { getSafeStorage } from "./utils/safeStorage";
|
||||||
import { useConfigStore } from "@/stores/useConfigStore";
|
import { useConfigStore } from "@/stores/useConfigStore";
|
||||||
|
import { useDirectoryStore } from "@/stores/useDirectoryStore";
|
||||||
|
|
||||||
|
export type CommandScope = 'user' | 'project';
|
||||||
|
|
||||||
export interface CommandConfig {
|
export interface CommandConfig {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -18,12 +21,20 @@ export interface CommandConfig {
|
|||||||
model?: string | null;
|
model?: string | null;
|
||||||
template?: string;
|
template?: string;
|
||||||
subtask?: boolean;
|
subtask?: boolean;
|
||||||
|
scope?: CommandScope;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Command extends CommandConfig {
|
export interface Command extends CommandConfig {
|
||||||
isBuiltIn?: boolean;
|
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 CONFIG_EVENT_SOURCE = "useCommandsStore";
|
||||||
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
const MAX_HEALTH_WAIT_MS = 20000;
|
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_INCREMENT_MS = 200;
|
||||||
const SLOW_HEALTH_POLL_MAX_MS = 2000;
|
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 {
|
interface CommandsStore {
|
||||||
|
|
||||||
selectedCommandName: string | null;
|
selectedCommandName: string | null;
|
||||||
commands: Command[];
|
commands: Command[];
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
|
commandDraft: CommandDraft | null;
|
||||||
|
|
||||||
setSelectedCommand: (name: string | null) => void;
|
setSelectedCommand: (name: string | null) => void;
|
||||||
|
setCommandDraft: (draft: CommandDraft | null) => void;
|
||||||
loadCommands: () => Promise<boolean>;
|
loadCommands: () => Promise<boolean>;
|
||||||
createCommand: (config: CommandConfig) => Promise<boolean>;
|
createCommand: (config: CommandConfig) => Promise<boolean>;
|
||||||
updateCommand: (name: string, config: Partial<CommandConfig>) => Promise<boolean>;
|
updateCommand: (name: string, config: Partial<CommandConfig>) => Promise<boolean>;
|
||||||
@@ -61,11 +84,16 @@ export const useCommandsStore = create<CommandsStore>()(
|
|||||||
selectedCommandName: null,
|
selectedCommandName: null,
|
||||||
commands: [],
|
commands: [],
|
||||||
isLoading: false,
|
isLoading: false,
|
||||||
|
commandDraft: null,
|
||||||
|
|
||||||
setSelectedCommand: (name: string | null) => {
|
setSelectedCommand: (name: string | null) => {
|
||||||
set({ selectedCommandName: name });
|
set({ selectedCommandName: name });
|
||||||
},
|
},
|
||||||
|
|
||||||
|
setCommandDraft: (draft: CommandDraft | null) => {
|
||||||
|
set({ commandDraft: draft });
|
||||||
|
},
|
||||||
|
|
||||||
loadCommands: async () => {
|
loadCommands: async () => {
|
||||||
set({ isLoading: true });
|
set({ isLoading: true });
|
||||||
const previousCommands = get().commands;
|
const previousCommands = get().commands;
|
||||||
@@ -74,7 +102,29 @@ export const useCommandsStore = create<CommandsStore>()(
|
|||||||
for (let attempt = 0; attempt < 3; attempt++) {
|
for (let attempt = 0; attempt < 3; attempt++) {
|
||||||
try {
|
try {
|
||||||
const commands = await opencodeClient.listCommandsWithDetails();
|
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;
|
return true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
lastError = error;
|
lastError = error;
|
||||||
@@ -102,10 +152,15 @@ export const useCommandsStore = create<CommandsStore>()(
|
|||||||
if (config.agent) commandConfig.agent = config.agent;
|
if (config.agent) commandConfig.agent = config.agent;
|
||||||
if (config.model) commandConfig.model = config.model;
|
if (config.model) commandConfig.model = config.model;
|
||||||
if (config.subtask !== undefined) commandConfig.subtask = config.subtask;
|
if (config.subtask !== undefined) commandConfig.subtask = config.subtask;
|
||||||
|
if (config.scope) commandConfig.scope = config.scope;
|
||||||
|
|
||||||
console.log('[CommandsStore] Command config to save:', commandConfig);
|
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',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(commandConfig)
|
body: JSON.stringify(commandConfig)
|
||||||
@@ -161,7 +216,11 @@ export const useCommandsStore = create<CommandsStore>()(
|
|||||||
|
|
||||||
console.log('[CommandsStore] Command config to update:', commandConfig);
|
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',
|
method: 'PATCH',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(commandConfig)
|
body: JSON.stringify(commandConfig)
|
||||||
@@ -204,7 +263,11 @@ export const useCommandsStore = create<CommandsStore>()(
|
|||||||
startConfigUpdate("Deleting command configuration…");
|
startConfigUpdate("Deleting command configuration…");
|
||||||
let requiresReload = false;
|
let requiresReload = false;
|
||||||
try {
|
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'
|
method: 'DELETE'
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import * as vscode from 'vscode';
|
|||||||
import * as os from 'os';
|
import * as os from 'os';
|
||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
import type { OpenCodeManager } from './opencode';
|
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';
|
import { removeProviderAuth } from './opencodeAuth';
|
||||||
|
|
||||||
export interface BridgeRequest {
|
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' };
|
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';
|
const normalizedMethod = typeof method === 'string' && method.trim() ? method.trim().toUpperCase() : 'GET';
|
||||||
if (normalizedMethod === 'GET') {
|
if (normalizedMethod === 'GET') {
|
||||||
const sources = getCommandSources(commandName);
|
const sources = getCommandSources(commandName, workingDirectory);
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
type,
|
type,
|
||||||
success: true,
|
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') {
|
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();
|
await ctx?.manager?.restart();
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
@@ -714,7 +720,7 @@ export async function handleBridgeMessage(message: BridgeRequest, ctx?: BridgeCo
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (normalizedMethod === 'PATCH') {
|
if (normalizedMethod === 'PATCH') {
|
||||||
updateCommand(commandName, (body || {}) as Record<string, unknown>);
|
updateCommand(commandName, (body || {}) as Record<string, unknown>, workingDirectory);
|
||||||
await ctx?.manager?.restart();
|
await ctx?.manager?.restart();
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
@@ -730,7 +736,7 @@ export async function handleBridgeMessage(message: BridgeRequest, ctx?: BridgeCo
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (normalizedMethod === 'DELETE') {
|
if (normalizedMethod === 'DELETE') {
|
||||||
deleteCommand(commandName);
|
deleteCommand(commandName, workingDirectory);
|
||||||
await ctx?.manager?.restart();
|
await ctx?.manager?.restart();
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
|
|||||||
@@ -10,9 +10,19 @@ const COMMAND_DIR = path.join(OPENCODE_CONFIG_DIR, 'command');
|
|||||||
const CONFIG_FILE = path.join(OPENCODE_CONFIG_DIR, 'opencode.json');
|
const CONFIG_FILE = path.join(OPENCODE_CONFIG_DIR, 'opencode.json');
|
||||||
const PROMPT_FILE_PATTERN = /^\{file:(.+)\}$/i;
|
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 = {
|
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[] };
|
json: { exists: boolean; path: string; fields: string[] };
|
||||||
|
projectMd?: { exists: boolean; path: string | null };
|
||||||
|
userMd?: { exists: boolean; path: string | null };
|
||||||
};
|
};
|
||||||
|
|
||||||
const ensureDirs = () => {
|
const ensureDirs = () => {
|
||||||
@@ -21,6 +31,58 @@ const ensureDirs = () => {
|
|||||||
if (!fs.existsSync(COMMAND_DIR)) fs.mkdirSync(COMMAND_DIR, { recursive: true });
|
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 => {
|
const isPromptFileReference = (value: unknown): value is string => {
|
||||||
return typeof value === 'string' && PROMPT_FILE_PATTERN.test(value.trim());
|
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 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();
|
const content = `---\n${yamlStr}---\n\n${body ?? ''}`.trimEnd();
|
||||||
fs.writeFileSync(filePath, content, 'utf8');
|
fs.writeFileSync(filePath, content, 'utf8');
|
||||||
};
|
};
|
||||||
@@ -208,19 +274,31 @@ export const deleteAgent = (agentName: string) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getCommandSources = (commandName: string): ConfigSources => {
|
export const getCommandSources = (commandName: string, workingDirectory?: string): ConfigSources => {
|
||||||
const mdPath = path.join(COMMAND_DIR, `${commandName}.md`);
|
// Check project level first (takes precedence)
|
||||||
const mdExists = fs.existsSync(mdPath);
|
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 config = readConfig();
|
||||||
const commandSection = (config.command as Record<string, unknown> | undefined)?.[commandName] as Record<string, unknown> | undefined;
|
const commandSection = (config.command as Record<string, unknown> | undefined)?.[commandName] as Record<string, unknown> | undefined;
|
||||||
|
|
||||||
const sources: ConfigSources = {
|
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: [] },
|
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);
|
const { frontmatter, body } = parseMdFile(mdPath);
|
||||||
sources.md.fields = Object.keys(frontmatter);
|
sources.md.fields = Object.keys(frontmatter);
|
||||||
if (body) sources.md.fields.push('template');
|
if (body) sources.md.fields.push('template');
|
||||||
@@ -233,39 +311,70 @@ export const getCommandSources = (commandName: string): ConfigSources => {
|
|||||||
return sources;
|
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();
|
ensureDirs();
|
||||||
|
|
||||||
const mdPath = path.join(COMMAND_DIR, `${commandName}.md`);
|
// Check if command already exists at either level
|
||||||
if (fs.existsSync(mdPath)) throw new Error(`Command ${commandName} already exists as .md file`);
|
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 existingConfig = readConfig();
|
||||||
const commandMap = existingConfig.command as Record<string, unknown> | undefined;
|
const commandMap = existingConfig.command as Record<string, unknown> | undefined;
|
||||||
if (commandMap?.[commandName]) throw new Error(`Command ${commandName} already exists in opencode.json`);
|
if (commandMap?.[commandName]) throw new Error(`Command ${commandName} already exists in opencode.json`);
|
||||||
|
|
||||||
const { template, ...frontmatter } = config as Record<string, unknown> & { template?: unknown };
|
// Determine target path based on requested scope
|
||||||
writeMdFile(mdPath, frontmatter, typeof template === 'string' ? template : '');
|
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();
|
ensureDirs();
|
||||||
|
|
||||||
const mdPath = path.join(COMMAND_DIR, `${commandName}.md`);
|
// Determine correct path: project level takes precedence
|
||||||
const mdExists = fs.existsSync(mdPath);
|
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 config = readConfig();
|
||||||
const commandMap = (config.command as Record<string, unknown> | undefined) ?? {};
|
const commandMap = (config.command as Record<string, unknown> | undefined) ?? {};
|
||||||
const jsonSection = commandMap[commandName] as Record<string, unknown> | undefined;
|
const jsonSection = commandMap[commandName] as Record<string, unknown> | undefined;
|
||||||
|
|
||||||
let mdModified = false;
|
let mdModified = false;
|
||||||
let jsonModified = false;
|
let jsonModified = false;
|
||||||
|
let creatingNewMd = !mdExists;
|
||||||
|
|
||||||
for (const [field, value] of Object.entries(updates || {})) {
|
for (const [field, value] of Object.entries(updates || {})) {
|
||||||
if (field === 'template') {
|
if (field === 'template') {
|
||||||
const normalizedValue = typeof value === 'string' ? value : value == null ? '' : String(value);
|
const normalizedValue = typeof value === 'string' ? value : value == null ? '' : String(value);
|
||||||
|
|
||||||
if (mdExists && mdData) {
|
if (mdExists || creatingNewMd) {
|
||||||
mdData.body = normalizedValue;
|
mdData.body = normalizedValue;
|
||||||
mdModified = true;
|
mdModified = true;
|
||||||
continue;
|
continue;
|
||||||
@@ -278,34 +387,44 @@ export const updateCommand = (commandName: string, updates: Record<string, unkno
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!config.command) config.command = {};
|
// Create new md file for the update
|
||||||
const target = (config.command as Record<string, unknown>)[commandName] as Record<string, unknown> | undefined;
|
mdData.body = normalizedValue;
|
||||||
(config.command as Record<string, unknown>)[commandName] = { ...(target || {}), template: normalizedValue };
|
mdModified = true;
|
||||||
jsonModified = true;
|
creatingNewMd = true;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const hasMdField = Boolean(mdData?.frontmatter?.[field] !== undefined);
|
const hasMdField = Boolean(mdData?.frontmatter?.[field] !== undefined);
|
||||||
const hasJsonField = Boolean(jsonSection?.[field] !== undefined);
|
const hasJsonField = Boolean(jsonSection?.[field] !== undefined);
|
||||||
|
|
||||||
if (hasMdField && mdData) {
|
if (hasMdField || creatingNewMd) {
|
||||||
mdData.frontmatter[field] = value;
|
mdData.frontmatter[field] = value;
|
||||||
mdModified = true;
|
mdModified = true;
|
||||||
continue;
|
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 (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;
|
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) {
|
if (mdModified && targetPath) {
|
||||||
writeMdFile(mdPath, mdData.frontmatter, mdData.body);
|
writeMdFile(targetPath, mdData.frontmatter, mdData.body);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (jsonModified) {
|
if (jsonModified) {
|
||||||
@@ -313,15 +432,26 @@ export const updateCommand = (commandName: string, updates: Record<string, unkno
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const deleteCommand = (commandName: string) => {
|
export const deleteCommand = (commandName: string, workingDirectory?: string) => {
|
||||||
const mdPath = path.join(COMMAND_DIR, `${commandName}.md`);
|
|
||||||
let deleted = false;
|
let deleted = false;
|
||||||
|
|
||||||
if (fs.existsSync(mdPath)) {
|
// Check project level first (takes precedence)
|
||||||
fs.unlinkSync(mdPath);
|
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;
|
deleted = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Also check json config
|
||||||
const config = readConfig();
|
const config = readConfig();
|
||||||
const commandMap = (config.command as Record<string, unknown> | undefined) ?? {};
|
const commandMap = (config.command as Record<string, unknown> | undefined) ?? {};
|
||||||
if (commandMap[commandName] !== undefined) {
|
if (commandMap[commandName] !== undefined) {
|
||||||
|
|||||||
@@ -1630,6 +1630,7 @@ function setupProxy(app) {
|
|||||||
req.path.startsWith('/themes/custom') ||
|
req.path.startsWith('/themes/custom') ||
|
||||||
req.path.startsWith('/config/agents') ||
|
req.path.startsWith('/config/agents') ||
|
||||||
req.path.startsWith('/config/settings') ||
|
req.path.startsWith('/config/settings') ||
|
||||||
|
req.path === '/config/reload' ||
|
||||||
req.path === '/health'
|
req.path === '/health'
|
||||||
) {
|
) {
|
||||||
return next();
|
return next();
|
||||||
@@ -2168,9 +2169,11 @@ async function main(options = {}) {
|
|||||||
updateAgent,
|
updateAgent,
|
||||||
deleteAgent,
|
deleteAgent,
|
||||||
getCommandSources,
|
getCommandSources,
|
||||||
|
getCommandScope,
|
||||||
createCommand,
|
createCommand,
|
||||||
updateCommand,
|
updateCommand,
|
||||||
deleteCommand
|
deleteCommand,
|
||||||
|
COMMAND_SCOPE
|
||||||
} = await import('./lib/opencode-config.js');
|
} = await import('./lib/opencode-config.js');
|
||||||
|
|
||||||
app.get('/api/config/agents/:name', (req, res) => {
|
app.get('/api/config/agents/:name', (req, res) => {
|
||||||
@@ -2259,11 +2262,13 @@ async function main(options = {}) {
|
|||||||
app.get('/api/config/commands/:name', (req, res) => {
|
app.get('/api/config/commands/:name', (req, res) => {
|
||||||
try {
|
try {
|
||||||
const commandName = req.params.name;
|
const commandName = req.params.name;
|
||||||
const sources = getCommandSources(commandName);
|
const workingDirectory = req.query.directory || openCodeWorkingDirectory;
|
||||||
|
const sources = getCommandSources(commandName, workingDirectory);
|
||||||
|
|
||||||
res.json({
|
res.json({
|
||||||
name: commandName,
|
name: commandName,
|
||||||
sources: sources,
|
sources: sources,
|
||||||
|
scope: sources.md.scope,
|
||||||
isBuiltIn: !sources.md.exists && !sources.json.exists
|
isBuiltIn: !sources.md.exists && !sources.json.exists
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -2275,12 +2280,14 @@ async function main(options = {}) {
|
|||||||
app.post('/api/config/commands/:name', async (req, res) => {
|
app.post('/api/config/commands/:name', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const commandName = req.params.name;
|
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] Creating command:', commandName);
|
||||||
console.log('[Server] Config received:', JSON.stringify(config, null, 2));
|
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', {
|
await refreshOpenCodeAfterConfigChange('command creation', {
|
||||||
commandName
|
commandName
|
||||||
});
|
});
|
||||||
@@ -2301,11 +2308,13 @@ async function main(options = {}) {
|
|||||||
try {
|
try {
|
||||||
const commandName = req.params.name;
|
const commandName = req.params.name;
|
||||||
const updates = req.body;
|
const updates = req.body;
|
||||||
|
const workingDirectory = req.query.directory || openCodeWorkingDirectory;
|
||||||
|
|
||||||
console.log(`[Server] Updating command: ${commandName}`);
|
console.log(`[Server] Updating command: ${commandName}`);
|
||||||
console.log('[Server] Updates:', JSON.stringify(updates, null, 2));
|
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');
|
await refreshOpenCodeAfterConfigChange('command update');
|
||||||
|
|
||||||
console.log(`[Server] Command ${commandName} updated successfully`);
|
console.log(`[Server] Command ${commandName} updated successfully`);
|
||||||
@@ -2326,8 +2335,9 @@ async function main(options = {}) {
|
|||||||
app.delete('/api/config/commands/:name', async (req, res) => {
|
app.delete('/api/config/commands/:name', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const commandName = req.params.name;
|
const commandName = req.params.name;
|
||||||
|
const workingDirectory = req.query.directory || openCodeWorkingDirectory;
|
||||||
|
|
||||||
deleteCommand(commandName);
|
deleteCommand(commandName, workingDirectory);
|
||||||
await refreshOpenCodeAfterConfigChange('command deletion');
|
await refreshOpenCodeAfterConfigChange('command deletion');
|
||||||
|
|
||||||
res.json({
|
res.json({
|
||||||
|
|||||||
@@ -10,6 +10,12 @@ const COMMAND_DIR = path.join(OPENCODE_CONFIG_DIR, 'command');
|
|||||||
const CONFIG_FILE = path.join(OPENCODE_CONFIG_DIR, 'opencode.json');
|
const CONFIG_FILE = path.join(OPENCODE_CONFIG_DIR, 'opencode.json');
|
||||||
const PROMPT_FILE_PATTERN = /^\{file:(.+)\}$/i;
|
const PROMPT_FILE_PATTERN = /^\{file:(.+)\}$/i;
|
||||||
|
|
||||||
|
// Command scope types
|
||||||
|
const COMMAND_SCOPE = {
|
||||||
|
USER: 'user',
|
||||||
|
PROJECT: 'project'
|
||||||
|
};
|
||||||
|
|
||||||
function ensureDirs() {
|
function ensureDirs() {
|
||||||
if (!fs.existsSync(OPENCODE_CONFIG_DIR)) {
|
if (!fs.existsSync(OPENCODE_CONFIG_DIR)) {
|
||||||
fs.mkdirSync(OPENCODE_CONFIG_DIR, { recursive: true });
|
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) {
|
function isPromptFileReference(value) {
|
||||||
if (typeof value !== 'string') {
|
if (typeof value !== 'string') {
|
||||||
return false;
|
return false;
|
||||||
@@ -111,7 +187,11 @@ function parseMdFile(filePath) {
|
|||||||
|
|
||||||
function writeMdFile(filePath, frontmatter, body) {
|
function writeMdFile(filePath, frontmatter, body) {
|
||||||
try {
|
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}`;
|
const content = `---\n${yamlStr}---\n\n${body}`;
|
||||||
fs.writeFileSync(filePath, content, 'utf8');
|
fs.writeFileSync(filePath, content, 'utf8');
|
||||||
console.log(`Successfully wrote markdown file: ${filePath}`);
|
console.log(`Successfully wrote markdown file: ${filePath}`);
|
||||||
@@ -289,9 +369,19 @@ function deleteAgent(agentName) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function getCommandSources(commandName) {
|
function getCommandSources(commandName, workingDirectory) {
|
||||||
const mdPath = path.join(COMMAND_DIR, `${commandName}.md`);
|
// Check project level first (takes precedence)
|
||||||
const mdExists = fs.existsSync(mdPath);
|
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 config = readConfig();
|
||||||
const jsonSection = config.command?.[commandName];
|
const jsonSection = config.command?.[commandName];
|
||||||
@@ -299,13 +389,23 @@ function getCommandSources(commandName) {
|
|||||||
const sources = {
|
const sources = {
|
||||||
md: {
|
md: {
|
||||||
exists: mdExists,
|
exists: mdExists,
|
||||||
path: mdExists ? mdPath : null,
|
path: mdPath,
|
||||||
|
scope: mdScope,
|
||||||
fields: []
|
fields: []
|
||||||
},
|
},
|
||||||
json: {
|
json: {
|
||||||
exists: !!jsonSection,
|
exists: !!jsonSection,
|
||||||
path: CONFIG_FILE,
|
path: CONFIG_FILE,
|
||||||
fields: []
|
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;
|
return sources;
|
||||||
}
|
}
|
||||||
|
|
||||||
function createCommand(commandName, config) {
|
function createCommand(commandName, config, workingDirectory, scope) {
|
||||||
ensureDirs();
|
ensureDirs();
|
||||||
|
|
||||||
const mdPath = path.join(COMMAND_DIR, `${commandName}.md`);
|
// Check if command already exists at either level
|
||||||
|
const projectPath = workingDirectory ? getProjectCommandPath(workingDirectory, commandName) : null;
|
||||||
if (fs.existsSync(mdPath)) {
|
const userPath = getUserCommandPath(commandName);
|
||||||
throw new Error(`Command ${commandName} already exists as .md file`);
|
|
||||||
|
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 existingConfig = readConfig();
|
||||||
@@ -338,31 +444,58 @@ function createCommand(commandName, config) {
|
|||||||
throw new Error(`Command ${commandName} already exists in opencode.json`);
|
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 || '');
|
// Extract scope from config - it's only used for path determination, not written to file
|
||||||
console.log(`Created new command: ${commandName}`);
|
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();
|
ensureDirs();
|
||||||
|
|
||||||
const mdPath = path.join(COMMAND_DIR, `${commandName}.md`);
|
// Determine correct path: project level takes precedence
|
||||||
const mdExists = fs.existsSync(mdPath);
|
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();
|
let config = readConfig();
|
||||||
const jsonSection = config.command?.[commandName];
|
const jsonSection = config.command?.[commandName];
|
||||||
|
|
||||||
let mdModified = false;
|
let mdModified = false;
|
||||||
let jsonModified = false;
|
let jsonModified = false;
|
||||||
|
let creatingNewMd = !mdExists;
|
||||||
|
|
||||||
for (const [field, value] of Object.entries(updates)) {
|
for (const [field, value] of Object.entries(updates)) {
|
||||||
|
|
||||||
if (field === 'template') {
|
if (field === 'template') {
|
||||||
const normalizedValue = typeof value === 'string' ? value : (value == null ? '' : String(value));
|
const normalizedValue = typeof value === 'string' ? value : (value == null ? '' : String(value));
|
||||||
|
|
||||||
if (mdExists) {
|
if (mdExists || creatingNewMd) {
|
||||||
mdData.body = normalizedValue;
|
mdData.body = normalizedValue;
|
||||||
mdModified = true;
|
mdModified = true;
|
||||||
} else if (isPromptFileReference(jsonSection?.template)) {
|
} else if (isPromptFileReference(jsonSection?.template)) {
|
||||||
@@ -377,10 +510,10 @@ function updateCommand(commandName, updates) {
|
|||||||
config.command[commandName].template = normalizedValue;
|
config.command[commandName].template = normalizedValue;
|
||||||
jsonModified = true;
|
jsonModified = true;
|
||||||
} else {
|
} else {
|
||||||
if (!config.command) config.command = {};
|
// Create new md file for the update
|
||||||
if (!config.command[commandName]) config.command[commandName] = {};
|
mdData.body = normalizedValue;
|
||||||
config.command[commandName].template = normalizedValue;
|
mdModified = true;
|
||||||
jsonModified = true;
|
creatingNewMd = true;
|
||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -388,30 +521,20 @@ function updateCommand(commandName, updates) {
|
|||||||
const inMd = mdData?.frontmatter?.[field] !== undefined;
|
const inMd = mdData?.frontmatter?.[field] !== undefined;
|
||||||
const inJson = jsonSection?.[field] !== undefined;
|
const inJson = jsonSection?.[field] !== undefined;
|
||||||
|
|
||||||
if (inMd) {
|
if (inMd || creatingNewMd) {
|
||||||
|
|
||||||
mdData.frontmatter[field] = value;
|
mdData.frontmatter[field] = value;
|
||||||
mdModified = true;
|
mdModified = true;
|
||||||
} else if (inJson) {
|
} else if (inJson) {
|
||||||
|
|
||||||
if (!config.command) config.command = {};
|
if (!config.command) config.command = {};
|
||||||
if (!config.command[commandName]) config.command[commandName] = {};
|
if (!config.command[commandName]) config.command[commandName] = {};
|
||||||
config.command[commandName][field] = value;
|
config.command[commandName][field] = value;
|
||||||
jsonModified = true;
|
jsonModified = true;
|
||||||
} else {
|
} else {
|
||||||
|
// New field - add to md if it exists or we're creating one
|
||||||
if (mdExists && jsonSection) {
|
if (mdExists || creatingNewMd) {
|
||||||
|
|
||||||
if (!config.command) config.command = {};
|
|
||||||
if (!config.command[commandName]) config.command[commandName] = {};
|
|
||||||
config.command[commandName][field] = value;
|
|
||||||
jsonModified = true;
|
|
||||||
} else if (mdExists) {
|
|
||||||
|
|
||||||
mdData.frontmatter[field] = value;
|
mdData.frontmatter[field] = value;
|
||||||
mdModified = true;
|
mdModified = true;
|
||||||
} else {
|
} else {
|
||||||
|
|
||||||
if (!config.command) config.command = {};
|
if (!config.command) config.command = {};
|
||||||
if (!config.command[commandName]) config.command[commandName] = {};
|
if (!config.command[commandName]) config.command[commandName] = {};
|
||||||
config.command[commandName][field] = value;
|
config.command[commandName][field] = value;
|
||||||
@@ -421,26 +544,38 @@ function updateCommand(commandName, updates) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (mdModified) {
|
if (mdModified) {
|
||||||
writeMdFile(mdPath, mdData.frontmatter, mdData.body);
|
writeMdFile(targetPath, mdData.frontmatter, mdData.body);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (jsonModified) {
|
if (jsonModified) {
|
||||||
writeConfig(config);
|
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) {
|
function deleteCommand(commandName, workingDirectory) {
|
||||||
const mdPath = path.join(COMMAND_DIR, `${commandName}.md`);
|
|
||||||
let deleted = false;
|
let deleted = false;
|
||||||
|
|
||||||
if (fs.existsSync(mdPath)) {
|
// Check project level first (takes precedence)
|
||||||
fs.unlinkSync(mdPath);
|
if (workingDirectory) {
|
||||||
console.log(`Deleted command .md file: ${mdPath}`);
|
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;
|
deleted = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Also check json config
|
||||||
const config = readConfig();
|
const config = readConfig();
|
||||||
if (config.command?.[commandName]) {
|
if (config.command?.[commandName]) {
|
||||||
delete config.command[commandName];
|
delete config.command[commandName];
|
||||||
@@ -460,6 +595,7 @@ export {
|
|||||||
updateAgent,
|
updateAgent,
|
||||||
deleteAgent,
|
deleteAgent,
|
||||||
getCommandSources,
|
getCommandSources,
|
||||||
|
getCommandScope,
|
||||||
createCommand,
|
createCommand,
|
||||||
updateCommand,
|
updateCommand,
|
||||||
deleteCommand,
|
deleteCommand,
|
||||||
@@ -467,5 +603,6 @@ export {
|
|||||||
writeConfig,
|
writeConfig,
|
||||||
AGENT_DIR,
|
AGENT_DIR,
|
||||||
COMMAND_DIR,
|
COMMAND_DIR,
|
||||||
CONFIG_FILE
|
CONFIG_FILE,
|
||||||
|
COMMAND_SCOPE
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user