mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 04:45:33 -08:00
Offer recent project folders in the launcher and the desktop app
AI Assisted
This commit is contained in:
1 parent
2e2b3e1139
commit
8459836d3b
14 files changed
+1037
-86
No files matched your search
@@ -8,6 +8,8 @@ The app is optional. The Node web console and the skills never depend on it, so
|
||||
|
||||
**Agent picker.** The launch card lists Claude Code, Devin and Codex, then any custom agents from `~/.plan2code/agents.json` (added in the console's User Preferences → Agents & models, the same list the `plan2code` command uses). The app starts on an agent that is installed (your last pick when it still is), never assumes Claude Code, and a custom agent has no effort row; New Session reuses whichever agent you started. The Model dropdown offers the same list the `plan2code` launcher's model question does (the shipped `models.json` plus anything you added in User Preferences), a custom agent its own `models`, and it hides for an agent with none; `/plan2code` only does something in an agent that loads the installed Plan2Code skills.
|
||||
|
||||
**Project picker.** The app takes its folder from `--project` (what the `plan2code` command and the desktop shortcut pass) and never reopens the last one by itself. Started with no folder, and from **Change project**, it shows one picker: **Choose a folder** (focused, the default; it opens the system folder dialog) with the recent folders under it, newest first, leaving out the folder already open. The list is `recentFolders` in `~/.plan2code/launcher.json`, shared with the `plan2code` command, which keeps it by the same rule: `recent_folders` and `open_recent_folder` in `src-tauri/src/main.rs` over `project.rs`, held to `scripts/fixtures/recent-folders-cases.json` (the launcher's JS runs the same cases). A recent folder that has gone away is left out of the list (one that vanishes between the listing and the click shows an error on the picker), and Change project is refused while an Implementation Loop runs.
|
||||
|
||||
**No agent installed.** The first-run checklist and the launch card show what an agent CLI is, each built-in's install command and an **Install page** link, and a note that other agents are added under Agents. Install one, press **Check again** (the app looks at `PATH` and `agents.json` again), and Start works without restarting the app.
|
||||
|
||||
**Taskbar signal.** The console page tells the app when it is busy, your move, or needs attention (the same states as its tab icon), and the app shows it:
|
||||
|
||||
@@ -36,7 +36,7 @@ file directly after checking it against the release's checksum list.
|
||||
launch card or checklist shown first, and New Session keeps them
|
||||
- [ ] `plan2code --classic` runs the agent in the terminal with the app installed
|
||||
- [ ] Linux only: with `DISPLAY` and `WAYLAND_DISPLAY` unset, `plan2code` runs the terminal flow
|
||||
- [ ] The desktop shortcut opens the folder picker and then the app
|
||||
- [ ] The desktop shortcut opens the folder menu (Choose a folder first, recent folders under it) and then the app
|
||||
- [ ] macOS: the first start is stopped by Gatekeeper, **Open Anyway** in System Settings (Privacy &
|
||||
Security) lets it through, and `docs/desktop-app.md` describes what you saw
|
||||
- [ ] macOS and Linux: start the app from the Dock, Finder or a `.desktop` file (not a terminal) on
|
||||
@@ -75,7 +75,8 @@ file directly after checking it against the release's checksum list.
|
||||
- [ ] The top bar's project and agent menus open under their name, close on a click elsewhere (the
|
||||
console frame and the terminal included) or Escape, and are not cut off by the bar
|
||||
- [ ] **Change project** in the top bar's project menu, with an agent running: it asks first, then the folder
|
||||
picker opens; canceling the picker leaves the running agent and its project untouched
|
||||
picker (Choose a folder, then recent folders) opens; canceling the picker leaves the running agent and its project untouched
|
||||
- [ ] Start the app with no arguments: it shows the folder picker, not the last project; a recent folder opens in one click
|
||||
- [ ] Change project, pick a different folder: the old agent and console stop, the new folder opens
|
||||
on the launch card (or the checklist, if its own first run has not passed yet)
|
||||
- [ ] Reload the window (or navigate away and back) while an agent is running: the terminal redraws
|
||||
|
||||
@@ -1,6 +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::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
@@ -812,8 +813,8 @@ async fn update_skills(
|
||||
Ok(UpdateOutcome { message, status })
|
||||
}
|
||||
|
||||
/// The OS folder picker, shown when no folder is known; a choice becomes the
|
||||
/// launcher's remembered folder.
|
||||
/// 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)]
|
||||
fn pick_project_folder(
|
||||
app: tauri::AppHandle,
|
||||
@@ -886,6 +887,68 @@ fn change_project(
|
||||
Ok(Some(text))
|
||||
}
|
||||
|
||||
/// The recent project folders that still exist, newest first, for the page's
|
||||
/// folder picker: `{ dir, name }` each, `name` the folder's own name (the full
|
||||
/// path for a root, which has none). The project already open is left out
|
||||
/// (none on a bare start), since picking it would change nothing. Off the
|
||||
/// main thread: each row checks the disk, and a saved folder on an
|
||||
/// unreachable share must not freeze the window.
|
||||
#[tauri::command(async)]
|
||||
fn recent_folders(state: State<'_, AppState>) -> Vec<serde_json::Value> {
|
||||
let current = state
|
||||
.project
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|p| p.as_ref().map(|p| p.dir.clone()));
|
||||
project::recent_folders(current.as_deref())
|
||||
.into_iter()
|
||||
.map(|dir| {
|
||||
let full = dir.to_string_lossy().into_owned();
|
||||
let name = dir
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| full.clone());
|
||||
serde_json::json!({ "dir": full, "name": name })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether opening `dir` must first tear the current project down: only when
|
||||
/// a project is set and it is a different folder (`same_folder`'s rule, so a
|
||||
/// trailing separator, and case on Windows, do not count).
|
||||
fn needs_teardown(current: Option<&Path>, dir: &Path, windows: bool) -> bool {
|
||||
current.is_some_and(|cur| {
|
||||
!project::same_folder(&cur.to_string_lossy(), &dir.to_string_lossy(), windows)
|
||||
})
|
||||
}
|
||||
|
||||
/// Open one of the recent folders from the folder picker. A different folder
|
||||
/// than the open project tears the old one down first (as `change_project`
|
||||
/// does) and goes to the top of the recent folders; the same folder is kept
|
||||
/// as it is, with nothing torn down.
|
||||
#[tauri::command(async)]
|
||||
fn open_recent_folder(state: State<'_, AppState>, dir: String) -> Result<Option<String>, String> {
|
||||
refuse_while_looping(&state, "project")?;
|
||||
let path = Path::new(&dir);
|
||||
if !path.is_dir() {
|
||||
return Err(format!("{dir} is not a folder"));
|
||||
}
|
||||
let current = state
|
||||
.project
|
||||
.lock()
|
||||
.map_err(|e| e.to_string())?
|
||||
.as_ref()
|
||||
.map(|p| p.dir.clone());
|
||||
match current {
|
||||
Some(cur) if !needs_teardown(Some(&cur), path, cfg!(windows)) => return Ok(Some(dir)),
|
||||
Some(_) => teardown_project(&state)?,
|
||||
None => {}
|
||||
}
|
||||
let choice = project::remember_folder(path)?;
|
||||
*state.project.lock().map_err(|e| e.to_string())? = Some(choice);
|
||||
Ok(Some(dir))
|
||||
}
|
||||
|
||||
/// 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. The one exception
|
||||
@@ -1362,6 +1425,8 @@ fn main() {
|
||||
check_new_release,
|
||||
update_skills,
|
||||
pick_project_folder,
|
||||
recent_folders,
|
||||
open_recent_folder,
|
||||
change_project,
|
||||
console_start,
|
||||
console_status,
|
||||
@@ -1927,4 +1992,21 @@ mod tests {
|
||||
"unexpected message: {err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_a_recent_folder_tears_down_only_a_different_project() {
|
||||
let dir = Path::new("/work/b");
|
||||
// No project yet: nothing to tear down.
|
||||
assert!(!needs_teardown(None, dir, false));
|
||||
// The same folder, as written or with a trailing separator.
|
||||
assert!(!needs_teardown(Some(Path::new("/work/b")), dir, false));
|
||||
assert!(!needs_teardown(Some(Path::new("/work/b/")), dir, false));
|
||||
// A different folder.
|
||||
assert!(needs_teardown(Some(Path::new("/work/a")), dir, false));
|
||||
// Case counts outside Windows, not on it.
|
||||
assert!(needs_teardown(Some(Path::new("/work/B")), dir, false));
|
||||
let win = Path::new(r"C:\Work\B");
|
||||
assert!(!needs_teardown(Some(Path::new(r"c:\work\b\")), win, true));
|
||||
assert!(needs_teardown(Some(Path::new(r"C:\Work\A")), win, true));
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,24 @@
|
||||
//! Which project folder the app works on: the folder the launcher passes in,
|
||||
//! else the one the launcher remembers, else the person picks. The launcher's
|
||||
//! memory is `~/.plan2code/launcher.json` (`lastFolder`, `lastCli`), shared so
|
||||
//! the app and `plan2code` agree on both.
|
||||
//! else the one the person picks from the page's folder picker (the recent
|
||||
//! folders, or the OS dialog). The launcher's memory is
|
||||
//! `~/.plan2code/launcher.json` (`lastFolder`, `lastCli`), shared so the app
|
||||
//! and `plan2code` agree on both. `recentFolders` (newest first, at
|
||||
//! most 5) holds the folders worked on; `lastFolder` is always its first entry.
|
||||
//! The rule for that list is written twice, here and in `src/launcher/plan2code.js`,
|
||||
//! and both are held to `scripts/fixtures/recent-folders-cases.json`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::agents;
|
||||
|
||||
/// Where the project folder came from, in the order it is tried.
|
||||
/// Where the project folder came from: the launcher's argument, or the picker.
|
||||
#[derive(Clone, Copy, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ProjectSource {
|
||||
Argument,
|
||||
Remembered,
|
||||
Picked,
|
||||
}
|
||||
|
||||
@@ -36,17 +40,103 @@ fn launcher_file() -> Option<PathBuf> {
|
||||
)
|
||||
}
|
||||
|
||||
fn read_launcher() -> serde_json::Map<String, serde_json::Value> {
|
||||
launcher_file()
|
||||
.and_then(|file| std::fs::read_to_string(file).ok())
|
||||
fn read_launcher_from(file: &Path) -> serde_json::Map<String, Value> {
|
||||
std::fs::read_to_string(file)
|
||||
.ok()
|
||||
.and_then(|text| serde_json::from_str(&text).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The folder the launcher remembers, when it is still a directory.
|
||||
fn remembered_folder() -> Option<PathBuf> {
|
||||
let dir = PathBuf::from(read_launcher().get("lastFolder")?.as_str()?);
|
||||
dir.is_dir().then_some(dir)
|
||||
fn read_launcher() -> serde_json::Map<String, Value> {
|
||||
launcher_file()
|
||||
.map(|file| read_launcher_from(&file))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// How many recent project folders the list keeps.
|
||||
const RECENT_FOLDERS_MAX: usize = 5;
|
||||
|
||||
/// One trailing `\` or `/` off a path, but never off a root (`C:\` or `/`).
|
||||
fn trim_folder(p: &str) -> &str {
|
||||
let b = p.as_bytes();
|
||||
let drive_root = b.len() == 3 && b[1] == b':' && b[0].is_ascii_alphabetic();
|
||||
if b.len() > 1 && matches!(b[b.len() - 1], b'\\' | b'/') && !drive_root {
|
||||
&p[..p.len() - 1]
|
||||
} else {
|
||||
p
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether two paths name the same folder: a trailing separator is ignored,
|
||||
/// and case is on Windows. Twin of `sameFolder` in the launcher.
|
||||
pub fn same_folder(a: &str, b: &str, windows: bool) -> bool {
|
||||
let (x, y) = (trim_folder(a), trim_folder(b));
|
||||
if windows {
|
||||
x.to_lowercase() == y.to_lowercase()
|
||||
} else {
|
||||
x == y
|
||||
}
|
||||
}
|
||||
|
||||
/// The recent folders in the launcher's state: `recentFolders`, else
|
||||
/// `[lastFolder]`, else none. Twin of `readRecent`.
|
||||
fn read_recent(state: &serde_json::Map<String, Value>) -> Vec<String> {
|
||||
if let Some(Value::Array(items)) = state.get("recentFolders") {
|
||||
return items
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.filter(|s| !s.is_empty())
|
||||
.take(RECENT_FOLDERS_MAX)
|
||||
.map(str::to_string)
|
||||
.collect();
|
||||
}
|
||||
match state.get("lastFolder").and_then(Value::as_str) {
|
||||
Some(last) if !last.is_empty() => vec![last.to_string()],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A new list with `dir` first, an earlier entry for the same folder removed,
|
||||
/// cut to the max. Twin of `pushRecent`.
|
||||
fn push_recent(list: &[String], dir: &str, windows: bool) -> Vec<String> {
|
||||
std::iter::once(dir.to_string())
|
||||
.chain(
|
||||
list.iter()
|
||||
.filter(|x| !same_folder(x, dir, windows))
|
||||
.cloned(),
|
||||
)
|
||||
.take(RECENT_FOLDERS_MAX)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The folders of `list` worth offering: ones that still exist, minus the one
|
||||
/// in `exclude`. Twin of `listRecent`.
|
||||
fn list_recent(
|
||||
list: &[String],
|
||||
exists: impl Fn(&str) -> bool,
|
||||
exclude: Option<&str>,
|
||||
windows: bool,
|
||||
) -> Vec<String> {
|
||||
list.iter()
|
||||
.filter(|x| exists(x) && !exclude.is_some_and(|e| same_folder(x, e, windows)))
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The folders the person worked on lately that are still folders, newest
|
||||
/// first, minus `exclude` (the project already open, by `same_folder`'s
|
||||
/// rule). The page's folder picker draws them.
|
||||
pub fn recent_folders(exclude: Option<&Path>) -> Vec<PathBuf> {
|
||||
let exclude = exclude.map(|p| p.to_string_lossy().into_owned());
|
||||
list_recent(
|
||||
&read_recent(&read_launcher()),
|
||||
|p| Path::new(p).is_dir(),
|
||||
exclude.as_deref(),
|
||||
cfg!(windows),
|
||||
)
|
||||
.into_iter()
|
||||
.map(PathBuf::from)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The id of the agent the launcher last ran (it may be a custom one). The
|
||||
@@ -127,41 +217,44 @@ pub fn launch_choice_in(args: &[String], agents_file: Option<&Path>) -> LaunchCh
|
||||
LaunchChoice { agent, model }
|
||||
}
|
||||
|
||||
/// The folder to open on: the launcher's argument wins, then its memory, then
|
||||
/// nothing (the page asks with the folder picker).
|
||||
/// The folder to open on: only the launcher's argument. Without one the page
|
||||
/// shows its folder picker; the last folder is the picker's first recent row,
|
||||
/// never reopened silently.
|
||||
pub fn resolve(args: &[String]) -> Option<ProjectDir> {
|
||||
if let Some(dir) = argument_folder(args) {
|
||||
return Some(ProjectDir {
|
||||
dir,
|
||||
source: ProjectSource::Argument,
|
||||
});
|
||||
}
|
||||
remembered_folder().map(|dir| ProjectDir {
|
||||
argument_folder(args).map(|dir| ProjectDir {
|
||||
dir,
|
||||
source: ProjectSource::Remembered,
|
||||
source: ProjectSource::Argument,
|
||||
})
|
||||
}
|
||||
|
||||
/// A folder the person picked becomes the remembered one, so the next start
|
||||
/// (app or launcher) opens on it. The launcher's other keys are kept.
|
||||
/// A folder the person picked goes to the top of the recent folders and
|
||||
/// becomes `lastFolder`, so the next start (app or launcher) lists it first.
|
||||
/// The launcher's other keys are kept.
|
||||
pub fn remember_folder(dir: &Path) -> Result<ProjectDir, String> {
|
||||
let file = launcher_file().ok_or("no home folder found")?;
|
||||
let mut state = read_launcher();
|
||||
state.insert(
|
||||
"lastFolder".to_string(),
|
||||
serde_json::Value::String(dir.to_string_lossy().into_owned()),
|
||||
);
|
||||
if let Some(parent) = file.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(err)?;
|
||||
}
|
||||
let json = serde_json::to_string_pretty(&serde_json::Value::Object(state)).map_err(err)?;
|
||||
crate::loop_driver::write_atomic(&file, &json)?;
|
||||
remember_folder_in(&file, dir)?;
|
||||
Ok(ProjectDir {
|
||||
dir: dir.to_path_buf(),
|
||||
source: ProjectSource::Picked,
|
||||
})
|
||||
}
|
||||
|
||||
/// `remember_folder`'s write, into `file`.
|
||||
fn remember_folder_in(file: &Path, dir: &Path) -> Result<(), String> {
|
||||
let mut state = read_launcher_from(file);
|
||||
let recent = push_recent(&read_recent(&state), &dir.to_string_lossy(), cfg!(windows));
|
||||
state.insert("lastFolder".to_string(), Value::String(recent[0].clone()));
|
||||
state.insert(
|
||||
"recentFolders".to_string(),
|
||||
Value::Array(recent.into_iter().map(Value::String).collect()),
|
||||
);
|
||||
if let Some(parent) = file.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(err)?;
|
||||
}
|
||||
let json = serde_json::to_string_pretty(&Value::Object(state)).map_err(err)?;
|
||||
crate::loop_driver::write_atomic(file, &json)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -286,4 +379,112 @@ mod tests {
|
||||
assert_eq!(found, Some(cwd.join("codex")));
|
||||
let _ = std::fs::remove_dir_all(&cwd);
|
||||
}
|
||||
|
||||
const CASES: &str = include_str!("../../../scripts/fixtures/recent-folders-cases.json");
|
||||
|
||||
/// Each case of the fixture group `group` with the platform values it runs under:
|
||||
/// `true` for Windows. Both platform sets run on every OS; a case with none runs under both.
|
||||
fn cases(group: &str) -> Vec<(Value, bool)> {
|
||||
let all: Value = serde_json::from_str(CASES).unwrap();
|
||||
let mut out = Vec::new();
|
||||
for case in all[group].as_array().unwrap() {
|
||||
let winds: &[bool] = match case.get("platform").and_then(Value::as_str) {
|
||||
Some("win32") => &[true],
|
||||
Some("posix") => &[false],
|
||||
_ => &[true, false],
|
||||
};
|
||||
for &windows in winds {
|
||||
out.push((case.clone(), windows));
|
||||
}
|
||||
}
|
||||
assert!(!out.is_empty(), "no {group} cases");
|
||||
out
|
||||
}
|
||||
|
||||
fn strings(value: &Value) -> Vec<String> {
|
||||
value
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|v| v.as_str().unwrap().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_recent_follows_the_shared_cases() {
|
||||
for (case, _) in cases("read") {
|
||||
let state = case["state"].as_object().unwrap();
|
||||
assert_eq!(
|
||||
read_recent(state),
|
||||
strings(&case["expect"]),
|
||||
"{}",
|
||||
case["name"]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn push_recent_follows_the_shared_cases() {
|
||||
for (case, windows) in cases("push") {
|
||||
let got = push_recent(
|
||||
&strings(&case["list"]),
|
||||
case["dir"].as_str().unwrap(),
|
||||
windows,
|
||||
);
|
||||
assert_eq!(
|
||||
got,
|
||||
strings(&case["expect"]),
|
||||
"{} (windows: {windows})",
|
||||
case["name"]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_recent_follows_the_shared_cases() {
|
||||
for (case, windows) in cases("list") {
|
||||
let exists = strings(&case["exists"]);
|
||||
let got = list_recent(
|
||||
&strings(&case["list"]),
|
||||
|p| exists.iter().any(|e| e == p),
|
||||
case["exclude"].as_str(),
|
||||
windows,
|
||||
);
|
||||
assert_eq!(
|
||||
got,
|
||||
strings(&case["expect"]),
|
||||
"{} (windows: {windows})",
|
||||
case["name"]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remember_folder_keeps_the_other_keys_and_writes_both_lists() {
|
||||
let home =
|
||||
std::env::temp_dir().join(format!("p2c-project-remember-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&home);
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
let file = home.join(".plan2code").join("launcher.json");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(
|
||||
&file,
|
||||
r#"{"lastFolder":"/old","lastCli":"codex","lastModels":{"codex":"m1"}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
remember_folder_in(&file, Path::new("/new")).unwrap();
|
||||
let state = read_launcher_from(&file);
|
||||
assert_eq!(state["lastCli"], "codex");
|
||||
assert_eq!(state["lastModels"]["codex"], "m1");
|
||||
assert_eq!(state["lastFolder"], "/new");
|
||||
assert_eq!(state["recentFolders"], serde_json::json!(["/new", "/old"]));
|
||||
|
||||
// Picking the older folder again moves it up, with no duplicate.
|
||||
remember_folder_in(&file, Path::new("/old")).unwrap();
|
||||
let state = read_launcher_from(&file);
|
||||
assert_eq!(state["lastFolder"], "/old");
|
||||
assert_eq!(state["recentFolders"], serde_json::json!(["/old", "/new"]));
|
||||
let _ = std::fs::remove_dir_all(&home);
|
||||
}
|
||||
}
|
||||
+144
-24
@@ -3,7 +3,7 @@
|
||||
// request) with a drag handle.
|
||||
|
||||
import { mountTerminal } from './terminal.js';
|
||||
import { NEW_RELEASE_COMMAND, attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, lastAgentNotice, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopLocks, loopStopLabels, loopWindowTitle, helloRetryAction, retryLabel, RETRY_AFTER_SECONDS } from './meter.js';
|
||||
import { NEW_RELEASE_COMMAND, attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, lastAgentNotice, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, folderPickerRows, loopBanner, loopLocks, loopStopLabels, loopWindowTitle, helloRetryAction, retryLabel, RETRY_AFTER_SECONDS } from './meter.js';
|
||||
|
||||
const { invoke, Channel } = window.__TAURI__.core;
|
||||
|
||||
@@ -57,6 +57,11 @@ const launchEffortEl = document.getElementById('launch-effort');
|
||||
const launchBypassEl = document.getElementById('launch-bypass');
|
||||
const launchBypassWarningEl = document.getElementById('launch-bypass-warning');
|
||||
const launchStartBtn = document.getElementById('launch-start');
|
||||
const folderPickerEl = document.getElementById('folder-picker');
|
||||
const folderPickerPanelEl = document.getElementById('folder-picker-panel');
|
||||
const folderPickerListEl = document.getElementById('folder-picker-list');
|
||||
const folderPickerErrorEl = document.getElementById('folder-picker-error');
|
||||
const folderPickerCancelBtn = document.getElementById('folder-picker-cancel');
|
||||
const firstRunEl = document.getElementById('first-run');
|
||||
const firstRunListEl = document.getElementById('first-run-list');
|
||||
const firstRunStartBtn = document.getElementById('first-run-start');
|
||||
@@ -1361,25 +1366,138 @@ function setProjectDir(dir) {
|
||||
window.__TAURI__.window.getCurrentWindow().setTitle(windowTitleFor(dir)).catch(() => {});
|
||||
}
|
||||
|
||||
// The state `main()` read at startup: `pickFolder()` and the first-run
|
||||
// The state `main()` read at startup: the folder picker and the first-run
|
||||
// checklist both need it once a folder lands, after the fact.
|
||||
let appState = null;
|
||||
|
||||
// Opens the OS folder picker. A canceled pick (or a failed one) lands on the
|
||||
// "No project folder chosen" state with a button that tries again.
|
||||
async function pickFolder() {
|
||||
try {
|
||||
const dir = await invoke('pick_project_folder');
|
||||
if (!dir) {
|
||||
showState('No project folder chosen', 'Choose folder', pickFolder);
|
||||
return;
|
||||
}
|
||||
setProjectDir(dir);
|
||||
if (appState) appState.projectDir = dir;
|
||||
afterProjectKnown();
|
||||
} catch (error) {
|
||||
showState(`Could not open the folder picker: ${error}`, 'Choose folder', pickFolder);
|
||||
// The open folder picker's way back to its caller (null while none is open).
|
||||
let folderPickerResolve = null;
|
||||
|
||||
function hideFolderPicker() {
|
||||
folderPickerEl.hidden = true;
|
||||
folderPickerEl.classList.remove('is-dialog');
|
||||
folderPickerListEl.replaceChildren();
|
||||
}
|
||||
|
||||
function closeFolderPicker(dir) {
|
||||
const resolve = folderPickerResolve;
|
||||
folderPickerResolve = null;
|
||||
hideFolderPicker();
|
||||
if (resolve) resolve(dir);
|
||||
}
|
||||
|
||||
function setFolderPickerError(text) {
|
||||
folderPickerErrorEl.textContent = text || '';
|
||||
folderPickerErrorEl.hidden = !text;
|
||||
}
|
||||
|
||||
function folderPickerButtons() {
|
||||
return [...folderPickerListEl.querySelectorAll('.folder-picker-row')];
|
||||
}
|
||||
|
||||
// One picker for a bare start (`dialog: false`, full screen) and Change
|
||||
// project (`dialog: true`, over the page, with Cancel and Escape). Choose a
|
||||
// folder runs the OS dialog; a recent row opens that folder. Resolves with
|
||||
// the folder opened, or null when the person cancels the dialog. A canceled
|
||||
// OS dialog comes back here, and an error shows inline with the rows usable.
|
||||
async function showFolderPicker({ dialog }) {
|
||||
if (folderPickerResolve) closeFolderPicker(null);
|
||||
stopRetryCountdown();
|
||||
stateBox.hidden = true;
|
||||
if (!dialog) {
|
||||
hideLaunchCard();
|
||||
hideFirstRun();
|
||||
}
|
||||
setFolderPickerError('');
|
||||
folderPickerCancelBtn.hidden = !dialog;
|
||||
folderPickerEl.classList.toggle('is-dialog', dialog);
|
||||
if (dialog) folderPickerPanelEl.setAttribute('aria-modal', 'true');
|
||||
else folderPickerPanelEl.removeAttribute('aria-modal');
|
||||
// The project already open is left out by the command itself.
|
||||
let recent = [];
|
||||
try {
|
||||
recent = (await invoke('recent_folders')) || [];
|
||||
} catch (error) {
|
||||
setFolderPickerError(`Could not read the recent folders: ${error}`);
|
||||
}
|
||||
folderPickerListEl.replaceChildren(
|
||||
...folderPickerRows(recent).map((row) => {
|
||||
const li = document.createElement('li');
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = `folder-picker-row is-${row.kind}`;
|
||||
const label = document.createElement('span');
|
||||
label.className = 'folder-picker-label';
|
||||
label.textContent = row.label;
|
||||
button.append(label);
|
||||
if (row.detail) {
|
||||
const detail = document.createElement('span');
|
||||
detail.className = 'folder-picker-detail';
|
||||
detail.textContent = row.detail;
|
||||
button.append(detail);
|
||||
}
|
||||
button.onclick = () => chooseFolderRow(row, button, dialog);
|
||||
li.append(button);
|
||||
return li;
|
||||
})
|
||||
);
|
||||
folderPickerEl.hidden = false;
|
||||
folderPickerButtons()[0].focus();
|
||||
return new Promise((resolve) => {
|
||||
folderPickerResolve = resolve;
|
||||
});
|
||||
}
|
||||
|
||||
// One row pressed: the OS dialog for Choose a folder (`change_project` from
|
||||
// Change project, which tears the old project down), else that recent
|
||||
// folder. Nothing chosen keeps the picker up, focus back on the row.
|
||||
async function chooseFolderRow(row, button, dialog) {
|
||||
const buttons = folderPickerButtons();
|
||||
buttons.forEach((b) => { b.disabled = true; });
|
||||
folderPickerCancelBtn.disabled = true;
|
||||
setFolderPickerError('');
|
||||
let dir = null;
|
||||
try {
|
||||
if (row.kind === 'browse') dir = await invoke(dialog ? 'change_project' : 'pick_project_folder');
|
||||
else dir = await invoke('open_recent_folder', { dir: row.dir });
|
||||
} catch (error) {
|
||||
setFolderPickerError(row.kind === 'browse' ? `Could not open the folder picker: ${error}` : `Could not open ${row.dir}: ${error}`);
|
||||
}
|
||||
buttons.forEach((b) => { b.disabled = false; });
|
||||
folderPickerCancelBtn.disabled = false;
|
||||
if (dir) {
|
||||
closeFolderPicker(dir);
|
||||
return;
|
||||
}
|
||||
button.focus();
|
||||
}
|
||||
|
||||
folderPickerCancelBtn.onclick = () => closeFolderPicker(null);
|
||||
// Escape is heard on the document: a click on the backdrop or the heading
|
||||
// leaves focus on the page, where a listener on the picker never sees it.
|
||||
document.addEventListener('keydown', (event) => {
|
||||
if (event.key !== 'Escape' || folderPickerEl.hidden) return;
|
||||
if (folderPickerCancelBtn.hidden || folderPickerCancelBtn.disabled) return;
|
||||
event.preventDefault();
|
||||
closeFolderPicker(null);
|
||||
});
|
||||
folderPickerEl.addEventListener('keydown', (event) => {
|
||||
if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;
|
||||
const buttons = folderPickerButtons();
|
||||
const at = buttons.indexOf(document.activeElement);
|
||||
if (at < 0) return;
|
||||
event.preventDefault();
|
||||
const next = event.key === 'ArrowDown' ? Math.min(at + 1, buttons.length - 1) : Math.max(at - 1, 0);
|
||||
buttons[next].focus();
|
||||
});
|
||||
|
||||
// A bare start: the picker, full screen, until a folder is opened.
|
||||
async function chooseStartFolder() {
|
||||
const dir = await showFolderPicker({ dialog: false });
|
||||
if (!dir) return;
|
||||
setProjectDir(dir);
|
||||
if (appState) appState.projectDir = dir;
|
||||
afterProjectKnown();
|
||||
}
|
||||
|
||||
// Once a project folder is known: the first-run checklist (once, until it
|
||||
@@ -1392,17 +1510,19 @@ function afterProjectKnown() {
|
||||
}
|
||||
}
|
||||
|
||||
// Switches to a folder picked fresh: the Rust side tears the old project's
|
||||
// agent and console down before the new one is remembered, so nothing from
|
||||
// it carries over. Picking nothing (canceled) leaves the current project as
|
||||
// it was.
|
||||
// Switches to a folder picked in the folder picker's dialog: the Rust side
|
||||
// tears the old project's agent and console down before the new one is
|
||||
// remembered, so nothing from it carries over. Cancel (or Escape) leaves
|
||||
// the current project as it was; the folder already open is not listed.
|
||||
async function doChangeProject() {
|
||||
showState('Choose the new project folder...');
|
||||
try {
|
||||
const dir = await invoke('change_project');
|
||||
const dir = await showFolderPicker({ dialog: true });
|
||||
if (!dir) {
|
||||
if (agentActive()) hideState();
|
||||
// Cancel leaves the page as it was: a running agent gets the keyboard
|
||||
// back, and a dashboard still on screen is never covered.
|
||||
if (agentActive() || frameReady) hideState();
|
||||
else afterProjectKnown();
|
||||
if (agentActive()) terminal.focus();
|
||||
return;
|
||||
}
|
||||
setProjectDir(dir);
|
||||
@@ -1533,7 +1653,7 @@ async function main() {
|
||||
setProjectDir(state.projectDir);
|
||||
afterProjectKnown();
|
||||
} else {
|
||||
pickFolder();
|
||||
chooseStartFolder();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -216,6 +216,42 @@
|
||||
#launch-start:hover { background: #357a5c; }
|
||||
#launch-start:disabled { background: #444; color: #888; cursor: not-allowed; }
|
||||
|
||||
/* The folder picker: full screen on a bare start, a dialog over the page
|
||||
(with Cancel) from Change project. Choose a folder comes first; each
|
||||
recent folder shows its name with the full path muted under it. */
|
||||
#folder-picker {
|
||||
position: absolute; inset: 0; z-index: 2; display: flex; align-items: center; justify-content: center;
|
||||
background: #1e1e1e; padding: 24px; box-sizing: border-box;
|
||||
}
|
||||
#folder-picker[hidden] { display: none; }
|
||||
#folder-picker.is-dialog { background: rgba(0, 0, 0, 0.55); }
|
||||
#folder-picker-panel { display: flex; flex-direction: column; gap: 12px; width: min(440px, 100%); max-height: 100%; }
|
||||
#folder-picker.is-dialog #folder-picker-panel {
|
||||
background: var(--panel); border: 1px solid var(--rule-2); border-radius: 10px; padding: 18px; box-sizing: border-box;
|
||||
}
|
||||
#folder-picker h2 { margin: 0; font-size: 17px; text-align: center; }
|
||||
#folder-picker-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; overflow-y: auto; }
|
||||
.folder-picker-row {
|
||||
appearance: none; width: 100%; text-align: left; font: inherit; cursor: pointer;
|
||||
display: flex; flex-direction: column; gap: 2px; padding: 8px 12px; border-radius: 8px;
|
||||
border: 1px solid var(--rule-2); background: var(--panel); color: var(--ink);
|
||||
}
|
||||
.folder-picker-row:hover:not(:disabled) { background: var(--panel-2); border-color: var(--accent-line); }
|
||||
.folder-picker-row:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.folder-picker-row:disabled { opacity: 0.6; cursor: default; }
|
||||
.folder-picker-row.is-browse { font-weight: 600; background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
||||
.folder-picker-row.is-browse:hover:not(:disabled) { background: var(--accent); border-color: var(--accent); filter: brightness(1.08); }
|
||||
.folder-picker-label { font-size: 13.5px; }
|
||||
.folder-picker-detail { font-size: 12px; color: var(--ink-3); overflow-wrap: anywhere; }
|
||||
#folder-picker-error { margin: 0; font-size: 12px; color: #d7ba7d; }
|
||||
#folder-picker-error[hidden], #folder-picker-cancel[hidden] { display: none; }
|
||||
#folder-picker-cancel {
|
||||
align-self: center; appearance: none; font: inherit; font-size: 13.5px; font-weight: 600; padding: 7px 13px;
|
||||
border-radius: 8px; cursor: pointer; border: 1px solid var(--rule-2); background: var(--panel); color: var(--ink);
|
||||
}
|
||||
#folder-picker-cancel:hover { background: var(--panel-2); }
|
||||
#folder-picker-cancel:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
|
||||
#first-run {
|
||||
position: absolute; inset: 0; z-index: 1; display: flex; flex-direction: column;
|
||||
align-items: stretch; justify-content: center; gap: 14px; background: #1e1e1e;
|
||||
@@ -359,6 +395,14 @@
|
||||
<button id="dashboard-state-cancel" hidden>Cancel</button>
|
||||
</span>
|
||||
</div>
|
||||
<div id="folder-picker" hidden>
|
||||
<div id="folder-picker-panel" role="dialog" aria-labelledby="folder-picker-title">
|
||||
<h2 id="folder-picker-title">Open a project</h2>
|
||||
<ul id="folder-picker-list"></ul>
|
||||
<p id="folder-picker-error" role="alert" hidden></p>
|
||||
<button id="folder-picker-cancel" type="button" hidden>Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="first-run" hidden>
|
||||
<h2>Before you start</h2>
|
||||
<ul id="first-run-list"></ul>
|
||||
|
||||
@@ -280,6 +280,18 @@ export function folderName(dir) {
|
||||
return lastSegment(dir) || String(dir || "").trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* The folder picker's rows: Choose a folder first (the OS dialog), then one
|
||||
* row per recent folder from the `recent_folders` command, newest first,
|
||||
* named by the folder with its full path as the detail.
|
||||
*/
|
||||
export function folderPickerRows(recent) {
|
||||
return [
|
||||
{ kind: 'browse', label: 'Choose a folder...' },
|
||||
...(recent || []).map((r) => ({ kind: 'folder', dir: r.dir, label: r.name, detail: r.dir })),
|
||||
];
|
||||
}
|
||||
|
||||
function lastSegment(dir) {
|
||||
return String(dir || "")
|
||||
.trim()
|
||||
|
||||
Reference in new issue
Block a user