mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 04:45:33 -08:00
Let people define custom agent CLIs and start them from the app and the launcher
AI Assisted
This commit is contained in:
1 parent
3e22d53bf5
commit
94063fc0a9
27 files changed
+4025
-95
No files matched your search
@@ -10,7 +10,7 @@ use std::thread;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::agents::{launch_spec, AgentKind, PermissionMode};
|
||||
use crate::agents::{agent_launch_spec, Agent, PermissionMode};
|
||||
use crate::pty_host::{PtyHost, StartOptions};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
@@ -33,7 +33,7 @@ pub type BeforeFresh = Arc<dyn Fn() -> Option<String> + Send + Sync>;
|
||||
pub struct AgentSnapshot {
|
||||
#[serde(flatten)]
|
||||
pub state: AgentState,
|
||||
pub kind: Option<AgentKind>,
|
||||
pub kind: Option<String>,
|
||||
pub generation: u64,
|
||||
/// The running (or last started) agent's permission mode, so the bar's
|
||||
/// note can name it instead of assuming bypass.
|
||||
@@ -61,7 +61,7 @@ struct Running {
|
||||
/// whole, unchanged choice (Task 9.6).
|
||||
#[derive(Clone)]
|
||||
struct StartChoice {
|
||||
kind: AgentKind,
|
||||
kind: Agent,
|
||||
model: Option<String>,
|
||||
effort: Option<String>,
|
||||
mode: PermissionMode,
|
||||
@@ -156,13 +156,13 @@ impl AgentManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Start `kind` on `model`, `effort` and `mode`, with `brief` (`None` is
|
||||
/// Start `kind` (built-in or custom) on `model`, `effort` and `mode`, with `brief` (`None` is
|
||||
/// the placeholder brief: the plain `/plan2code` prompt, which opens the
|
||||
/// dashboard). A second start while an agent runs is refused. Restart
|
||||
/// reuses this exact choice, so a later call replaces it for good.
|
||||
pub fn start(
|
||||
&self,
|
||||
kind: AgentKind,
|
||||
kind: Agent,
|
||||
model: Option<String>,
|
||||
effort: Option<String>,
|
||||
mode: PermissionMode,
|
||||
@@ -271,7 +271,7 @@ impl Shared {
|
||||
fn snapshot(&self, inner: &Inner) -> AgentSnapshot {
|
||||
AgentSnapshot {
|
||||
state: inner.state.clone(),
|
||||
kind: inner.last_start.as_ref().map(|(choice, _)| choice.kind),
|
||||
kind: inner.last_start.as_ref().map(|(choice, _)| choice.kind.id().to_string()),
|
||||
mode: inner.last_start.as_ref().map(|(choice, _)| choice.mode),
|
||||
generation: self.generation.load(Ordering::SeqCst),
|
||||
brief_note: inner.brief_note.clone(),
|
||||
@@ -287,7 +287,7 @@ impl Shared {
|
||||
let (choice, brief) = inner.last_start.clone().ok_or("no agent has been started")?;
|
||||
let prompt = brief.unwrap_or_else(|| choice.kind.default_prompt().to_string());
|
||||
let mut spec =
|
||||
launch_spec(choice.kind, &self.folder, choice.model.as_deref(), choice.effort.as_deref(), choice.mode, &prompt);
|
||||
agent_launch_spec(&choice.kind, &self.folder, choice.model.as_deref(), choice.effort.as_deref(), choice.mode, &prompt);
|
||||
if let Ok(extra) = self.extra_env.lock() {
|
||||
spec.env.extend(extra.iter().cloned());
|
||||
}
|
||||
|
||||
@@ -4,7 +4,10 @@
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::Serialize;
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
/// Tests only: run this program instead of the real agent, for any `AgentKind`,
|
||||
/// so the fake agent stands in for Claude, Devin and Codex.
|
||||
@@ -76,6 +79,16 @@ impl AgentKind {
|
||||
AgentKind::Codex => "npm i -g @openai/codex",
|
||||
}
|
||||
}
|
||||
|
||||
/// The official page to install this agent from. The same links as the
|
||||
/// launcher's `CLIS` and the overview's Quick Reference: change all together.
|
||||
pub fn install_url(self) -> &'static str {
|
||||
match self {
|
||||
AgentKind::Claude => "https://code.claude.com/docs/en/setup",
|
||||
AgentKind::Devin => "https://docs.devin.ai/work-with-devin/devin-cli",
|
||||
AgentKind::Codex => "https://github.com/openai/codex",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether permission checks run while the agent works. Bypass is always an
|
||||
@@ -260,6 +273,427 @@ pub fn windows_command(program: &str, args: Vec<String>, path_var: &str) -> (Str
|
||||
(program.to_string(), args)
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ custom agents */
|
||||
|
||||
pub const MAX_CUSTOM_AGENTS: usize = 50;
|
||||
const BUILTIN_IDS: [&str; 3] = ["claude", "devin", "codex"];
|
||||
const MAX_NAME: usize = 60;
|
||||
const DEFAULT_CUSTOM_PROMPT: &str = "/plan2code";
|
||||
|
||||
/// One model a custom agent offers.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct CustomModel {
|
||||
pub id: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub label: Option<String>,
|
||||
}
|
||||
|
||||
/// One entry of `~/.plan2code/agents.json`, with every default filled. The
|
||||
/// rules live in `src/web-console/agents.mjs`; `scripts/fixtures/agents-cases.json`
|
||||
/// pins this reader to them. Unknown keys are not kept here (the console is the
|
||||
/// file's only writer).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CustomAgent {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub command: String,
|
||||
#[serde(default)]
|
||||
pub args: Vec<String>,
|
||||
#[serde(default = "default_custom_prompt")]
|
||||
pub prompt: String,
|
||||
#[serde(default)]
|
||||
pub bypass_args: Vec<String>,
|
||||
#[serde(default = "default_model_args")]
|
||||
pub model_args: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub models: Vec<CustomModel>,
|
||||
}
|
||||
|
||||
fn default_custom_prompt() -> String {
|
||||
DEFAULT_CUSTOM_PROMPT.to_string()
|
||||
}
|
||||
|
||||
fn default_model_args() -> Vec<String> {
|
||||
vec!["--model".to_string(), "{model}".to_string()]
|
||||
}
|
||||
|
||||
/// `~/.plan2code/agents.json`.
|
||||
pub fn agents_file() -> Option<PathBuf> {
|
||||
Some(std::env::home_dir()?.join(".plan2code").join("agents.json"))
|
||||
}
|
||||
|
||||
/// The custom agents in `file` and the warnings about what was skipped. A
|
||||
/// missing file is no agents and no warnings; a bad file is no agents and a
|
||||
/// warning. Never panics.
|
||||
pub fn load_custom_agents(file: &Path) -> (Vec<CustomAgent>, Vec<String>) {
|
||||
match std::fs::read_to_string(file) {
|
||||
Ok(text) => parse_agents_file(&text),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => (Vec::new(), Vec::new()),
|
||||
Err(e) => (Vec::new(), vec![format!("agents.json could not be read ({e}), so no custom agents are used")]),
|
||||
}
|
||||
}
|
||||
|
||||
/// `normalizeAgents` for the file's text.
|
||||
pub fn parse_agents_file(text: &str) -> (Vec<CustomAgent>, Vec<String>) {
|
||||
let none = |warning: String| (Vec::new(), vec![warning]);
|
||||
let Ok(file) = serde_json::from_str::<Value>(text) else {
|
||||
return none("agents.json is not valid JSON, so no custom agents are used".to_string());
|
||||
};
|
||||
let Some(file) = file.as_object() else {
|
||||
return none("agents.json is not an object, so no custom agents are used".to_string());
|
||||
};
|
||||
if file.get("schema").and_then(Value::as_f64) != Some(1.0) {
|
||||
let shown = file.get("schema").map_or("undefined".to_string(), |v| v.to_string());
|
||||
return none(format!("agents.json has schema {shown}, not 1, so no custom agents are used"));
|
||||
}
|
||||
let list = match file.get("agents") {
|
||||
None | Some(Value::Null) => return (Vec::new(), Vec::new()),
|
||||
Some(Value::Array(list)) => list,
|
||||
Some(_) => return none("agents.json: agents is not a list, so no custom agents are used".to_string()),
|
||||
};
|
||||
|
||||
let mut warnings = Vec::new();
|
||||
let mut list: &[Value] = list;
|
||||
if list.len() > MAX_CUSTOM_AGENTS {
|
||||
warnings.push(format!("agents.json lists {} agents; only the first {MAX_CUSTOM_AGENTS} are used", list.len()));
|
||||
list = &list[..MAX_CUSTOM_AGENTS];
|
||||
}
|
||||
let mut agents: Vec<CustomAgent> = Vec::new();
|
||||
let mut ids = HashSet::new();
|
||||
let mut names = HashSet::new();
|
||||
for (index, entry) in list.iter().enumerate() {
|
||||
match check_entry(entry, &ids, &names) {
|
||||
Ok(agent) => {
|
||||
ids.insert(agent.id.clone());
|
||||
names.insert(agent.name.to_lowercase());
|
||||
agents.push(agent);
|
||||
}
|
||||
Err(error) => warnings.push(format!("agents[{index}] skipped: {error}")),
|
||||
}
|
||||
}
|
||||
(agents, warnings)
|
||||
}
|
||||
|
||||
fn valid_agent_id(id: &str) -> bool {
|
||||
let mut chars = id.chars();
|
||||
let first_ok = chars.next().is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit());
|
||||
first_ok && id.len() <= 32 && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
|
||||
}
|
||||
|
||||
fn text_list(entry: &Value, field: &str, default: Vec<String>) -> Result<Vec<String>, String> {
|
||||
match entry.get(field) {
|
||||
None | Some(Value::Null) => Ok(default),
|
||||
Some(Value::Array(items)) => items
|
||||
.iter()
|
||||
.map(|item| item.as_str().map(str::to_string))
|
||||
.collect::<Option<Vec<_>>>()
|
||||
.ok_or_else(|| format!("{field} must be a list of text")),
|
||||
Some(_) => Err(format!("{field} must be a list of text")),
|
||||
}
|
||||
}
|
||||
|
||||
// One entry against the rules, in the same order as `checkEntry` in agents.mjs.
|
||||
fn check_entry(entry: &Value, ids: &HashSet<String>, names: &HashSet<String>) -> Result<CustomAgent, String> {
|
||||
let Some(object) = entry.as_object() else { return Err("not an object".to_string()) };
|
||||
let id = match object.get("id").and_then(Value::as_str) {
|
||||
Some(id) if !id.is_empty() => id,
|
||||
_ => return Err("id is missing".to_string()),
|
||||
};
|
||||
if BUILTIN_IDS.contains(&id) {
|
||||
return Err(format!("id \"{id}\" belongs to a built-in agent"));
|
||||
}
|
||||
if !valid_agent_id(id) {
|
||||
return Err(format!(
|
||||
"id \"{id}\" must be 1 to 32 lowercase letters, digits or dashes, starting with a letter or digit"
|
||||
));
|
||||
}
|
||||
if ids.contains(id) {
|
||||
return Err(format!("id \"{id}\" is already used"));
|
||||
}
|
||||
|
||||
let name = object.get("name").and_then(Value::as_str).map_or("", str::trim);
|
||||
if name.is_empty() {
|
||||
return Err("name is missing".to_string());
|
||||
}
|
||||
if name.encode_utf16().count() > MAX_NAME {
|
||||
return Err(format!("name is longer than {MAX_NAME} characters"));
|
||||
}
|
||||
if names.contains(&name.to_lowercase()) {
|
||||
return Err(format!("name \"{name}\" is already used"));
|
||||
}
|
||||
|
||||
let command = object.get("command").and_then(Value::as_str).map_or("", str::trim);
|
||||
if command.is_empty() {
|
||||
return Err("command is missing".to_string());
|
||||
}
|
||||
|
||||
let args = text_list(entry, "args", Vec::new())?;
|
||||
let bypass_args = text_list(entry, "bypassArgs", Vec::new())?;
|
||||
let model_args = text_list(entry, "modelArgs", default_model_args())?;
|
||||
|
||||
let prompt = match object.get("prompt") {
|
||||
None | Some(Value::Null) => default_custom_prompt(),
|
||||
Some(Value::String(text)) => text.clone(),
|
||||
Some(_) => return Err("prompt must be text".to_string()),
|
||||
};
|
||||
|
||||
let mut models: Vec<CustomModel> = Vec::new();
|
||||
match object.get("models") {
|
||||
None | Some(Value::Null) => {}
|
||||
Some(Value::Array(items)) => {
|
||||
let mut seen = HashSet::new();
|
||||
for item in items {
|
||||
let Some(model_id) = item.get("id").and_then(Value::as_str) else {
|
||||
return Err("every model in models needs an id".to_string());
|
||||
};
|
||||
let model_id = model_id.trim();
|
||||
if model_id.is_empty() || !seen.insert(model_id.to_string()) {
|
||||
continue;
|
||||
}
|
||||
let label = item.get("label").and_then(Value::as_str).map(str::trim).filter(|l| !l.is_empty());
|
||||
models.push(CustomModel { id: model_id.to_string(), label: label.map(str::to_string) });
|
||||
}
|
||||
}
|
||||
Some(_) => return Err("models must be a list".to_string()),
|
||||
}
|
||||
|
||||
Ok(CustomAgent {
|
||||
id: id.to_string(),
|
||||
name: name.to_string(),
|
||||
command: command.to_string(),
|
||||
args,
|
||||
prompt,
|
||||
bypass_args,
|
||||
model_args,
|
||||
models,
|
||||
})
|
||||
}
|
||||
|
||||
/// The arguments that start a custom agent, in order (`buildArgs` in
|
||||
/// agents.mjs): `args` with `{prompt}` filled (the prompt appended when no
|
||||
/// argument holds it), then `model_args` when a model is chosen, then
|
||||
/// `bypass_args` when checks are off. `prompt` defaults to the entry's own; a
|
||||
/// blank one drops an argument that is exactly `{prompt}`. Plain text only.
|
||||
pub fn build_custom_args(agent: &CustomAgent, prompt: Option<&str>, model: Option<&str>, bypass: bool) -> Vec<String> {
|
||||
let text = prompt.unwrap_or(&agent.prompt);
|
||||
let blank = text.trim().is_empty();
|
||||
let mut out = Vec::new();
|
||||
let mut placed = false;
|
||||
for arg in &agent.args {
|
||||
if !arg.contains("{prompt}") {
|
||||
out.push(arg.clone());
|
||||
continue;
|
||||
}
|
||||
placed = true;
|
||||
if arg == "{prompt}" && blank {
|
||||
continue;
|
||||
}
|
||||
out.push(arg.replace("{prompt}", text));
|
||||
}
|
||||
if !placed && !blank {
|
||||
out.push(text.to_string());
|
||||
}
|
||||
if let Some(model) = model.filter(|m| !m.is_empty()) {
|
||||
out.extend(agent.model_args.iter().map(|arg| arg.replace("{model}", model)));
|
||||
}
|
||||
if bypass {
|
||||
out.extend(agent.bypass_args.iter().cloned());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An agent the app can run: one of the three built-ins or a custom entry.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Agent {
|
||||
Builtin(AgentKind),
|
||||
Custom(CustomAgent),
|
||||
}
|
||||
|
||||
impl Agent {
|
||||
pub fn id(&self) -> &str {
|
||||
match self {
|
||||
Agent::Builtin(kind) => kind.id(),
|
||||
Agent::Custom(agent) => &agent.id,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(&self) -> &str {
|
||||
match self {
|
||||
Agent::Builtin(kind) => kind.label(),
|
||||
Agent::Custom(agent) => &agent.name,
|
||||
}
|
||||
}
|
||||
|
||||
/// What a first start types.
|
||||
pub fn default_prompt(&self) -> &str {
|
||||
match self {
|
||||
Agent::Builtin(kind) => kind.default_prompt(),
|
||||
Agent::Custom(agent) => &agent.prompt,
|
||||
}
|
||||
}
|
||||
|
||||
/// A custom agent has no effort of its own.
|
||||
pub fn has_effort(&self) -> bool {
|
||||
matches!(self, Agent::Builtin(kind) if kind.has_effort())
|
||||
}
|
||||
|
||||
/// Where this agent's program runs from, or `None` when it cannot be run.
|
||||
/// `PLAN2CODE_APP_AGENT_BIN` still overrides the program (tests only).
|
||||
pub fn installed_at(&self) -> Option<PathBuf> {
|
||||
match self {
|
||||
Agent::Builtin(kind) => installed_at(*kind),
|
||||
Agent::Custom(agent) => {
|
||||
let bin = std::env::var(AGENT_BIN_ENV).ok().filter(|b| !b.is_empty());
|
||||
let command = bin.as_deref().unwrap_or(&agent.command);
|
||||
resolve_command(command, crate::node_check::resolved_path())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The agent named `id`: a built-in first, else an entry of `agents.json`.
|
||||
pub fn find_agent(id: &str) -> Option<Agent> {
|
||||
find_agent_in(id, agents_file().as_deref())
|
||||
}
|
||||
|
||||
/// `find_agent` against a given agents file (`None`: built-ins only).
|
||||
pub fn find_agent_in(id: &str, file: Option<&Path>) -> Option<Agent> {
|
||||
if let Some(kind) = AgentKind::from_id(id) {
|
||||
return Some(Agent::Builtin(kind));
|
||||
}
|
||||
let (agents, _) = load_custom_agents(file?);
|
||||
agents.into_iter().find(|agent| agent.id == id).map(Agent::Custom)
|
||||
}
|
||||
|
||||
/// Every custom agent in `~/.plan2code/agents.json`, read afresh.
|
||||
pub fn custom_agents() -> Vec<CustomAgent> {
|
||||
agents_file().map(|file| load_custom_agents(&file).0).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn clean_command(command: &str) -> &str {
|
||||
let command = command.trim();
|
||||
command.strip_prefix('"').and_then(|c| c.strip_suffix('"')).unwrap_or(command)
|
||||
}
|
||||
|
||||
fn has_separator(command: &str, windows: bool) -> bool {
|
||||
command.contains('/') || (windows && command.contains('\\'))
|
||||
}
|
||||
|
||||
// A file as written, or on Windows with an extension a program can have.
|
||||
fn file_with_extensions(base: PathBuf) -> Option<PathBuf> {
|
||||
if base.is_file() {
|
||||
return Some(base);
|
||||
}
|
||||
if cfg!(windows) && base.extension().is_none() {
|
||||
for ext in ["exe", "cmd", "bat"] {
|
||||
let mut candidate = base.clone().into_os_string();
|
||||
candidate.push(format!(".{ext}"));
|
||||
let candidate = PathBuf::from(candidate);
|
||||
if candidate.is_file() {
|
||||
return Some(candidate);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Where `command` runs from: a full path is checked as a file, a bare name is
|
||||
/// looked for on `path_var`. Never runs anything.
|
||||
fn resolve_command(command: &str, path_var: &str) -> Option<PathBuf> {
|
||||
let command = clean_command(command);
|
||||
if command.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if has_separator(command, cfg!(windows)) {
|
||||
return file_with_extensions(PathBuf::from(command));
|
||||
}
|
||||
if let Some(found) = find_on_path(command, path_var) {
|
||||
return Some(found);
|
||||
}
|
||||
// A name that already carries its extension (`tool.cmd`).
|
||||
path_var
|
||||
.split(if cfg!(windows) { ';' } else { ':' })
|
||||
.filter(|dir| !dir.is_empty())
|
||||
.map(|dir| Path::new(dir.trim_matches('"')).join(command))
|
||||
.find(|candidate| candidate.is_file())
|
||||
}
|
||||
|
||||
/// How to start `agent` in `folder`: a built-in exactly as `launch_spec`, a
|
||||
/// custom agent from its resolved command and `build_custom_args` (bypass when
|
||||
/// `mode` is `Bypass`; effort does not apply).
|
||||
pub fn agent_launch_spec(
|
||||
agent: &Agent,
|
||||
folder: &Path,
|
||||
model: Option<&str>,
|
||||
effort: Option<&str>,
|
||||
mode: PermissionMode,
|
||||
prompt: &str,
|
||||
) -> LaunchSpec {
|
||||
match agent {
|
||||
Agent::Builtin(kind) => launch_spec(*kind, folder, model, effort, mode, prompt),
|
||||
Agent::Custom(custom) => {
|
||||
if let Some(bin) = std::env::var(AGENT_BIN_ENV).ok().filter(|bin| !bin.is_empty()) {
|
||||
return LaunchSpec { program: bin, args: vec![], env: vec![], cwd: folder.to_path_buf() };
|
||||
}
|
||||
let resolved = agent.installed_at();
|
||||
custom_launch_spec(
|
||||
custom,
|
||||
resolved.as_deref(),
|
||||
folder,
|
||||
model,
|
||||
mode,
|
||||
prompt,
|
||||
crate::node_check::resolved_path(),
|
||||
cfg!(windows),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// `agent_launch_spec` for a custom agent, with the lookup result and the
|
||||
// platform passed in so the Windows rules can be tested anywhere.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn custom_launch_spec(
|
||||
custom: &CustomAgent,
|
||||
resolved: Option<&Path>,
|
||||
folder: &Path,
|
||||
model: Option<&str>,
|
||||
mode: PermissionMode,
|
||||
prompt: &str,
|
||||
base_path: &str,
|
||||
windows: bool,
|
||||
) -> LaunchSpec {
|
||||
let mut args = build_custom_args(custom, Some(prompt), model, mode == PermissionMode::Bypass);
|
||||
let mut path = base_path.to_string();
|
||||
let mut program =
|
||||
resolved.map_or_else(|| clean_command(&custom.command).to_string(), |p| p.to_string_lossy().into_owned());
|
||||
if windows {
|
||||
let ext = resolved.and_then(|p| p.extension()).map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_default();
|
||||
if let (true, Some(file)) = (ext == "cmd" || ext == "bat", resolved) {
|
||||
let file_name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
// A full path may have a space in its folder, and `cmd /c` mangles a
|
||||
// command line that starts with a quote: run the bare file name with
|
||||
// its folder at the front of the child's PATH instead.
|
||||
if has_separator(clean_command(&custom.command), true) {
|
||||
if let Some(dir) = file.parent() {
|
||||
path = format!("{};{}", dir.to_string_lossy(), base_path);
|
||||
}
|
||||
}
|
||||
let mut wrapped = vec!["/c".to_string(), file_name];
|
||||
wrapped.append(&mut args);
|
||||
args = wrapped;
|
||||
program = "cmd".to_string();
|
||||
}
|
||||
}
|
||||
LaunchSpec { program, args, env: vec![("PATH".to_string(), path)], cwd: folder.to_path_buf() }
|
||||
}
|
||||
|
||||
/// The page a built-in agent installs from; any other id is an error.
|
||||
pub fn install_page_url(id: &str) -> Result<&'static str, String> {
|
||||
AgentKind::from_id(id).map(AgentKind::install_url).ok_or_else(|| format!("no install page for agent: {id}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -470,4 +904,143 @@ mod tests {
|
||||
}
|
||||
assert_eq!(AgentKind::from_id("nope"), None);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ custom agents */
|
||||
|
||||
const CASES: &str = include_str!("../../../scripts/fixtures/agents-cases.json");
|
||||
|
||||
fn cases() -> Value {
|
||||
serde_json::from_str(CASES).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fixture_files_cases_read_the_same() {
|
||||
let cases = cases();
|
||||
let files = cases["files"].as_array().unwrap();
|
||||
assert!(files.len() >= 20);
|
||||
for case in files {
|
||||
let name = case["name"].as_str().unwrap();
|
||||
let (agents, warnings) = match case["raw"].as_str() {
|
||||
Some(raw) => parse_agents_file(raw),
|
||||
None => (Vec::new(), Vec::new()),
|
||||
};
|
||||
let want: Vec<CustomAgent> = serde_json::from_value(case["agents"].clone()).unwrap();
|
||||
assert_eq!(agents, want, "{name}");
|
||||
let parts = case["warnings"].as_array().unwrap();
|
||||
if parts.is_empty() {
|
||||
assert!(warnings.is_empty(), "{name}: {warnings:?}");
|
||||
}
|
||||
for part in parts {
|
||||
let part = part.as_str().unwrap();
|
||||
assert!(warnings.iter().any(|w| w.contains(part)), "{name}: no warning names {part}: {warnings:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fixture_build_args_cases_build_the_same() {
|
||||
let cases = cases();
|
||||
let list = cases["buildArgs"].as_array().unwrap();
|
||||
assert!(list.len() >= 10);
|
||||
for case in list {
|
||||
let name = case["name"].as_str().unwrap();
|
||||
let entry: CustomAgent = serde_json::from_value(case["entry"].clone()).unwrap();
|
||||
let options = &case["options"];
|
||||
let got = build_custom_args(
|
||||
&entry,
|
||||
options["prompt"].as_str(),
|
||||
options["model"].as_str(),
|
||||
options["bypass"].as_bool().unwrap_or(false),
|
||||
);
|
||||
let want: Vec<String> = serde_json::from_value(case["args"].clone()).unwrap();
|
||||
assert_eq!(got, want, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
fn temp_dir(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("plan2code-agents-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
const GOOSE: &str = r#"{"schema":1,"agents":[{"id":"goose","name":"Goose","command":"goose","args":["{prompt}"],"bypassArgs":["--yes"]}]}"#;
|
||||
|
||||
#[test]
|
||||
fn a_missing_file_is_empty_and_a_bad_one_warns() {
|
||||
let dir = temp_dir("load");
|
||||
assert_eq!(load_custom_agents(&dir.join("agents.json")), (Vec::new(), Vec::new()));
|
||||
std::fs::write(dir.join("agents.json"), "{ nope").unwrap();
|
||||
let (agents, warnings) = load_custom_agents(&dir.join("agents.json"));
|
||||
assert!(agents.is_empty() && warnings.len() == 1);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_agent_prefers_built_ins_then_the_file() {
|
||||
let dir = temp_dir("find");
|
||||
let file = dir.join("agents.json");
|
||||
std::fs::write(&file, GOOSE).unwrap();
|
||||
assert_eq!(find_agent_in("claude", Some(&file)), Some(Agent::Builtin(AgentKind::Claude)));
|
||||
let goose = find_agent_in("goose", Some(&file)).unwrap();
|
||||
assert_eq!((goose.id(), goose.label(), goose.has_effort(), goose.default_prompt()), ("goose", "Goose", false, "/plan2code"));
|
||||
assert_eq!(find_agent_in("goose", None), None);
|
||||
assert_eq!(find_agent_in("nope", Some(&file)), None);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
fn goose() -> CustomAgent {
|
||||
parse_agents_file(GOOSE).0.remove(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_custom_launch_spec_has_its_program_and_arguments() {
|
||||
let bin = Path::new("tools").join("goose");
|
||||
let spec = custom_launch_spec(&goose(), Some(&bin), &folder(), None, PermissionMode::Checked, "/plan2code", "P", false);
|
||||
assert_eq!(spec.program, bin.to_string_lossy());
|
||||
assert_eq!(spec.args, ["/plan2code"]);
|
||||
assert_eq!(spec.env, [("PATH".to_string(), "P".to_string())]);
|
||||
let spec = custom_launch_spec(&goose(), Some(&bin), &folder(), Some("m"), PermissionMode::Bypass, "/plan2code", "P", false);
|
||||
assert_eq!(spec.args, ["/plan2code", "--model", "m", "--yes"]);
|
||||
let spec = custom_launch_spec(&goose(), None, &folder(), None, PermissionMode::Checked, "", "P", false);
|
||||
assert_eq!((spec.program.as_str(), spec.args.len()), ("goose", 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_windows_cmd_runs_through_cmd_with_its_folder_on_path_for_a_full_path() {
|
||||
let mut full = goose();
|
||||
full.command = "C:\\with space\\goose.cmd".to_string();
|
||||
let found = Path::new("C:\\with space").join("goose.cmd");
|
||||
let spec = custom_launch_spec(&full, Some(&found), &folder(), None, PermissionMode::Checked, "/p", "BASE", true);
|
||||
assert_eq!(spec.program, "cmd");
|
||||
assert_eq!(spec.args, ["/c", "goose.cmd", "/p"]);
|
||||
assert_eq!(spec.env[0].1, format!("{};BASE", found.parent().unwrap().to_string_lossy()));
|
||||
// A bare name keeps the plain PATH.
|
||||
let bare = custom_launch_spec(&goose(), Some(&found), &folder(), None, PermissionMode::Checked, "/p", "BASE", true);
|
||||
assert_eq!((bare.program.as_str(), bare.env[0].1.as_str()), ("cmd", "BASE"));
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_full_path_cmd_in_a_spaced_folder_resolves_and_wraps() {
|
||||
let dir = temp_dir("spaced").join("with space");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("goose.cmd"), "@echo off").unwrap();
|
||||
let mut agent = goose();
|
||||
agent.command = dir.join("goose.cmd").to_string_lossy().into_owned();
|
||||
let found = Agent::Custom(agent.clone()).installed_at().expect("resolves");
|
||||
let spec = custom_launch_spec(&agent, Some(&found), &folder(), None, PermissionMode::Checked, "/p", "BASE", true);
|
||||
assert_eq!((spec.program.as_str(), spec.args[1].as_str()), ("cmd", "goose.cmd"));
|
||||
assert!(spec.env[0].1.starts_with(&dir.to_string_lossy().to_string()));
|
||||
let _ = std::fs::remove_dir_all(dir.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_pages_are_for_built_ins_only() {
|
||||
assert_eq!(install_page_url("codex").unwrap(), "https://github.com/openai/codex");
|
||||
assert!(install_page_url("goose").is_err());
|
||||
for kind in AgentKind::ALL {
|
||||
assert!(kind.install_url().starts_with("https://"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::agents::AgentKind;
|
||||
use crate::agents;
|
||||
|
||||
/// Where the project folder came from, in the order it is tried.
|
||||
#[derive(Clone, Copy, Serialize)]
|
||||
@@ -45,10 +45,11 @@ fn remembered_folder() -> Option<PathBuf> {
|
||||
dir.is_dir().then_some(dir)
|
||||
}
|
||||
|
||||
/// The agent the launcher last ran. The bar's picker starts on it until the
|
||||
/// app has a choice of its own (`settings.rs`).
|
||||
pub fn remembered_agent() -> Option<AgentKind> {
|
||||
AgentKind::from_id(read_launcher().get("lastCli")?.as_str()?)
|
||||
/// The id of the agent the launcher last ran (it may be a custom one). The
|
||||
/// bar's picker starts on it until the app has a choice of its own
|
||||
/// (`settings.rs`); a caller ignores an id that no longer resolves.
|
||||
pub fn remembered_agent() -> Option<String> {
|
||||
Some(read_launcher().get("lastCli")?.as_str()?.to_string()).filter(|id| !id.is_empty())
|
||||
}
|
||||
|
||||
/// `--project <dir>`, `--project=<dir>` or the first bare argument: the folder
|
||||
@@ -85,7 +86,8 @@ fn argument_folder(args: &[String]) -> Option<PathBuf> {
|
||||
/// an agent, since a model name belongs to one agent.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct LaunchChoice {
|
||||
pub agent: Option<AgentKind>,
|
||||
/// An agent id, built-in or custom; resolved at use through `agents::find_agent`.
|
||||
pub agent: Option<String>,
|
||||
pub model: Option<String>,
|
||||
}
|
||||
|
||||
@@ -106,8 +108,15 @@ fn flag_value(args: &[String], flag: &str) -> Option<String> {
|
||||
}
|
||||
|
||||
pub fn launch_choice(args: &[String]) -> LaunchChoice {
|
||||
let agent = flag_value(args, "--agent").and_then(|id| AgentKind::from_id(&id.to_lowercase()));
|
||||
let model = agent.and_then(|_| flag_value(args, "--model"));
|
||||
launch_choice_in(args, agents::agents_file().as_deref())
|
||||
}
|
||||
|
||||
/// `launch_choice` with the custom agents read from `agents_file` (`None`: built-ins only).
|
||||
pub fn launch_choice_in(args: &[String], agents_file: Option<&Path>) -> LaunchChoice {
|
||||
let agent = flag_value(args, "--agent")
|
||||
.map(|id| id.to_lowercase())
|
||||
.filter(|id| agents::find_agent_in(id, agents_file).is_some());
|
||||
let model = agent.as_ref().and_then(|_| flag_value(args, "--model"));
|
||||
LaunchChoice { agent, model }
|
||||
}
|
||||
|
||||
@@ -140,6 +149,11 @@ pub fn remember_folder(dir: &Path) -> Result<ProjectDir, String> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::agents::AgentKind;
|
||||
|
||||
fn launch_choice(args: &[String]) -> LaunchChoice {
|
||||
launch_choice_in(args, None)
|
||||
}
|
||||
|
||||
fn args(list: &[&str]) -> Vec<String> {
|
||||
std::iter::once("plan2code-app").chain(list.iter().copied()).map(str::to_string).collect()
|
||||
@@ -147,7 +161,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn the_launcher_choice_reads_agent_and_model_in_both_forms() {
|
||||
let want = LaunchChoice { agent: Some(AgentKind::Codex), model: Some("gpt-5".into()) };
|
||||
let want = LaunchChoice { agent: Some(AgentKind::Codex.id().to_string()), model: Some("gpt-5".into()) };
|
||||
assert_eq!(launch_choice(&args(&["--project", ".", "--agent", "codex", "--model", "gpt-5"])), want);
|
||||
assert_eq!(launch_choice(&args(&["--agent=codex", "--model=gpt-5"])), want);
|
||||
assert_eq!(launch_choice(&args(&["--agent", "CODEX", "--model", "gpt-5"])), want);
|
||||
@@ -157,7 +171,7 @@ mod tests {
|
||||
fn an_agent_alone_is_a_choice_and_a_model_alone_is_not() {
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent", "claude"])),
|
||||
LaunchChoice { agent: Some(AgentKind::Claude), model: None }
|
||||
LaunchChoice { agent: Some(AgentKind::Claude.id().to_string()), model: None }
|
||||
);
|
||||
assert_eq!(launch_choice(&args(&["--model", "opus"])), LaunchChoice::default());
|
||||
}
|
||||
@@ -171,10 +185,23 @@ mod tests {
|
||||
assert_eq!(launch_choice(&args(&[])), LaunchChoice::default());
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent", "devin", "--model"])),
|
||||
LaunchChoice { agent: Some(AgentKind::Devin), model: None }
|
||||
LaunchChoice { agent: Some(AgentKind::Devin.id().to_string()), model: None }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_custom_agent_id_is_accepted_when_the_file_names_it() {
|
||||
let dir = std::env::temp_dir().join(format!("p2c-project-custom-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("agents.json");
|
||||
std::fs::write(&file, r#"{"schema":1,"agents":[{"id":"goose","name":"Goose","command":"goose"}]}"#).unwrap();
|
||||
let want = LaunchChoice { agent: Some("goose".into()), model: Some("m1".into()) };
|
||||
assert_eq!(launch_choice_in(&args(&["--agent", "goose", "--model", "m1"]), Some(&file)), want);
|
||||
assert_eq!(launch_choice_in(&args(&["--agent", "other", "--model", "m1"]), Some(&file)), LaunchChoice::default());
|
||||
assert_eq!(launch_choice_in(&args(&["--agent", "goose"]), None), LaunchChoice::default());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_agent_and_model_values_are_never_taken_for_a_folder() {
|
||||
// A folder named like the agent exists right here, so a bare-argument reading would pick it.
|
||||
|
||||
@@ -4,8 +4,6 @@
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::agents::AgentKind;
|
||||
|
||||
const LAST_AGENT_KEY: &str = "lastAgent";
|
||||
const TERM_DOCK_KEY: &str = "termDock";
|
||||
const TERM_FRACTION_KEY: &str = "termFraction";
|
||||
@@ -38,15 +36,16 @@ fn read(file: &Path) -> serde_json::Map<String, serde_json::Value> {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The agent saved in `file`, when it still names one the app can run.
|
||||
pub fn load_last_agent(file: &Path) -> Option<AgentKind> {
|
||||
AgentKind::from_id(read(file).get(LAST_AGENT_KEY)?.as_str()?)
|
||||
/// The agent id saved in `file` (built-in or custom). Whether it still
|
||||
/// resolves is the caller's check (`agents::find_agent`).
|
||||
pub fn load_last_agent(file: &Path) -> Option<String> {
|
||||
Some(read(file).get(LAST_AGENT_KEY)?.as_str()?.to_string()).filter(|id| !id.is_empty())
|
||||
}
|
||||
|
||||
/// Save the pick, keeping any other key the file holds.
|
||||
pub fn save_last_agent(file: &Path, kind: AgentKind) -> Result<(), String> {
|
||||
pub fn save_last_agent(file: &Path, id: &str) -> Result<(), String> {
|
||||
let mut settings = read(file);
|
||||
settings.insert(LAST_AGENT_KEY.to_string(), serde_json::Value::String(kind.id().to_string()));
|
||||
settings.insert(LAST_AGENT_KEY.to_string(), serde_json::Value::String(id.to_string()));
|
||||
write(file, settings)
|
||||
}
|
||||
|
||||
@@ -129,18 +128,21 @@ mod tests {
|
||||
let file = temp_file("round-trip");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, r#"{"other": 1}"#).unwrap();
|
||||
save_last_agent(&file, AgentKind::Devin).unwrap();
|
||||
assert_eq!(load_last_agent(&file), Some(AgentKind::Devin));
|
||||
save_last_agent(&file, "devin").unwrap();
|
||||
assert_eq!(load_last_agent(&file), Some("devin".to_string()));
|
||||
save_last_agent(&file, "goose").unwrap();
|
||||
assert_eq!(load_last_agent(&file), Some("goose".to_string()), "a custom id round-trips");
|
||||
assert!(std::fs::read_to_string(&file).unwrap().contains("\"other\""));
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_agent_is_ignored() {
|
||||
fn an_id_is_returned_as_stored_and_the_caller_checks_it() {
|
||||
let file = temp_file("unknown");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, r#"{"lastAgent": "nope"}"#).unwrap();
|
||||
assert_eq!(load_last_agent(&file), None);
|
||||
assert_eq!(load_last_agent(&file), Some("nope".to_string()));
|
||||
assert!(crate::agents::find_agent_in("nope", None).is_none());
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::sync::{Arc, Mutex, Once};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentSnapshot, AgentState};
|
||||
use plan2code_app_lib::agents::{AgentKind, PermissionMode, AGENT_BIN_ENV};
|
||||
use plan2code_app_lib::agents::{Agent, AgentKind, PermissionMode, AGENT_BIN_ENV};
|
||||
|
||||
mod common;
|
||||
use common::process_alive;
|
||||
@@ -99,7 +99,7 @@ impl Harness {
|
||||
}
|
||||
|
||||
fn start_and_wait_ready(&mut self) {
|
||||
self.manager.start(AgentKind::Claude, None, None, PermissionMode::Bypass, None).expect("start the fake agent");
|
||||
self.manager.start(Agent::Builtin(AgentKind::Claude), None, None, PermissionMode::Bypass, None).expect("start the fake agent");
|
||||
self.wait_for_output(READY, 1);
|
||||
}
|
||||
|
||||
@@ -118,7 +118,7 @@ fn a_second_start_while_running_is_refused() {
|
||||
h.start_and_wait_ready();
|
||||
let generation = h.manager.snapshot().generation;
|
||||
|
||||
let refused = h.manager.start(AgentKind::Devin, None, None, PermissionMode::Bypass, None);
|
||||
let refused = h.manager.start(Agent::Builtin(AgentKind::Devin), None, None, PermissionMode::Bypass, None);
|
||||
assert!(refused.is_err(), "a second start must be refused");
|
||||
let after = h.manager.snapshot();
|
||||
assert_eq!(after.state, AgentState::Running);
|
||||
@@ -130,18 +130,18 @@ fn a_second_start_while_running_is_refused() {
|
||||
fn restart_keeps_the_previous_agent_kind_mode_model_and_effort() {
|
||||
let mut h = Harness::new();
|
||||
h.manager
|
||||
.start(AgentKind::Codex, Some("gpt-5".to_string()), Some("high".to_string()), PermissionMode::Checked, None)
|
||||
.start(Agent::Builtin(AgentKind::Codex), Some("gpt-5".to_string()), Some("high".to_string()), PermissionMode::Checked, None)
|
||||
.expect("start the fake agent");
|
||||
h.wait_for_output(READY, 1);
|
||||
let before = h.manager.snapshot();
|
||||
assert_eq!(before.kind, Some(AgentKind::Codex));
|
||||
assert_eq!(before.kind, Some("codex".to_string()));
|
||||
assert_eq!(before.mode, Some(PermissionMode::Checked));
|
||||
assert_eq!(h.manager.model_and_effort(), (Some("gpt-5".to_string()), Some("high".to_string())));
|
||||
|
||||
h.manager.restart().unwrap();
|
||||
h.wait_for_output(READY, 2);
|
||||
let after = h.manager.snapshot();
|
||||
assert_eq!(after.kind, Some(AgentKind::Codex), "restart must keep the same agent");
|
||||
assert_eq!(after.kind, Some("codex".to_string()), "restart must keep the same agent");
|
||||
assert_eq!(after.mode, Some(PermissionMode::Checked), "restart must keep the same permission mode");
|
||||
assert_eq!(
|
||||
h.manager.model_and_effort(),
|
||||
|
||||
+112
-16
@@ -2,7 +2,7 @@
|
||||
// agent's terminal panel docked at the bottom with a drag handle.
|
||||
|
||||
import { mountTerminal } from './terminal.js';
|
||||
import { barNextSteps, continueKeys, defaultRightFraction, folderName, windowTitleFor } from './meter.js';
|
||||
import { barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, windowTitleFor } from './meter.js';
|
||||
|
||||
const { invoke, Channel } = window.__TAURI__.core;
|
||||
|
||||
@@ -27,6 +27,7 @@ const launchCard = document.getElementById('launch-card');
|
||||
const launchAgentEl = document.getElementById('launch-agent');
|
||||
const launchMissingEl = document.getElementById('launch-missing');
|
||||
const launchModelEl = document.getElementById('launch-model');
|
||||
const launchModelListEl = document.getElementById('launch-model-list');
|
||||
const launchEffortRow = document.getElementById('launch-effort-row');
|
||||
const launchEffortEl = document.getElementById('launch-effort');
|
||||
const launchBypassEl = document.getElementById('launch-bypass');
|
||||
@@ -63,7 +64,10 @@ const MAXIMIZED_PANE = 0.80;
|
||||
const SMALL_PANE = 0.15;
|
||||
const QUIET_BADGE_MS = 10000;
|
||||
|
||||
const AGENT_LABELS = { claude: 'Claude Code', devin: 'Devin', codex: 'Codex' };
|
||||
// Only the bar's fallback, before (or without) agent_availability: the launch
|
||||
// card and the bar otherwise read each agent's label from that list.
|
||||
const FALLBACK_LABELS = { claude: 'Claude Code', devin: 'Devin', codex: 'Codex' };
|
||||
const agentLabel = (id) => (agentAvailability[id] && agentAvailability[id].label) || FALLBACK_LABELS[id] || id || '';
|
||||
// Devin's model ids already carry their effort (`swe-2-high`); only these two
|
||||
// take a separate effort, at the levels their own CLI documents.
|
||||
const EFFORT_OPTIONS = {
|
||||
@@ -109,7 +113,7 @@ function applyAgentState(next, { skipReset } = {}) {
|
||||
lastOutputAt = Date.now();
|
||||
}
|
||||
agent = next;
|
||||
const label = AGENT_LABELS[agent.kind] || '';
|
||||
const label = agentLabel(agent.kind);
|
||||
const active = agentActive();
|
||||
|
||||
const ended = agent.state === 'ended';
|
||||
@@ -259,19 +263,94 @@ function confirmRestart(onYes) {
|
||||
}
|
||||
|
||||
// What the launch card offers for each agent: whether its CLI was found on
|
||||
// PATH (else how to install it) and whether it takes its own effort.
|
||||
// PATH (else how to install it) and whether it takes its own effort. The list
|
||||
// keeps the order Rust sent (built-ins, then custom agents); the map is by id.
|
||||
let agentList = [];
|
||||
let agentAvailability = {};
|
||||
|
||||
async function loadAgentAvailability() {
|
||||
try {
|
||||
const list = await invoke('agent_availability');
|
||||
agentAvailability = Object.fromEntries(list.map((entry) => [entry.id, entry]));
|
||||
agentList = await invoke('agent_availability');
|
||||
agentAvailability = Object.fromEntries(agentList.map((entry) => [entry.id, entry]));
|
||||
} catch {
|
||||
// Nothing to show is not a reason to block the card: Start just tries it.
|
||||
agentList = [];
|
||||
agentAvailability = {};
|
||||
}
|
||||
}
|
||||
|
||||
// The launch card's agent choices, from the availability list. With nothing
|
||||
// to list (the check failed) the fixed options in index.html stay as they are.
|
||||
function populateAgentSelect(selected) {
|
||||
if (agentList.length === 0) return;
|
||||
launchAgentEl.replaceChildren(
|
||||
...agentList.map((entry) => {
|
||||
const option = document.createElement('option');
|
||||
option.value = entry.id;
|
||||
option.textContent = entry.label || entry.id;
|
||||
return option;
|
||||
})
|
||||
);
|
||||
if (selected) launchAgentEl.value = selected;
|
||||
}
|
||||
|
||||
// Pick the agent to start on and show the card's state for it.
|
||||
function applyDefaultAgent(remembered) {
|
||||
populateAgentSelect(pickDefaultAgent(agentList, remembered));
|
||||
refreshLaunchCard();
|
||||
}
|
||||
|
||||
// A button that opens a built-in agent's install page in the browser.
|
||||
function installPageButton(id) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'agent-link';
|
||||
button.textContent = 'Install page';
|
||||
button.onclick = () => {
|
||||
invoke('open_install_page', { id }).catch((error) => {
|
||||
setAgentStatus(`Could not open the install page: ${error}`, { error: true });
|
||||
});
|
||||
};
|
||||
return button;
|
||||
}
|
||||
|
||||
// Shown when no agent CLI is installed, in the first-run checklist and on the
|
||||
// launch card: what an agent CLI is, each built-in's install command and page,
|
||||
// and a way to look again once one is installed.
|
||||
function noAgentExplainer() {
|
||||
const box = document.createElement('div');
|
||||
box.className = 'agent-explainer';
|
||||
const intro = document.createElement('p');
|
||||
intro.className = 'agent-explainer';
|
||||
intro.textContent = 'An agent CLI is the AI coding assistant Plan2Code runs for you in its terminal. None was found on PATH. Install one of these:';
|
||||
const list = document.createElement('ul');
|
||||
for (const entry of agentList.filter((a) => !a.custom)) {
|
||||
const item = document.createElement('li');
|
||||
item.append(`${entry.label}: `);
|
||||
const code = document.createElement('code');
|
||||
code.textContent = entry.installHint || '';
|
||||
item.append(code, installPageButton(entry.id));
|
||||
list.append(item);
|
||||
}
|
||||
const other = document.createElement('p');
|
||||
other.className = 'agent-explainer';
|
||||
other.textContent = 'Already use another agent CLI? Add it in User Preferences under Agents.';
|
||||
const check = document.createElement('button');
|
||||
check.type = 'button';
|
||||
check.textContent = 'Check again';
|
||||
check.onclick = checkAgentsAgain;
|
||||
box.append(intro, list, other, check);
|
||||
return box;
|
||||
}
|
||||
|
||||
// Re-read the agents from disk (a CLI installed or a custom agent added since),
|
||||
// then redraw whatever shows them and pick the default again.
|
||||
async function checkAgentsAgain() {
|
||||
await loadAgentAvailability();
|
||||
applyDefaultAgent((appState && appState.lastAgent) || launchAgentEl.value);
|
||||
if (!firstRunEl.hidden && appState) renderFirstRun(appState);
|
||||
}
|
||||
|
||||
function refreshLaunchCard() {
|
||||
const kind = launchAgentEl.value;
|
||||
const info = agentAvailability[kind];
|
||||
@@ -280,13 +359,28 @@ function refreshLaunchCard() {
|
||||
launchMissingEl.hidden = installed;
|
||||
launchMissingEl.replaceChildren();
|
||||
if (!installed) {
|
||||
const label = (info && info.label) || AGENT_LABELS[kind] || kind;
|
||||
launchMissingEl.append(`${label} was not found on PATH. Install it: `);
|
||||
const code = document.createElement('code');
|
||||
code.textContent = (info && info.installHint) || '';
|
||||
launchMissingEl.append(code);
|
||||
if (!agentList.some((a) => a.installed)) {
|
||||
launchMissingEl.append(noAgentExplainer());
|
||||
} else {
|
||||
launchMissingEl.append(`${agentLabel(kind)} was not found on PATH.`);
|
||||
if (info && !info.custom) {
|
||||
launchMissingEl.append(' Install it: ');
|
||||
const code = document.createElement('code');
|
||||
code.textContent = info.installHint || '';
|
||||
launchMissingEl.append(code, installPageButton(kind));
|
||||
}
|
||||
}
|
||||
}
|
||||
const levels = EFFORT_OPTIONS[kind] || [];
|
||||
// A custom agent has no separate effort, and offers its models as
|
||||
// suggestions in the (still free-text) model field.
|
||||
launchModelListEl.replaceChildren();
|
||||
for (const model of (info && info.custom && info.models) || []) {
|
||||
const option = document.createElement('option');
|
||||
option.value = model.id;
|
||||
if (model.label) option.label = model.label;
|
||||
launchModelListEl.append(option);
|
||||
}
|
||||
const levels = info && info.custom ? [] : EFFORT_OPTIONS[kind] || [];
|
||||
launchEffortRow.hidden = levels.length === 0;
|
||||
launchEffortEl.replaceChildren();
|
||||
const def = document.createElement('option');
|
||||
@@ -350,11 +444,13 @@ function renderFirstRun(state) {
|
||||
const nodeDetail = `${state.nodeVersion || 'found'} (18 or newer)${state.nodeBinary ? ` — ${state.nodeBinary}` : ''}`;
|
||||
firstRunListEl.append(firstRunRow(true, 'Node.js', nodeDetail));
|
||||
|
||||
const agentsKnown = Object.values(agentAvailability);
|
||||
const agentsKnown = agentList;
|
||||
const anyAgentInstalled = agentsKnown.length === 0 || agentsKnown.some((a) => a.installed);
|
||||
const agentsDetail = document.createElement('span');
|
||||
if (agentsKnown.length === 0) {
|
||||
agentsDetail.textContent = 'Could not check.';
|
||||
} else if (!anyAgentInstalled) {
|
||||
agentsDetail.append(noAgentExplainer());
|
||||
} else {
|
||||
agentsKnown.forEach((a, i) => {
|
||||
if (i > 0) agentsDetail.append(', ');
|
||||
@@ -397,7 +493,8 @@ async function startAgent(event) {
|
||||
if (event) event.preventDefault();
|
||||
const kind = launchAgentEl.value;
|
||||
const model = launchModelEl.value.trim() || null;
|
||||
const effort = (EFFORT_OPTIONS[kind] || []).length > 0 ? launchEffortEl.value || null : null;
|
||||
const info = agentAvailability[kind];
|
||||
const effort = !(info && info.custom) && (EFFORT_OPTIONS[kind] || []).length > 0 ? launchEffortEl.value || null : null;
|
||||
const mode = launchBypassEl.checked ? 'bypass' : 'checked';
|
||||
setAgentStatus('');
|
||||
showState('Waiting for the agent to open the dashboard');
|
||||
@@ -929,7 +1026,6 @@ async function main() {
|
||||
return;
|
||||
}
|
||||
appState = state;
|
||||
if (AGENT_LABELS[state.lastAgent]) launchAgentEl.value = state.lastAgent;
|
||||
if (typeof state.launchModel === 'string' && state.launchModel) launchModelEl.value = state.launchModel;
|
||||
if (state.termPanel) {
|
||||
paneDock = state.termPanel.dock === 'right' ? 'right' : 'bottom';
|
||||
@@ -945,7 +1041,7 @@ async function main() {
|
||||
}
|
||||
applyPaneLayout();
|
||||
await loadAgentAvailability();
|
||||
refreshLaunchCard();
|
||||
applyDefaultAgent(state.lastAgent);
|
||||
setInterval(updateBadge, BADGE_POLL_MS);
|
||||
checkVersions();
|
||||
|
||||
|
||||
@@ -146,6 +146,11 @@
|
||||
}
|
||||
#launch-missing { margin: 0; font-size: 12px; color: #d7ba7d; }
|
||||
#launch-missing code { color: #ddd; }
|
||||
.agent-explainer { margin: 0; font-size: 12px; line-height: 1.5; }
|
||||
.agent-explainer ul { margin: 4px 0; padding-left: 18px; }
|
||||
.agent-explainer code { color: #ddd; }
|
||||
.agent-explainer button, #launch-missing button { font: inherit; font-size: 12px; margin-left: 6px; padding: 1px 8px; cursor: pointer; }
|
||||
.agent-explainer .agent-link, #launch-missing .agent-link { background: none; border: 0; padding: 0; color: #75beff; text-decoration: underline; }
|
||||
#launch-effort-row[hidden] { display: none; }
|
||||
#launch-bypass-row { display: flex; align-items: center; gap: 8px; color: #ccc; font-size: 13px; cursor: pointer; }
|
||||
#launch-bypass-row input { margin: 0; }
|
||||
@@ -292,7 +297,8 @@
|
||||
</select>
|
||||
<p id="launch-missing" hidden></p>
|
||||
<label for="launch-model">Model</label>
|
||||
<input id="launch-model" type="text" placeholder="Default (your account setting)" autocomplete="off">
|
||||
<input id="launch-model" type="text" placeholder="Default (your account setting)" autocomplete="off" list="launch-model-list">
|
||||
<datalist id="launch-model-list"></datalist>
|
||||
<div id="launch-effort-row">
|
||||
<label for="launch-effort">Effort</label>
|
||||
<select id="launch-effort"></select>
|
||||
|
||||
@@ -17,7 +17,8 @@ export const NEXT_STEP_LABELS = {
|
||||
* text as a queued message while its turn is busy, and the button only shows
|
||||
* once the agent stopped checking in with the console, so by then the turn is
|
||||
* stuck and the queued word would never send by itself: for it, the send-now
|
||||
* chord (ctrl+x ctrl+s) follows.
|
||||
* chord (ctrl+x ctrl+s) follows. Any id it does not know (a custom agent)
|
||||
* gets the plain word and Enter.
|
||||
*/
|
||||
export function continueKeys(kind) {
|
||||
const keys = ['continue', '\r'];
|
||||
@@ -25,6 +26,25 @@ export function continueKeys(kind) {
|
||||
return keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Which agent the launch card starts on, from `agent_availability`'s list
|
||||
* (built-ins first, then custom agents): the remembered id when it is
|
||||
* installed, else the first installed built-in, else the first installed
|
||||
* custom agent, else the remembered id or the first entry, so the card's
|
||||
* missing-agent line explains what is wrong instead of picking silently.
|
||||
*/
|
||||
export function pickDefaultAgent(availability, remembered) {
|
||||
const list = Array.isArray(availability) ? availability : [];
|
||||
const rememberedEntry = list.find((a) => a.id === remembered);
|
||||
if (rememberedEntry && rememberedEntry.installed) return remembered;
|
||||
const builtIn = list.find((a) => a.installed && !a.custom);
|
||||
if (builtIn) return builtIn.id;
|
||||
const custom = list.find((a) => a.installed && a.custom);
|
||||
if (custom) return custom.id;
|
||||
if (remembered) return remembered;
|
||||
return list.length > 0 ? list[0].id : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the right end of the bar offers, most pressing first: the bar shows
|
||||
* the first step (short text plus its one button) and counts the rest as
|
||||
|
||||
Reference in new issue
Block a user