Add the agent-less setup page, a shared agent list and the split Agents & models tab

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-03 04:08:27 -08:00
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)
+1
View File
@@ -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;
+177 -22
View File
@@ -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(&notice.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(&notice.url, &notice.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.
+237
View File
@@ -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"))]
);
}
}
+19 -1
View File
@@ -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('%') {
+3 -4
View File
@@ -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
}
);
+1 -1
View File
@@ -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));
}
@@ -9,7 +9,7 @@ use std::time::{Duration, Instant};
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentSnapshot, AgentState};
use plan2code_app_lib::agents::{
agent_launch_spec, parse_agents_file, Agent, AgentKind, PermissionMode, AGENT_BIN_ENV,
agent_launch_spec, builtin_entry, parse_agents_file, Agent, PermissionMode, AGENT_BIN_ENV,
};
mod common;
@@ -113,7 +113,7 @@ impl Harness {
fn start_and_wait_ready(&mut self) {
self.manager
.start(
Agent::Builtin(AgentKind::Claude),
Agent::Builtin(builtin_entry("claude").unwrap()),
None,
None,
PermissionMode::Bypass,
@@ -139,7 +139,7 @@ fn a_second_start_while_running_is_refused() {
let generation = h.manager.snapshot().generation;
let refused = h.manager.start(
Agent::Builtin(AgentKind::Devin),
Agent::Builtin(builtin_entry("devin").unwrap()),
None,
None,
PermissionMode::Bypass,
@@ -160,7 +160,7 @@ fn restart_keeps_the_previous_agent_kind_mode_model_and_effort() {
let mut h = Harness::new();
h.manager
.start(
Agent::Builtin(AgentKind::Codex),
Agent::Builtin(builtin_entry("codex").unwrap()),
Some("gpt-5".to_string()),
Some("high".to_string()),
PermissionMode::Checked,
+93 -37
View File
@@ -2,7 +2,7 @@
// agent's terminal panel docked at the bottom with a drag handle.
import { mountTerminal } from './terminal.js';
import { attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopLocks, loopStopLabels, loopWindowTitle } from './meter.js';
import { attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, lastAgentNotice, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopLocks, loopStopLabels, loopWindowTitle } from './meter.js';
const { invoke, Channel } = window.__TAURI__.core;
@@ -49,7 +49,7 @@ const launchAgentEl = document.getElementById('launch-agent');
const launchMissingEl = document.getElementById('launch-missing');
const launchWarningEl = document.getElementById('launch-agents-warning');
const launchModelEl = document.getElementById('launch-model');
const launchModelListEl = document.getElementById('launch-model-list');
const launchModelRowEl = document.getElementById('launch-model-row');
const launchEffortRow = document.getElementById('launch-effort-row');
const launchEffortEl = document.getElementById('launch-effort');
const launchBypassEl = document.getElementById('launch-bypass');
@@ -58,6 +58,8 @@ const launchStartBtn = document.getElementById('launch-start');
const firstRunEl = document.getElementById('first-run');
const firstRunListEl = document.getElementById('first-run-list');
const firstRunStartBtn = document.getElementById('first-run-start');
const launchNoticeEl = document.getElementById('launch-notice');
const setupCloseBtn = document.getElementById('setup-close');
const nextStepEl = document.getElementById('next-step');
const nextStepTextEl = document.getElementById('next-step-text');
const nextStepBtn = document.getElementById('next-step-button');
@@ -339,6 +341,11 @@ function populateAgentSelect(selected) {
// Pick the agent to start on and show the card's state for it.
function applyDefaultAgent(remembered) {
// The saved (last used) agent is gone but another works: one line, then
// carry on (FR-13). lastAgentNotice gives the pick it names.
const using = lastAgentNotice(agentList, remembered);
launchNoticeEl.hidden = !using;
if (using) launchNoticeEl.textContent = `${agentLabel(remembered)} (last used) was not found, using ${agentLabel(using)}`;
populateAgentSelect(pickDefaultAgent(agentList, remembered));
refreshLaunchCard();
}
@@ -357,33 +364,63 @@ function installPageButton(id) {
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);
// Where the setup page was opened from, while it is up: the screen to return
// to when it closes or reports agent-found. Null: no setup page up.
let setupReturn = null;
// The Set up an agent button, shown wherever the app says "no agent" (FR-17).
function setupButton(returnTo) {
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'setup-agent-btn';
btn.textContent = 'Set up an agent';
btn.onclick = () => openAgentSetup(returnTo);
return btn;
}
// Open the console's agent-less setup page in this window (FR-15, FR-17). No
// poll timer: a dead setup page needs no reconnect, and the Back button still
// returns.
async function openAgentSetup(returnTo) {
try {
const session = await invoke('console_setup_start');
setupReturn = returnTo;
hideState();
hideFirstRun();
hideLaunchCard();
markConsoleAlive();
consoleKnown = true;
setupCloseBtn.hidden = false;
loadFrame(session.url);
} catch (error) {
const text = String(error);
// A missing console.mjs means the skills install itself is gone (FR-16).
setAgentStatus(
text.includes('not installed') || text.includes('console.mjs')
? "Plan2Code's skills are missing: run `plan2code update`."
: `Could not open the setup page: ${text}`,
{ error: true }
);
}
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;
}
// The setup page is done: it found an agent (agent-found carries its id) or
// the person pressed Back. Return to where the app was, recheck the agents,
// and pick the found one on the launch card for the person to press Start
// (FR-14, FR-17).
async function finishSetup(foundId) {
if (setupReturn === null) return;
const returnTo = setupReturn;
setupReturn = null;
setupCloseBtn.hidden = true;
currentUrl = null;
frameReady = false;
frame.src = 'about:blank';
invoke('console_stop').catch(() => {});
await loadAgentAvailability(true);
applyDefaultAgent(foundId || (appState && appState.lastAgent) || launchAgentEl.value);
if (returnTo === 'first-run' && appState) showFirstRun(appState);
else showLaunchCard();
}
// Re-read the agents from disk (a CLI installed or a custom agent added since),
@@ -403,7 +440,11 @@ function refreshLaunchCard() {
launchMissingEl.replaceChildren();
if (!installed) {
if (!agentList.some((a) => a.installed)) {
launchMissingEl.append(noAgentExplainer());
launchMissingEl.append('No agent found. ', setupButton('launch-card'));
} else if (info && info.state === 'outside') {
// Found on the saved PATH, in npm's folder or an install folder, but
// not on PATH itself: setup, not a fresh install.
launchMissingEl.append(`${agentLabel(kind)} was found${info.folder ? ` in ${info.folder}` : ''}, but it is not on PATH. `, setupButton('launch-card'));
} else {
launchMissingEl.append(`${agentLabel(kind)} was not found on PATH.`);
if (info && !info.custom) {
@@ -416,15 +457,26 @@ function refreshLaunchCard() {
}
launchWarningEl.hidden = agentWarnings.length === 0;
launchWarningEl.textContent = agentWarnings.map((warning) => `agents.json: ${warning}`).join('\n');
// 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) || []) {
// The model dropdown lists what the `plan2code` launcher would ask with:
// built-ins get the shipped + user models.json merge from Rust, customs
// their own agents.json models. An empty list hides the row, like the
// launcher's skipped model question; the first option passes no flag, so
// the agent runs on its own (last-used) model.
const models = (info && info.models) || [];
launchModelEl.replaceChildren();
const noModel = document.createElement('option');
noModel.value = '';
noModel.textContent = "Default (the agent's own model)";
launchModelEl.append(noModel);
for (const model of models) {
const option = document.createElement('option');
option.value = model.id;
if (model.label) option.label = model.label;
launchModelListEl.append(option);
option.textContent = model.label ? `${model.id}: ${model.label}` : model.id;
launchModelEl.append(option);
}
launchModelRowEl.hidden = models.length === 0;
// A model the launcher picked (--model) sticks only while it is listed.
if (appState && models.some((model) => model.id === appState.launchModel)) launchModelEl.value = appState.launchModel;
const levels = info && info.custom ? [] : EFFORT_OPTIONS[kind] || [];
launchEffortRow.hidden = levels.length === 0;
launchEffortEl.replaceChildren();
@@ -495,7 +547,7 @@ function renderFirstRun(state) {
if (agentsKnown.length === 0) {
agentsDetail.textContent = 'Could not check.';
} else if (!anyAgentInstalled) {
agentsDetail.append(noAgentExplainer());
agentsDetail.append('No agent found. ', setupButton('first-run'));
} else {
agentsKnown.forEach((a, i) => {
if (i > 0) agentsDetail.append(', ');
@@ -537,7 +589,7 @@ firstRunStartBtn.onclick = async () => {
async function startAgent(event) {
if (event) event.preventDefault();
const kind = launchAgentEl.value;
const model = launchModelEl.value.trim() || null;
const model = launchModelEl.value || 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';
@@ -563,6 +615,7 @@ async function agentAction(command) {
}
launchCard.addEventListener('submit', startAgent);
setupCloseBtn.onclick = () => finishSetup();
restartBtn.onclick = () => confirmRestart(() => agentAction('agent_restart'));
// Only ever enabled once the agent has ended: nothing active to lose, so no confirm.
changeAgentBtn.onclick = () => {
@@ -700,6 +753,9 @@ window.addEventListener('message', (event) => {
} else if (kind === 'attention') {
const signal = attentionSignal(event.data);
if (signal) invoke('set_attention', { signal }).catch(() => {});
} else if (kind === 'agent-found') {
const id = typeof event.data.id === 'string' ? event.data.id : '';
void finishSetup(id || null);
} else if (kind === 'taskbar') {
const on = taskbarSwitch(event.data);
if (on === null) return;
+18 -4
View File
@@ -188,6 +188,17 @@
background: #2a2a2a; color: #ddd; border: 1px solid #555; border-radius: 4px; font: inherit;
}
#launch-missing { margin: 0; font-size: 12px; color: #d7ba7d; }
#launch-notice { margin: 0; font-size: 12px; color: #9ab; }
#launch-notice[hidden] { display: none; }
/* Set up an agent, shown wherever the app says "no agent". */
.setup-agent-btn { font: inherit; font-size: 12px; margin-top: 4px; padding: 3px 10px; cursor: pointer;
background: var(--accent); color: var(--accent-ink); border: 1px solid var(--accent); border-radius: 4px; }
/* The way out of the setup page, over its frame. */
#setup-close { position: absolute; top: 10px; right: 10px; z-index: 2; font: inherit; font-size: 12px;
padding: 4px 10px; border-radius: 6px; cursor: pointer; border: 1px solid var(--rule-2);
background: var(--panel); color: var(--ink); }
#setup-close:hover { background: var(--panel-2); }
#setup-close[hidden] { display: none; }
#launch-missing code { color: #ddd; }
#launch-agents-warning { margin: 0; font-size: 12px; color: #d7ba7d; white-space: pre-line; }
#launch-agents-warning[hidden] { display: none; }
@@ -196,7 +207,7 @@
.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-effort-row[hidden], #launch-model-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; }
#launch-bypass-warning { margin: 0; font-size: 12px; color: #d7ba7d; }
@@ -321,6 +332,7 @@
<div id="workspace">
<main id="dashboard">
<iframe id="console-frame" title="Plan2Code console dashboard" allow="clipboard-write"></iframe>
<button id="setup-close" type="button" hidden>Back</button>
<div id="dashboard-state" hidden>
<!-- Planny on a coffee break: shown only before a New Session press,
the one state here that is a question rather than a status. The
@@ -362,11 +374,13 @@
<option value="devin">Devin</option>
<option value="codex">Codex</option>
</select>
<p id="launch-notice" hidden></p>
<p id="launch-missing" hidden></p>
<p id="launch-agents-warning" hidden></p>
<label for="launch-model">Model</label>
<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-model-row">
<label for="launch-model">Model</label>
<select id="launch-model"></select>
</div>
<div id="launch-effort-row">
<label for="launch-effort">Effort</label>
<select id="launch-effort"></select>
+16
View File
@@ -47,6 +47,22 @@ export function pickDefaultAgent(availability, remembered) {
return list.length > 0 ? list[0].id : null;
}
/**
* The one-line notice for the launch card when the remembered agent is gone
* but another works (FR-13): the id the card picks instead, or null when the
* remembered one still runs or nothing else does.
*/
export function lastAgentNotice(list, remembered) {
const entries = Array.isArray(list) ? list : [];
if (!remembered) return null;
const hit = entries.find((a) => a.id === remembered);
if (hit && hit.installed) return null;
const using = pickDefaultAgent(entries, remembered);
if (!using || using === remembered) return null;
const usingEntry = entries.find((a) => a.id === using);
return usingEntry && usingEntry.installed ? using : 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