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
@@ -109,7 +109,7 @@ plan2code/
|
||||
| `version.json` | Version metadata (name, version, description) |
|
||||
| `QUICK-REFERENCE.md` | User quick-reference card |
|
||||
| `src/statusline-claude/` | Claude CLI status bar (see [the status line file](./AGENTS-architecture-statusline.md)) |
|
||||
| `src/launcher/plan2code.js` | Global `plan2code` command that opens the dashboard skill in Claude Code, Devin or Codex (installed by `I` and Advanced → `E`; also via Advanced → `D`). When the desktop app is installed (`~/.plan2code/app/plan2code-app[.exe]`, or the file `PLAN2CODE_APP` names) and a display exists (Windows and macOS always; Linux needs `DISPLAY` or `WAYLAND_DISPLAY`), it opens the app after the agent and model questions with `--project <folder> --agent <id> [--model <id>]` and exits; `--classic` (never forwarded to the CLI) and a failed spawn keep the terminal flow. The app reads all three (`project::launch_choice`): the picker starts on `--agent`, and `--model` applies to that agent on every start and Restart (`AgentManager::set_model`); a model never applies to another agent. Its menu, lookup and no-agent flow come from `agents.json` through `agent-lookup.mjs`, loaded by dynamic `import()` from `~/.plan2code/bin/` (the launcher's one stated exception to its Node-built-ins-only rule; a missing copy falls back to the plain printed install steps) |
|
||||
| `src/launcher/plan2code.js` | Global `plan2code` command that opens the dashboard skill in Claude Code, Devin or Codex (installed by `I` and Advanced → `E`; also via Advanced → `D`). When the desktop app is installed (`~/.plan2code/app/plan2code-app[.exe]`, or the file `PLAN2CODE_APP` names) and a display exists (Windows and macOS always; Linux needs `DISPLAY` or `WAYLAND_DISPLAY`), it opens the app after the agent and model questions with `--project <folder> --agent <id> [--model <id>]` and exits; `--classic` (never forwarded to the CLI) and a failed spawn keep the terminal flow. The app reads all three (`project::launch_choice`): the picker starts on `--agent`, and `--model` applies to that agent on every start and Restart (`AgentManager::set_model`); a model never applies to another agent. The folder comes from `--project` alone: with none (a bare start of the app) the app shows its own picker, Choose a folder first and focused with the recent folders under it (`project::recent_folders`, the `recent_folders` and `open_recent_folder` commands), and Change project opens the same picker. The list is `recentFolders` in `~/.plan2code/launcher.json`, one rule written twice (`readRecent`, `pushRecent`, `listRecent` in the launcher, their twins in `project.rs`) and held to `scripts/fixtures/recent-folders-cases.json`. Its menu, lookup and no-agent flow come from `agents.json` through `agent-lookup.mjs`, loaded by dynamic `import()` from `~/.plan2code/bin/` (the launcher's one stated exception to its Node-built-ins-only rule; a missing copy falls back to the plain printed install steps) |
|
||||
| `plan2code-app/` | Tauri desktop app (Rust host, xterm panel, the console's dashboard in a frame; its own README). `RELEASE-CHECKLIST.md` lists the by-hand checks before each release. `src-tauri/src/versions.rs` compares the app's version (`tauri.conf.json`) with the installed skills' (`~/.plan2code/bin/version.json`) for the bar's **Update skills** line, which runs `node ~/.plan2code/bin/plan2code.js update` only when pressed |
|
||||
| `plan2code-app/src-tauri/src/attention.rs` | The taskbar signal's rules, pure and knowing nothing about Tauri: `Signal` (`busy`, `ready`, `attention`, `plain`), `badge_for(signal, os, enabled)` (Windows: green dot on `ready`, red on `attention`; macOS: red `!` on `attention` only; Linux: count 1 on `attention`), `should_flash(prev, next, focused, enabled)` (once, only on a change into `ready` or `attention` while unfocused) and `dot_rgba()` (the dot's pixels, in the favicon's colors, which a test checks against `public/favicon.js`). `main.rs` applies the result through `set_attention`, `set_taskbar_signal` and `clear_attention_cmd`; the page asks with the `attention` and `taskbar` messages (`public/app-bridge.js`) and the switch is `taskbarSignal` in the app's own `~/.plan2code/app.json`. |
|
||||
| `plan2code-app/src-tauri/src/quit_prompt.rs`, `task_dialog.rs` | The quit check shown while an agent runs. `quit_prompt(last_signal)` is pure: the page's last taskbar signal `ready` or `plain` is the waiting case ("Done for now?", Info icon), and `busy`, `attention` or none yet is the working case ("Leave while your agent is busy?", Warning icon). `task_dialog.rs` (Windows only) draws it with `TaskDialogIndirect` through `winapi`: a heading, Stay as the default, and the app's icon in the title bar, since the dialog plugin has no heading and Windows copies its icon into the title bar (the warning once showed twice). `confirm_quit` in `main.rs` runs it on its own thread; macOS and Linux use the plugin box with the same words, where Quit stays the default button (putting Stay first would make Esc quit). A page reload or an unanswered page clears the signal to none (`clear_attention`), so the box stays on the working words until the page reports again; `QUIT_OPEN` keeps a second box from stacking |
|
||||
@@ -209,7 +209,7 @@ Typing `plan2code` in any directory opens the dashboard skill against the curren
|
||||
|
||||
The bracketed flags (each entry's `bypassArgs`; a custom agent's own `bypassArgs`) go in only when permission prompts are off. Right after the agent is chosen, and only when it has such a flag, `chooseBypass()` asks `Turn <CLI>'s permission prompts off?` (Codex: `approval prompts and its sandbox`, worded by `bypassQuestion()`) on every launch, with Yes as the default and no answer remembered; `--keep-permissions` answers no and `--bypass-permissions` answers yes (neither is forwarded; keep wins when both are given), and with no TTY on stdin the prompts stay on unless `--bypass-permissions` is given. When the desktop app will take over, the question is skipped (its launch card has its own tick) and asked only if the app fails to start. The installer prints no warning about it.
|
||||
|
||||
On a terminal it first prints a Planny banner (`renderBanner()`). With more than one on `PATH` it asks `Plan2Code opens inside an AI coding agent. Pick which one to use:` as a numbered menu, the last pick pre-selected and marked `(last used)` (Enter keeps it; a number or a CLI id also works); with one installed it uses that without asking, printing `Opening with <CLI>…` (as does a `--cli` pick); with none it runs the setup flow when a person can see a page (`hasDisplay()` and a TTY or the shortcut; the desktop app first when it is installed, else the console's agent-less `setup` page in the browser) and otherwise prints the install steps (`printNoAgentGuidance()`: each built-in's install command and page, how to add another agent in `~/.plan2code/agents.json`, and to run `plan2code` again) and exits 127. An uninstalled `--cli` pick goes to the same setup flow on that agent when a page can open, else prints that CLI's own steps after its error. `--cli claude` / `devin` / `codex` (or `--cli=<name>`) skips the menu and is never forwarded; an unknown name exits 2, an uninstalled one 127. The pick is saved as `lastCli` in `~/.plan2code/launcher.json`, merged beside `lastFolder`. Before spawning, unless the forwarded args carry `--model` / `--model=` (or, for Codex, `-m`), it asks `Which model should <CLI> use?` from `models.json` plus the user's additions, Enter keeping the model the CLI last used — Ctrl+C at any launcher prompt exits 130. With no TTY on stdin there is no menu (last pick, else the first installed) and no model question: it prints that the CLI will use the model last used in it (switch it in that CLI on its own, or pass `--model <name>`). Headings, numbers, defaults, retry lines and the `plan2code:` error prefixes are colored with `paint()` (the escape values of `install.js`'s `COLORS`, copied), stdout only when stdout is a TTY and stderr only when stderr is, and never when `NO_COLOR` is set; piped runs print plain text and no banner. Other arguments are forwarded to the CLI (`plan2code --model opus`), and its exit code is passed back. `plan2code update` and `plan2code uninstall [--yes] [--purge]` are the two subcommands: neither is forwarded and neither opens an agent. Update runs `npx --yes --allow-git=all git+https://github.com/jparkerweb/plan2code.git --update`, so `install.js --update` reinstalls what `~/.plan2code/install.json` lists; uninstall runs the same npx line with `--uninstall` (an unknown flag exits 2 before npx runs), and `install.js` confirms, removes everything the menu's U option does, then asks about `~/.plan2code` (see `--uninstall` in Development Commands). On every other start, before spawning the CLI, it prints one line when a newer release is out (`Plan2Code v<latest> is out (you have v<installed>). Run: plan2code update`), compared against `~/.plan2code/bin/version.json` and read from the console's cached release check (`~/.plan2code/console/update-check.json`); it never waits on the network, and when the cache is missing or stale it refreshes it in a detached background process so the next start knows. Tests: `scripts/test-launcher.mjs` (run by `npm test`) spawns the launcher against stand-in `claude`/`devin`/`codex` commands and a temp home.
|
||||
On a terminal it first prints a Planny banner (`renderBanner()`). With more than one on `PATH` it asks `Plan2Code opens inside an AI coding agent. Pick which one to use:` as a numbered menu, the last pick pre-selected and marked `(last used)` (Enter keeps it; a number or a CLI id also works); with one installed it uses that without asking, printing `Opening with <CLI>…` (as does a `--cli` pick); with none it runs the setup flow when a person can see a page (`hasDisplay()` and a TTY or the shortcut; the desktop app first when it is installed, else the console's agent-less `setup` page in the browser) and otherwise prints the install steps (`printNoAgentGuidance()`: each built-in's install command and page, how to add another agent in `~/.plan2code/agents.json`, and to run `plan2code` again) and exits 127. An uninstalled `--cli` pick goes to the same setup flow on that agent when a page can open, else prints that CLI's own steps after its error. `--cli claude` / `devin` / `codex` (or `--cli=<name>`) skips the menu and is never forwarded; an unknown name exits 2, an uninstalled one 127. The pick is saved as `lastCli` in `~/.plan2code/launcher.json`, merged beside `lastFolder`, `recentFolders` and `lastModels`. Then, at a terminal with recent folders to offer, it asks `Which project folder?` as a numbered menu in the style of the model menu: the current folder first (Enter keeps it), the recent folders (at most 5, newest first), then `Choose another folder...` for the native picker. With no recent folders other than the current one (the typed command leaves the current folder out of the list), or no TTY on stdin, there is no menu and it opens the current folder as before. The folder is recorded as `recentFolders` (with `lastFolder` always its first entry) only after the project check passes (`recordFolder()`), on every path including the global command; declining the check records nothing. Before spawning, unless the forwarded args carry `--model` / `--model=` (or, for Codex, `-m`), it asks `Which model should <CLI> use?` from `models.json` plus the user's additions, Enter keeping the model the CLI last used — Ctrl+C at any launcher prompt exits 130. With no TTY on stdin there is no menu (last pick, else the first installed) and no model question: it prints that the CLI will use the model last used in it (switch it in that CLI on its own, or pass `--model <name>`). Headings, numbers, defaults, retry lines and the `plan2code:` error prefixes are colored with `paint()` (the escape values of `install.js`'s `COLORS`, copied), stdout only when stdout is a TTY and stderr only when stderr is, and never when `NO_COLOR` is set; piped runs print plain text and no banner. Other arguments are forwarded to the CLI (`plan2code --model opus`), and its exit code is passed back. `plan2code update` and `plan2code uninstall [--yes] [--purge]` are the two subcommands: neither is forwarded and neither opens an agent. Update runs `npx --yes --allow-git=all git+https://github.com/jparkerweb/plan2code.git --update`, so `install.js --update` reinstalls what `~/.plan2code/install.json` lists; uninstall runs the same npx line with `--uninstall` (an unknown flag exits 2 before npx runs), and `install.js` confirms, removes everything the menu's U option does, then asks about `~/.plan2code` (see `--uninstall` in Development Commands). On every other start, before spawning the CLI, it prints one line when a newer release is out (`Plan2Code v<latest> is out (you have v<installed>). Run: plan2code update`), compared against `~/.plan2code/bin/version.json` and read from the console's cached release check (`~/.plan2code/console/update-check.json`); it never waits on the network, and when the cache is missing or stale it refreshes it in a detached background process so the next start knows. Tests: `scripts/test-launcher.mjs` (run by `npm test`) spawns the launcher against stand-in `claude`/`devin`/`codex` commands and a temp home.
|
||||
|
||||
**Design constraints:**
|
||||
- **Stable copy, not the package dir** — the installer normally runs from an npx cache directory npm may delete, so `installLauncher()` copies `src/launcher/plan2code.js` to `~/.plan2code/bin/plan2code.js` and the shims point there. Beside it go `update-check.mjs` (the web console's release check, for the terminal notice), `agents.json` and `agent-lookup.mjs` (the shared agent list and lookup rule; `plan2code update` restores a missing copy) and a `version.json` (the installed version). (The metrics/bot wrappers point into `__dirname` and don't have this protection.)
|
||||
@@ -218,7 +218,7 @@ On a terminal it first prints a Planny banner (`renderBanner()`). With more than
|
||||
- **Marker-based ownership** — every shim contains `plan2code-launcher`; `uninstallLauncher()` removes only files carrying it, leaving any other `plan2code` bin alone.
|
||||
- **Resolving the CLI** — `findAgent()` in the shared `agent-lookup.mjs` does the lookup: `PATH` (+ `PATHEXT` on Windows), the saved Windows PATH from the registry (`addSavedWindowsPath()`), npm's global bin and each entry's `installDirs`, giving `found` / `outside` / `missing` (the desktop app's `find_on_path` in `agents.rs` is its twin, held to `scripts/fixtures/agent-lookup-cases.json`). An `.exe` is spawned directly; a `.cmd`/`.bat` wrapper goes through `cmd.exe /d /s /c` with quoted args, since Node refuses to spawn batch files without a shell. The installer warns only when neither `claude` nor `devin` is on `PATH`.
|
||||
- **No bin-name overlap** — the installer's own bin in `package.json` is `plan2code-install` (→ `install.js`), so `plan2code` belongs to the launcher alone. npx runs a package's only bin whatever it's named, so the README's `npx … plan2code.git` command is unaffected; keep it the only bin, or npx will need `-c plan2code-install`.
|
||||
- **`--pick-folder` is shortcut-only** — the launcher strips it before building the CLI's args. The shortcut runs the CLI menu, then the folder picker, then the model menu. With it, a native folder picker chooses the cwd instead: on Windows, the Explorer-style `IFileOpenDialog` (`FOS_PICKFOLDERS`) via `powershell -STA -EncodedCommand`, its C# interop (`WINDOWS_PICKER_SOURCE`) passed in an env var and compiled with `Add-Type` (~0.5s), with a TopMost owner form so it doesn't open behind the console — Windows PowerShell's `FolderBrowserDialog` is the old tree-only dialog, and is kept only as the fallback when `Add-Type` is blocked (Constrained Language Mode, AppLocker); `osascript choose folder` on macOS, and `zenity` then `kdialog` on Linux (only when `DISPLAY`/`WAYLAND_DISPLAY` is set). If there's no picker, or the picker fails, it falls back to a typed `Project folder [last]:` prompt. A picker that exits 0/1 with nothing printed means the person canceled, so the launcher exits 0. The picker starts on the last pick, stored in `~/.plan2code/launcher.json`. From the shortcut, a non-zero exit other than Ctrl+C (130 / `0xC000013A`) waits for Enter so the error doesn't vanish with the window. Typed in a terminal, `plan2code` behaves exactly as before.
|
||||
- **`--pick-folder` is shortcut-only** — the launcher strips it before building the CLI's args. The shortcut runs the CLI menu, then the folder menu (`Choose a folder...` first and the default, the recent folders under it; with no recent folders, or no TTY, it goes straight to the picker), then the model menu. `Choose a folder...` runs a native folder picker that chooses the cwd instead: on Windows, the Explorer-style `IFileOpenDialog` (`FOS_PICKFOLDERS`) via `powershell -STA -EncodedCommand`, its C# interop (`WINDOWS_PICKER_SOURCE`) passed in an env var and compiled with `Add-Type` (~0.5s), with a TopMost owner form so it doesn't open behind the console — Windows PowerShell's `FolderBrowserDialog` is the old tree-only dialog, and is kept only as the fallback when `Add-Type` is blocked (Constrained Language Mode, AppLocker); `osascript choose folder` on macOS, and `zenity` then `kdialog` on Linux (only when `DISPLAY`/`WAYLAND_DISPLAY` is set). If there's no picker, or the picker fails, it falls back to a typed `Project folder [last]:` prompt. A picker that exits 0/1 with nothing printed means the person canceled, so the launcher exits 0. The picker starts on the last pick, stored in `~/.plan2code/launcher.json`. From the shortcut, a non-zero exit other than Ctrl+C (130 / `0xC000013A`) waits for Enter so the error doesn't vanish with the window. Typed in a terminal, `plan2code` behaves exactly as before.
|
||||
|
||||
**Desktop shortcut** — after the shims are written, `installLauncher()` (now async) calls `offerDesktopShortcut()`. It asks `Also add a Plan2Code shortcut to your desktop? (y/N)`, skips the question when stdin isn't a TTY, and refreshes an existing marked shortcut without asking. `installDesktopShortcut()` writes it to the real desktop (`[Environment]::GetFolderPath('Desktop')` on Windows, which covers OneDrive redirection; `xdg-user-dir DESKTOP` on Linux; `~/Desktop` otherwise):
|
||||
|
||||
|
||||
@@ -90,7 +90,7 @@ custom agent that has none; for Codex the question names its sandbox, which that
|
||||
launch and remembers no answer. `plan2code --keep-permissions` keeps the prompts without asking, and
|
||||
`plan2code --bypass-permissions` turns them off without asking. With no terminal to ask on (a script or a pipe) the
|
||||
prompts stay on unless `--bypass-permissions` is given. The installer then offers a desktop shortcut (answer `y`),
|
||||
which opens a folder picker first. Uninstalling (`U`, or `plan2code uninstall` from any terminal) removes both.
|
||||
which opens a folder menu first: Choose a folder, with the project folders you opened lately under it (with none yet, it goes straight to the folder dialog). In a terminal, `plan2code` offers the same recent folders as a numbered menu. Uninstalling (`U`, or `plan2code uninstall` from any terminal) removes both.
|
||||
</details>
|
||||
|
||||
<details>
|
||||
|
||||
+4
-2
@@ -48,7 +48,9 @@ You also need Node.js 18 or newer (the app checks at start and says what to inst
|
||||
Run `plan2code` in your project, as always. When the app is installed and a window can open,
|
||||
`plan2code` asks which agent and model (as before) and then opens the app on that folder instead of
|
||||
running the agent in your terminal. The desktop shortcut the installer can create runs the same
|
||||
command, so it opens the app too.
|
||||
command, so it opens the app too; it asks for the folder first, with **Choose a folder** at the top and the folders you opened lately under it (with none yet, it goes straight to the folder dialog).
|
||||
|
||||
Start the app itself (from the Start menu, the Dock or a launcher) and it asks for a folder the same way: **Choose a folder** first, then your recent folders, newest first. It no longer reopens the last folder on its own.
|
||||
|
||||
Three things keep today's terminal flow:
|
||||
|
||||
@@ -112,7 +114,7 @@ separate context-window meter of its own, so there is only ever one gauge to rea
|
||||
threshold is tuned. The terminal panel has its own toolbar: dock it to the bottom or the right, collapse
|
||||
it to a thin strip, or maximize it; its size is remembered. An "agent may need you" badge appears on a
|
||||
collapsed or small panel once the agent has sat quiet for a while. **Change project** (in the project
|
||||
menu) asks first if an agent is running, then stops it and the console before opening the new folder.
|
||||
menu) asks first if an agent is running, then stops it and the console before opening the new folder. It shows the same folder picker, with **Choose a folder** first and the recent folders under it (the one already open is left out); Cancel or Escape keeps the project as it is.
|
||||
|
||||
If the console itself ever needs reconnecting (it stopped, or the skills were just updated), every path
|
||||
to that offers the same **Reconnect the console** button — never "Restart the console" in one place and
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
{
|
||||
"$comment": "The rule of the recent-folders list in ~/.plan2code/launcher.json (`recentFolders`, newest first, at most 5) as cases both writers' tests load: the launcher (src/launcher/plan2code.js) and the desktop app (plan2code-app/src-tauri/src/project.rs). A case may carry `platform`: `win32` or `posix`; it runs only with that platform's rule (a case with none runs under both). Paths are plain strings. read: `state` is the launcher.json object, `expect` the list. push: `list`, `dir`, `expect`. list: `list`, `exists` (the folders that exist), `exclude` (a folder or null), `expect`.",
|
||||
"read": [
|
||||
{
|
||||
"name": "the list is used as it is",
|
||||
"state": { "recentFolders": ["/b", "/a"], "lastFolder": "/z" },
|
||||
"expect": ["/b", "/a"]
|
||||
},
|
||||
{
|
||||
"name": "an empty list is used as it is, not replaced by the last folder",
|
||||
"state": { "recentFolders": [], "lastFolder": "/a" },
|
||||
"expect": []
|
||||
},
|
||||
{
|
||||
"name": "no list falls back to the last folder",
|
||||
"state": { "lastFolder": "/a" },
|
||||
"expect": ["/a"]
|
||||
},
|
||||
{
|
||||
"name": "neither key gives an empty list",
|
||||
"state": { "lastCli": "claude" },
|
||||
"expect": []
|
||||
},
|
||||
{
|
||||
"name": "an empty state gives an empty list",
|
||||
"state": {},
|
||||
"expect": []
|
||||
},
|
||||
{
|
||||
"name": "entries that are not strings or are empty are dropped",
|
||||
"state": { "recentFolders": ["/a", 7, "", null, "/b", { "x": 1 }] },
|
||||
"expect": ["/a", "/b"]
|
||||
},
|
||||
{
|
||||
"name": "a list that is not an array falls back to the last folder",
|
||||
"state": { "recentFolders": "/x", "lastFolder": "/a" },
|
||||
"expect": ["/a"]
|
||||
},
|
||||
{
|
||||
"name": "a list that is not an array and no last folder gives an empty list",
|
||||
"state": { "recentFolders": { "0": "/x" } },
|
||||
"expect": []
|
||||
},
|
||||
{
|
||||
"name": "an empty last folder is no folder",
|
||||
"state": { "lastFolder": "" },
|
||||
"expect": []
|
||||
},
|
||||
{
|
||||
"name": "more than 5 entries are cut to 5",
|
||||
"state": { "recentFolders": ["/1", "/2", "/3", "/4", "/5", "/6", "/7"] },
|
||||
"expect": ["/1", "/2", "/3", "/4", "/5"]
|
||||
}
|
||||
],
|
||||
"push": [
|
||||
{
|
||||
"name": "a new folder goes first",
|
||||
"list": ["/b", "/a"],
|
||||
"dir": "/c",
|
||||
"expect": ["/c", "/b", "/a"]
|
||||
},
|
||||
{
|
||||
"name": "a first folder starts the list",
|
||||
"list": [],
|
||||
"dir": "/a",
|
||||
"expect": ["/a"]
|
||||
},
|
||||
{
|
||||
"name": "an existing folder moves to the top without a duplicate",
|
||||
"list": ["/c", "/b", "/a"],
|
||||
"dir": "/a",
|
||||
"expect": ["/a", "/c", "/b"]
|
||||
},
|
||||
{
|
||||
"name": "a sixth folder drops the oldest",
|
||||
"list": ["/5", "/4", "/3", "/2", "/1"],
|
||||
"dir": "/6",
|
||||
"expect": ["/6", "/5", "/4", "/3", "/2"]
|
||||
},
|
||||
{
|
||||
"name": "a folder already first stays first",
|
||||
"list": ["/a", "/b"],
|
||||
"dir": "/a",
|
||||
"expect": ["/a", "/b"]
|
||||
},
|
||||
{
|
||||
"name": "a trailing slash matches the bare path",
|
||||
"list": ["/b", "/a"],
|
||||
"dir": "/a/",
|
||||
"expect": ["/a/", "/b"]
|
||||
},
|
||||
{
|
||||
"name": "a bare path matches a listed trailing slash",
|
||||
"list": ["/b", "/a/"],
|
||||
"dir": "/a",
|
||||
"expect": ["/a", "/b"]
|
||||
},
|
||||
{
|
||||
"name": "a trailing backslash matches the bare path",
|
||||
"list": ["D:\\x", "C:\\a"],
|
||||
"dir": "C:\\a\\",
|
||||
"expect": ["C:\\a\\", "D:\\x"]
|
||||
},
|
||||
{
|
||||
"name": "a drive root keeps its separator",
|
||||
"list": ["C:\\", "C:\\a"],
|
||||
"dir": "C:\\a\\",
|
||||
"expect": ["C:\\a\\", "C:\\"]
|
||||
},
|
||||
{
|
||||
"name": "the root of a posix tree is not stripped to nothing",
|
||||
"list": ["/a"],
|
||||
"dir": "/",
|
||||
"expect": ["/", "/a"]
|
||||
},
|
||||
{
|
||||
"name": "a drive root is not the bare drive",
|
||||
"list": ["C:"],
|
||||
"dir": "C:\\",
|
||||
"expect": ["C:\\", "C:"]
|
||||
},
|
||||
{
|
||||
"name": "a drive root with a slash is not the bare drive",
|
||||
"list": ["C:"],
|
||||
"dir": "C:/",
|
||||
"expect": ["C:/", "C:"]
|
||||
},
|
||||
{
|
||||
"name": "a drive root matches itself",
|
||||
"list": ["C:\\"],
|
||||
"dir": "C:\\",
|
||||
"expect": ["C:\\"]
|
||||
},
|
||||
{
|
||||
"name": "the posix root is not an empty path",
|
||||
"list": ["/a", ""],
|
||||
"dir": "/",
|
||||
"expect": ["/", "/a", ""]
|
||||
},
|
||||
{
|
||||
"platform": "win32",
|
||||
"name": "windows ignores case and keeps the new spelling",
|
||||
"list": ["D:\\x", "c:\\git\\a"],
|
||||
"dir": "C:\\Git\\A",
|
||||
"expect": ["C:\\Git\\A", "D:\\x"]
|
||||
},
|
||||
{
|
||||
"platform": "posix",
|
||||
"name": "posix tells case apart",
|
||||
"list": ["/x", "/git/a"],
|
||||
"dir": "/Git/A",
|
||||
"expect": ["/Git/A", "/x", "/git/a"]
|
||||
}
|
||||
],
|
||||
"list": [
|
||||
{
|
||||
"name": "folders that are gone are skipped and the order is kept",
|
||||
"list": ["/c", "/b", "/a"],
|
||||
"exists": ["/a", "/c"],
|
||||
"exclude": null,
|
||||
"expect": ["/c", "/a"]
|
||||
},
|
||||
{
|
||||
"name": "nothing existing gives an empty list",
|
||||
"list": ["/b", "/a"],
|
||||
"exists": [],
|
||||
"exclude": null,
|
||||
"expect": []
|
||||
},
|
||||
{
|
||||
"name": "the excluded folder is removed",
|
||||
"list": ["/c", "/b", "/a"],
|
||||
"exists": ["/a", "/b", "/c"],
|
||||
"exclude": "/b",
|
||||
"expect": ["/c", "/a"]
|
||||
},
|
||||
{
|
||||
"name": "the excluded folder matches past a trailing slash",
|
||||
"list": ["/c", "/b", "/a"],
|
||||
"exists": ["/a", "/b", "/c"],
|
||||
"exclude": "/b/",
|
||||
"expect": ["/c", "/a"]
|
||||
},
|
||||
{
|
||||
"name": "excluding a drive root leaves the bare drive",
|
||||
"list": ["C:", "C:\\"],
|
||||
"exists": ["C:", "C:\\"],
|
||||
"exclude": "C:\\",
|
||||
"expect": ["C:"]
|
||||
},
|
||||
{
|
||||
"platform": "win32",
|
||||
"name": "windows excludes by folder, not by spelling",
|
||||
"list": ["C:\\Git\\A", "D:\\x"],
|
||||
"exists": ["C:\\Git\\A", "D:\\x"],
|
||||
"exclude": "c:\\git\\a\\",
|
||||
"expect": ["D:\\x"]
|
||||
},
|
||||
{
|
||||
"platform": "posix",
|
||||
"name": "posix keeps a folder that differs only in case",
|
||||
"list": ["/Git/A", "/x"],
|
||||
"exists": ["/Git/A", "/x"],
|
||||
"exclude": "/git/a",
|
||||
"expect": ["/Git/A", "/x"]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { helloRetryAction, retryLabel, RETRY_AFTER_SECONDS, attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopRunText, loopLocks, loopStopLabels, loopWindowTitle, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS, NEW_RELEASE_COMMAND } from "../plan2code-app/ui/meter.js";
|
||||
import { helloRetryAction, retryLabel, RETRY_AFTER_SECONDS, attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, folderPickerRows, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopRunText, loopLocks, loopStopLabels, loopWindowTitle, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS, NEW_RELEASE_COMMAND } from "../plan2code-app/ui/meter.js";
|
||||
import { findBrowser, launchBrowser } from "./browser.mjs";
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
@@ -134,6 +134,19 @@ test("the bar reads project menu, New Session, agent menu, with both menus outsi
|
||||
assert.match(INDEX_HTML, /<div id="project-menu"[\s\S]*?<button id="change-project" role="menuitem">/, "Change project lives in the project menu");
|
||||
});
|
||||
|
||||
test("folderPickerRows puts Choose a folder first, then the recent folders in the order given", () => {
|
||||
assert.deepEqual(folderPickerRows([]), [{ kind: "browse", label: "Choose a folder..." }]);
|
||||
const rows = folderPickerRows([
|
||||
{ dir: "C:\\git\\b", name: "b" },
|
||||
{ dir: "/home/me/a", name: "a" },
|
||||
]);
|
||||
assert.deepEqual(rows, [
|
||||
{ kind: "browse", label: "Choose a folder..." },
|
||||
{ kind: "folder", dir: "C:\\git\\b", label: "b", detail: "C:\\git\\b" },
|
||||
{ kind: "folder", dir: "/home/me/a", label: "a", detail: "/home/me/a" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("folderName shows the project folder's own name, or the whole path when it has none", () => {
|
||||
assert.equal(folderName("C:\\git\\azw3-to-pdf"), "azw3-to-pdf");
|
||||
assert.equal(folderName("/home/me/plan2code/"), "plan2code");
|
||||
@@ -530,7 +543,7 @@ test("main.rs guards the window's agent and project commands, and registers loop
|
||||
assert.ok(at > 0, `${name} exists`);
|
||||
return rust.slice(at, rust.indexOf("\n}\n", at));
|
||||
};
|
||||
for (const [name, what] of [["agent_start", "agent"], ["agent_restart", "agent"], ["change_project", "project"], ["pick_project_folder", "project"]]) {
|
||||
for (const [name, what] of [["agent_start", "agent"], ["agent_restart", "agent"], ["change_project", "project"], ["pick_project_folder", "project"], ["open_recent_folder", "project"]]) {
|
||||
assert.ok(body(name).includes(`refuse_while_looping(&state, "${what}")?;`), `${name} refuses while a loop runs`);
|
||||
}
|
||||
assert.ok(!body("agent_input").includes("refuse_while_looping"), "typing stays open for a trust or login prompt");
|
||||
|
||||
+151
-6
@@ -131,6 +131,18 @@ function sandbox(clis, { installed, project = true, lookup = true, agents } = {}
|
||||
|
||||
const NOTICE_LINE = /is out \(you have v/;
|
||||
|
||||
/**
|
||||
* The run's folder was recorded: first in `recentFolders` (compared by real path, since a temp
|
||||
* folder can reach the launcher under another spelling), `lastFolder` equal to it, and `older`
|
||||
* after it in order.
|
||||
*/
|
||||
function assertRecordedFirst({ recentFolders, lastFolder }, folder, older = []) {
|
||||
assert.ok(Array.isArray(recentFolders), "recentFolders is written");
|
||||
assert.equal(fs.realpathSync(recentFolders[0]), fs.realpathSync(folder));
|
||||
assert.equal(lastFolder, recentFolders[0]);
|
||||
assert.deepEqual(recentFolders.slice(1), older);
|
||||
}
|
||||
|
||||
/** Write the console's cached release check, `ageMs` old. */
|
||||
function writeCache(box, latest, ageMs = 0) {
|
||||
fs.mkdirSync(path.dirname(box.cacheFile), { recursive: true });
|
||||
@@ -307,11 +319,9 @@ test("launcher: a launched model is remembered per agent in launcher.json", (t)
|
||||
assert.equal(box.run(["--cli", "claude", "--model", "opus"]).status, 0);
|
||||
assert.equal(box.run(["--cli", "codex", "-m", "x"]).status, 0);
|
||||
assert.equal(box.run(["--cli", "codex", "-my"]).status, 0);
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(box.stateFile, "utf8")), {
|
||||
lastFolder: box.home,
|
||||
lastCli: "codex",
|
||||
lastModels: { claude: "opus", codex: "y" },
|
||||
});
|
||||
const { recentFolders, lastFolder, ...rest } = JSON.parse(fs.readFileSync(box.stateFile, "utf8"));
|
||||
assert.deepEqual(rest, { lastCli: "codex", lastModels: { claude: "opus", codex: "y" } });
|
||||
assertRecordedFirst({ recentFolders, lastFolder }, box.dir, [box.home]);
|
||||
});
|
||||
|
||||
test("launcher: --cli picks the CLI and is never forwarded; the pick is merged into launcher.json", (t) => {
|
||||
@@ -326,7 +336,9 @@ test("launcher: --cli picks the CLI and is never forwarded; the pick is merged i
|
||||
assert.deepEqual(box.argsOf("devin"), ["--", "/plan2code"]);
|
||||
}
|
||||
assert.equal(box.argsOf("claude"), null);
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(box.stateFile, "utf8")), { lastFolder: box.home, lastCli: "devin" });
|
||||
const { recentFolders, lastFolder, ...rest } = JSON.parse(fs.readFileSync(box.stateFile, "utf8"));
|
||||
assert.deepEqual(rest, { lastCli: "devin" });
|
||||
assertRecordedFirst({ recentFolders, lastFolder }, box.dir, [box.home]);
|
||||
});
|
||||
|
||||
test("launcher: with both installed and no terminal to ask in, the last pick wins", (t) => {
|
||||
@@ -1319,3 +1331,136 @@ test("launcher setup: no agent and no display keeps the old 127 and install step
|
||||
assert.match(result.stderr, /none was found/);
|
||||
assert.equal(box.appExists(), false);
|
||||
});
|
||||
|
||||
// The recent-folders rule: the same cases the desktop app's project.rs loads (the fixture holds
|
||||
// both platforms' rules, so each runs on every OS: "win32" and "linux" are passed explicitly).
|
||||
const RECENT_CASES = JSON.parse(fs.readFileSync(path.join(ROOT, "scripts", "fixtures", "recent-folders-cases.json"), "utf8"));
|
||||
const RECENT_PLATFORMS = { win32: "win32", posix: "linux" };
|
||||
|
||||
/** The platform values ("win32" or "linux") a fixture case runs under. */
|
||||
function recentPlatforms(testCase) {
|
||||
return testCase.platform ? [RECENT_PLATFORMS[testCase.platform]] : ["win32", "linux"];
|
||||
}
|
||||
|
||||
test("launcher recent folders: readRecent follows the shared cases", () => {
|
||||
const { readRecent } = require(LAUNCHER);
|
||||
assert.ok(RECENT_CASES.read.length > 0);
|
||||
for (const c of RECENT_CASES.read) assert.deepEqual(readRecent(c.state), c.expect, c.name);
|
||||
});
|
||||
|
||||
test("launcher recent folders: pushRecent follows the shared cases", () => {
|
||||
const { pushRecent } = require(LAUNCHER);
|
||||
assert.ok(RECENT_CASES.push.length > 0);
|
||||
for (const c of RECENT_CASES.push) {
|
||||
for (const platform of recentPlatforms(c)) assert.deepEqual(pushRecent(c.list, c.dir, platform), c.expect, `${c.name} (${platform})`);
|
||||
}
|
||||
});
|
||||
|
||||
test("launcher recent folders: listRecent follows the shared cases", () => {
|
||||
const { listRecent } = require(LAUNCHER);
|
||||
assert.ok(RECENT_CASES.list.length > 0);
|
||||
for (const c of RECENT_CASES.list) {
|
||||
const exists = new Set(c.exists);
|
||||
for (const platform of recentPlatforms(c)) {
|
||||
assert.deepEqual(listRecent(c.list, { exists: (p) => exists.has(p), exclude: c.exclude, platform }), c.expect, `${c.name} (${platform})`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("launcher recent folders: pushRecent returns a new array and leaves its input alone", () => {
|
||||
const { pushRecent } = require(LAUNCHER);
|
||||
const list = ["/b", "/a"];
|
||||
pushRecent(list, "/c", "linux");
|
||||
assert.deepEqual(list, ["/b", "/a"]);
|
||||
});
|
||||
|
||||
test("launcher recent folders: recordFolder writes both keys from a state with only lastFolder and keeps the rest", (t) => {
|
||||
const box = sandbox([]);
|
||||
t.after(box.cleanup);
|
||||
fs.mkdirSync(path.dirname(box.stateFile), { recursive: true });
|
||||
fs.writeFileSync(box.stateFile, JSON.stringify({ lastFolder: "/old", lastCli: "devin" }));
|
||||
const picked = path.join(box.dir, "picked");
|
||||
const script = `require(${JSON.stringify(LAUNCHER)}).recordFolder(${JSON.stringify(picked)});`;
|
||||
const result = spawnSync(process.execPath, ["-e", script], {
|
||||
encoding: "utf8",
|
||||
env: { ...process.env, HOME: box.home, USERPROFILE: box.home },
|
||||
});
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(box.stateFile, "utf8")), {
|
||||
lastFolder: picked,
|
||||
recentFolders: [picked, "/old"],
|
||||
lastCli: "devin",
|
||||
});
|
||||
});
|
||||
|
||||
test("launcher folder menu: from the command, the current folder comes first, then the recents, then browse", () => {
|
||||
const { folderMenuRows } = require(LAUNCHER);
|
||||
const cwd = path.join(os.tmpdir(), "here");
|
||||
const recent = [path.join(os.tmpdir(), "one"), path.join(os.tmpdir(), "two")];
|
||||
assert.deepEqual(folderMenuRows({ fromShortcut: false, cwd, recent }), [
|
||||
{ kind: "folder", dir: cwd, name: "here", detail: `${cwd} (current folder)`, label: `here ${cwd} (current folder)` },
|
||||
{ kind: "folder", dir: recent[0], name: "one", detail: recent[0], label: `one ${recent[0]}` },
|
||||
{ kind: "folder", dir: recent[1], name: "two", detail: recent[1], label: `two ${recent[1]}` },
|
||||
{ kind: "browse", label: "Choose another folder..." },
|
||||
]);
|
||||
});
|
||||
|
||||
test("launcher folder menu: from the shortcut, browse comes first, then the recents", () => {
|
||||
const { folderMenuRows } = require(LAUNCHER);
|
||||
const recent = [path.join(os.tmpdir(), "one")];
|
||||
assert.deepEqual(folderMenuRows({ fromShortcut: true, cwd: os.tmpdir(), recent }), [
|
||||
{ kind: "browse", label: "Choose a folder..." },
|
||||
{ kind: "folder", dir: recent[0], name: "one", detail: recent[0], label: `one ${recent[0]}` },
|
||||
]);
|
||||
});
|
||||
|
||||
test("launcher folder menu: a drive root keeps its full text as its name", () => {
|
||||
const { folderMenuRows } = require(LAUNCHER);
|
||||
const root = path.parse(process.cwd()).root;
|
||||
const [row] = folderMenuRows({ fromShortcut: false, cwd: root, recent: [] });
|
||||
assert.equal(row.label, `${root} ${root} (current folder)`);
|
||||
assert.equal(row.name, root);
|
||||
assert.equal(row.detail, `${root} (current folder)`);
|
||||
});
|
||||
|
||||
test("launcher folder menu: Enter picks row 1, a number its row, anything else asks again", () => {
|
||||
const { folderMenuPick } = require(LAUNCHER);
|
||||
const rows = [{ kind: "folder", dir: "/a", label: "a" }, { kind: "folder", dir: "/b", label: "b" }, { kind: "browse", label: "x" }];
|
||||
assert.equal(folderMenuPick(rows, ""), rows[0]);
|
||||
assert.equal(folderMenuPick(rows, " "), rows[0]);
|
||||
assert.equal(folderMenuPick(rows, "2"), rows[1]);
|
||||
assert.equal(folderMenuPick(rows, " 3 "), rows[2]);
|
||||
for (const answer of ["0", "9", "x", "1.5", "-1"]) assert.equal(folderMenuPick(rows, answer), null, answer);
|
||||
});
|
||||
|
||||
test("launcher folder menu: with recent folders but no terminal, it starts in the current folder without a menu and records it", (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
const older = path.join(box.dir, "older");
|
||||
fs.mkdirSync(older);
|
||||
fs.mkdirSync(path.dirname(box.stateFile), { recursive: true });
|
||||
fs.writeFileSync(box.stateFile, JSON.stringify({ recentFolders: [older], lastFolder: older, lastCli: "claude" }));
|
||||
const result = box.run([]);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.doesNotMatch(result.stdout, /Which project folder\?/);
|
||||
assert.doesNotMatch(result.stdout, /Opening Plan2Code in/);
|
||||
assert.notEqual(box.argsOf("claude"), null);
|
||||
const { recentFolders, lastFolder, ...rest } = JSON.parse(fs.readFileSync(box.stateFile, "utf8"));
|
||||
assert.deepEqual(rest, { lastCli: "claude" });
|
||||
assertRecordedFirst({ recentFolders, lastFolder }, box.dir, [older]);
|
||||
});
|
||||
|
||||
test("launcher folder menu: a folder that fails the project check is not recorded", (t) => {
|
||||
const box = sandbox(["claude"], { project: false });
|
||||
t.after(box.cleanup);
|
||||
const older = path.join(box.dir, "older");
|
||||
fs.mkdirSync(older);
|
||||
fs.mkdirSync(path.dirname(box.stateFile), { recursive: true });
|
||||
const state = { recentFolders: [older], lastFolder: older, lastCli: "claude" };
|
||||
fs.writeFileSync(box.stateFile, JSON.stringify(state));
|
||||
const result = box.run([]);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stderr, /doesn't look like a project/);
|
||||
assert.equal(box.argsOf("claude"), null);
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(box.stateFile, "utf8")), state);
|
||||
});
|
||||
+131
-10
@@ -37,8 +37,18 @@
|
||||
* Preferences in the web console) are listed after the built-ins and started the same way, with
|
||||
* `--cli <id>` or from the menu. Their rules are copied from src/web-console/agents.mjs below.
|
||||
*
|
||||
* `--pick-folder` (passed by the desktop shortcut, never forwarded to the CLI) asks for the
|
||||
* project folder with a native folder picker first, starting on the folder picked last time.
|
||||
* Folders: the launcher keeps the last 5 project folders opened, newest first, in
|
||||
* ~/.plan2code/launcher.json (`recentFolders`, with `lastFolder` always its first entry; the
|
||||
* desktop app reads and writes the same list by the same rule). At a terminal with recent folders
|
||||
* to offer, it asks which folder to open in a numbered menu: the current folder first (Enter
|
||||
* keeps it), the recent folders, then Choose another folder... for the native folder picker.
|
||||
* With none to offer, or no terminal, it opens in the current folder without asking. A folder is
|
||||
* added to the list only once it passes the project check.
|
||||
*
|
||||
* `--pick-folder` (passed by the desktop shortcut, never forwarded to the CLI) puts Choose a
|
||||
* folder... first in that menu (Enter opens the native folder picker, starting on the folder
|
||||
* opened last time, the first recent folder), with the recent folders under it; with none to
|
||||
* offer it opens the picker straight away.
|
||||
*
|
||||
* When the desktop app is installed (~/.plan2code/app/) and a display exists, `plan2code` opens
|
||||
* the app on the chosen folder, agent and model instead of running the agent in this terminal.
|
||||
@@ -714,7 +724,7 @@ function isDirectory(dir) {
|
||||
}
|
||||
}
|
||||
|
||||
/** `~/.plan2code/launcher.json`: `{ lastFolder, lastCli, lastModels }`, any key possibly missing. */
|
||||
/** `~/.plan2code/launcher.json`: `{ lastFolder, recentFolders, lastCli, lastModels }`, any key possibly missing. */
|
||||
function readState() {
|
||||
try {
|
||||
const state = JSON.parse(fs.readFileSync(STATE_FILE, 'utf8'));
|
||||
@@ -736,6 +746,104 @@ function readLastFolder() {
|
||||
return lastFolder && isDirectory(lastFolder) ? lastFolder : os.homedir();
|
||||
}
|
||||
|
||||
/** How many recent project folders the list keeps. */
|
||||
const RECENT_FOLDERS_MAX = 5;
|
||||
|
||||
/** One trailing `\` or `/` off a path, but never off a root (`C:\` or `/`). */
|
||||
function trimFolder(p) {
|
||||
if (p.length > 1 && /[\\/]$/.test(p) && !/^[A-Za-z]:[\\/]$/.test(p)) return p.slice(0, -1);
|
||||
return p;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether two paths name the same folder: a trailing separator is ignored, and case is on
|
||||
* Windows. The desktop app's `same_folder` (project.rs) holds the same rule, both to
|
||||
* scripts/fixtures/recent-folders-cases.json.
|
||||
*/
|
||||
function sameFolder(a, b, platform = process.platform) {
|
||||
const x = trimFolder(a);
|
||||
const y = trimFolder(b);
|
||||
return platform === 'win32' ? x.toLowerCase() === y.toLowerCase() : x === y;
|
||||
}
|
||||
|
||||
/** The recent folders in `launcher.json`'s state: `recentFolders`, else `[lastFolder]`, else none. */
|
||||
function readRecent(state) {
|
||||
const { recentFolders, lastFolder } = state || {};
|
||||
if (Array.isArray(recentFolders)) {
|
||||
return recentFolders.filter((x) => typeof x === 'string' && x !== '').slice(0, RECENT_FOLDERS_MAX);
|
||||
}
|
||||
return typeof lastFolder === 'string' && lastFolder !== '' ? [lastFolder] : [];
|
||||
}
|
||||
|
||||
/** A new list with `dir` first, an earlier entry for the same folder removed, cut to the max. */
|
||||
function pushRecent(list, dir, platform = process.platform) {
|
||||
return [dir, ...list.filter((x) => !sameFolder(x, dir, platform))].slice(0, RECENT_FOLDERS_MAX);
|
||||
}
|
||||
|
||||
/** The folders of `list` worth offering: ones that still exist, minus the one in `exclude`. */
|
||||
function listRecent(list, { exists = isDirectory, exclude = null, platform = process.platform } = {}) {
|
||||
return list.filter((x) => exists(x) && !(exclude && sameFolder(x, exclude, platform)));
|
||||
}
|
||||
|
||||
/** Put `dir` at the top of the recent folders; `lastFolder` stays the newest entry. */
|
||||
function recordFolder(dir) {
|
||||
const recentFolders = pushRecent(readRecent(readState()), dir);
|
||||
saveState({ recentFolders, lastFolder: recentFolders[0] });
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows of the folder menu. From the `plan2code` command: the current folder first (Enter
|
||||
* keeps it), the recent folders, then a row to browse. From the desktop shortcut: the browse row
|
||||
* first, then the recent folders. `recent` comes already filtered by listRecent.
|
||||
*/
|
||||
function folderMenuRows({ fromShortcut, cwd, recent }) {
|
||||
const name = (dir) => path.basename(dir) || dir;
|
||||
const folder = (dir, detail) => ({ kind: 'folder', dir, name: name(dir), detail, label: `${name(dir)} ${detail}` });
|
||||
const folders = recent.map((dir) => folder(dir, dir));
|
||||
if (fromShortcut) return [{ kind: 'browse', label: 'Choose a folder...' }, ...folders];
|
||||
return [
|
||||
folder(cwd, `${cwd} (current folder)`),
|
||||
...folders,
|
||||
{ kind: 'browse', label: 'Choose another folder...' },
|
||||
];
|
||||
}
|
||||
|
||||
/** The row an answer to the folder menu picks: Enter is row 1, a number its row, else null (ask again). */
|
||||
function folderMenuPick(rows, answer) {
|
||||
const text = String(answer || '').trim();
|
||||
if (!text) return rows[0];
|
||||
if (!/^\d+$/.test(text)) return null;
|
||||
const n = Number(text);
|
||||
return n >= 1 && n <= rows.length ? rows[n - 1] : null;
|
||||
}
|
||||
|
||||
/** One folder menu row as printed: the folder name plain, its path dimmed. */
|
||||
function folderMenuLine(row) {
|
||||
if (row.kind !== 'folder') return row.label;
|
||||
return `${row.name} ${c.dim(row.detail)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask which project folder to open, from the recent folders. `{ kind: 'folder', dir }` opens
|
||||
* that folder; `{ kind: 'browse' }` asks with the folder picker. With no recent folders to offer
|
||||
* or no terminal to ask on, nothing is printed and the answer is what it was before the menu:
|
||||
* the current folder, or the picker from the shortcut.
|
||||
*/
|
||||
async function chooseFolder({ fromShortcut, cwd }) {
|
||||
const recent = listRecent(readRecent(readState()), { exclude: fromShortcut ? null : cwd });
|
||||
if (!recent.length || !process.stdin.isTTY) return { kind: fromShortcut ? 'browse' : 'folder', dir: cwd };
|
||||
const rows = folderMenuRows({ fromShortcut, cwd, recent });
|
||||
console.log('');
|
||||
console.log(c.bright('Which project folder?'));
|
||||
console.log('');
|
||||
rows.forEach((row, i) => console.log(` ${c.cyan(`${i + 1})`)} ${folderMenuLine(row)}`));
|
||||
for (;;) {
|
||||
const row = folderMenuPick(rows, await ask(`Choice ${c.green('[1]')}: `));
|
||||
if (row) return row;
|
||||
console.log(c.dim(`Type a number from 1 to ${rows.length}, or press Enter for row 1.`));
|
||||
}
|
||||
}
|
||||
|
||||
function ask(prompt) {
|
||||
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
||||
// readline swallows Ctrl+C while it owns the terminal; treat it as leaving.
|
||||
@@ -1437,24 +1545,37 @@ async function pickFolder() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The folder to open in, confirmed as a project: process.cwd(), or the shortcut's folder pick
|
||||
* plus the same check. `{ cwd }` to carry on; `{ exit }` with the code to leave on when the
|
||||
* person canceled, picked a non-folder, or declined the project check.
|
||||
* The folder to open in, confirmed as a project: picked from the folder menu (chooseFolder: the
|
||||
* current folder, a recent one, or the folder picker), plus the project check. The folder is
|
||||
* recorded in the recent folders only once the check passes. `{ cwd }` to carry on; `{ exit }`
|
||||
* with the code to leave on when the person canceled, picked a non-folder, or declined the
|
||||
* project check.
|
||||
*/
|
||||
async function projectCwd(fromShortcut) {
|
||||
let cwd = process.cwd();
|
||||
if (fromShortcut) {
|
||||
const choice = await chooseFolder({ fromShortcut, cwd: process.cwd() });
|
||||
let cwd;
|
||||
if (choice.kind === 'browse') {
|
||||
const folder = await pickFolder();
|
||||
if (!folder) return { exit: 0 };
|
||||
if (!isDirectory(folder)) {
|
||||
console.error(`${ce.red('plan2code:')} ${folder} is not a folder.`);
|
||||
return { exit: 1 };
|
||||
}
|
||||
saveState({ lastFolder: folder });
|
||||
cwd = folder;
|
||||
console.log(`Opening Plan2Code in ${c.cyan(folder)}`);
|
||||
} else {
|
||||
cwd = choice.dir;
|
||||
if (cwd !== process.cwd()) {
|
||||
// A recent folder can be deleted between the menu listing it and the pick.
|
||||
if (!isDirectory(cwd)) {
|
||||
console.error(`${ce.red('plan2code:')} ${cwd} is not a folder.`);
|
||||
return { exit: 1 };
|
||||
}
|
||||
console.log(`Opening Plan2Code in ${c.cyan(cwd)}`);
|
||||
}
|
||||
}
|
||||
if (!(await confirmProject(cwd))) return { exit: 0 };
|
||||
recordFolder(cwd);
|
||||
return { cwd };
|
||||
}
|
||||
|
||||
@@ -1726,4 +1847,4 @@ async function launch() {
|
||||
// Run only when invoked directly; requiring the file (the tests do) is load-only.
|
||||
if (require.main === module) launch();
|
||||
|
||||
module.exports = { bypassQuestion, normalizeAgents, buildArgs, parseRegQueryValue, expandPercentVars, addSavedWindowsPath, customClis, resolveCustomCommand, runnableClis, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject, lastUsedNotice, leadInstall, installLine, findConsoleMjs, runSetupFlow, projectCwd };
|
||||
module.exports = { bypassQuestion, normalizeAgents, buildArgs, parseRegQueryValue, expandPercentVars, addSavedWindowsPath, customClis, resolveCustomCommand, runnableClis, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject, lastUsedNotice, leadInstall, installLine, findConsoleMjs, runSetupFlow, projectCwd, sameFolder, readRecent, pushRecent, listRecent, recordFolder, folderMenuRows, folderMenuPick };
|
||||
Reference in new issue
Block a user