mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 20:45:33 -08:00
Add the agent-less setup page, a shared agent list and the split Agents & models tab
AI Assisted
This commit is contained in:
1 parent
c122332657
commit
33f1783979
55 files changed
+5453
-1345
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -42,6 +42,7 @@ pub struct ConsoleSupervisor {
|
||||
console_dir: PathBuf,
|
||||
project_dir: PathBuf,
|
||||
embed_origin: String,
|
||||
workflow: String,
|
||||
session: ConsoleSession,
|
||||
stopped: bool,
|
||||
}
|
||||
@@ -177,12 +178,25 @@ impl ConsoleSupervisor {
|
||||
/// the project folder with `PLAN2CODE_EMBED_ORIGIN` set, and keep the
|
||||
/// session it prints.
|
||||
pub fn start(project_dir: PathBuf, embed_origin: String) -> Result<ConsoleSupervisor, String> {
|
||||
Self::start_with_workflow(project_dir, embed_origin, "dashboard")
|
||||
}
|
||||
|
||||
/// `start` for another workflow: today only `setup`, the agent-less page
|
||||
/// the app itself opens for Set up an agent (the one exception to the
|
||||
/// app never starting a console of its own).
|
||||
pub fn start_with_workflow(
|
||||
project_dir: PathBuf,
|
||||
embed_origin: String,
|
||||
workflow: &str,
|
||||
) -> Result<ConsoleSupervisor, String> {
|
||||
let console_dir = find_console_dir()?;
|
||||
let session = Self::open_session(&console_dir, &project_dir, &embed_origin, None)?;
|
||||
let session =
|
||||
Self::open_session(&console_dir, &project_dir, &embed_origin, None, workflow)?;
|
||||
Ok(ConsoleSupervisor {
|
||||
console_dir,
|
||||
project_dir,
|
||||
embed_origin,
|
||||
workflow: workflow.to_string(),
|
||||
session,
|
||||
stopped: false,
|
||||
})
|
||||
@@ -211,6 +225,7 @@ impl ConsoleSupervisor {
|
||||
console_dir,
|
||||
project_dir,
|
||||
embed_origin,
|
||||
workflow: "dashboard".to_string(),
|
||||
session,
|
||||
stopped: false,
|
||||
})
|
||||
@@ -221,12 +236,13 @@ impl ConsoleSupervisor {
|
||||
project_dir: &Path,
|
||||
embed_origin: &str,
|
||||
resume: Option<&str>,
|
||||
workflow: &str,
|
||||
) -> Result<ConsoleSession, String> {
|
||||
let mut command = node_command(console_dir);
|
||||
command.arg("open");
|
||||
match resume {
|
||||
Some(sid) => command.args(["--resume", sid, "--no-open"]),
|
||||
None => command.args(["--workflow", "dashboard", "--no-open"]),
|
||||
None => command.args(["--workflow", workflow, "--no-open"]),
|
||||
};
|
||||
let output = command
|
||||
.current_dir(project_dir)
|
||||
@@ -318,10 +334,14 @@ impl ConsoleSupervisor {
|
||||
}
|
||||
let sid = self.session.sid.clone();
|
||||
let on_disk = session_on_disk(&sid);
|
||||
let (console_dir, project_dir, embed_origin) =
|
||||
(&self.console_dir, &self.project_dir, &self.embed_origin);
|
||||
let (console_dir, project_dir, embed_origin, workflow) = (
|
||||
&self.console_dir,
|
||||
&self.project_dir,
|
||||
&self.embed_origin,
|
||||
&self.workflow,
|
||||
);
|
||||
self.session = resume_or_fresh(&sid, on_disk, |resume| {
|
||||
Self::open_session(console_dir, project_dir, embed_origin, resume)
|
||||
Self::open_session(console_dir, project_dir, embed_origin, resume, workflow)
|
||||
})?;
|
||||
self.stopped = false;
|
||||
Ok(true)
|
||||
|
||||
@@ -12,6 +12,7 @@ pub mod loop_driver;
|
||||
pub mod loop_notify;
|
||||
pub mod loop_report;
|
||||
pub mod loop_tools;
|
||||
pub mod models;
|
||||
pub mod node_check;
|
||||
pub mod project;
|
||||
pub mod pty_host;
|
||||
|
||||
@@ -5,13 +5,14 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentState, BeforeFresh, Sink};
|
||||
use plan2code_app_lib::agents::{self, Agent, AgentKind, PermissionMode};
|
||||
use plan2code_app_lib::agents::{self, Agent, PermissionMode};
|
||||
use plan2code_app_lib::announce::{AnnounceServer, PageNotice};
|
||||
use plan2code_app_lib::attention::{self, Badge, Signal};
|
||||
use plan2code_app_lib::console_supervisor::{
|
||||
app_origin, origin_of, session_on_disk, ConsoleSupervisor,
|
||||
};
|
||||
use plan2code_app_lib::loop_driver::{self, Hooks, LastLoop, LoopFacts, LoopSlot};
|
||||
use plan2code_app_lib::models;
|
||||
use plan2code_app_lib::node_check;
|
||||
use plan2code_app_lib::project::{self, ProjectDir};
|
||||
use plan2code_app_lib::quit_prompt::{loop_quit_prompt, quit_prompt, QuitCase};
|
||||
@@ -87,28 +88,34 @@ fn platform_info() -> serde_json::Value {
|
||||
// warnings about agents.json.
|
||||
#[tauri::command]
|
||||
fn agent_availability(refresh: Option<bool>) -> serde_json::Value {
|
||||
// "Check again" also works the PATH out again, so a CLI whose installer
|
||||
// added a new folder to it is found without restarting the app.
|
||||
// "Check again" also works the PATH out again and re-reads the shipped
|
||||
// agent list, so a CLI whose installer added a new folder to PATH, or a
|
||||
// list an update rewrote, is seen without restarting the app.
|
||||
if refresh == Some(true) {
|
||||
node_check::refresh_path();
|
||||
agents::refresh_agent_list();
|
||||
}
|
||||
// Built-ins first, then the custom agents, read afresh on every call so
|
||||
// "Check again" sees a change to agents.json.
|
||||
let mut entries: Vec<_> = AgentKind::ALL
|
||||
// Built-ins from the shipped list first, then the custom agents, read
|
||||
// afresh on every call so "Check again" sees a change to agents.json.
|
||||
// `state` is the shared lookup's answer: found (on PATH), outside (on
|
||||
// the saved PATH, in npm's folder or an install folder: needs setup,
|
||||
// not missing) or missing. `folder` names where an outside hit lives.
|
||||
let mut entries: Vec<_> = agents::builtin_entries()
|
||||
.iter()
|
||||
.map(|&kind| {
|
||||
let at = agents::installed_at(kind);
|
||||
.map(|entry| {
|
||||
let hit = agents::lookup_agent(entry);
|
||||
serde_json::json!({
|
||||
"id": kind.id(),
|
||||
"label": kind.label(),
|
||||
"installed": at.is_some(),
|
||||
// Which binary was used (Task 9.9), when one was found.
|
||||
"path": at.map(|p| p.to_string_lossy().into_owned()),
|
||||
"installHint": kind.install_hint(),
|
||||
"installUrl": kind.install_url(),
|
||||
"hasEffort": kind.has_effort(),
|
||||
"id": entry.id,
|
||||
"label": entry.name,
|
||||
"installed": hit.state == "found",
|
||||
"state": hit.state,
|
||||
"path": hit.path.map(|p| p.to_string_lossy().into_owned()),
|
||||
"folder": hit.folder.map(|p| p.to_string_lossy().into_owned()),
|
||||
"installHint": agents::install_hint(entry),
|
||||
"installUrl": entry.install_url,
|
||||
"hasEffort": agents::has_effort(&entry.id),
|
||||
"custom": false,
|
||||
"models": null,
|
||||
"models": models::models_for_builtin(&entry.id),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
@@ -119,6 +126,7 @@ fn agent_availability(refresh: Option<bool>) -> serde_json::Value {
|
||||
"id": custom.id,
|
||||
"label": custom.name,
|
||||
"installed": at.is_some(),
|
||||
"state": if at.is_some() { "found" } else { "missing" },
|
||||
"path": at.map(|p| p.to_string_lossy().into_owned()),
|
||||
"installHint": null,
|
||||
"installUrl": null,
|
||||
@@ -145,11 +153,11 @@ fn open_install_page(id: String) -> Result<(), String> {
|
||||
}
|
||||
let mut command = if cfg!(windows) {
|
||||
let mut c = std::process::Command::new("rundll32.exe");
|
||||
c.args(["url.dll,FileProtocolHandler", url]);
|
||||
c.args(["url.dll,FileProtocolHandler", &url]);
|
||||
c
|
||||
} else if cfg!(target_os = "macos") {
|
||||
let mut c = std::process::Command::new("open");
|
||||
c.arg(url);
|
||||
c.arg(&url);
|
||||
c
|
||||
} else {
|
||||
let browser = std::env::var("BROWSER")
|
||||
@@ -157,7 +165,7 @@ fn open_install_page(id: String) -> Result<(), String> {
|
||||
.filter(|b| !b.is_empty())
|
||||
.unwrap_or_else(|| "xdg-open".to_string());
|
||||
let mut c = std::process::Command::new(browser);
|
||||
c.arg(url);
|
||||
c.arg(&url);
|
||||
c
|
||||
};
|
||||
command
|
||||
@@ -298,6 +306,13 @@ fn take_announced(
|
||||
if !on_disk(¬ice.sid) {
|
||||
return false;
|
||||
}
|
||||
// An agent-less setup session never takes the window by announcing
|
||||
// itself (NFR-2): the only setup console allowed here is the one the app
|
||||
// itself started for Set up an agent, which carries no announce
|
||||
// variables and drives the frame through console_setup_start instead.
|
||||
if notice.workflow == "setup" {
|
||||
return false;
|
||||
}
|
||||
if let Ok(mut guard) = state.console.lock() {
|
||||
match guard.as_mut() {
|
||||
Some(sup) => sup.follow(¬ice.url, ¬ice.sid),
|
||||
@@ -857,8 +872,10 @@ fn change_project(
|
||||
|
||||
/// The console the agent opened, alive and as it is now, or restarted on the
|
||||
/// same session when it died. The app never starts a dashboard of its own:
|
||||
/// the agent does, by running the skill, and announces it. Nothing to show yet
|
||||
/// is an error the page words for the person.
|
||||
/// the agent does, by running the skill, and announces it. The one exception
|
||||
/// is `console_setup_start` below: the agent-less `setup` page, which is no
|
||||
/// dashboard and has no agent to announce it, so the app opens it itself.
|
||||
/// Nothing to show yet is an error the page words for the person.
|
||||
#[tauri::command]
|
||||
fn console_start(state: State<'_, AppState>) -> Result<serde_json::Value, String> {
|
||||
console_start_impl(&state)
|
||||
@@ -901,6 +918,44 @@ fn console_stop(state: State<'_, AppState>) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set up an agent: the agent-less `setup` page shown in this window. This
|
||||
/// is the one exception to the app never starting a console of its own (see
|
||||
/// `console_start` above): the setup page is not a dashboard and has no
|
||||
/// agent behind it, and nothing else can open it here. The console is
|
||||
/// started the way the `plan2code` command starts it (`console.mjs open
|
||||
/// --workflow setup`, no announce variables, so it never claims the window
|
||||
/// on its own), and the URL comes back for the page to frame. When
|
||||
/// `console.mjs` cannot be found the error names it, and the page shows its
|
||||
/// plain "skills are missing" checklist row.
|
||||
#[tauri::command]
|
||||
fn console_setup_start(
|
||||
app: tauri::AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<serde_json::Value, String> {
|
||||
let origin = window_origin(&app);
|
||||
console_setup_start_impl(&state, &origin)
|
||||
}
|
||||
|
||||
fn console_setup_start_impl(state: &AppState, origin: &str) -> Result<serde_json::Value, String> {
|
||||
refuse_while_looping(state, "console")?;
|
||||
let dir = state
|
||||
.project
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|p| p.as_ref().map(|p| p.dir.clone()))
|
||||
.ok_or("no project folder chosen")?;
|
||||
// The setup console starts before the old one is stopped: a failed open
|
||||
// (a missing console.mjs, a dead session store) leaves what was showing.
|
||||
let sup = ConsoleSupervisor::start_with_workflow(dir, origin.to_string(), "setup")?;
|
||||
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
|
||||
if let Some(mut old) = guard.take() {
|
||||
let _ = old.stop();
|
||||
}
|
||||
let session = serde_json::to_value(sup.session()).map_err(|e| e.to_string())?;
|
||||
*guard = Some(sup);
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
// What the setup screen shows about the agent a loop would use: the running
|
||||
// agent's launch choice, else what the launcher chose.
|
||||
#[tauri::command]
|
||||
@@ -1255,6 +1310,7 @@ fn main() {
|
||||
console_start,
|
||||
console_status,
|
||||
console_stop,
|
||||
console_setup_start,
|
||||
loop_start,
|
||||
loop_notify_test,
|
||||
loop_facts,
|
||||
@@ -1537,6 +1593,105 @@ mod tests {
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_setup_session_is_never_taken_from_an_announce() {
|
||||
// NFR-2: the only setup page in the window is the one the app itself
|
||||
// opened for Set up an agent. Whatever announces "setup" is refused,
|
||||
// even a session the console store really holds.
|
||||
let state = state_for("project-a");
|
||||
let mut setup = notice("setup-console");
|
||||
setup.workflow = "setup".into();
|
||||
assert!(!take_announced(
|
||||
&state,
|
||||
&setup,
|
||||
app_origin().to_string(),
|
||||
|_| true
|
||||
));
|
||||
assert!(state.console.lock().unwrap().is_none(), "nothing adopted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_setup_console_needs_a_project_to_open_in() {
|
||||
let state = AppState::default();
|
||||
let error = console_setup_start_impl(&state, "http://127.0.0.1:1430")
|
||||
.expect_err("no project, no setup page");
|
||||
assert!(error.contains("project"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_setup_console_starts_on_the_setup_workflow() {
|
||||
// Same setup as `real_console` below: the repo's own console source,
|
||||
// a throwaway session home, no browser, no in-app variables.
|
||||
let console_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console");
|
||||
if !have_node() || !console_dir.join("console.mjs").is_file() {
|
||||
eprintln!("skipping: node or the console source is not here");
|
||||
return;
|
||||
}
|
||||
let pid = std::process::id();
|
||||
let project = std::env::temp_dir().join(format!("p2c-setup-test-project-{pid}"));
|
||||
std::fs::create_dir_all(&project).unwrap();
|
||||
std::env::set_var("PLAN2CODE_CONSOLE_DIR", &console_dir);
|
||||
std::env::set_var(
|
||||
"PLAN2CODE_CONSOLE_HOME",
|
||||
std::env::temp_dir().join(format!("p2c-setup-test-home-{pid}")),
|
||||
);
|
||||
std::env::set_var("PLAN2CODE_NO_BROWSER", "1");
|
||||
for name in [
|
||||
"PLAN2CODE_IN_APP",
|
||||
"PLAN2CODE_APP_ANNOUNCE",
|
||||
"PLAN2CODE_APP_TOKEN",
|
||||
"PLAN2CODE_CONSOLE_SID",
|
||||
] {
|
||||
std::env::remove_var(name);
|
||||
}
|
||||
|
||||
let state = state_for("project-a");
|
||||
state.project.lock().unwrap().as_mut().unwrap().dir = project.clone();
|
||||
let session = console_setup_start_impl(&state, "http://127.0.0.1:1430")
|
||||
.expect("the setup page opens");
|
||||
let url = session["url"].as_str().unwrap();
|
||||
assert!(url.starts_with("http://127.0.0.1:"), "{url}");
|
||||
let sid = session["sid"].as_str().unwrap();
|
||||
// It is an agent-less setup session on disk, not a dashboard.
|
||||
let home = std::env::var("PLAN2CODE_CONSOLE_HOME").unwrap();
|
||||
let on_disk: serde_json::Value = serde_json::from_str(
|
||||
&std::fs::read_to_string(
|
||||
PathBuf::from(home)
|
||||
.join("sessions")
|
||||
.join(sid)
|
||||
.join("state.json"),
|
||||
)
|
||||
.expect("the session's own state"),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(on_disk["workflow"].as_str(), Some("setup"), "{on_disk}");
|
||||
let _ = state.console.lock().unwrap().take().unwrap().stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn availability_reports_each_builtins_lookup_state() {
|
||||
// Every entry carries the shared lookup's state: found (on PATH),
|
||||
// outside (needing setup, not missing) or missing, with `folder` for
|
||||
// where an outside hit lives.
|
||||
let json = agent_availability(None);
|
||||
let entries = json["agents"].as_array().unwrap();
|
||||
assert!(!entries.is_empty());
|
||||
let mut builtins = 0;
|
||||
for entry in entries {
|
||||
let state = entry["state"].as_str().unwrap();
|
||||
assert!(["found", "outside", "missing"].contains(&state), "{entry}");
|
||||
if entry["custom"] == false {
|
||||
builtins += 1;
|
||||
assert!(entry["installUrl"].is_string() || entry["installUrl"].is_null());
|
||||
}
|
||||
if state == "found" {
|
||||
assert_eq!(entry["installed"], true, "{entry}");
|
||||
assert!(entry["path"].is_string(), "{entry}");
|
||||
}
|
||||
}
|
||||
assert!(builtins >= 3, "claude, devin and codex are listed");
|
||||
}
|
||||
|
||||
/// A real console, the same way `tests/console_supervisor.rs` sets one
|
||||
/// up: `PLAN2CODE_CONSOLE_DIR` points at the repo's own console source,
|
||||
/// `PLAN2CODE_CONSOLE_HOME` keeps its session files out of the real one.
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
//! The launch card's model menu for a built-in agent: the same list the
|
||||
//! `plan2code` launcher's model question offers (`listModels` in
|
||||
//! `src/launcher/plan2code.js`). The shipped `bin/models.json` (refreshed by
|
||||
//! every install, and baked in here as the fallback) comes first, then the
|
||||
//! user's own additions in `~/.plan2code/models.json` (written by User
|
||||
//! Preferences) whose ids the shipped list does not already have. Custom
|
||||
//! agents never come through here: their menu is their own `models` in
|
||||
//! agents.json.
|
||||
|
||||
use serde_json::Value;
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::agents::CustomModel;
|
||||
|
||||
/// The shipped model menu, baked in beside agents.json so the launch card
|
||||
/// still offers a list when the installed `bin/models.json` cannot be read.
|
||||
const BAKED_MODELS: &str = include_str!("../../../src/launcher/models.json");
|
||||
|
||||
/// The shipped `bin/models.json`: `PLAN2CODE_MODELS_DIR/bin/models.json` when
|
||||
/// the tests relocate the models home, else the launcher's own
|
||||
/// `~/.plan2code/bin/models.json` (`PLAN2CODE_LAUNCHER_DIR` still honored).
|
||||
fn shipped_models_file() -> Option<PathBuf> {
|
||||
if let Ok(dir) = std::env::var("PLAN2CODE_MODELS_DIR") {
|
||||
return Some(PathBuf::from(dir).join("bin").join("models.json"));
|
||||
}
|
||||
crate::versions::launcher_dir().map(|dir| dir.join("models.json"))
|
||||
}
|
||||
|
||||
/// The user's `models.json`: `PLAN2CODE_MODELS_DIR/models.json` when set, else
|
||||
/// `~/.plan2code/models.json` (the same file the console's User Preferences
|
||||
/// writes, `USER_MODELS_FILE` in files.mjs).
|
||||
fn user_models_file() -> Option<PathBuf> {
|
||||
if let Ok(dir) = std::env::var("PLAN2CODE_MODELS_DIR") {
|
||||
return Some(PathBuf::from(dir).join("models.json"));
|
||||
}
|
||||
Some(std::env::home_dir()?.join(".plan2code").join("models.json"))
|
||||
}
|
||||
|
||||
/// `[{ id, label }]` from a parsed models file for one agent; anything
|
||||
/// malformed is skipped (`modelEntries` in plan2code.js: an entry needs a
|
||||
/// non-empty string `id` and a string `label`; a blank label is no label).
|
||||
fn model_entries(file: &Value, cli_id: &str) -> Vec<CustomModel> {
|
||||
let mut models = Vec::new();
|
||||
let Some(items) = file.get(cli_id).and_then(Value::as_array) else {
|
||||
return models;
|
||||
};
|
||||
for item in items {
|
||||
let Some(id) = item.get("id").and_then(Value::as_str) else {
|
||||
continue;
|
||||
};
|
||||
let id = id.trim();
|
||||
if id.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some(label) = item.get("label").and_then(Value::as_str) else {
|
||||
continue;
|
||||
};
|
||||
let label = label.trim();
|
||||
models.push(CustomModel {
|
||||
id: id.to_string(),
|
||||
label: (!label.is_empty()).then(|| label.to_string()),
|
||||
});
|
||||
}
|
||||
models
|
||||
}
|
||||
|
||||
/// The shipped list first, then the user's additions the shipped list does not
|
||||
/// already have (`mergeModels` in plan2code.js).
|
||||
fn merge_models(shipped: Vec<CustomModel>, user: Vec<CustomModel>) -> Vec<CustomModel> {
|
||||
let mut seen: HashSet<String> = shipped.iter().map(|m| m.id.clone()).collect();
|
||||
let mut out = shipped;
|
||||
out.extend(user.into_iter().filter(|m| seen.insert(m.id.clone())));
|
||||
out
|
||||
}
|
||||
|
||||
fn read_json(file: &Path) -> Option<Value> {
|
||||
serde_json::from_str(&std::fs::read_to_string(file).ok()?).ok()
|
||||
}
|
||||
|
||||
/// One built-in's menu from explicit file paths, so tests never touch the real
|
||||
/// home. A shipped file that is missing or will not parse falls back to the
|
||||
/// baked list; a user file the same way means no additions.
|
||||
fn models_for(
|
||||
cli_id: &str,
|
||||
shipped_file: Option<&Path>,
|
||||
user_file: Option<&Path>,
|
||||
) -> Vec<CustomModel> {
|
||||
let shipped = shipped_file
|
||||
.and_then(read_json)
|
||||
.or_else(|| serde_json::from_str(BAKED_MODELS).ok())
|
||||
.unwrap_or(Value::Null);
|
||||
let user = user_file.and_then(read_json).unwrap_or(Value::Null);
|
||||
merge_models(
|
||||
model_entries(&shipped, cli_id),
|
||||
model_entries(&user, cli_id),
|
||||
)
|
||||
}
|
||||
|
||||
/// The launch card's model menu for the built-in `cli_id` (empty when it has
|
||||
/// none, like the launcher's skipped question; `models` on a custom agent's
|
||||
/// agents.json entry covers customs).
|
||||
pub fn models_for_builtin(cli_id: &str) -> Vec<CustomModel> {
|
||||
models_for(
|
||||
cli_id,
|
||||
shipped_models_file().as_deref(),
|
||||
user_models_file().as_deref(),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn model(id: &str, label: Option<&str>) -> CustomModel {
|
||||
CustomModel {
|
||||
id: id.to_string(),
|
||||
label: label.map(str::to_string),
|
||||
}
|
||||
}
|
||||
|
||||
fn temp_dir(tag: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("models-test-{}-{tag}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(dir.join("bin")).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_entries_keeps_only_id_and_label_pairs() {
|
||||
let file = json!({
|
||||
"_note": "not a list",
|
||||
"claude": [
|
||||
{ "id": "sonnet", "label": "Sonnet - latest" },
|
||||
{ "id": "opus" },
|
||||
{ "id": " ", "label": "blank id" },
|
||||
{ "label": "no id" },
|
||||
"not an object",
|
||||
{ "id": "haiku", "label": " " },
|
||||
{ "id": "fable", "label": "Fable" }
|
||||
]
|
||||
});
|
||||
assert_eq!(
|
||||
model_entries(&file, "claude"),
|
||||
vec![
|
||||
model("sonnet", Some("Sonnet - latest")),
|
||||
model("haiku", None),
|
||||
model("fable", Some("Fable")),
|
||||
]
|
||||
);
|
||||
assert!(model_entries(&file, "codex").is_empty());
|
||||
assert!(model_entries(&Value::Null, "claude").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_models_appends_only_the_user_ids_the_shipped_list_lacks() {
|
||||
let shipped = vec![model("a", Some("A")), model("b", Some("B"))];
|
||||
let user = vec![
|
||||
model("b", Some("user's B")),
|
||||
model("c", Some("C")),
|
||||
model("c", Some("dupe")),
|
||||
];
|
||||
assert_eq!(
|
||||
merge_models(shipped, user),
|
||||
vec![
|
||||
model("a", Some("A")),
|
||||
model("b", Some("B")),
|
||||
model("c", Some("C"))
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn models_for_merges_the_shipped_and_user_files() {
|
||||
let dir = temp_dir("merge");
|
||||
std::fs::write(
|
||||
dir.join("bin").join("models.json"),
|
||||
r#"{ "claude": [{ "id": "sonnet", "label": "Sonnet" }] }"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
dir.join("models.json"),
|
||||
r#"{ "claude": [
|
||||
{ "id": "sonnet", "label": "ignored dupe" },
|
||||
{ "id": "my-new", "label": "Mine" }
|
||||
] }"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
models_for(
|
||||
"claude",
|
||||
Some(&dir.join("bin").join("models.json")),
|
||||
Some(&dir.join("models.json"))
|
||||
),
|
||||
vec![
|
||||
model("sonnet", Some("Sonnet")),
|
||||
model("my-new", Some("Mine"))
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn models_for_falls_back_to_the_baked_list() {
|
||||
// No shipped file at all (or one that will not parse): the baked copy
|
||||
// of src/launcher/models.json still offers its list.
|
||||
let dir = temp_dir("baked");
|
||||
let missing = dir.join("bin").join("models.json");
|
||||
let baked = models_for("claude", Some(&missing), Some(&missing));
|
||||
assert_eq!(baked.first().map(|m| m.id.as_str()), Some("default"));
|
||||
assert!(baked.len() > 1);
|
||||
std::fs::write(&missing, "{ nope").unwrap();
|
||||
assert!(models_for("claude", Some(&missing), Some(&missing)).len() > 1);
|
||||
assert!(models_for("codex", Some(&missing), Some(&missing)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn models_for_ignores_an_unreadable_user_file() {
|
||||
let dir = temp_dir("user");
|
||||
let shipped = dir.join("bin").join("models.json");
|
||||
let user = dir.join("models.json");
|
||||
std::fs::write(
|
||||
&shipped,
|
||||
r#"{ "claude": [{ "id": "sonnet", "label": "S" }] }"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(&user, "{ nope").unwrap();
|
||||
assert_eq!(
|
||||
models_for("claude", Some(&shipped), Some(&user)),
|
||||
vec![model("sonnet", Some("S"))]
|
||||
);
|
||||
assert_eq!(
|
||||
models_for("claude", Some(&shipped), None),
|
||||
vec![model("sonnet", Some("S"))]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -171,9 +171,27 @@ fn parse_reg_query_value(output: &str) -> Option<String> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The saved system and user PATH as one PATH string (Windows only): what a
|
||||
/// newly opened terminal gets, kept apart from the process PATH so the agent
|
||||
/// lookup can answer `saved-path`. "" elsewhere / when tests ask it off
|
||||
/// (PLAN2CODE_NO_SAVED_PATH, as the launcher's addSavedWindowsPath() honors).
|
||||
pub fn saved_path_value() -> String {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
if std::env::var_os("PLAN2CODE_NO_SAVED_PATH").is_some_and(|v| !v.is_empty()) {
|
||||
return String::new();
|
||||
}
|
||||
saved_windows_path().join(";")
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// `%NAME%` replaced with `lookup(NAME)`; an unknown name stays as written.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn expand_percent_vars(text: &str, lookup: impl Fn(&str) -> Option<String>) -> String {
|
||||
pub(crate) fn expand_percent_vars(text: &str, lookup: impl Fn(&str) -> Option<String>) -> String {
|
||||
let mut out = String::new();
|
||||
let mut rest = text;
|
||||
while let Some(start) = rest.find('%') {
|
||||
|
||||
@@ -165,7 +165,6 @@ 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)
|
||||
@@ -181,7 +180,7 @@ mod tests {
|
||||
#[test]
|
||||
fn the_launcher_choice_reads_agent_and_model_in_both_forms() {
|
||||
let want = LaunchChoice {
|
||||
agent: Some(AgentKind::Codex.id().to_string()),
|
||||
agent: Some("codex".to_string()),
|
||||
model: Some("gpt-5".into()),
|
||||
};
|
||||
assert_eq!(
|
||||
@@ -210,7 +209,7 @@ mod tests {
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent", "claude"])),
|
||||
LaunchChoice {
|
||||
agent: Some(AgentKind::Claude.id().to_string()),
|
||||
agent: Some("claude".to_string()),
|
||||
model: None
|
||||
}
|
||||
);
|
||||
@@ -239,7 +238,7 @@ mod tests {
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent", "devin", "--model"])),
|
||||
LaunchChoice {
|
||||
agent: Some(AgentKind::Devin.id().to_string()),
|
||||
agent: Some("devin".to_string()),
|
||||
model: None
|
||||
}
|
||||
);
|
||||
|
||||
@@ -30,7 +30,7 @@ pub struct VersionStatus {
|
||||
|
||||
/// `~/.plan2code/bin`, or `PLAN2CODE_LAUNCHER_DIR` when it is set (tests only, the same
|
||||
/// convention `PLAN2CODE_CONSOLE_HOME` and `PLAN2CODE_APP_AGENT_BIN` already use).
|
||||
fn launcher_dir() -> Option<PathBuf> {
|
||||
pub(crate) fn launcher_dir() -> Option<PathBuf> {
|
||||
if let Ok(dir) = std::env::var("PLAN2CODE_LAUNCHER_DIR") {
|
||||
return Some(PathBuf::from(dir));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user