Add Update and restart, a remembered window and safer copy and paste to the desktop app

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-17 18:07:59 -08:00
1 parent c07e679105
commit 710c751c2f
24 files changed
+4347 -422

No files matched your search

+1
View File
@@ -22,4 +22,5 @@ pub mod session_reader;
pub mod settings;
#[cfg(windows)]
pub mod task_dialog;
pub mod ui_confirm;
pub mod versions;
+113 -2
View File
@@ -1131,14 +1131,17 @@ pub fn prompt_support(agent: &Agent) -> bool {
// -------------------------------------------------------- starting a loop
/// `specs/<name>`: one folder directly under `specs/`, not a link.
/// `specs/<name>`: one folder directly under `specs/`, not a link. The name may
/// hold dots (`polish-3.2`) but never start with one, which also refuses `.`
/// and `..`, matching the page's `isDeletableSpecDir`.
pub fn validate_spec(project: &Path, spec: &str) -> Result<(), String> {
let bad = || format!("not a spec folder: {spec}");
let name = spec.strip_prefix("specs/").ok_or_else(bad)?;
if name.is_empty()
|| name.starts_with('.')
|| !name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
{
return Err(bad());
}
@@ -1390,6 +1393,70 @@ pub fn confirm_text(rec: &RunningRecord) -> String {
text
}
/// The same Start confirm as lines for the shell's modal: the question, the quick check in a code
/// block, the resume notes as text, and the trunk warning as an amber callout, with no literal
/// backticks (`confirm_text` stays the plain-text form).
pub fn confirm_lines(rec: &RunningRecord) -> Vec<crate::ui_confirm::ConfirmLine> {
use crate::ui_confirm::ConfirmLine;
let name = rec.spec.strip_prefix("specs/").unwrap_or(&rec.spec);
let n = rec.phases.len();
let phases = if n == 1 {
"1 phase".to_string()
} else {
format!("{n} phases")
};
let mut lines = vec![ConfirmLine::text(format!("Build {phases} of {name}?"))];
let check = rec.setup.quick_check.trim();
if check.is_empty() {
lines.push(ConfirmLine::text("No quick check is set."));
} else {
lines.push(ConfirmLine::text(
"After each phase the app runs this quick check:",
));
lines.push(ConfirmLine::code(check));
}
if !rec.rebuilt.is_empty() {
let list: Vec<String> = rec.rebuilt.iter().map(|n| format!("Phase {n}")).collect();
lines.push(ConfirmLine::text(format!(
"{} is marked done but has no commit in the log, so it is built again.",
list.join(" and ")
)));
}
if let Some(files) = rec.resumed_files {
let files = if files == 1 {
"1 uncommitted file".to_string()
} else {
format!("{files} uncommitted files")
};
lines.push(ConfirmLine::text(format!(
"The resumed phase's commit will take {files} already in the tree."
)));
}
if !rec.setup.notify_url.is_empty() {
let when = if rec.setup.notify_phases {
"after each phase, when the loop needs you, or when it ends"
} else {
"When the loop needs you or ends"
};
lines.push(ConfirmLine::text(format!(
"{}, {}.",
capitalized(when),
loop_notify::describe(
rec.setup.notify_kind,
&rec.setup.notify_url,
&rec.setup.notify_param
)
)));
}
if commits_to_trunk(rec) {
let branch = rec.branch.as_deref().unwrap_or_default();
lines.push(ConfirmLine::callout(format!(
"You are on {branch}: every phase will commit straight to it. Start only if that is what you want."
)));
}
lines
}
fn capitalized(text: &str) -> String {
let mut chars = text.chars();
chars
@@ -3778,6 +3845,44 @@ mod tests {
.contains("After each phase, when the loop needs you, or when it ends"));
}
#[test]
fn the_start_confirm_as_lines_has_the_check_in_a_code_block_and_the_trunk_warning_as_a_callout()
{
let mut s = setup();
s.quick_check = "npm test".into();
s.commit = true;
let mut rec = RunningRecord::new("p".into(), "specs/x".into(), s, vec![phase(1), phase(2)]);
rec.branch = Some("main".into());
let lines = confirm_lines(&rec);
assert_eq!(lines[0].text, "Build 2 phases of x?");
assert!(lines
.iter()
.any(|l| l.kind == "code" && l.text == "npm test"));
let callout = lines
.iter()
.find(|l| l.kind == "callout")
.expect("a callout");
assert!(callout
.text
.contains("You are on main: every phase will commit straight to it."));
assert!(
lines.iter().all(|l| !l.text.contains('`')),
"no literal backticks"
);
assert_eq!(
lines.last().map(|l| l.kind),
Some("callout"),
"the warning reads last"
);
rec.setup.quick_check = String::new();
rec.branch = Some("feature/x".into());
let plain = confirm_lines(&rec);
assert!(plain.iter().any(|l| l.text == "No quick check is set."));
assert!(plain
.iter()
.all(|l| l.kind != "callout" && l.kind != "code"));
}
#[test]
fn no_web_address_means_no_call_and_an_older_entry_reads_with_none() {
assert_eq!(notify(&setup(), "x"), None);
@@ -4657,9 +4762,15 @@ second line"
let dir = std::env::temp_dir().join(format!("plan2code-loop-spec-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("specs").join("lunch-vote")).unwrap();
std::fs::create_dir_all(dir.join("specs").join("polish-3.2")).unwrap();
std::fs::create_dir_all(dir.join("specs").join(".hidden")).unwrap();
std::fs::write(dir.join("specs").join("a-file"), "x").unwrap();
assert!(validate_spec(&dir, "specs/lunch-vote").is_ok());
assert!(validate_spec(&dir, "specs/polish-3.2").is_ok());
for bad in [
"specs/.hidden",
"specs/.",
"specs/..",
"specs/missing",
"specs/a-file",
"specs/../x",
+431 -66
View File
@@ -1,7 +1,7 @@
// Hide the extra console window on Windows release builds.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::path::Path;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
@@ -22,6 +22,7 @@ use plan2code_app_lib::session_reader;
use plan2code_app_lib::settings;
#[cfg(windows)]
use plan2code_app_lib::task_dialog;
use plan2code_app_lib::ui_confirm;
use plan2code_app_lib::versions;
use tauri::ipc::{Channel, InvokeResponseBody};
use tauri::{Emitter, Manager, State};
@@ -42,12 +43,9 @@ struct AppState {
page: PageChannel,
// This window's endpoint for pages the agent's `console.mjs open` wants shown here.
announce: Arc<Mutex<Option<AnnounceServer>>>,
// The Node version `main()` found before opening the window (Task 1.7 exits
// cleanly on anything else, so this is always a passing version once the
// window exists), and which binary that was, with `resolved_path`'s PATH
// (Task 9.9): the first-run checklist's Node row names both.
node_version: Option<String>,
node_binary: Option<String>,
// The Node check's result: it runs on a background thread after the
// window opens (Task 9.10), so this is unchecked until it reports.
node: Mutex<NodeReport>,
// What the taskbar entry last said, and whether it may say anything.
attention: Mutex<AttentionState>,
// The app itself, once it is set up: the agent's sink clears the taskbar
@@ -60,6 +58,69 @@ struct AppState {
// kept after the running record is gone so Resume, Fix together with an agent and
// Finalize still work. Memory only.
last_loop: Mutex<Option<LastLoop>>,
// The version this app was running before an "Update and restart" brought it up: read
// from app.json once at launch (and cleared there), for the page to say "Updated to vX".
updated_from: Option<String>,
// Confirms the shell's own modal is asked (ui_confirm.rs): the answers still to come, and
// whether the page has begun listening for requests (until then the OS box asks instead).
confirms: ui_confirm::Pending,
confirm_ready: AtomicBool,
}
/// What the Node check found, as the page reads it (`app_state` and the
/// `node-status` event share this shape). `checked` is false until the check
/// has finished; `problem` is the failure message, if any.
#[derive(Clone, Default, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct NodeReport {
checked: bool,
version: Option<String>,
binary: Option<String>,
problem: Option<String>,
}
/// Run the Node check off the main thread and publish its result: store it,
/// tell the page, and on a failure show the dialog and end the app, as
/// `main()` did before the window existed (FR-13).
fn spawn_node_check(app: tauri::AppHandle) {
std::thread::spawn(move || {
let status = node_check::check_node();
let problem = node_check::problem_message(&status);
let version = match &status {
node_check::NodeStatus::Ok(version) => Some(version.clone()),
_ => None,
};
let binary = version
.as_ref()
.and_then(|_| node_check::node_binary_path());
let report = NodeReport {
checked: true,
version,
binary,
problem: problem.clone(),
};
if let Ok(mut slot) = app.state::<AppState>().node.lock() {
*slot = report.clone();
}
let _ = app.emit("node-status", &report);
if let Some(message) = problem {
// The first button is the default: Open nodejs.org, then the app ends either way.
let open_site = app
.dialog()
.message(&message)
.title("Plan2Code needs Node.js")
.kind(MessageDialogKind::Error)
.buttons(MessageDialogButtons::OkCancelCustom(
"Open nodejs.org".to_string(),
"Quit".to_string(),
))
.blocking_show();
if open_site {
let _ = open_url("https://nodejs.org");
}
std::process::exit(1);
}
});
}
// The console page's last state as the taskbar shows it (attention.rs), and
@@ -146,7 +207,12 @@ fn agent_availability(refresh: Option<bool>) -> serde_json::Value {
// is an error: the page never names the link itself.
#[tauri::command]
fn open_install_page(id: String) -> Result<(), String> {
let url = agents::install_page_url(&id)?;
open_url(&agents::install_page_url(&id)?)
}
// Opens a web address in the default browser, with the same switches as the console
// open-link.mjs.
fn open_url(url: &str) -> Result<(), String> {
// The same switches as the console open-link.mjs.
if std::env::var_os("NO_BROWSER").is_some_and(|v| !v.is_empty())
|| std::env::var_os("PLAN2CODE_NO_BROWSER").is_some_and(|v| !v.is_empty())
@@ -155,11 +221,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")
@@ -167,7 +233,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
@@ -480,6 +546,100 @@ struct QuitOpen;
impl Drop for QuitOpen {
fn drop(&mut self) {
QUIT_OPEN.store(false, Ordering::SeqCst);
// Stay was the answer (a Quit has already taken the plan): no restart is pending.
if let Ok(mut plan) = RESTART_ON_QUIT.lock() {
*plan = None;
}
}
}
// What an "Update and restart" starts once the app has shut down: the app file to run, the
// project folder to hand it, and this app's version for the "Updated to vX" note.
struct RestartPlan {
exe: PathBuf,
project: Option<PathBuf>,
from_version: String,
}
// Set by `restart_app`, taken by `quit_app`. A Stay answer to the quit check clears it
// (`QuitOpen`'s drop), so a later ordinary quit never restarts.
static RESTART_ON_QUIT: Mutex<Option<RestartPlan>> = Mutex::new(None);
// Starts the new app, detached so it outlives this process. The note for its first page goes
// to app.json first.
fn spawn_restart(plan: &RestartPlan) -> Result<(), String> {
if let Some(file) = settings::settings_file() {
let _ = settings::save_updated_from(&file, &plan.from_version);
}
let mut command = std::process::Command::new(&plan.exe);
command
.args(versions::restart_args(plan.project.as_deref()))
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x0000_0008 | 0x0000_0200); // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
}
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
command.process_group(0);
}
command
.spawn()
.map(|_| ())
.map_err(|e| format!("could not start {}: {e}", plan.exe.display()))
}
// Asks through the shell's own modal and waits for the answer: one look for every confirm, with the
// safe button first and focused. None when the page cannot show it (no window yet, or its modal is
// not listening): the caller then asks with the OS box. Blocks, so never call it on the event loop.
fn ask_in_window(
app: &tauri::AppHandle,
build: impl FnOnce(String) -> ui_confirm::ConfirmRequest,
) -> Option<bool> {
let state = app.state::<AppState>();
if !state.confirm_ready.load(Ordering::SeqCst) || app.get_webview_window("main").is_none() {
return None;
}
let (id, rx) = state.confirms.register();
let request = build(id.clone());
if app.emit("confirm-request", &request).is_err() {
state.confirms.forget(&id);
return None;
}
let yes = ui_confirm::wait_for(&rx, ui_confirm::ANSWER_TIMEOUT);
state.confirms.forget(&id);
// Whatever the page still shows for this request goes away with it.
let _ = app.emit("confirm-cancel", &id);
Some(yes)
}
// The modal's answer, by the id the request carried. A stale or invented id changes nothing.
#[tauri::command]
fn confirm_answer(state: State<'_, AppState>, id: String, yes: bool) {
state.confirms.answer(&id, yes);
}
// The page is listening for `confirm-request` from now on.
#[tauri::command]
fn confirm_ready(state: State<'_, AppState>) {
state.confirm_ready.store(true, Ordering::SeqCst);
// A page that has only now started listening (a reload) shows no older modal: whatever was
// asked before it listened is Cancel, not a thread waiting out the timeout with the quit
// check (QUIT_OPEN) held.
state.confirms.cancel_all();
}
// The bar's "..." menu and the macOS menu's Quit: the same quit check as closing the window.
#[tauri::command]
fn request_quit(app: tauri::AppHandle) {
if agent_is_active(&app) {
confirm_quit(&app);
} else {
quit_app(&app);
}
}
@@ -523,27 +683,46 @@ fn confirm_quit(app: &tauri::AppHandle) {
QuitCase::Waiting => MessageDialogKind::Info,
QuitCase::Working => MessageDialogKind::Warning,
};
// The plugin makes its first button the default, so off Windows Enter
// means Quit. Stay first would make Esc quit instead, since the plugin
// reads Esc as "not the first button".
// Off Windows the shell's own modal asks, with Stay first and focused, so Stay is the default
// answer everywhere (the plugin's box makes Quit the default). The OS box is the fallback for a
// page that cannot show it. Both wait off the event loop.
let app = app.clone();
app.dialog()
.message(prompt.message.clone())
.title(prompt.heading.clone())
.kind(kind)
.buttons(MessageDialogButtons::OkCancelCustom(
prompt.quit.clone(),
prompt.stay.clone(),
))
.show({
let app = app.clone();
move |quit| {
let _open = open;
std::thread::spawn(move || {
let _open = open;
#[cfg(not(windows))]
{
let asked = ask_in_window(&app, |id| {
ui_confirm::quit_request(
id,
&prompt.heading,
&prompt.message,
&prompt.quit,
&prompt.stay,
)
});
if let Some(quit) = asked {
if quit {
quit_app(&app);
}
return;
}
});
}
// The plugin makes its first button the default, so here Enter means Quit. Stay first
// would make Esc quit instead, since the plugin reads Esc as "not the first button".
let quit = app
.dialog()
.message(prompt.message.clone())
.title(prompt.heading.clone())
.kind(kind)
.buttons(MessageDialogButtons::OkCancelCustom(
prompt.quit.clone(),
prompt.stay.clone(),
))
.blocking_show();
if quit {
quit_app(&app);
}
});
}
// A running loop counts even between two phases, when no agent runs for a moment.
@@ -557,6 +736,7 @@ fn agent_is_active(app: &tauri::AppHandle) -> bool {
// its record is dropped without a word to the page, so its watch thread never
// takes the ended agent for a crash.
fn quit_app(app: &tauri::AppHandle) {
let restart = RESTART_ON_QUIT.lock().ok().and_then(|mut plan| plan.take());
let state = app.state::<AppState>();
loop_driver::abandon(&state.loop_run);
if let Some(agent) = current_agent(&state) {
@@ -567,6 +747,11 @@ fn quit_app(app: &tauri::AppHandle) {
let _ = console.stop();
}
}
if let Some(plan) = restart {
if let Err(error) = spawn_restart(&plan) {
eprintln!("plan2code: restart failed: {error}");
}
}
app.exit(0);
}
@@ -723,15 +908,24 @@ fn app_state(state: State<'_, AppState>) -> serde_json::Value {
let first_run_done = settings_file
.as_ref()
.is_some_and(|file| settings::load_first_run_done(file));
let node = state.node.lock().map(|n| n.clone()).unwrap_or_default();
let terminal_font_size = settings_file
.as_ref()
.map_or(settings::DEFAULT_TERMINAL_FONT_SIZE, |file| {
settings::load_terminal_font_size(file)
});
serde_json::json!({
"projectDir": project.as_ref().map(|p| p.dir.to_string_lossy().into_owned()),
"projectDirSource": project.as_ref().map(|p| p.source),
"lastAgent": last_agent,
"launchModel": state.launch.model,
// Task 1.7 already exits before the window opens on a missing or too-old
// Node, so this is always a pass; the checklist's Node row just names it.
"nodeVersion": state.node_version,
"nodeBinary": state.node_binary,
// The Node check runs after the window opens: `nodeChecked` is false
// until it finishes, then `node-status` is emitted with the same
// fields. A failure shows its dialog and ends the app.
"nodeChecked": node.checked,
"nodeVersion": node.version,
"nodeBinary": node.binary,
"nodeProblem": node.problem,
"skillsVersion": versions::installed_skills_version(),
"firstRunDone": first_run_done,
// The launcher always passes `--project` alongside `--agent`, so an
@@ -739,6 +933,14 @@ fn app_state(state: State<'_, AppState>) -> serde_json::Value {
// or launch card shown.
"autoStart": state.launch.agent,
"termPanel": term_panel,
"terminalFontSize": terminal_font_size,
"copyOnSelect": settings_file.as_ref().map_or_else(
settings::default_copy_on_select,
|file| settings::load_copy_on_select(file),
),
// Set only on the launch right after an "Update and restart": the version the old app
// ran. The page says "Updated to v<this app's version>" once.
"updatedFrom": state.updated_from,
// The Desktop app switch, for the page's User Preferences.
"taskbarSignal": state.attention.lock().map_or(true, |guard| guard.enabled),
})
@@ -753,6 +955,30 @@ fn save_term_panel(dock: String, fraction: f64, collapsed: bool) -> Result<(), S
settings::save_term_panel(&file, &dock, fraction, collapsed)
}
/// The terminal's font size (Ctrl/Cmd plus, minus and 0), kept in app.json.
/// A size outside 8 to 32 is refused.
#[tauri::command]
fn save_terminal_font_size(size: u32) -> Result<(), String> {
let file = settings::settings_file().ok_or("no home folder found")?;
settings::save_terminal_font_size(&file, size)
}
/// Copy-on-select for the terminal (Task 10.6): whether selecting text copies it at once.
/// The saved choice, or the OS default (on for Linux, off on Windows and macOS).
#[tauri::command]
fn get_copy_on_select() -> bool {
settings::settings_file().map_or_else(settings::default_copy_on_select, |file| {
settings::load_copy_on_select(&file)
})
}
/// Save the copy-on-select choice in app.json.
#[tauri::command]
fn set_copy_on_select(on: bool) -> Result<(), String> {
let file = settings::settings_file().ok_or("no home folder found")?;
settings::save_copy_on_select(&file, on)
}
/// The first-run checklist passed once: later launches go straight to the
/// launch card (Task 9.4).
#[tauri::command]
@@ -771,15 +997,19 @@ fn version_status(app: tauri::AppHandle) -> versions::VersionStatus {
)
}
/// The newest GitHub release's version when it is newer than this app, else none (also none on
/// any failure to ask). The page asks once at start and never waits on it.
/// The release check: `{ latest, problem }`. `latest` is the newest GitHub release's version
/// when it is newer than this app, else null; `problem` is a short sentence when the check
/// could not run (git missing, no network), else null. The page asks at start and again every
/// few hours, and never waits on it.
#[tauri::command]
async fn check_new_release(app: tauri::AppHandle) -> Option<String> {
async fn check_new_release(app: tauri::AppHandle) -> versions::ReleaseCheck {
let version = app.package_info().version.to_string();
tauri::async_runtime::spawn_blocking(move || versions::check_new_release(&version))
.await
.ok()
.flatten()
.unwrap_or_else(|_| versions::ReleaseCheck {
latest: None,
problem: Some("Could not check for updates: the check did not finish.".to_string()),
})
}
/// What `update_skills` resolves with: the installer's last line, and the version status
@@ -813,6 +1043,60 @@ async fn update_skills(
Ok(UpdateOutcome { message, status })
}
/// "Update and restart", step one: the installer unpinned (the newest release, not this app's
/// own tag), with its output live on `progress`. On success the old app keeps running until
/// `restart_app`; on failure it stays as it was and the error is a readable reason.
#[tauri::command]
async fn update_to_newest(
app: tauri::AppHandle,
progress: Channel<String>,
) -> Result<UpdateOutcome, String> {
let message = tauri::async_runtime::spawn_blocking(move || {
versions::run_update_newest(|line| {
let _ = progress.send(line.to_string());
})
})
.await
.map_err(|e| e.to_string())??;
let status = versions::status(
&app.package_info().version.to_string(),
versions::installed_skills_version(),
);
Ok(UpdateOutcome { message, status })
}
/// "Update and restart", step two: start the freshly installed app with this one's `--project`
/// and end this one. With an agent or loop running it first asks through the existing quit
/// check (Windows TaskDialog, or the shell's own modal elsewhere; the plugin box only while the page is not listening) and answers "asking"; Stay leaves
/// everything as it was. `confirmed: true` skips that check, for a page that has already asked
/// in its own confirm. Answers "restarting" when it goes ahead. Fails, leaving this app
/// running, when the installed app file is missing.
#[tauri::command]
fn restart_app(
app: tauri::AppHandle,
state: State<'_, AppState>,
confirmed: bool,
) -> Result<&'static str, String> {
let exe = versions::installed_app_path()
.ok_or("the new app file was not found, so Plan2Code was not restarted")?;
let project = state
.project
.lock()
.ok()
.and_then(|p| p.as_ref().map(|p| p.dir.clone()));
*RESTART_ON_QUIT.lock().map_err(|e| e.to_string())? = Some(RestartPlan {
exe,
project,
from_version: app.package_info().version.to_string(),
});
if !confirmed && agent_is_active(&app) {
confirm_quit(&app);
return Ok("asking");
}
quit_app(&app);
Ok("restarting")
}
/// The OS folder picker, the folder picker's Choose a folder row on a bare
/// start; a choice goes to the top of the recent folders.
#[tauri::command(async)]
@@ -1176,16 +1460,36 @@ async fn start_loop(
&& last.confirmed_notify == notify
});
if !unchanged {
let go = app
.dialog()
.message(loop_driver::confirm_text(&record))
.title("Implementation Loop")
.kind(MessageDialogKind::Info)
.buttons(MessageDialogButtons::OkCancelCustom(
"Start".to_string(),
"Cancel".to_string(),
))
.blocking_show();
// The shell's modal: the quick check in a code block, the trunk warning as a callout.
let lines = loop_driver::confirm_lines(&record);
let asker = app.clone();
let asked = tauri::async_runtime::spawn_blocking(move || {
ask_in_window(&asker, |id| ui_confirm::ConfirmRequest {
id,
title: "Start the Implementation Loop?".to_string(),
lines,
primary: "Start".to_string(),
cancel: "Cancel".to_string(),
danger: false,
safe_first: true,
})
})
.await
.map_err(|e| e.to_string())?;
let go = match asked {
Some(go) => go,
// The page cannot show it: the OS box, with the same words as one paragraph.
None => app
.dialog()
.message(loop_driver::confirm_text(&record))
.title("Implementation Loop")
.kind(MessageDialogKind::Info)
.buttons(MessageDialogButtons::OkCancelCustom(
"Start".to_string(),
"Cancel".to_string(),
))
.blocking_show(),
};
if !go {
return Ok(false);
}
@@ -1382,26 +1686,76 @@ fn loop_dashboard(state: State<'_, AppState>) -> Result<serde_json::Value, Strin
Ok(session)
}
fn main() {
// Without Node 18+ the console and skills cannot run: say so and stop (FR-13).
let status = node_check::check_node();
let node_problem = node_check::problem_message(&status);
let node_version = match &status {
node_check::NodeStatus::Ok(version) => Some(version.clone()),
_ => None,
};
let node_binary = node_version
.as_ref()
.and_then(|_| node_check::node_binary_path());
/// True when the window-state plugin's file does not exist yet.
fn first_launch(app: &tauri::AppHandle) -> bool {
use tauri_plugin_window_state::AppHandleExt;
app.path()
.app_config_dir()
.map(|dir| !dir.join(app.filename()).exists())
.unwrap_or(false)
}
// macOS gets a real menu bar: Plan2Code (About, Check for Updates, Help, Quit) and the standard Edit
// menu, so Copy, Paste and Select All work in the page's fields. The three custom items tell the
// page (the same actions as the bar's "..." menu); Quit is the predefined one, and the exit it asks
// for goes through the quit check in the run loop below.
#[cfg(target_os = "macos")]
fn build_mac_menu(app: &mut tauri::App) -> tauri::Result<()> {
use tauri::menu::{MenuBuilder, MenuItemBuilder, SubmenuBuilder};
let about = MenuItemBuilder::with_id("about", "About Plan2Code").build(app)?;
let check = MenuItemBuilder::with_id("check-updates", "Check for Updates...").build(app)?;
let help = MenuItemBuilder::with_id("help", "Plan2Code Help").build(app)?;
let app_menu = SubmenuBuilder::new(app, "Plan2Code")
.item(&about)
.item(&check)
.separator()
.item(&help)
.separator()
.quit()
.build()?;
let edit = SubmenuBuilder::new(app, "Edit")
.undo()
.redo()
.separator()
.cut()
.copy()
.paste()
.select_all()
.build()?;
let menu = MenuBuilder::new(app).items(&[&app_menu, &edit]).build()?;
app.set_menu(menu)?;
app.on_menu_event(|app, event| {
let id = event.id().as_ref();
if matches!(id, "about" | "check-updates" | "help") {
let _ = app.emit("app-menu", id);
}
});
Ok(())
}
fn main() {
let args = std::env::args().collect::<Vec<_>>();
tauri::Builder::default()
.plugin(tauri_plugin_dialog::init())
// Opens the terminal's http and https links (the capability scopes it to those).
.plugin(tauri_plugin_opener::init())
// Size and position come back on the next launch. Not VISIBLE (the
// window stays hidden until the page shows it), nor DECORATIONS or
// FULLSCREEN (an Activities game's full screen must not stick).
.plugin(
tauri_plugin_window_state::Builder::default()
.with_state_flags(
tauri_plugin_window_state::StateFlags::SIZE
| tauri_plugin_window_state::StateFlags::POSITION
| tauri_plugin_window_state::StateFlags::MAXIMIZED,
)
.build(),
)
.manage(AppState {
project: Mutex::new(project::resolve(&args)),
launch: project::launch_choice(&args),
node_version,
node_binary,
updated_from: settings::settings_file()
.and_then(|file| settings::take_updated_from(&file)),
attention: Mutex::new(AttentionState {
last: None,
enabled: settings::settings_file()
@@ -1411,6 +1765,9 @@ fn main() {
})
.invoke_handler(tauri::generate_handler![
platform_info,
confirm_answer,
confirm_ready,
request_quit,
agent_availability,
open_install_page,
agent_start,
@@ -1420,10 +1777,15 @@ fn main() {
agent_reattach,
app_state,
save_term_panel,
save_terminal_font_size,
save_first_run_done,
version_status,
check_new_release,
update_skills,
update_to_newest,
restart_app,
get_copy_on_select,
set_copy_on_select,
pick_project_folder,
recent_folders,
open_recent_folder,
@@ -1496,14 +1858,17 @@ fn main() {
// Without it the agent opens pages the plain way; nothing else breaks.
Err(error) => eprintln!("plan2code: no announce endpoint: {error}"),
}
if let Some(message) = &node_problem {
app.dialog()
.message(message)
.title("Plan2Code needs Node.js")
.kind(MessageDialogKind::Error)
.blocking_show();
std::process::exit(1);
// First launch ever (the window-state plugin has saved nothing yet):
// open maximized. Later launches get the saved size, position and
// maximized state from the plugin.
if first_launch(app.handle()) {
if let Some(window) = app.get_webview_window("main") {
let _ = window.maximize();
}
}
#[cfg(target_os = "macos")]
build_mac_menu(app)?;
spawn_node_check(app.handle().clone());
Ok(())
})
.build(tauri::generate_context!())
+135 -4
View File
@@ -77,14 +77,65 @@ fn node_override_dir(args: &[String]) -> Option<String> {
#[cfg(unix)]
fn login_shell_path() -> Option<String> {
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
// `printenv PATH`, not `echo $PATH`: fish expands `$PATH` to a list and
// echoes it space-separated, which is no PATH at all.
let out = Command::new(&shell)
.args(["-lc", "echo $PATH"])
.args(["-lc", "printenv PATH"])
.output()
.ok()?;
let path = String::from_utf8_lossy(&out.stdout).trim().to_string();
let path = parse_path_output(&String::from_utf8_lossy(&out.stdout));
(out.status.success() && !path.is_empty()).then_some(path)
}
/// A PATH out of a shell's output: the last non-empty line (a login shell's
/// profile may print a banner first), and a space-separated list of absolute
/// folders (what fish's `echo $PATH` prints) turned into a `:` list. A single
/// folder with a space in its name is left alone.
#[cfg_attr(windows, allow(dead_code))]
fn parse_path_output(output: &str) -> String {
let line = output
.lines()
.map(str::trim)
.rfind(|l| !l.is_empty())
.unwrap_or("");
let tokens: Vec<&str> = line.split_whitespace().collect();
let spaced_list = !line.contains(':')
&& tokens.len() > 1
&& tokens
.iter()
.all(|t| t.starts_with('/') || t.starts_with('~'));
if spaced_list {
tokens.join(":")
} else {
line.to_string()
}
}
/// What the PATH lookup is named after in the failure message: the login
/// shell on macOS and Linux (its own file name, such as `fish`), the saved
/// system and user PATH on Windows.
pub fn path_source_label() -> String {
#[cfg(unix)]
{
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
shell_name(&shell)
}
#[cfg(not(unix))]
{
"Windows (the system and user PATH)".to_string()
}
}
#[cfg_attr(windows, allow(dead_code))]
fn shell_name(shell: &str) -> String {
let name = shell.rsplit(['/', '\\']).next().unwrap_or(shell);
if name.is_empty() {
"sh".to_string()
} else {
name.to_string()
}
}
static RESOLVED_PATH: Mutex<Option<String>> = Mutex::new(None);
/// The PATH every process this app spawns should run with: an explicit
@@ -250,13 +301,28 @@ pub fn node_binary_path() -> Option<String> {
/// The plain message shown when the check fails; `None` when Node is fine.
pub fn problem_message(status: &NodeStatus) -> Option<String> {
problem_message_from(status, &path_source_label())
}
/// `problem_message` with the PATH source named by the caller, so a test need
/// not depend on this machine's shell.
pub fn problem_message_from(status: &NodeStatus, source: &str) -> Option<String> {
let advice = format!(
"Install the current LTS release from https://nodejs.org and start Plan2Code again.
Looked on PATH from {source}."
);
match status {
NodeStatus::Ok(_) => None,
NodeStatus::TooOld(v) => Some(format!(
"Plan2Code needs Node.js {MIN_NODE_MAJOR} or newer, and this computer has {v}.\n\nInstall the current LTS release from https://nodejs.org and start Plan2Code again."
"Plan2Code needs Node.js {MIN_NODE_MAJOR} or newer, and this computer has {v}.
{advice}"
)),
NodeStatus::Missing => Some(format!(
"Plan2Code needs Node.js {MIN_NODE_MAJOR} or newer, and it was not found.\n\nInstall the current LTS release from https://nodejs.org and start Plan2Code again."
"Plan2Code needs Node.js {MIN_NODE_MAJOR} or newer, and it was not found.
{advice}"
)),
}
}
@@ -372,4 +438,69 @@ mod tests {
let inherited = std::env::var("PATH").unwrap_or_default();
assert!(resolved_path().ends_with(&inherited));
}
#[test]
fn the_failure_message_names_where_it_looked() {
let text = problem_message_from(&NodeStatus::Missing, "fish").unwrap();
assert!(text.contains("Looked on PATH from fish."));
assert!(text.contains("https://nodejs.org"));
assert!(problem_message_from(&NodeStatus::Ok("v20.0.0".into()), "fish").is_none());
}
#[test]
fn shell_names_come_from_the_last_path_part() {
assert_eq!(shell_name("/usr/bin/fish"), "fish");
assert_eq!(shell_name("/bin/zsh"), "zsh");
assert_eq!(shell_name("bash"), "bash");
assert_eq!(shell_name(""), "sh");
}
#[test]
fn a_colon_path_is_kept_as_it_is() {
assert_eq!(
parse_path_output(
"/usr/local/bin:/usr/bin:/bin
"
),
"/usr/local/bin:/usr/bin:/bin"
);
}
#[test]
fn fish_s_space_separated_list_becomes_a_colon_list() {
assert_eq!(
parse_path_output(
"/home/sam/.nvm/bin /usr/local/bin /usr/bin
"
),
"/home/sam/.nvm/bin:/usr/local/bin:/usr/bin"
);
}
#[test]
fn a_banner_before_the_path_and_a_folder_with_a_space_are_handled() {
assert_eq!(
parse_path_output(
"Welcome back
/usr/bin:/bin
"
),
"/usr/bin:/bin"
);
assert_eq!(
parse_path_output(
"/Users/Jo Smith/bin
"
),
"/Users/Jo Smith/bin"
);
assert_eq!(
parse_path_output(
"
"
),
""
);
}
}
+141
View File
@@ -10,6 +10,13 @@ const TERM_FRACTION_KEY: &str = "termFraction";
const TERM_COLLAPSED_KEY: &str = "termCollapsed";
const FIRST_RUN_DONE_KEY: &str = "firstRunDone";
const TASKBAR_SIGNAL_KEY: &str = "taskbarSignal";
const TERMINAL_FONT_SIZE_KEY: &str = "terminalFontSize";
const COPY_ON_SELECT_KEY: &str = "copyOnSelect";
const UPDATED_FROM_KEY: &str = "updatedFrom";
pub const DEFAULT_TERMINAL_FONT_SIZE: u32 = 13;
pub const TERMINAL_FONT_SIZE_MIN: u32 = 8;
pub const TERMINAL_FONT_SIZE_MAX: u32 = 32;
/// The terminal pane's remembered shape: which edge it docks to, how much of
/// the window it takes (a fraction, not collapsed or maximized), and whether
@@ -111,6 +118,34 @@ pub fn save_term_panel(
write(file, settings)
}
/// The terminal's font size in pixels: the saved one, clamped to its range,
/// or 13 when the file has none (an old file) or holds something else.
pub fn load_terminal_font_size(file: &Path) -> u32 {
read(file)
.get(TERMINAL_FONT_SIZE_KEY)
.and_then(|v| v.as_u64())
.map_or(DEFAULT_TERMINAL_FONT_SIZE, |size| {
size.clamp(
u64::from(TERMINAL_FONT_SIZE_MIN),
u64::from(TERMINAL_FONT_SIZE_MAX),
) as u32
})
}
/// Save the terminal's font size, keeping any other key the file holds. A
/// size outside 8 to 32 is rejected rather than saved.
pub fn save_terminal_font_size(file: &Path, size: u32) -> Result<(), String> {
if !(TERMINAL_FONT_SIZE_MIN..=TERMINAL_FONT_SIZE_MAX).contains(&size) {
return Err(format!("font size out of range: {size}"));
}
let mut settings = read(file);
settings.insert(
TERMINAL_FONT_SIZE_KEY.to_string(),
serde_json::Value::from(size),
);
write(file, settings)
}
/// Whether the first-run checklist has already passed once. Once it has,
/// later launches go straight to the launch card (Task 9.4).
pub fn load_first_run_done(file: &Path) -> bool {
@@ -147,6 +182,54 @@ pub fn save_taskbar_signal(file: &Path, on: bool) -> Result<(), String> {
write(file, settings)
}
/// Copy-on-select's default: on for Linux, where selecting text is the
/// copy gesture, off on Windows and macOS, where it would replace what the
/// person last copied.
pub fn default_copy_on_select() -> bool {
cfg!(target_os = "linux")
}
/// Whether selecting text in the terminal copies it at once (Task 10.6). The
/// saved choice, or the per-OS default when the file has none or holds
/// something other than a boolean.
pub fn load_copy_on_select(file: &Path) -> bool {
read(file)
.get(COPY_ON_SELECT_KEY)
.and_then(|v| v.as_bool())
.unwrap_or_else(default_copy_on_select)
}
/// Save the choice, keeping any other key the file holds.
pub fn save_copy_on_select(file: &Path, on: bool) -> Result<(), String> {
let mut settings = read(file);
settings.insert(COPY_ON_SELECT_KEY.to_string(), serde_json::Value::Bool(on));
write(file, settings)
}
/// Note the version the app was running before an "Update and restart", for
/// the new app to say "Updated to vX" once (`take_updated_from`).
pub fn save_updated_from(file: &Path, version: &str) -> Result<(), String> {
let mut settings = read(file);
settings.insert(
UPDATED_FROM_KEY.to_string(),
serde_json::Value::String(version.to_string()),
);
write(file, settings)
}
/// The version noted by `save_updated_from`, read once: the key is removed
/// as it is read, so the message shows one time only.
pub fn take_updated_from(file: &Path) -> Option<String> {
let mut settings = read(file);
let from = settings
.remove(UPDATED_FROM_KEY)?
.as_str()
.map(str::to_string)
.filter(|v| !v.is_empty());
let _ = write(file, settings);
from
}
fn write(file: &Path, settings: serde_json::Map<String, serde_json::Value>) -> Result<(), String> {
if let Some(parent) = file.parent() {
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
@@ -278,4 +361,62 @@ mod tests {
assert_eq!(loaded.fraction, 0.25);
let _ = std::fs::remove_dir_all(file.parent().unwrap());
}
#[test]
fn the_terminal_font_size_defaults_round_trips_and_keeps_other_keys() {
let file = temp_file("font-size");
assert_eq!(load_terminal_font_size(&file), 13, "missing file");
save_last_agent(&file, "claude").unwrap();
assert_eq!(
load_terminal_font_size(&file),
13,
"old file without the field"
);
save_terminal_font_size(&file, 18).unwrap();
assert_eq!(load_terminal_font_size(&file), 18);
assert_eq!(load_last_agent(&file).as_deref(), Some("claude"));
save_term_panel(&file, "bottom", 0.4, false).unwrap();
assert_eq!(load_terminal_font_size(&file), 18);
}
#[test]
fn an_out_of_range_terminal_font_size_is_refused_and_a_bad_one_on_disk_is_clamped() {
let file = temp_file("font-size-range");
assert!(save_terminal_font_size(&file, 7).is_err());
assert!(save_terminal_font_size(&file, 33).is_err());
assert_eq!(load_terminal_font_size(&file), 13, "nothing was written");
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
std::fs::write(&file, r#"{"terminalFontSize": 400}"#).unwrap();
assert_eq!(load_terminal_font_size(&file), 32);
std::fs::write(&file, r#"{"terminalFontSize": 2}"#).unwrap();
assert_eq!(load_terminal_font_size(&file), 8);
std::fs::write(&file, r#"{"terminalFontSize": "big"}"#).unwrap();
assert_eq!(load_terminal_font_size(&file), 13);
}
#[test]
fn copy_on_select_defaults_per_os_and_keeps_a_saved_choice() {
let file = temp_file("copy-on-select");
// No file: Linux copies on select, Windows and macOS do not.
assert_eq!(default_copy_on_select(), cfg!(target_os = "linux"));
assert_eq!(load_copy_on_select(&file), cfg!(target_os = "linux"));
save_copy_on_select(&file, !default_copy_on_select()).unwrap();
assert_eq!(load_copy_on_select(&file), !default_copy_on_select());
save_copy_on_select(&file, default_copy_on_select()).unwrap();
assert_eq!(load_copy_on_select(&file), default_copy_on_select());
// Something other than a boolean reads as the default.
std::fs::write(&file, r#"{"copyOnSelect":"yes"}"#).unwrap();
assert_eq!(load_copy_on_select(&file), default_copy_on_select());
}
#[test]
fn the_updated_marker_is_read_once_and_keeps_other_keys() {
let file = temp_file("updated-from");
assert_eq!(take_updated_from(&file), None);
save_last_agent(&file, "claude").unwrap();
save_updated_from(&file, "3.1.0").unwrap();
assert_eq!(take_updated_from(&file).as_deref(), Some("3.1.0"));
assert_eq!(take_updated_from(&file), None);
assert_eq!(load_last_agent(&file).as_deref(), Some("claude"));
}
}
+217
View File
@@ -0,0 +1,217 @@
//! Confirms the Rust side asks the person, drawn by the shell's own modal (`ui/app.js`
//! `confirmModal`) instead of the OS message box: one look, Stay or Cancel first and focused,
//! `role="alertdialog"`. This module is the request's shape and the table of waiting answers; it
//! knows nothing about Tauri. main.rs emits a `confirm-request` event with a [`ConfirmRequest`]
//! and blocks on the [`Receiver`] until the page calls `confirm_answer`.
use std::collections::HashMap;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::Mutex;
use std::time::Duration;
/// How long a confirm may stay unanswered before it counts as Cancel (a reloaded window would
/// otherwise leave its thread waiting for good).
pub const ANSWER_TIMEOUT: Duration = Duration::from_secs(15 * 60);
/// One line of a confirm's body: plain text, a code block or an amber callout.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
pub struct ConfirmLine {
pub kind: &'static str,
pub text: String,
}
impl ConfirmLine {
pub fn text(text: impl Into<String>) -> Self {
Self {
kind: "text",
text: text.into(),
}
}
pub fn code(text: impl Into<String>) -> Self {
Self {
kind: "code",
text: text.into(),
}
}
pub fn callout(text: impl Into<String>) -> Self {
Self {
kind: "callout",
text: text.into(),
}
}
}
/// What the modal shows. `safe_first` puts Cancel (or Stay) first and gives it focus; `danger`
/// colors the primary as the named danger verb.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ConfirmRequest {
pub id: String,
pub title: String,
pub lines: Vec<ConfirmLine>,
pub primary: String,
pub cancel: String,
pub danger: bool,
pub safe_first: bool,
}
/// The answers still to come, by request id.
#[derive(Default)]
pub struct Pending {
waiting: Mutex<HashMap<String, Sender<bool>>>,
next: Mutex<u64>,
}
impl Pending {
/// A new request id and the receiver its answer arrives on.
pub fn register(&self) -> (String, Receiver<bool>) {
let id = {
let mut next = self.next.lock().unwrap_or_else(|e| e.into_inner());
*next += 1;
format!("confirm-{}", *next)
};
let (tx, rx) = channel();
self.waiting
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(id.clone(), tx);
(id, rx)
}
/// The page's answer. False when no such request is waiting (a stale or invented id), which
/// changes nothing.
pub fn answer(&self, id: &str, yes: bool) -> bool {
let tx = self
.waiting
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(id);
tx.is_some_and(|tx| tx.send(yes).is_ok())
}
/// Answers every waiting request with Cancel: a page that has just started listening is not
/// showing an older modal, so whatever was asked before it listened will never be answered.
pub fn cancel_all(&self) {
let waiting = std::mem::take(&mut *self.waiting.lock().unwrap_or_else(|e| e.into_inner()));
for tx in waiting.into_values() {
let _ = tx.send(false);
}
}
/// Forgets a request that was never answered (a timeout, or a window that could not be told).
pub fn forget(&self, id: &str) {
self.waiting
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(id);
}
}
/// Waits for an answer: true only for an explicit yes; a timeout, a dropped sender or a no is Cancel.
pub fn wait_for(rx: &Receiver<bool>, timeout: Duration) -> bool {
rx.recv_timeout(timeout).unwrap_or(false)
}
/// The quit check's request: the safe answer (Stay) first and focused, the quit verb last.
pub fn quit_request(
id: String,
heading: &str,
message: &str,
quit: &str,
stay: &str,
) -> ConfirmRequest {
ConfirmRequest {
id,
title: heading.to_string(),
lines: vec![ConfirmLine::text(message)],
primary: quit.to_string(),
cancel: stay.to_string(),
danger: true,
safe_first: true,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_answer_reaches_the_waiting_request_once() {
let pending = Pending::default();
let (id, rx) = pending.register();
assert!(pending.answer(&id, true));
assert!(wait_for(&rx, Duration::from_millis(50)));
assert!(
!pending.answer(&id, true),
"answered already: a second answer finds nothing"
);
}
#[test]
fn ids_are_distinct_and_an_unknown_id_answers_nothing() {
let pending = Pending::default();
let (a, _ra) = pending.register();
let (b, _rb) = pending.register();
assert_ne!(a, b);
assert!(!pending.answer("confirm-999", true));
}
#[test]
fn cancel_all_answers_every_waiting_request_with_cancel() {
let pending = Pending::default();
let (a, ra) = pending.register();
let (b, rb) = pending.register();
pending.cancel_all();
assert!(!wait_for(&ra, Duration::from_millis(50)));
assert!(!wait_for(&rb, Duration::from_millis(50)));
assert!(
!pending.answer(&a, true) && !pending.answer(&b, true),
"nothing is left waiting"
);
pending.cancel_all();
}
#[test]
fn no_answer_in_time_is_cancel_and_so_is_a_no() {
let pending = Pending::default();
let (id, rx) = pending.register();
assert!(
!wait_for(&rx, Duration::from_millis(10)),
"timeout is Cancel"
);
let (id2, rx2) = pending.register();
pending.answer(&id2, false);
assert!(!wait_for(&rx2, Duration::from_millis(50)));
pending.forget(&id);
assert!(
!pending.answer(&id, true),
"a forgotten request takes no answer"
);
}
#[test]
fn the_quit_request_puts_stay_first_and_quit_last_as_the_danger_verb() {
let request = quit_request("c1".into(), "Done for now?", "It ends.", "Quit", "Stay");
assert!(request.safe_first && request.danger);
assert_eq!(
(request.primary.as_str(), request.cancel.as_str()),
("Quit", "Stay")
);
let json = serde_json::to_value(&request).unwrap();
assert_eq!(json["safeFirst"], true, "camelCase for the page");
assert_eq!(json["lines"][0]["kind"], "text");
}
#[test]
fn no_text_carries_an_em_dash() {
let request = quit_request("c1".into(), "Done for now?", "It ends.", "Quit", "Stay");
for text in [
&request.title,
&request.lines[0].text,
&request.primary,
&request.cancel,
] {
assert!(!text.contains('\u{2014}'));
}
}
}
+160 -12
View File
@@ -105,10 +105,32 @@ pub fn newer_release(app: &str, ls_remote: &str) -> Option<String> {
(parse(&latest)? > parse(app)?).then_some(latest)
}
/// Ask GitHub for the newest release and return its version when it is newer than `app`.
/// None on any failure (no git, no network, a login prompt, the timeout): a missing answer
/// is never a reason to nag. No prompt and no console window.
pub fn check_new_release(app: &str) -> Option<String> {
/// What a release check found, as the page reads it: `latest` is the newest release's version
/// when it is newer than the app; `problem` is a short sentence when the check itself could not
/// run (no git, no network, a timeout), else none. An app that is simply current has neither.
#[derive(Debug, PartialEq, Eq, Serialize)]
pub struct ReleaseCheck {
pub latest: Option<String>,
pub problem: Option<String>,
}
/// The check's result from `git ls-remote --tags` output, or the reason it could not run.
pub fn release_check_from(app: &str, tags: Result<String, String>) -> ReleaseCheck {
match tags {
Ok(text) => ReleaseCheck {
latest: newer_release(app, &text),
problem: None,
},
Err(reason) => ReleaseCheck {
latest: None,
problem: Some(format!("Could not check for updates: {reason}.")),
},
}
}
/// `git ls-remote --tags` output, or a short reason it could not be had. No prompt and no
/// console window.
fn fetch_tags() -> Result<String, String> {
let mut command = Command::new("git");
command
.env("PATH", crate::node_check::resolved_path())
@@ -126,8 +148,14 @@ pub fn check_new_release(app: &str) -> Option<String> {
use std::os::windows::process::CommandExt;
command.creation_flags(0x08000000); // CREATE_NO_WINDOW, as the console calls are
}
let mut child = command.spawn().ok()?;
let mut stdout = child.stdout.take()?;
let mut child = command.spawn().map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
"git was not found on PATH".to_string()
} else {
"git could not be run".to_string()
}
})?;
let mut stdout = child.stdout.take().ok_or("git gave no output")?;
let (tx, rx) = mpsc::channel::<String>();
std::thread::spawn(move || {
let mut text = String::new();
@@ -138,19 +166,72 @@ pub fn check_new_release(app: &str) -> Option<String> {
Ok(text) => {
let ok = child.wait().is_ok_and(|status| status.success());
if ok {
newer_release(app, &text)
Ok(text)
} else {
None
Err("GitHub did not answer".to_string())
}
}
Err(_) => {
let _ = child.kill();
let _ = child.wait();
None
Err("GitHub did not answer in time".to_string())
}
}
}
/// Ask GitHub for the newest release and report it when it is newer than `app`. A failure
/// (no git, no network, a login prompt, the timeout) comes back as a `problem` sentence, never
/// as an error: nothing waits on it.
pub fn check_new_release(app: &str) -> ReleaseCheck {
release_check_from(app, fetch_tags())
}
/// The app file an "Update and restart" starts: `PLAN2CODE_APP` (the launcher's override, also
/// for tests), else the installer's own place, `~/.plan2code/app/plan2code-app[.exe]`, which an
/// update has just replaced; else none. Never this process's own path: a running file the
/// installer renamed aside would still be the old build.
pub fn installed_app_path() -> Option<PathBuf> {
let file = match std::env::var_os("PLAN2CODE_APP").filter(|v| !v.is_empty()) {
Some(file) => PathBuf::from(file),
None => std::env::home_dir()?
.join(".plan2code")
.join("app")
.join(if cfg!(windows) {
"plan2code-app.exe"
} else {
"plan2code-app"
}),
};
file.is_file().then_some(file)
}
/// The arguments the restarted app gets: the same `--project` folder, when there is one.
pub fn restart_args(project: Option<&Path>) -> Vec<std::ffi::OsString> {
match project {
Some(dir) => vec!["--project".into(), dir.as_os_str().to_owned()],
None => Vec::new(),
}
}
/// Which release an installer run installs. `Pinned` is the desktop app's own tag (Update
/// skills never pulls in work the app does not know about); `Newest` passes no tag, so the
/// launcher picks the newest published release itself (Update and restart).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UpdateTarget<'a> {
Pinned(&'a str),
Newest,
}
/// The launcher's arguments after its script path for `target`.
pub fn update_args(target: UpdateTarget) -> Vec<String> {
let mut args = vec!["update".to_string()];
if let UpdateTarget::Pinned(version) = target {
args.push("--tag".to_string());
args.push(format!("v{version}"));
}
args
}
/// Run the existing installer's update (`plan2code update`, through the launcher's own copy),
/// which brings the skills, the launcher and the app level. Pinned to the release tag `app_version`
/// names, not `main`, so Update skills never pulls in work the app does not know about yet. Blocks
@@ -161,11 +242,25 @@ pub fn run_update(app_version: &str, on_line: impl FnMut(&str)) -> Result<String
run_update_within(app_version, UPDATE_TIMEOUT, on_line)
}
/// "Update and restart"'s install: the same installer and progress readout, unpinned, so the
/// launcher installs the newest release (the newest-tag rule of `plan2code update`).
pub fn run_update_newest(on_line: impl FnMut(&str)) -> Result<String, String> {
run_installer(UpdateTarget::Newest, UPDATE_TIMEOUT, on_line)
}
/// `run_update`, with the timeout as a parameter so a test can use a short one instead of
/// `UPDATE_TIMEOUT`'s real five minutes.
fn run_update_within(
app_version: &str,
timeout: Duration,
on_line: impl FnMut(&str),
) -> Result<String, String> {
run_installer(UpdateTarget::Pinned(app_version), timeout, on_line)
}
fn run_installer(
target: UpdateTarget,
timeout: Duration,
mut on_line: impl FnMut(&str),
) -> Result<String, String> {
let launcher = launcher_dir()
@@ -184,9 +279,7 @@ fn run_update_within(
command.env("PATH", crate::node_check::resolved_path());
command
.arg(&launcher)
.arg("update")
.arg("--tag")
.arg(format!("v{app_version}"))
.args(update_args(target))
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
@@ -408,4 +501,59 @@ mod tests {
});
assert!(result.unwrap_err().contains("is missing"));
}
#[test]
fn the_target_picks_a_pinned_or_an_unpinned_install() {
assert_eq!(
update_args(UpdateTarget::Pinned("3.1.0")),
vec!["update", "--tag", "v3.1.0"]
);
assert_eq!(update_args(UpdateTarget::Newest), vec!["update"]);
}
#[test]
fn a_restart_hands_over_the_same_project_folder() {
assert_eq!(
restart_args(Some(Path::new("/work/app"))),
vec![
std::ffi::OsString::from("--project"),
std::ffi::OsString::from("/work/app")
]
);
assert!(restart_args(None).is_empty());
}
#[test]
fn run_update_newest_passes_no_tag() {
let result = with_fake_launcher(
"newest",
"console.log(process.argv.slice(2).join(' '));",
|| run_update_newest(|_| {}),
);
assert_eq!(result, Ok("update".to_string()));
}
#[test]
fn a_release_check_says_why_it_could_not_run() {
assert_eq!(
release_check_from("3.0.0", Ok(TAGS.to_string())),
ReleaseCheck {
latest: Some("3.10.0".into()),
problem: None
}
);
assert_eq!(
release_check_from("3.10.0", Ok(TAGS.to_string())),
ReleaseCheck {
latest: None,
problem: None
}
);
let failed = release_check_from("3.0.0", Err("git was not found on PATH".into()));
assert_eq!(failed.latest, None);
assert_eq!(
failed.problem.as_deref(),
Some("Could not check for updates: git was not found on PATH.")
);
}
}