Show on the desktop app's taskbar when Plan2Code needs you

AI Assisted
This commit is contained in:
jparkerweb committed 2026-10-26 06:36:45 -07:00
1 parent 765d2b3536
commit c602dfed57
25 files changed
+1038 -112

No files matched your search

+73 -19
View File
@@ -139,7 +139,7 @@ pub fn find_on_path(program: &str, path_var: &str) -> Option<PathBuf> {
pub fn installed_at(kind: AgentKind) -> Option<PathBuf> {
let bin = std::env::var(AGENT_BIN_ENV).ok().filter(|b| !b.is_empty());
let program = bin.unwrap_or_else(|| kind.program_name().to_string());
find_on_path(&program, crate::node_check::resolved_path())
find_on_path(&program, &crate::node_check::resolved_path())
}
/// Whether `kind`'s CLI can be run at all.
@@ -244,7 +244,7 @@ fn launch_spec_with(
// A Dock or Start-menu launch often lacks nvm, Homebrew or Volta's
// directories (Task 9.9): the agent CLI itself, and anything it shells
// out to, needs a PATH that finds them anyway.
let env = vec![("PATH".to_string(), crate::node_check::resolved_path().to_string())];
let env = vec![("PATH".to_string(), crate::node_check::resolved_path())];
LaunchSpec { program: program.to_string(), args, env, cwd }
}
@@ -546,7 +546,7 @@ impl Agent {
Agent::Custom(agent) => {
let bin = std::env::var(AGENT_BIN_ENV).ok().filter(|b| !b.is_empty());
let command = bin.as_deref().unwrap_or(&agent.command);
resolve_command(command, crate::node_check::resolved_path())
resolve_command(command, &crate::node_check::resolved_path())
}
}
}
@@ -566,9 +566,10 @@ pub fn find_agent_in(id: &str, file: Option<&Path>) -> Option<Agent> {
agents.into_iter().find(|agent| agent.id == id).map(Agent::Custom)
}
/// Every custom agent in `~/.plan2code/agents.json`, read afresh.
pub fn custom_agents() -> Vec<CustomAgent> {
agents_file().map(|file| load_custom_agents(&file).0).unwrap_or_default()
/// Every custom agent in `~/.plan2code/agents.json`, read afresh, with the
/// warnings about anything in the file that was skipped.
pub fn custom_agents() -> (Vec<CustomAgent>, Vec<String>) {
agents_file().map(|file| load_custom_agents(&file)).unwrap_or_default()
}
fn clean_command(command: &str) -> &str {
@@ -644,7 +645,7 @@ pub fn agent_launch_spec(
model,
mode,
prompt,
crate::node_check::resolved_path(),
&crate::node_check::resolved_path(),
cfg!(windows),
)
}
@@ -668,6 +669,7 @@ fn custom_launch_spec(
let mut path = base_path.to_string();
let mut program =
resolved.map_or_else(|| clean_command(&custom.command).to_string(), |p| p.to_string_lossy().into_owned());
let mut extra_env = Vec::new();
if windows {
let ext = resolved.and_then(|p| p.extension()).map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_default();
if let (true, Some(file)) = (ext == "cmd" || ext == "bat", resolved) {
@@ -680,13 +682,36 @@ fn custom_launch_spec(
path = format!("{};{}", dir.to_string_lossy(), base_path);
}
}
let mut wrapped = vec!["/c".to_string(), file_name];
wrapped.append(&mut args);
args = wrapped;
// The pseudo-terminal quotes only arguments with a space or a quote,
// so `cmd` would read `&`, `|` or `%` in the rest itself. The line is
// quoted as the launcher's `quoteForCmd` does and handed over in a
// variable: `cmd` expands it once and then parses it, so its quotes
// hold and a `%` inside it is not expanded again.
let line: Vec<String> = std::iter::once(file_name).chain(args).map(|arg| quote_for_cmd(&arg)).collect();
extra_env.push((CMD_LINE_ENV.to_string(), line.join(" ")));
// `cmd` looks in the current folder (the project) before PATH: a
// same-named file there must not run in the agent's place.
extra_env.push(("NoDefaultCurrentDirectoryInExePath".to_string(), "1".to_string()));
args = vec!["/d".to_string(), "/c".to_string(), format!("%{CMD_LINE_ENV}%")];
program = "cmd".to_string();
}
}
LaunchSpec { program, args, env: vec![("PATH".to_string(), path)], cwd: folder.to_path_buf() }
let mut env = vec![("PATH".to_string(), path)];
env.append(&mut extra_env);
LaunchSpec { program, args, env, cwd: folder.to_path_buf() }
}
/// The variable a custom `.cmd` or `.bat` agent's command line reaches `cmd` in.
const CMD_LINE_ENV: &str = "PLAN2CODE_AGENT_LINE";
/// One argument of a `cmd` line, quoted when `cmd` would otherwise read it: the
/// launcher's `quoteForCmd`.
fn quote_for_cmd(arg: &str) -> String {
let special = |c: char| c.is_whitespace() || "\"&|<>^%!()".contains(c);
if !arg.is_empty() && !arg.chars().any(special) {
return arg.to_string();
}
format!("\"{}\"", arg.replace('"', "\"\""))
}
/// The page a built-in agent installs from; any other id is an error.
@@ -1013,26 +1038,55 @@ mod tests {
let found = Path::new("C:\\with space").join("goose.cmd");
let spec = custom_launch_spec(&full, Some(&found), &folder(), None, PermissionMode::Checked, "/p", "BASE", true);
assert_eq!(spec.program, "cmd");
assert_eq!(spec.args, ["/c", "goose.cmd", "/p"]);
assert_eq!(spec.args, ["/d", "/c", "%PLAN2CODE_AGENT_LINE%"]);
assert_eq!(spec.env[0].1, format!("{};BASE", found.parent().unwrap().to_string_lossy()));
assert_eq!(spec.env[1], ("PLAN2CODE_AGENT_LINE".to_string(), "goose.cmd /p".to_string()));
assert_eq!(spec.env[2], ("NoDefaultCurrentDirectoryInExePath".to_string(), "1".to_string()));
// A bare name keeps the plain PATH.
let bare = custom_launch_spec(&goose(), Some(&found), &folder(), None, PermissionMode::Checked, "/p", "BASE", true);
assert_eq!((bare.program.as_str(), bare.env[0].1.as_str()), ("cmd", "BASE"));
}
#[test]
fn a_cmd_line_quotes_what_cmd_would_read_as_the_launcher_does() {
assert_eq!(quote_for_cmd("--yes"), "--yes");
assert_eq!(quote_for_cmd(""), "\"\"");
assert_eq!(quote_for_cmd("a|b"), "\"a|b\"");
assert_eq!(quote_for_cmd("%X%"), "\"%X%\"");
assert_eq!(quote_for_cmd("say \"hi\""), "\"say \"\"hi\"\"\"");
let mut agent = goose();
agent.args = vec!["--filter=a|b".to_string(), "{prompt}".to_string()];
let found = Path::new("C:\\tools").join("goose.cmd");
let spec = custom_launch_spec(&agent, Some(&found), &folder(), None, PermissionMode::Checked, "/p & x", "BASE", true);
assert_eq!(spec.env[1].1, "goose.cmd \"--filter=a|b\" \"/p & x\"");
}
#[cfg(windows)]
#[test]
fn a_full_path_cmd_in_a_spaced_folder_resolves_and_wraps() {
let dir = temp_dir("spaced").join("with space");
fn a_full_path_cmd_in_a_spaced_folder_runs_with_its_arguments_intact_and_not_a_project_copy() {
let root = temp_dir("spaced");
let dir = root.join("with space");
let project = root.join("project");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("goose.cmd"), "@echo off").unwrap();
std::fs::create_dir_all(&project).unwrap();
std::fs::write(dir.join("goose.cmd"), "@echo off\r\necho REAL [%1] [%2]\r\n").unwrap();
// A same-named file in the project folder must not run instead.
std::fs::write(project.join("goose.cmd"), "@echo off\r\necho DECOY\r\n").unwrap();
let mut agent = goose();
agent.command = dir.join("goose.cmd").to_string_lossy().into_owned();
agent.args = vec!["a|b".to_string(), "%PATH%".to_string()];
let found = Agent::Custom(agent.clone()).installed_at().expect("resolves");
let spec = custom_launch_spec(&agent, Some(&found), &folder(), None, PermissionMode::Checked, "/p", "BASE", true);
assert_eq!((spec.program.as_str(), spec.args[1].as_str()), ("cmd", "goose.cmd"));
assert!(spec.env[0].1.starts_with(&dir.to_string_lossy().to_string()));
let _ = std::fs::remove_dir_all(dir.parent().unwrap());
let spec = custom_launch_spec(&agent, Some(&found), &project, None, PermissionMode::Checked, "", &std::env::var("PATH").unwrap_or_default(), true);
let mut command = std::process::Command::new(&spec.program);
// Some shells already set the switch the spec sets; start without it.
command.args(&spec.args).current_dir(&spec.cwd).env_remove("NoDefaultCurrentDirectoryInExePath");
for (key, value) in &spec.env {
command.env(key, value);
}
let out = command.output().expect("cmd runs");
let text = String::from_utf8_lossy(&out.stdout);
assert_eq!(text.trim(), "REAL [\"a|b\"] [\"%PATH%\"]", "{text}");
let _ = std::fs::remove_dir_all(&root);
}
#[test]
+234
View File
@@ -0,0 +1,234 @@
//! The taskbar entry's attention signal. It decides which of four states the
//! desktop app is in (busy, ready, attention, plain), which badge the platform
//! shows for that state, whether a change into a state that wants the person
//! should flash the window, and the pixels of the colored dot. The states and
//! the dot colors mirror the web console's favicon. Knows nothing about Tauri.
//! The caller turns these decisions into calls on the window.
/// What Plan2Code is doing, as the web console's favicon shows it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Signal {
Busy,
Ready,
Attention,
Plain,
}
/// The two dot colors the taskbar badge can show.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DotColor {
Green,
Red,
}
/// The badge a platform shows on the taskbar entry.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Badge {
None,
Dot(DotColor),
Label(&'static str),
Count(i64),
}
/// The default size, in pixels, of the square dot image.
pub const DOT_SIZE: u32 = 16;
const GREEN_HEX: &str = "#22c55e";
const RED_HEX: &str = "#e5484d";
const RING_HEX: &str = "#3b332c";
impl Signal {
/// The signal named by a favicon state id ("busy", "ready", "attention"
/// or "plain"). Any other text is `None`.
pub fn from_id(id: &str) -> Option<Signal> {
match id {
"busy" => Some(Signal::Busy),
"ready" => Some(Signal::Ready),
"attention" => Some(Signal::Attention),
"plain" => Some(Signal::Plain),
_ => None,
}
}
}
/// The badge for `signal` on the platform named by `os` (the value of
/// `std::env::consts::OS`). When the badge is turned off, there is none.
/// Windows shows a dot, macOS a "!" label and Linux a count of 1, and only
/// for the states that want the person.
pub fn badge_for(signal: Signal, os: &str, enabled: bool) -> Badge {
if !enabled {
return Badge::None;
}
match (os, signal) {
("windows", Signal::Ready) => Badge::Dot(DotColor::Green),
("windows", Signal::Attention) => Badge::Dot(DotColor::Red),
("macos", Signal::Attention) => Badge::Label("!"),
("linux", Signal::Attention) => Badge::Count(1),
_ => Badge::None,
}
}
/// Whether the window should flash. It does so only when flashing is on, the
/// window is not focused, and the signal just changed into Ready or Attention.
/// A repeat of the same signal does not flash again.
pub fn should_flash(prev: Option<Signal>, next: Signal, focused: bool, enabled: bool) -> bool {
enabled && !focused && matches!(next, Signal::Ready | Signal::Attention) && prev != Some(next)
}
/// The dot as RGBA bytes, row by row: a filled, anti-aliased circle with a
/// 1 px dark ring at its edge, on a transparent square of `size` pixels. The
/// result is `size * size * 4` bytes long, with straight (not premultiplied)
/// alpha.
pub fn dot_rgba(color: DotColor, size: u32) -> Vec<u8> {
let fill = parse_hex(match color {
DotColor::Green => GREEN_HEX,
DotColor::Red => RED_HEX,
});
let ring = parse_hex(RING_HEX);
let n = size as usize;
let mut out = vec![0u8; n * n * 4];
let center = size as f32 / 2.0;
let radius = center - 0.5;
for y in 0..n {
for x in 0..n {
// Distance from the pixel's center to the circle's center.
let dx = x as f32 + 0.5 - center;
let dy = y as f32 + 0.5 - center;
let distance = (dx * dx + dy * dy).sqrt();
let coverage = (radius + 0.5 - distance).clamp(0.0, 1.0);
let rgb = if distance > radius - 1.0 { ring } else { fill };
let alpha = (coverage * 255.0).round() as u8;
let i = (y * n + x) * 4;
out[i..i + 4].copy_from_slice(&[rgb[0], rgb[1], rgb[2], alpha]);
}
}
out
}
/// The three bytes of a `#rrggbb` color. A malformed pair reads as 0.
fn parse_hex(hex: &str) -> [u8; 3] {
let digits = hex.strip_prefix('#').unwrap_or(hex);
let byte = |i: usize| {
digits
.get(i..i + 2)
.and_then(|pair| u8::from_str_radix(pair, 16).ok())
.unwrap_or(0)
};
[byte(0), byte(2), byte(4)]
}
#[cfg(test)]
mod tests {
use super::*;
const SIGNALS: [Signal; 4] = [Signal::Busy, Signal::Ready, Signal::Attention, Signal::Plain];
fn pixel(buf: &[u8], size: u32, x: u32, y: u32) -> [u8; 4] {
let i = ((y * size + x) * 4) as usize;
[buf[i], buf[i + 1], buf[i + 2], buf[i + 3]]
}
#[test]
fn the_badge_follows_the_platform_table() {
let table: [(Signal, &str, Badge); 16] = [
(Signal::Busy, "windows", Badge::None),
(Signal::Ready, "windows", Badge::Dot(DotColor::Green)),
(Signal::Attention, "windows", Badge::Dot(DotColor::Red)),
(Signal::Plain, "windows", Badge::None),
(Signal::Busy, "macos", Badge::None),
(Signal::Ready, "macos", Badge::None),
(Signal::Attention, "macos", Badge::Label("!")),
(Signal::Plain, "macos", Badge::None),
(Signal::Busy, "linux", Badge::None),
(Signal::Ready, "linux", Badge::None),
(Signal::Attention, "linux", Badge::Count(1)),
(Signal::Plain, "linux", Badge::None),
(Signal::Busy, "freebsd", Badge::None),
(Signal::Ready, "freebsd", Badge::None),
(Signal::Attention, "freebsd", Badge::None),
(Signal::Plain, "freebsd", Badge::None),
];
for (signal, os, want) in table {
assert_eq!(badge_for(signal, os, true), want, "{signal:?} on {os}, enabled");
assert_eq!(badge_for(signal, os, false), Badge::None, "{signal:?} on {os}, disabled");
}
}
#[test]
fn from_id_reads_the_four_words_and_refuses_the_rest() {
assert_eq!(Signal::from_id("busy"), Some(Signal::Busy));
assert_eq!(Signal::from_id("ready"), Some(Signal::Ready));
assert_eq!(Signal::from_id("attention"), Some(Signal::Attention));
assert_eq!(Signal::from_id("plain"), Some(Signal::Plain));
assert_eq!(Signal::from_id("sleeping"), None);
assert_eq!(Signal::from_id("Ready"), None, "the ids are lowercase");
}
#[test]
fn a_change_into_ready_or_attention_flashes_when_unfocused() {
assert!(should_flash(Some(Signal::Busy), Signal::Ready, false, true));
assert!(should_flash(None, Signal::Attention, false, true));
}
#[test]
fn no_flash_while_the_window_is_focused() {
assert!(!should_flash(Some(Signal::Busy), Signal::Ready, true, true));
}
#[test]
fn no_flash_for_a_repeat_of_the_same_signal() {
assert!(!should_flash(Some(Signal::Ready), Signal::Ready, false, true));
assert!(!should_flash(Some(Signal::Attention), Signal::Attention, false, true));
}
#[test]
fn no_flash_for_busy_or_plain() {
for prev in [None, Some(Signal::Ready), Some(Signal::Attention)] {
assert!(!should_flash(prev, Signal::Busy, false, true), "busy from {prev:?}");
assert!(!should_flash(prev, Signal::Plain, false, true), "plain from {prev:?}");
}
}
#[test]
fn no_flash_when_flashing_is_turned_off() {
for signal in SIGNALS.iter().copied() {
assert!(!should_flash(Some(Signal::Busy), signal, false, false), "{signal:?} while disabled");
}
}
#[test]
fn parse_hex_reads_the_byte_pairs() {
assert_eq!(parse_hex("#22c55e"), [0x22, 0xc5, 0x5e]);
assert_eq!(parse_hex("e5484d"), [0xe5, 0x48, 0x4d]);
}
#[test]
fn the_green_dot_is_a_transparent_square_with_a_filled_middle() {
let size = DOT_SIZE;
let buf = dot_rgba(DotColor::Green, size);
assert_eq!(buf.len(), (size * size * 4) as usize);
assert_eq!(pixel(&buf, size, 0, 0)[3], 0, "a corner is transparent");
let center = pixel(&buf, size, 8, 8);
assert_eq!(center[3], 255, "the middle is opaque");
assert_eq!(&center[..3], &parse_hex(GREEN_HEX)[..], "the middle is the green fill");
}
#[test]
fn the_red_dot_is_a_transparent_square_with_a_filled_middle() {
let size = DOT_SIZE;
let buf = dot_rgba(DotColor::Red, size);
assert_eq!(buf.len(), (size * size * 4) as usize);
assert_eq!(pixel(&buf, size, 0, 0)[3], 0, "a corner is transparent");
let center = pixel(&buf, size, 8, 8);
assert_eq!(center[3], 255, "the middle is opaque");
assert_eq!(&center[..3], &parse_hex(RED_HEX)[..], "the middle is the red fill");
}
#[test]
fn the_fill_colors_match_the_web_console_favicon() {
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../src/web-console/public/favicon.js");
let text = std::fs::read_to_string(path).unwrap();
assert!(text.contains(&format!("ready: \"{GREEN_HEX}\"")), "ready color in favicon.js");
assert!(text.contains(&format!("attention: \"{RED_HEX}\"")), "attention color in favicon.js");
}
}
+1
View File
@@ -3,6 +3,7 @@
pub mod agent_manager;
pub mod agents;
pub mod announce;
pub mod attention;
pub mod brief;
pub mod console_supervisor;
pub mod handoff;
+152 -11
View File
@@ -1,11 +1,12 @@
// Hide the extra console window on Windows release builds.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Mutex, OnceLock};
use plan2code_app_lib::announce::{AnnounceServer, PageNotice};
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, BeforeFresh, Sink};
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentState, BeforeFresh, Sink};
use plan2code_app_lib::agents::{self, Agent, AgentKind, PermissionMode};
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::node_check;
use plan2code_app_lib::project::{self, ProjectDir};
@@ -37,6 +38,24 @@ struct AppState {
// (Task 9.9): the first-run checklist's Node row names both.
node_version: Option<String>,
node_binary: Option<String>,
// 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
// through it when the agent ends.
app: Arc<OnceLock<tauri::AppHandle>>,
}
// The console page's last state as the taskbar shows it (attention.rs), and
// the Desktop app switch, `taskbarSignal` in app.json.
struct AttentionState {
last: Option<Signal>,
enabled: bool,
}
impl Default for AttentionState {
fn default() -> Self {
AttentionState { last: None, enabled: true }
}
}
// The operating system and, on Windows, the build number xterm needs for ConPTY.
@@ -47,9 +66,15 @@ fn platform_info() -> serde_json::Value {
}
// What the launch card offers per agent: whether its CLI is on PATH (else how
// to install it), and whether it takes its own reasoning effort.
// to install it), and whether it takes its own reasoning effort; plus the
// warnings about agents.json.
#[tauri::command]
fn agent_availability() -> serde_json::Value {
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.
if refresh == Some(true) {
node_check::refresh_path();
}
// 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
@@ -70,7 +95,8 @@ fn agent_availability() -> serde_json::Value {
})
})
.collect();
for custom in agents::custom_agents() {
let (customs, warnings) = agents::custom_agents();
for custom in customs {
let at = Agent::Custom(custom.clone()).installed_at();
entries.push(serde_json::json!({
"id": custom.id,
@@ -84,7 +110,9 @@ fn agent_availability() -> serde_json::Value {
"models": custom.models,
}));
}
serde_json::json!(entries)
// What was skipped in agents.json, so a custom agent that vanished from
// the picker is explained, as the launcher and the console do.
serde_json::json!({ "agents": entries, "warnings": warnings })
}
// Opens a built-in agent install page in the default browser. Any other id
@@ -130,9 +158,15 @@ fn windows_build() -> Option<u32> {
}
// Sends the agent's output as raw bytes and its state changes as JSON, on the
// page's latest channel. Nothing is sent while no page has registered one.
fn page_sink(page: PageChannel) -> Sink {
// page's latest channel. Nothing is sent while no page has registered one. An
// agent that ends takes the taskbar's dot with it, page or no page.
fn page_sink(page: PageChannel, app: Arc<OnceLock<tauri::AppHandle>>) -> Sink {
Arc::new(move |event| {
if let AgentEvent::State(snapshot) = &event {
if let (AgentState::Ended { .. }, Some(app)) = (&snapshot.state, app.get()) {
clear_attention(app);
}
}
let Ok(guard) = page.lock() else { return };
let Some(channel) = guard.as_ref() else { return };
let body = match event {
@@ -162,7 +196,7 @@ fn agent_for_project(state: &AppState) -> Result<Arc<AgentManager>, String> {
return Ok(Arc::clone(agent));
}
}
let sink = page_sink(Arc::clone(&state.page));
let sink = page_sink(Arc::clone(&state.page), Arc::clone(&state.app));
let agent = Arc::new(AgentManager::new(dir, sink));
agent.set_before_fresh(before_fresh_hook(state));
*guard = Some(Arc::clone(&agent));
@@ -361,6 +395,99 @@ fn quit_app(app: &tauri::AppHandle) {
app.exit(0);
}
// The console page's state, told on every change (`attention` from the page):
// the taskbar's dot for this system, and one flash on a change into the
// person's move or needs attention while the window is not focused. An
// unknown word does nothing.
#[tauri::command]
fn set_attention(app: tauri::AppHandle, state: State<'_, AppState>, signal: String) {
let Some(next) = Signal::from_id(&signal) else { return };
let Some(window) = app.get_webview_window("main") else { return };
let (prev, enabled) = {
let Ok(mut guard) = state.attention.lock() else { return };
(guard.last.replace(next), guard.enabled)
};
apply_badge(&window, attention::badge_for(next, std::env::consts::OS, enabled));
if attention::should_flash(prev, next, window.is_focused().unwrap_or(true), enabled) {
let _ = window.request_user_attention(Some(tauri::UserAttentionType::Informational));
}
}
// The one place a badge reaches the window, in each system's own form. A call
// that fails changes nothing else: the taskbar is a hint, never a blocker.
#[cfg_attr(not(any(target_os = "windows", target_os = "macos", target_os = "linux")), allow(unused_variables))]
fn apply_badge(window: &tauri::WebviewWindow, badge: Badge) {
#[cfg(target_os = "windows")]
{
let icon = match badge {
Badge::Dot(color) => Some(tauri::image::Image::new_owned(
attention::dot_rgba(color, attention::DOT_SIZE),
attention::DOT_SIZE,
attention::DOT_SIZE,
)),
_ => None,
};
let _ = window.set_overlay_icon(icon);
}
#[cfg(target_os = "macos")]
{
let label = match badge {
Badge::Label(text) => Some(text.to_string()),
_ => None,
};
let _ = window.set_badge_label(label);
}
#[cfg(target_os = "linux")]
{
let count = match badge {
Badge::Count(count) => Some(count),
_ => None,
};
let _ = window.set_badge_count(count);
}
}
// No dot and no flash: the agent ended, the page went away, or the switch was
// turned off. The next state the page tells starts from plain.
fn clear_attention(app: &tauri::AppHandle) {
if let Ok(mut guard) = app.state::<AppState>().attention.lock() {
guard.last = Some(Signal::Plain);
}
let Some(window) = app.get_webview_window("main") else { return };
apply_badge(&window, Badge::None);
let _ = window.request_user_attention(None);
}
// The app page clears it when a new page loads in the frame or none answers.
#[tauri::command]
fn clear_attention_cmd(app: tauri::AppHandle) {
clear_attention(&app);
}
// The Desktop app switch in the console's User Preferences (`taskbar` from the
// page). Off clears the dot and stops flashes; on shows the dot for the state
// the page last told at once, since the page only tells it again on a change.
// Either way the last state is kept. Saved in the app's own app.json, never
// in the console's files.
#[tauri::command]
fn set_taskbar_signal(app: tauri::AppHandle, state: State<'_, AppState>, on: bool) -> Result<(), String> {
let saved = settings::settings_file()
.ok_or_else(|| "no home folder found".to_string())
.and_then(|file| settings::save_taskbar_signal(&file, on));
let last = {
let Ok(mut guard) = state.attention.lock() else { return saved };
guard.enabled = on;
guard.last.unwrap_or(Signal::Plain)
};
if let Some(window) = app.get_webview_window("main") {
apply_badge(&window, attention::badge_for(last, std::env::consts::OS, on));
if !on {
let _ = window.request_user_attention(None);
}
}
saved
}
/// What the page draws its bar from: the folder (or that none is chosen yet)
/// and the agent the picker starts on.
#[tauri::command]
@@ -402,6 +529,8 @@ fn app_state(state: State<'_, AppState>) -> serde_json::Value {
// or launch card shown.
"autoStart": state.launch.agent,
"termPanel": term_panel,
// The Desktop app switch, for the page's User Preferences.
"taskbarSignal": state.attention.lock().map_or(true, |guard| guard.enabled),
})
}
@@ -499,7 +628,7 @@ fn teardown_project(state: &AppState) -> Result<(), String> {
/// the old one (its agent stopped, its console stopped) before the new
/// folder is remembered, so `agent_for_project` and `console_start` start
/// fresh for it rather than reusing anything from the one just left. Picking
/// nothing (cancelled) leaves the current project untouched. One project per
/// nothing (canceled) leaves the current project untouched. One project per
/// window stays; this replaces it, it does not add a second.
#[tauri::command]
fn change_project(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<Option<String>, String> {
@@ -580,6 +709,10 @@ fn main() {
launch: project::launch_choice(&args),
node_version,
node_binary,
attention: Mutex::new(AttentionState {
last: None,
enabled: settings::settings_file().map_or(true, |file| settings::load_taskbar_signal(&file)),
}),
..AppState::default()
})
.invoke_handler(tauri::generate_handler![
@@ -600,9 +733,16 @@ fn main() {
change_project,
console_start,
console_status,
console_stop
console_stop,
set_attention,
clear_attention_cmd,
set_taskbar_signal
])
.on_window_event(|window, event| {
// Looking at the window is the answer to its flash.
if let tauri::WindowEvent::Focused(true) = event {
let _ = window.request_user_attention(None);
}
// Closing with an agent running asks first; "no" keeps the window open.
if let tauri::WindowEvent::CloseRequested { api, .. } = event {
let app = window.app_handle().clone();
@@ -613,6 +753,7 @@ fn main() {
}
})
.setup(move |app| {
let _ = app.state::<AppState>().app.set(app.handle().clone());
// Pages the agent's `open` announces: the supervisor and the agent's
// environment follow the console, and the page frame shows it.
let handle = app.handle().clone();
+125 -20
View File
@@ -9,7 +9,7 @@
//! `console_supervisor`, `versions` and `agents` all use it.
use std::process::Command;
use std::sync::OnceLock;
use std::sync::Mutex;
pub const MIN_NODE_MAJOR: u32 = 18;
@@ -73,30 +73,110 @@ fn login_shell_path() -> Option<String> {
(out.status.success() && !path.is_empty()).then_some(path)
}
static RESOLVED_PATH: Mutex<Option<String>> = Mutex::new(None);
/// The PATH every process this app spawns should run with: an explicit
/// `--node`'s directory first, then (macOS and Linux) the login shell's own
/// PATH, then this process's own PATH, each included only once. Resolved
/// once per launch: none of these change while the app runs.
pub fn resolved_path() -> &'static str {
static PATH: OnceLock<String> = OnceLock::new();
PATH.get_or_init(|| {
let args: Vec<String> = std::env::args().collect();
let inherited = std::env::var("PATH").unwrap_or_default();
let mut parts = Vec::new();
if let Some(dir) = node_override_dir(&args) {
parts.push(dir);
}
#[cfg(unix)]
if let Some(login) = login_shell_path() {
parts.push(login);
}
if !inherited.is_empty() {
parts.push(inherited);
}
parts.join(if cfg!(windows) { ";" } else { ":" })
/// PATH, then this process's own PATH, each included only once. Worked out
/// once per launch, and again only on `refresh_path`.
pub fn resolved_path() -> String {
let mut cached = RESOLVED_PATH.lock().unwrap_or_else(|e| e.into_inner());
cached.get_or_insert_with(|| build_path(false)).clone()
}
/// Work the PATH out again, for "Check again" after an agent CLI was
/// installed: an installer may have added a folder (the login shell's
/// profile on macOS and Linux, the saved user or system PATH on Windows)
/// that this process's own PATH has never had.
pub fn refresh_path() {
let fresh = build_path(true);
*RESOLVED_PATH.lock().unwrap_or_else(|e| e.into_inner()) = Some(fresh);
}
fn build_path(fresh: bool) -> String {
let args: Vec<String> = std::env::args().collect();
let inherited = std::env::var("PATH").unwrap_or_default();
let mut parts = Vec::new();
if let Some(dir) = node_override_dir(&args) {
parts.push(dir);
}
#[cfg(unix)]
if let Some(login) = login_shell_path() {
parts.push(login);
}
// At start this process's PATH already is the saved one; only a refresh
// needs to read it again.
#[cfg(windows)]
if fresh {
parts.extend(saved_windows_path());
}
#[cfg(not(windows))]
let _ = fresh;
if !inherited.is_empty() {
parts.push(inherited);
}
parts.join(if cfg!(windows) { ";" } else { ":" })
}
/// The system then the user PATH as saved in the registry, with `%NAME%`
/// expanded: what a newly opened terminal would get.
#[cfg(windows)]
fn saved_windows_path() -> Vec<String> {
use std::os::windows::process::CommandExt;
let keys = [r"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment", r"HKCU\Environment"];
keys.iter()
.filter_map(|key| {
let out = Command::new("reg")
.args(["query", key, "/v", "Path"])
.creation_flags(0x0800_0000) // CREATE_NO_WINDOW
.output()
.ok()?;
let value = parse_reg_query_value(&String::from_utf8_lossy(&out.stdout))?;
Some(expand_percent_vars(&value, |name| std::env::var(name).ok()))
})
.collect()
}
/// The value from `reg query <key> /v <name>` output: the text after the
/// `REG_SZ` or `REG_EXPAND_SZ` column on its line.
#[cfg_attr(not(windows), allow(dead_code))]
fn parse_reg_query_value(output: &str) -> Option<String> {
output.lines().find_map(|line| {
let (_, rest) = line.split_once("REG_EXPAND_SZ").or_else(|| line.split_once("REG_SZ"))?;
let value = rest.trim();
(!value.is_empty()).then(|| value.to_string())
})
}
/// `%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 {
let mut out = String::new();
let mut rest = text;
while let Some(start) = rest.find('%') {
out.push_str(&rest[..start]);
let after = &rest[start + 1..];
match after.find('%') {
Some(end) if end > 0 => match lookup(&after[..end]) {
Some(value) => {
out.push_str(&value);
rest = &after[end + 1..];
}
None => {
out.push('%');
rest = after;
}
},
_ => {
out.push('%');
rest = after;
}
}
}
out.push_str(rest);
out
}
/// Where `node` actually resolves, with `resolved_path`: for the first-run
/// checklist to name (Task 9.9), not for `check_node` itself to decide with.
pub fn node_binary_path() -> Option<String> {
@@ -172,4 +252,29 @@ mod tests {
assert_eq!(node_override_dir(&args(&["--node="])), None);
assert_eq!(node_override_dir(&args(&["--agent", "claude"])), None);
}
#[test]
fn reads_the_saved_path_out_of_reg_query_output() {
let out = "\r\nHKEY_CURRENT_USER\\Environment\r\n Path REG_EXPAND_SZ %USERPROFILE%\\.local\\bin;C:\\Tools\r\n\r\n";
assert_eq!(parse_reg_query_value(out).as_deref(), Some("%USERPROFILE%\\.local\\bin;C:\\Tools"));
let plain = "HKEY_LOCAL_MACHINE\\x\r\n Path REG_SZ C:\\Windows\r\n";
assert_eq!(parse_reg_query_value(plain).as_deref(), Some("C:\\Windows"));
assert_eq!(parse_reg_query_value("ERROR: The system was unable to find the specified registry key or value.\r\n"), None);
}
#[test]
fn expands_known_percent_names_and_keeps_the_rest() {
let lookup = |name: &str| (name == "USERPROFILE").then(|| "C:\\Users\\sam".to_string());
assert_eq!(expand_percent_vars("%USERPROFILE%\\.local\\bin;C:\\x", lookup), "C:\\Users\\sam\\.local\\bin;C:\\x");
assert_eq!(expand_percent_vars("%NOPE%\\bin;%USERPROFILE%", lookup), "%NOPE%\\bin;C:\\Users\\sam");
assert_eq!(expand_percent_vars("50%", lookup), "50%");
assert_eq!(expand_percent_vars("a%%b", lookup), "a%%b");
}
#[test]
fn refresh_path_keeps_this_process_path() {
refresh_path();
let inherited = std::env::var("PATH").unwrap_or_default();
assert!(resolved_path().ends_with(&inherited));
}
}
+30
View File
@@ -9,6 +9,7 @@ const TERM_DOCK_KEY: &str = "termDock";
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";
/// 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
@@ -100,6 +101,20 @@ pub fn save_first_run_done(file: &Path) -> Result<(), String> {
write(file, settings)
}
/// Whether the taskbar entry shows when Plan2Code needs the person (the
/// Desktop app switch in the console's User Preferences). On unless the file
/// says `false`; anything but a boolean reads as on.
pub fn load_taskbar_signal(file: &Path) -> bool {
read(file).get(TASKBAR_SIGNAL_KEY).and_then(|v| v.as_bool()).unwrap_or(true)
}
/// Save the switch, keeping any other key the file holds.
pub fn save_taskbar_signal(file: &Path, on: bool) -> Result<(), String> {
let mut settings = read(file);
settings.insert(TASKBAR_SIGNAL_KEY.to_string(), serde_json::Value::Bool(on));
write(file, settings)
}
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())?;
@@ -187,6 +202,21 @@ mod tests {
let _ = std::fs::remove_dir_all(file.parent().unwrap());
}
#[test]
fn the_taskbar_signal_is_on_until_it_is_switched_off() {
assert!(load_taskbar_signal(&temp_file("taskbar-missing")));
let file = temp_file("taskbar");
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
std::fs::write(&file, r#"{"other": 1, "taskbarSignal": "no"}"#).unwrap();
assert!(load_taskbar_signal(&file), "not a boolean reads as on");
save_taskbar_signal(&file, false).unwrap();
assert!(!load_taskbar_signal(&file));
save_taskbar_signal(&file, true).unwrap();
assert!(load_taskbar_signal(&file));
assert!(std::fs::read_to_string(&file).unwrap().contains("\"other\""));
let _ = std::fs::remove_dir_all(file.parent().unwrap());
}
#[test]
fn a_bad_dock_or_out_of_range_fraction_on_disk_reads_as_the_default() {
let file = temp_file("term-bad-load");