Rebuild the desktop app's top bar and drop its context meter

AI Assisted
This commit is contained in:
jparkerweb committed 2026-10-25 12:50:11 -07:00
1 parent 442904e6f2
commit efc96e91c2
15 files changed
+606 -1247

No files matched your search

+9 -3
View File
@@ -6,20 +6,26 @@ All notable changes to Plan2Code will be documented in this file.
### ✨ Added
- **desktop app**: a cross-platform app (Rust, Tauri) that is the single window for working with an AI agent. It opens the Plan2Code dashboard as its main surface, runs Claude Code, Devin or Codex in a pseudo-terminal panel it owns, and adds a **Restart** button that replaces the agent with a fresh one on a brief the app builds from its own record of the session, with the in-progress work and recent activity carried over. Every console page (Ask, Workspace, Help, Preferences, Git, Notebook) opens inside the app, not a separate browser tab.
- **desktop app**: a context meter in the bar reads how full the running agent's context window is: a real-ish number from Claude's own transcript or Codex's session log (labeled best-effort, since both formats are undocumented), a clearly labeled estimate for Devin or any agent with no documented signal, and a gentle nudge near 70% suggesting Restart, shown only for a real or best-effort reading.
- **desktop app**: **Update skills** in the bar brings the installed skills level with the app from the exact release the app ships, with live progress and a **Restart the console** offer once it finishes; an app older than the installed skills says so instead of trying to fix it by updating skills again.
- **desktop app**: a cross-platform app (Rust, Tauri) that is the single window for working with an AI agent. It opens the Plan2Code dashboard as its main surface, runs Claude Code, Devin or Codex in a pseudo-terminal panel it owns, and adds a **New Session** button that replaces the agent with a fresh one on a brief the app builds from its own record of the session, with the in-progress work and recent activity carried over. Every console page (Ask, Workspace, Help, Preferences, Git, Notebook) opens inside the app, not a separate browser tab.
- **desktop app**: **Update skills** in the bar brings the installed skills level with the app from the exact release the app ships, with live progress and a **Reconnect the console** offer once it finishes; an app older than the installed skills says so instead of trying to fix it by updating skills again.
- **desktop app**: the window's own title (and so its taskbar entry) now reads **Plan2Code - <folder name>** once a project is open, instead of a plain **Plan2Code** every window shares; two or more windows on different projects read apart without opening each one to check.
- `plan2code` opens the app automatically when a desktop is available; `plan2code --classic` (or no desktop, e.g. over SSH) keeps today's terminal-only flow unchanged, and the installer brings the app in alongside the skills and the command.
### 🔧 Changed
- **launcher**: `plan2code` no longer treats an SSH or service session on macOS or Windows as having a desktop, and asks before opening a folder that looks like it is not a project (no `.git`, `AGENTS.md` or `specs/`).
- **desktop app**: the app's own bar no longer repeats the open page as a second "page: " label; the console's own bar, inside the window, already names it. The web console now knows when the agent driving it is the desktop app (the same signal that already routed `open` to the app's window) and, only there, drops advice that assumed a plain terminal: its session meter, the finished-step guide and the dashboard's red-session banner point at the app's own **New Session** button instead of a command to paste into a new conversation; its own "update available" banner, a copy-pasted shell command, never shows, since **Update skills** already covers it in one click with no shell involved; and a slash command still offered to continue a step says to paste it into the app's terminal panel, which runs the real agent CLI, rather than "a new conversation" that does not exist there. Running a plain terminal is unchanged.
- **desktop app**: dropped the bar's own context-window meter and its restart nudge, front and back: a second, separately-tuned gauge beside the console's own Session meter (how much plan2code work this session has done) read as a duplicate of it, so there is now just the one, and it already points at New Session under the app (see above). The `agent_context` command, the Claude/Codex transcript readers behind it, and the context-nudge setting it read are removed from the Rust side too, not just unwired in the page. Every button that reconnects the console (after it stops, or after Update skills) is now labeled **Reconnect the console**, replacing the earlier mix of "Restart the console" and "Start it again" for the same action, and only one shows at a time.
- **web console**: Help's "When an update is out" line now knows when it is read inside the app too: there, it names **Update skills** in the bar instead of describing the dashboard's UPDATE AVAILABLE banner and a terminal command, since that banner never shows under the app and the command has no terminal to run in.
- **desktop app**: the top bar's **Restart** button is now **New Session**, and every place the console names it under the app (the session meter, the dashboard's red-session banner, the finished-step guide, the Welcome tip, Help's Ask and Finishing topics, the handoff copy button's description) says so too; the meter's own advice under the app is a single **Start a New Session** button in the user's highlight colour. Its confirmation no longer claims "What it was doing is not saved" (not always true).
- **desktop app**: the agent no longer prints the console's web address in the terminal panel, since the page is already in the window beside it: `terminalLine` under the app points at the dashboard instead, and the agent contract says to give no link there.
- **desktop app**: the console's "Not running... type **continue**" line makes **continue** a button under the app, which types `continue` and Enter into the agent's terminal panel for you; the session meter's **Start a New Session** button presses the bar's own New Session (its confirmation included), replacing a "Press New Session at the top of the window" sentence now that the press works from there.
- **desktop app**: **New Session** now starts the fresh agent on a new console session, so the session meter starts over at green. Before, the fresh agent joined the window's old session, and the meter stayed red after the very press it asks for. The brief of where you were is still written from the old session first, and the old console shuts itself down once the window moves on.
- **web console**: the **Wrapping up** dialog after **Stop session** no longer closes itself when the stop lands: it turns into **Done**, with every step ticked, and stays up until you close it, so someone who stepped away comes back to an answer. Its "you can close the window/tab if you need to" line is gone.
- **web console**: a plan's **Build order** card has a **Combine phases** button beside **No changes**. One click fills the box with a request to merge phases where possible while keeping each to a clear concern. It shows only in Plan and Revise plan, where the breakdown is phases.
- **web console**: Help now reads right in the desktop app throughout, not just in the topics fixed before: what this page is and how long it runs, the troubleshooting table and its diagram, scroll memory, drafts, the session meter's red advice, Ask's "no agent" line and Privacy's link and address notes all name the app's window, its terminal panel, **New Session** and **Reconnect the console** instead of a browser tab, a link or a new conversation. The status line's approval hint says "the terminal panel" there too. In a browser, Help is unchanged.
- **desktop app**: the top bar's buttons now look like the console's own: rounded, quiet until hovered, then in your highlight color from User Preferences (the app keeps it for the next launch), with **New Session** outlined in it as the likely next step.
- **desktop app**: the top bar is rebuilt around two menus and one next step. The project shows as its folder name, with the full path and **Change project** in its menu; **New Session** always sits just left of the agent's menu, which carries a state dot, an amber **checks off** badge in place of the "Permission checks are off for ..." sentence, and **Change agent** once the agent has ended. The console's and the skills' messages share one slot at the right end that shows the most pressing step with its button (**Reconnect the console**, **Update skills**) and "+N more" for the rest, so the bar no longer overflows when several things go wrong at once. The repeated "Plan2Code" label, the full path, the "agent:" prefix and the long "Nothing starts until you press New Session" line are gone.
## v2.11.1
+34 -10
View File
@@ -1,7 +1,7 @@
# The Plan2Code desktop app
One window for working with an AI agent. The app opens the Plan2Code dashboard as its main surface,
runs your agent (Claude Code, Devin or Codex) in a terminal panel it owns, and has a **Restart**
runs your agent (Claude Code, Devin or Codex) in a terminal panel it owns, and has a **New Session**
button that replaces the agent with a fresh one on a brief the app builds from its own record of the
session. The fresh agent gets a console session of its own, so the Session meter starts over with it.
It is an addition: `/plan2code` typed inside an agent works exactly as before, with or
@@ -60,18 +60,42 @@ The first time the app opens on a folder, a checklist confirms Node, the agent C
folder and the skills version before anything else shows; a later launch skips straight past it.
A **launch card** then asks which agent (Claude, Devin or Codex), model and effort (Claude and Codex
only) to start on. Permission checks off is its own tick, unchanged unless you choose it (Restart
only) to start on. Permission checks off is its own tick, unchanged unless you choose it (New Session
keeps whatever you picked); a CLI the app cannot find is named, with how to install it, instead of
just being greyed out. The card is skipped when the launcher already passed an agent to start.
Once an agent is running, a slim top bar holds the project name, **Restart** and **Change project**,
and a status strip beneath it shows the page the agent opened (not only the dashboard — every console
page, including Ask, Workspace, Notebook, Help, Preferences and Git, opens inside the window), the
agent's name and status, a context meter once one is readable, and the permission mode in use. 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** asks first if an agent is running,
then stops it and the console before opening the new folder.
The window's own title (and so its taskbar entry) reads **Plan2Code - <folder name>** once a
project is open, so two or more windows on different projects read apart without opening each one
to check.
A slim top bar reads, left to right: the project folder's name, a menu holding its full path and
**Change project**; **New Session**, whenever an agent exists; the agent's own menu, with a dot for its
state, an amber **checks off** badge while permission checks are off, and **Change agent** once it has
ended; a short line (why the agent ended, a New Session's brief, or what went wrong); and, at the right
end, the one next step for the console or the skills when there is one (**Reconnect the console**,
**Update skills**), with "+N more" if anything else is waiting behind it. The console itself, opening inside the
window (not only the dashboard — every console page, including Ask, Workspace, Notebook, Help,
Preferences and Git), already shows which page is open and its own **Session** meter (how much plan2code
work this session has done) in its own bar, so the app's bar does not repeat either. That Session meter
is the one place for "is this session getting long" under the app, too: the app does not keep a second,
separate context-window meter of its own, so there is only ever one gauge to read and only one place its
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.
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
"Start it again" in another for the same action — and only one shows at a time.
The console also knows when it is running inside the app (the agent it talks to carries that signal):
its session meter, the "Before you close this" guide on a finished step, and the dashboard's red-session
banner all point at the app's own **New Session** button instead of a command to paste into a new
conversation, since New Session already does that in one click; and the console's own "update available"
banner never shows, since the app's **Update skills** button (below) already covers it with no shell
involved. A slash command still offered to continue a step (such as `/plan2code-4-finalize`) stays
exactly as it would in a terminal: paste it into the app's own terminal panel, which runs the real
agent CLI.
## Keep it up to date
+20 -19
View File
@@ -26,7 +26,7 @@ failure.
the `plan2code` command are still installed
- [ ] `plan2code` in a project asks for the agent and model, then opens the app on that folder
- [ ] The agent and model picked in the launcher are the ones the app starts at once, with no
launch card or checklist shown first, and Restart keeps them
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
@@ -44,8 +44,11 @@ failure.
- [ ] The dashboard shows in the frame and the terminal panel is visible beneath it
- [ ] Resizing the window keeps both usable; dragging the handle resizes the panel
- [ ] The bar shows the project folder and the context meter; the permission note appears only
while an agent started with checks off is running, never otherwise
- [ ] The bar shows the project folder; the permission note appears only while an agent started
with checks off is running, never otherwise
- [ ] The OS window title (and so the taskbar entry) reads **Plan2Code - <folder name>**,
not just **Plan2Code**; open a second window on a different folder and confirm they read
apart in the taskbar without needing to restore either one
- [ ] The first run (no `firstRunDone` saved yet) shows the checklist (Node, an agent CLI, the
project folder, the skills version) before the launch card; a later launch goes straight to
the launch card
@@ -58,14 +61,17 @@ failure.
before collapsing is remembered
- [ ] Collapse the terminal (or shrink it small), let the agent go quiet for a while mid-answer: the
"agent may need you" badge appears on the strip; expanding it clears the badge
- [ ] **Change project** in the top bar, with an agent running: it asks first, then the folder
- [ ] 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; cancelling the picker leaves the running agent and its project untouched
- [ ] 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
from where it was, not blank, and the dashboard reconnects to the same session
- [ ] When the app and the installed skills differ in version, the bar offers **Update skills**, and
nothing updates until it is pressed
- [ ] When the app and the installed skills differ in version, the bar's right end offers **Update
skills**, and nothing updates until it is pressed; with the console stopped as well, Reconnect
the console shows first and "+1 more" names the update
## The terminal panel, with each real agent (each system)
@@ -79,26 +85,21 @@ Do each of Claude Code, Devin and Codex for a few minutes:
- [ ] A line with Unicode and emoji
- [ ] Select text in the terminal: it copies on its own; Ctrl+Shift+C (Windows, Linux) or Cmd+C
(macOS) copies the selection too; Ctrl+V / Cmd+V pastes
- [ ] Exiting the agent: the bar says it ended and offers Restart
- [ ] Exiting the agent: the agent menu reads "ended" with the reason beside it, and New Session stays
just left of it
## Agent lifecycle
- [ ] Start, then **Restart**: it confirms once, then a fresh agent starts on the same agent, model,
effort and permission mode, and the dashboard shows the pick-up chip with a brief that
matches the session
- [ ] An agent that ends by itself leaves the app asking nothing until Restart or **Change agent**
is pressed; Change agent reopens the launch card with a real choice to make again
- [ ] Start, then **New Session**: it confirms once, with no claim about unsaved
work, then a fresh agent starts on the same agent, model, effort and permission mode, and the
dashboard shows the pick-up chip with a brief that matches the session
- [ ] An agent that ends by itself leaves the app asking nothing until New Session or **Change agent**
(in the agent menu) is pressed; Change agent reopens the launch card with a real choice to make again
- [ ] Closing the window while an agent runs asks first, and "no" keeps the window open
- [ ] Cmd+Q on macOS asks the same
- [ ] Windows only: start a CLI installed through npm (a `.cmd` shim), then Restart; check Task
- [ ] Windows only: start a CLI installed through npm (a `.cmd` shim), then New Session; check Task
Manager and confirm no leftover `node.exe` (or the CLI's own process) is left running
## Context meter
- [ ] Claude Code and Codex: the meter moves during a long session and the nudge appears once
- [ ] Devin: the meter is labeled as an estimate
- [ ] `~/.claude/settings.json` and your own status line are byte-identical before and after a session
## Standalone path
- [ ] `/plan2code` typed inside an agent with the app closed opens the dashboard exactly as before
@@ -1,7 +1,7 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Permissions for the main window: its own commands need none, so only listening to the page events the app sends",
"description": "Permissions for the main window: its own commands need none, so only listening to the page events the app sends, plus setting the window's own title to the open project's name",
"windows": ["main"],
"permissions": ["core:event:allow-listen", "core:event:allow-unlisten"]
"permissions": ["core:event:allow-listen", "core:event:allow-unlisten", "core:window:allow-set-title"]
}
@@ -1,228 +0,0 @@
//! Claude's context, read from its own transcript: the last `assistant` message's
//! token usage, as a fraction of its context window. Claude Code writes one file
//! per session under `~/.claude/projects/<cwd, every non-alphanumeric character
//! replaced with `-`>/<session id>.jsonl` (relocatable via `CLAUDE_CONFIG_DIR`),
//! and names it after the session's own id, so a project folder's newest file
//! since the agent started is this run's transcript (Task 10.1's spike; the
//! same approach `codex.rs` uses for Codex's log). The entry format is
//! undocumented ("internal and may change between versions" per Claude's own
//! docs), so a usable reading is `BestEffort`, never `Real`. An unreadable line
//! is skipped, and a transcript with no usable line, or no transcript at all,
//! is `Unknown`.
use std::fs::{self, File};
use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use serde_json::Value;
use super::{ContextReader, ContextReading};
/// How much of a transcript's end is read; the newest usage is near the end.
pub const TAIL_BYTES: u64 = 256 * 1024;
pub struct ClaudeReader {
pub projects_dir: PathBuf,
pub folder: PathBuf,
/// Only a transcript written at or after this moment belongs to the running agent.
pub since: SystemTime,
/// The context window to read the usage against (`super::window_for`).
pub window: u64,
}
impl ContextReader for ClaudeReader {
fn read(&self) -> ContextReading {
match newest_transcript(&self.projects_dir.join(encode(&self.folder)), self.since) {
Some(file) => reading_from_file(&file, self.window),
None => ContextReading::Unknown,
}
}
}
/// `folder` with every non-alphanumeric character replaced by `-`, the way
/// Claude Code names a project's transcripts directory.
fn encode(folder: &Path) -> String {
folder.to_string_lossy().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect()
}
/// The newest `*.jsonl` file directly under `dir` that was written at or after `since`.
fn newest_transcript(dir: &Path, since: SystemTime) -> Option<PathBuf> {
let entries = fs::read_dir(dir).ok()?;
let mut newest: Option<(SystemTime, PathBuf)> = None;
for entry in entries.flatten() {
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
continue;
}
let Ok(modified) = entry.metadata().and_then(|m| m.modified()) else { continue };
if modified < since {
continue;
}
if newest.as_ref().is_none_or(|(best, _)| modified > *best) {
newest = Some((modified, path));
}
}
newest.map(|(_, path)| path)
}
/// The percent of `window` the last usable `assistant` usage line in `text` used.
pub fn reading_from_text(text: &str, window: u64) -> ContextReading {
for line in text.lines().rev() {
if let Some(percent) = percent_from_line(line, window) {
return ContextReading::BestEffort { percent };
}
}
ContextReading::Unknown
}
fn percent_from_line(line: &str, window: u64) -> Option<u8> {
if window == 0 {
return None;
}
let value: Value = serde_json::from_str(line).ok()?;
if value.get("type")?.as_str()? != "assistant" {
return None;
}
let usage = value.get("message")?.get("usage")?;
let input = usage.get("input_tokens")?.as_u64()?;
let cache_read = usage.get("cache_read_input_tokens").and_then(Value::as_u64).unwrap_or(0);
let cache_creation = usage.get("cache_creation_input_tokens").and_then(Value::as_u64).unwrap_or(0);
let used = input.saturating_add(cache_read).saturating_add(cache_creation);
Some((used.saturating_mul(100) / window).min(100) as u8)
}
/// Reads the end of `file`. A file that cannot be opened or read is `Unknown`.
fn reading_from_file(file: &Path, window: u64) -> ContextReading {
let Ok(mut handle) = File::open(file) else { return ContextReading::Unknown };
let Ok(len) = handle.metadata().map(|m| m.len()) else { return ContextReading::Unknown };
if len > TAIL_BYTES && handle.seek(SeekFrom::Start(len - TAIL_BYTES)).is_err() {
return ContextReading::Unknown;
}
let mut bytes = Vec::new();
if handle.read_to_end(&mut bytes).is_err() {
return ContextReading::Unknown;
}
// The first line of a partial tail is cut short; it fails to parse and is skipped.
reading_from_text(&String::from_utf8_lossy(&bytes), window)
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
const GOOD: &str = r#"{"type":"assistant","message":{"usage":{"input_tokens":2,"cache_creation_input_tokens":724,"cache_read_input_tokens":205907}}}"#;
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("plan2code-claude-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
dir
}
fn epoch_plus(secs: u64) -> SystemTime {
SystemTime::UNIX_EPOCH + Duration::from_secs(secs)
}
fn write_transcript(dir: &Path, name: &str, body: &str, modified: SystemTime) -> PathBuf {
fs::create_dir_all(dir).unwrap();
let file = dir.join(format!("{name}.jsonl"));
fs::write(&file, body).unwrap();
File::options().write(true).open(&file).unwrap().set_modified(modified).unwrap();
file
}
#[test]
fn the_last_assistant_usage_gives_the_percent_of_the_window() {
assert_eq!(reading_from_text(GOOD, 206_633), ContextReading::BestEffort { percent: 100 });
assert_eq!(reading_from_text(GOOD, 1_000_000), ContextReading::BestEffort { percent: 20 });
}
#[test]
fn a_normal_transcript_is_read_from_the_newest_assistant_line() {
let early = r#"{"type":"assistant","message":{"usage":{"input_tokens":2,"cache_creation_input_tokens":0,"cache_read_input_tokens":99998}}}"#;
let text = format!("{early}\n{GOOD}");
assert_eq!(reading_from_text(&text, 206_633), ContextReading::BestEffort { percent: 100 });
}
#[test]
fn a_partial_last_line_is_skipped_in_favour_of_the_line_before_it() {
let text = format!("{GOOD}\n{{\"type\":\"assistant\",\"mess");
assert_eq!(reading_from_text(&text, 1_000_000), ContextReading::BestEffort { percent: 20 });
}
#[test]
fn non_assistant_and_malformed_lines_are_skipped() {
let text = format!("not json\n{{bad\n{{\"type\":\"user\",\"message\":{{}}}}\n{GOOD}");
assert_eq!(reading_from_text(&text, 1_000_000), ContextReading::BestEffort { percent: 20 });
}
#[test]
fn a_line_with_no_usable_usage_is_unknown() {
assert_eq!(reading_from_text("", 1_000_000), ContextReading::Unknown);
assert_eq!(reading_from_text(r#"{"type":"assistant","message":{}}"#, 1_000_000), ContextReading::Unknown);
assert_eq!(reading_from_text(GOOD, 0), ContextReading::Unknown);
}
#[test]
fn a_missing_file_is_unknown() {
let reader = ClaudeReader {
projects_dir: temp_dir("missing").join("projects"),
folder: PathBuf::from(r"C:\git\project"),
since: epoch_plus(0),
window: 200_000,
};
assert_eq!(reader.read(), ContextReading::Unknown);
}
#[test]
fn a_long_transcript_is_read_from_its_end() {
let dir = temp_dir("long");
let file = write_transcript(&dir, "long", &format!("{}\n{GOOD}", "x".repeat(TAIL_BYTES as usize + 100)), epoch_plus(0));
assert_eq!(reading_from_file(&file, 206_633), ContextReading::BestEffort { percent: 100 });
let _ = fs::remove_dir_all(dir);
}
#[test]
fn the_newest_transcript_for_this_folder_is_read() {
let root = temp_dir("newest");
let projects = root.join("projects");
let dir = projects.join(encode(Path::new(r"C:\git\project")));
write_transcript(&dir, "a-old", GOOD, epoch_plus(100));
let newest = write_transcript(&dir, "b-new", &GOOD.replace("205907", "500000"), epoch_plus(200));
let reader = ClaudeReader { projects_dir: projects, folder: PathBuf::from(r"C:\git\project"), since: epoch_plus(0), window: 1_000_000 };
assert_eq!(reader.read(), ContextReading::BestEffort { percent: 50 });
let _ = fs::remove_dir_all(root);
let _ = newest;
}
#[test]
fn a_rotated_file_is_read_from_the_new_one() {
let root = temp_dir("rotated");
let projects = root.join("projects");
let dir = projects.join(encode(Path::new(r"C:\git\project")));
write_transcript(&dir, "first", GOOD, epoch_plus(100));
let reader = ClaudeReader { projects_dir: projects.clone(), folder: PathBuf::from(r"C:\git\project"), since: epoch_plus(0), window: 1_000_000 };
assert_eq!(reader.read(), ContextReading::BestEffort { percent: 20 });
write_transcript(&dir, "second", &GOOD.replace("205907", "500000"), epoch_plus(200));
assert_eq!(reader.read(), ContextReading::BestEffort { percent: 50 });
let _ = fs::remove_dir_all(root);
}
#[test]
fn a_transcript_from_before_the_agent_started_is_ignored() {
let root = temp_dir("since");
let projects = root.join("projects");
let dir = projects.join(encode(Path::new(r"C:\git\project")));
write_transcript(&dir, "old", GOOD, epoch_plus(100));
let reader = ClaudeReader { projects_dir: projects, folder: PathBuf::from(r"C:\git\project"), since: epoch_plus(200), window: 1_000_000 };
assert_eq!(reader.read(), ContextReading::Unknown);
let _ = fs::remove_dir_all(root);
}
#[test]
fn the_cwd_is_encoded_the_way_claude_code_names_its_projects_folder() {
assert_eq!(encode(Path::new(r"C:\git\plan2code")), "C--git-plan2code");
}
}
@@ -1,315 +0,0 @@
//! Codex's context, read from its session log. Codex writes each run to
//! `sessions/YYYY/MM/DD/rollout-*.jsonl` under its home folder (`CODEX_HOME`,
//! or `~/.codex`). The app reads the newest log for its project folder, from
//! its end, and never writes there. The format is undocumented, so the reading
//! is `BestEffort`: an unrecognised line is skipped, and a log with no usable
//! line, or no log at all, is `Unknown`. Nothing here is an error.
use std::fs::{self, File};
use std::io::{BufRead, BufReader, Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use serde_json::Value;
use super::{ContextReader, ContextReading};
/// How much of a log's end is read. The newest token count is near the end,
/// so a long log is never read whole.
pub const TAIL_BYTES: u64 = 256 * 1024;
/// How deep the sessions folder is searched: year, month, day, file.
const SEARCH_DEPTH: u32 = 4;
pub struct CodexReader {
pub sessions_dir: PathBuf,
pub folder: PathBuf,
/// Only logs written at or after this moment belong to the running agent.
pub since: SystemTime,
}
impl ContextReader for CodexReader {
fn read(&self) -> ContextReading {
match newest_log(&self.sessions_dir, &self.folder, self.since) {
Some(file) => reading_from_file(&file),
None => ContextReading::Unknown,
}
}
}
/// The percent of the model's window the newest request used, from the last
/// usable `token_count` line in `text`.
pub fn reading_from_text(text: &str) -> ContextReading {
for line in text.lines().rev() {
if let Some(percent) = percent_from_line(line) {
return ContextReading::BestEffort { percent };
}
}
ContextReading::Unknown
}
fn percent_from_line(line: &str) -> Option<u8> {
let value: Value = serde_json::from_str(line).ok()?;
if value.get("type")?.as_str()? != "event_msg" {
return None;
}
let payload = value.get("payload")?;
if payload.get("type")?.as_str()? != "token_count" {
return None;
}
let info = payload.get("info")?;
let used = info.get("last_token_usage")?.get("input_tokens")?.as_u64()?;
let window = info.get("model_context_window")?.as_u64()?;
if window == 0 {
return None;
}
Some((used.saturating_mul(100) / window).min(100) as u8)
}
/// Reads the end of `file`. A file that cannot be opened or read is `Unknown`.
fn reading_from_file(file: &Path) -> ContextReading {
let Ok(mut handle) = File::open(file) else { return ContextReading::Unknown };
let Ok(len) = handle.metadata().map(|m| m.len()) else { return ContextReading::Unknown };
if len > TAIL_BYTES && handle.seek(SeekFrom::Start(len - TAIL_BYTES)).is_err() {
return ContextReading::Unknown;
}
let mut bytes = Vec::new();
if handle.read_to_end(&mut bytes).is_err() {
return ContextReading::Unknown;
}
// The first line of a partial tail is cut short; it fails to parse and is skipped.
reading_from_text(&String::from_utf8_lossy(&bytes))
}
/// The newest log under `sessions_dir` that was written since `since` and
/// whose first line names `folder` as its working directory.
pub fn newest_log(sessions_dir: &Path, folder: &Path, since: SystemTime) -> Option<PathBuf> {
let mut logs = Vec::new();
collect_logs(sessions_dir, SEARCH_DEPTH, since, &mut logs);
let mut recent: Vec<(SystemTime, PathBuf)> = logs
.into_iter()
.filter_map(|file| {
let modified = fs::metadata(&file).ok()?.modified().ok()?;
(modified >= since).then_some((modified, file))
})
.collect();
recent.sort_by(|a, b| b.0.cmp(&a.0));
recent.into_iter().map(|(_, file)| file).find(|file| names_folder(file, folder))
}
// A day folder not touched since `since` holds no log of this run (creating a
// log updates its own folder, and only that one), so it is skipped: the walk
// stays short however many old logs Codex has kept. Year and month folders are
// always entered, as their own times say nothing about the logs below them.
// `depth` is 2 while the entries of a month folder are listed.
fn collect_logs(dir: &Path, depth: u32, since: SystemTime, out: &mut Vec<PathBuf>) {
let Ok(entries) = fs::read_dir(dir) else { return };
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
let touched = fs::metadata(&path).and_then(|m| m.modified()).is_ok_and(|m| m >= since);
if depth > 0 && (depth != 2 || touched) {
collect_logs(&path, depth - 1, since, out);
}
} else if is_rollout(&path) {
out.push(path);
}
}
}
fn is_rollout(path: &Path) -> bool {
path.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name.starts_with("rollout-") && name.ends_with(".jsonl"))
}
/// True when the log's first line is a `session_meta` for `folder`.
fn names_folder(file: &Path, folder: &Path) -> bool {
let Ok(handle) = File::open(file) else { return false };
let mut first = String::new();
if BufReader::new(handle).read_line(&mut first).is_err() {
return false;
}
let Ok(value) = serde_json::from_str::<Value>(&first) else { return false };
if value.get("type").and_then(Value::as_str) != Some("session_meta") {
return false;
}
value
.get("payload")
.and_then(|payload| payload.get("cwd"))
.and_then(Value::as_str)
.is_some_and(|cwd| same_folder(cwd, folder))
}
/// Compares two folder paths the way Windows does: case, slash style and a
/// trailing separator do not count.
fn same_folder(cwd: &str, folder: &Path) -> bool {
let norm = |s: &str| {
s.trim_start_matches(r"\\?\").trim_end_matches(['\\', '/']).replace('/', "\\").to_ascii_lowercase()
};
norm(cwd) == norm(&folder.to_string_lossy())
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
const GOOD: &str = r#"{"type":"event_msg","payload":{"type":"token_count","info":{"last_token_usage":{"input_tokens":21839},"model_context_window":258400}}}"#;
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("plan2code-codex-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
dir
}
// A log whose first line names `cwd`, then `body` lines, dated `modified`.
fn write_log(sessions: &Path, name: &str, cwd: &str, body: &str, modified: SystemTime) -> PathBuf {
let day = sessions.join("2026").join("10").join("22");
fs::create_dir_all(&day).unwrap();
let file = day.join(format!("rollout-{name}.jsonl"));
let meta = serde_json::json!({ "type": "session_meta", "payload": { "cwd": cwd } });
fs::write(&file, format!("{meta}\n{body}")).unwrap();
// `meta` is a JSON value, so its text is escaped for the log.
fs::File::options().write(true).open(&file).unwrap().set_modified(modified).unwrap();
file
}
fn epoch_plus(secs: u64) -> SystemTime {
SystemTime::UNIX_EPOCH + Duration::from_secs(secs)
}
#[test]
fn the_last_token_count_gives_the_percent_of_the_window() {
assert_eq!(reading_from_text(GOOD), ContextReading::BestEffort { percent: 8 });
}
#[test]
fn unrecognised_and_malformed_lines_are_skipped() {
let text = format!("not json\n{{bad\n{GOOD}\n{}", r#"{"type":"event_msg","payload":{"type":"other"}}"#);
assert_eq!(reading_from_text(&text), ContextReading::BestEffort { percent: 8 });
}
#[test]
fn a_log_with_no_usable_line_is_unknown() {
assert_eq!(reading_from_text(""), ContextReading::Unknown);
assert_eq!(reading_from_text("garbage\n{}"), ContextReading::Unknown);
let zero_window = GOOD.replace("258400", "0");
assert_eq!(reading_from_text(&zero_window), ContextReading::Unknown);
}
#[test]
fn an_early_token_count_without_info_is_skipped() {
let early = r#"{"type":"event_msg","payload":{"type":"token_count","info":null}}"#;
assert_eq!(reading_from_text(&format!("{GOOD}\n{early}")), ContextReading::BestEffort { percent: 8 });
assert_eq!(reading_from_text(early), ContextReading::Unknown);
}
#[test]
fn only_a_session_meta_with_this_folder_names_it() {
let root = temp_dir("names");
let folder = Path::new(r"C:\git\project");
let verbatim = serde_json::json!({ "type": "session_meta", "payload": { "cwd": r"\\?\C:\git\project" } });
let cases = [
("not json".to_string(), false),
(r#"{"type":"other","payload":{"cwd":"x"}}"#.to_string(), false),
(r#"{"type":"session_meta","payload":{}}"#.to_string(), false),
(verbatim.to_string(), true),
];
for (i, (line, expected)) in cases.iter().enumerate() {
let file = root.join(format!("rollout-{i}.jsonl"));
fs::write(&file, format!("{line}\n{GOOD}\n")).unwrap();
assert_eq!(names_folder(&file, folder), *expected, "{line}");
}
let _ = fs::remove_dir_all(root);
}
#[test]
fn a_long_log_is_read_from_its_end() {
let dir = temp_dir("long");
let file = dir.join("long.jsonl");
fs::write(&file, format!("{}\n{GOOD}\n", "x".repeat(TAIL_BYTES as usize + 100))).unwrap();
assert_eq!(reading_from_file(&file), ContextReading::BestEffort { percent: 8 });
let _ = fs::remove_dir_all(dir);
}
#[test]
fn a_missing_log_is_unknown() {
assert_eq!(reading_from_file(Path::new("no-such-dir/rollout-x.jsonl")), ContextReading::Unknown);
}
#[test]
fn a_missing_sessions_folder_is_unknown() {
let reader = CodexReader {
sessions_dir: temp_dir("none").join("sessions"),
folder: PathBuf::from(r"C:\git\project"),
since: epoch_plus(0),
};
assert_eq!(reader.read(), ContextReading::Unknown);
}
#[test]
fn the_newest_log_for_this_folder_is_read() {
let root = temp_dir("newest");
let sessions = root.join("sessions");
write_log(&sessions, "a-old", r"C:\git\project", GOOD, epoch_plus(100));
write_log(&sessions, "b-other", r"C:\git\elsewhere", GOOD, epoch_plus(300));
let newest = write_log(&sessions, "c-new", r"c:\git\project\", &GOOD.replace("21839", "129200"), epoch_plus(200));
assert_eq!(newest_log(&sessions, Path::new(r"C:\git\project"), epoch_plus(0)), Some(newest));
let _ = fs::remove_dir_all(root);
}
// Sets a folder's modified time; Windows needs the backup-semantics flag to open one.
fn set_dir_modified(dir: &Path, time: SystemTime) {
let mut options = fs::OpenOptions::new();
#[cfg(windows)]
{
use std::os::windows::fs::OpenOptionsExt;
options.write(true).custom_flags(0x0200_0000);
}
#[cfg(not(windows))]
options.read(true);
options.open(dir).unwrap().set_modified(time).unwrap();
}
#[test]
fn old_year_and_month_folders_do_not_hide_todays_log() {
let root = temp_dir("parents");
let sessions = root.join("sessions");
let log = write_log(&sessions, "today", r"C:\git\project", GOOD, epoch_plus(500));
// Creating a log touches only its day folder: the parents keep their old times.
set_dir_modified(&sessions.join("2026"), epoch_plus(10));
set_dir_modified(&sessions.join("2026").join("10"), epoch_plus(20));
assert_eq!(newest_log(&sessions, Path::new(r"C:\git\project"), epoch_plus(100)), Some(log));
// A day folder untouched since the agent started is skipped.
set_dir_modified(&sessions.join("2026").join("10").join("22"), epoch_plus(30));
assert_eq!(newest_log(&sessions, Path::new(r"C:\git\project"), epoch_plus(100)), None);
let _ = fs::remove_dir_all(root);
}
#[test]
fn a_log_from_before_the_agent_started_is_ignored() {
let root = temp_dir("since");
let sessions = root.join("sessions");
write_log(&sessions, "old", r"C:\git\project", GOOD, epoch_plus(100));
assert_eq!(newest_log(&sessions, Path::new(r"C:\git\project"), epoch_plus(200)), None);
let _ = fs::remove_dir_all(root);
}
#[test]
fn a_rotated_log_is_read_from_the_new_file() {
let root = temp_dir("rotated");
let sessions = root.join("sessions");
write_log(&sessions, "first", r"C:\git\project", GOOD, epoch_plus(100));
let reader = CodexReader {
sessions_dir: sessions.clone(),
folder: PathBuf::from(r"C:\git\project"),
since: epoch_plus(0),
};
assert_eq!(reader.read(), ContextReading::BestEffort { percent: 8 });
write_log(&sessions, "second", r"C:\git\project", &GOOD.replace("21839", "129200"), epoch_plus(200));
assert_eq!(reader.read(), ContextReading::BestEffort { percent: 50 });
let _ = fs::remove_dir_all(root);
}
}
-313
View File
@@ -1,313 +0,0 @@
//! How full the agent's context is. A reader says one of four things: a real
//! number (`Real`, documented by the agent and verified), a best-effort number
//! (`BestEffort`, works today but undocumented), a labeled estimate (`Estimate`)
//! or `Unknown`. Knows nothing about Tauri: the page asks for a reading and
//! draws what it gets.
pub mod claude;
pub mod codex;
use std::time::SystemTime;
use serde::Serialize;
use crate::agents::AgentKind;
/// A rough token window used only by the estimate, and by `claude.rs` when no
/// window comes with the signal it reads. The estimate is labeled as one
/// everywhere it is shown, so the exact size does not have to be right.
pub const ESTIMATE_TOKEN_WINDOW: u64 = 200_000;
/// The window for a model whose id names it a long-context one (Claude Code's
/// `[1m]` model id suffix).
pub const LONG_CONTEXT_TOKEN_WINDOW: u64 = 1_000_000;
/// The usual rule of thumb: about four characters of text per token.
pub const BYTES_PER_TOKEN: u64 = 4;
/// The context window to read `kind`'s usage against, or `None` when no
/// window is documented for it at all (Devin today), in which case a byte
/// count is not even a meaningful guess. `model` is the id the person picked,
/// if any; one naming a long-context model (Claude Code's `[1m]` suffix) gets
/// the bigger window.
pub fn window_for(kind: Option<AgentKind>, model: Option<&str>) -> Option<u64> {
match kind {
Some(AgentKind::Claude) | Some(AgentKind::Codex) => {
let long_context = model.is_some_and(|m| m.to_ascii_lowercase().contains("[1m]"));
Some(if long_context { LONG_CONTEXT_TOKEN_WINDOW } else { ESTIMATE_TOKEN_WINDOW })
}
Some(AgentKind::Devin) | None => None,
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum ContextReading {
Real { percent: u8 },
BestEffort { percent: u8 },
Estimate { percent: u8 },
Unknown,
}
/// One agent's way of reading its context. The estimate is the fallback every
/// agent has; a reader for an agent that documents its usage returns `Real`.
pub trait ContextReader {
fn read(&self) -> ContextReading;
}
/// The percent of `window` that `bytes` of text fills, capped at 100 and
/// rounded up: any text at all reads as at least 1 percent, never a flat 0
/// while the agent is working.
pub fn estimate_percent(bytes: u64, window: u64) -> u8 {
let tokens = bytes / BYTES_PER_TOKEN;
if tokens == 0 || window == 0 {
return 0;
}
tokens.saturating_mul(100).div_ceil(window).min(100) as u8
}
/// Where the output scan is inside a terminal control sequence.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum Escape {
#[default]
None,
Esc,
Intermediate,
Csi,
Osc,
OscEnd,
}
/// Counts the text an agent run has produced and been given. A new agent
/// (a new `generation`) starts the count over, and nothing is counted while
/// no agent runs.
#[derive(Debug, Default)]
pub struct Meter {
generation: u64,
seen: bool,
running: bool,
bytes: u64,
escape: Escape,
kind: Option<AgentKind>,
// When the current agent run began: its own log must be written after this.
since: Option<SystemTime>,
}
impl Meter {
/// Called on every agent state change: a new generation resets the count.
pub fn observe(&mut self, generation: u64, running: bool) {
if !self.seen || generation != self.generation {
self.generation = generation;
self.seen = true;
self.bytes = 0;
self.escape = Escape::None;
self.since = Some(SystemTime::now());
}
self.running = running;
}
pub fn set_kind(&mut self, kind: Option<AgentKind>) {
self.kind = kind;
}
pub fn kind(&self) -> Option<AgentKind> {
self.kind
}
pub fn since(&self) -> Option<SystemTime> {
self.since
}
/// Output from the agent, or text typed to it, while it runs.
/// Output from the agent. Terminal control sequences (colours, cursor
/// moves, window titles) are not text the agent holds, so only the visible
/// bytes count. A sequence cut across two chunks is still skipped whole.
pub fn add_output(&mut self, chunk: &[u8]) {
let mut visible = 0usize;
for &byte in chunk {
self.escape = match self.escape {
Escape::None => match byte {
0x1b => Escape::Esc,
b'\n' | b'\t' => {
visible += 1;
Escape::None
}
0x20..=0x7e | 0x80..=0xff => {
visible += 1;
Escape::None
}
_ => Escape::None,
},
Escape::Esc => match byte {
b'[' => Escape::Csi,
// OSC, and the other strings that end the same way: DCS, SOS, PM, APC.
b']' | b'P' | b'X' | b'^' | b'_' => Escape::Osc,
// `ESC ( B` and the like: intermediate bytes, then one final byte.
0x20..=0x2f => Escape::Intermediate,
_ => Escape::None,
},
Escape::Intermediate => match byte {
0x20..=0x2f => Escape::Intermediate,
_ => Escape::None,
},
Escape::Csi => match byte {
0x40..=0x7e => Escape::None,
_ => Escape::Csi,
},
Escape::Osc => match byte {
0x07 => Escape::None,
0x1b => Escape::OscEnd,
_ => Escape::Osc,
},
Escape::OscEnd => Escape::None,
};
}
self.add(visible);
}
/// Text typed to the agent, or any count of visible bytes.
pub fn add(&mut self, bytes: usize) {
if self.running {
self.bytes = self.bytes.saturating_add(bytes as u64);
}
}
pub fn reading(&self) -> ContextReading {
if !self.seen || !self.running {
return ContextReading::Unknown;
}
match window_for(self.kind, None) {
Some(window) => ContextReading::Estimate { percent: estimate_percent(self.bytes, window) },
None => ContextReading::Unknown,
}
}
}
impl ContextReader for Meter {
fn read(&self) -> ContextReading {
self.reading()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn no_text_is_zero_percent() {
assert_eq!(estimate_percent(0, ESTIMATE_TOKEN_WINDOW), 0);
}
#[test]
fn half_the_window_is_fifty_percent() {
assert_eq!(estimate_percent(ESTIMATE_TOKEN_WINDOW * BYTES_PER_TOKEN / 2, ESTIMATE_TOKEN_WINDOW), 50);
}
#[test]
fn more_than_the_window_caps_at_one_hundred() {
assert_eq!(estimate_percent(u64::MAX / 2, ESTIMATE_TOKEN_WINDOW), 100);
}
#[test]
fn any_text_at_all_rounds_up_instead_of_reading_zero() {
assert_eq!(estimate_percent(BYTES_PER_TOKEN, ESTIMATE_TOKEN_WINDOW), 1);
}
#[test]
fn a_long_context_model_gets_the_bigger_window() {
assert_eq!(window_for(Some(AgentKind::Claude), Some("claude-sonnet-4-5-20250929[1m]")), Some(LONG_CONTEXT_TOKEN_WINDOW));
assert_eq!(window_for(Some(AgentKind::Claude), Some("sonnet")), Some(ESTIMATE_TOKEN_WINDOW));
assert_eq!(window_for(Some(AgentKind::Claude), None), Some(ESTIMATE_TOKEN_WINDOW));
}
#[test]
fn devin_and_an_unknown_agent_have_no_basis_for_a_window() {
assert_eq!(window_for(Some(AgentKind::Devin), None), None);
assert_eq!(window_for(None, None), None);
}
fn counted(chunks: &[&[u8]]) -> u64 {
let mut meter = Meter::default();
meter.observe(1, true);
for chunk in chunks {
meter.add_output(chunk);
}
meter.bytes
}
#[test]
fn plain_text_counts_and_control_sequences_do_not() {
assert_eq!(counted(&[b"hello\n"]), 6);
assert_eq!(counted(&[b"\x1b[31mred\x1b[0m"]), 3);
assert_eq!(counted(&[b"\x1b[2K\x1b[1A\x1b[Gx"]), 1);
assert_eq!(counted(&[b"\x1b]0;a title\x07ok"]), 2);
assert_eq!(counted(&[b"\x1b]0;a title\x1b\\ok"]), 2);
}
#[test]
fn charset_and_string_sequences_are_skipped() {
assert_eq!(counted(&[b"\x1b(Bok"]), 2);
assert_eq!(counted(&[b"\x1bPq#0;2;0;0;0\x1b\\ok"]), 2);
}
#[test]
fn a_sequence_split_across_chunks_is_still_skipped() {
assert_eq!(counted(&[b"ab\x1b[3", b"1mcd"]), 4);
assert_eq!(counted(&[b"\x1b", b"[0m", b"z"]), 1);
}
#[test]
fn nothing_running_is_unknown() {
let mut meter = Meter::default();
assert_eq!(meter.reading(), ContextReading::Unknown);
meter.observe(1, false);
meter.add(10_000);
assert_eq!(meter.reading(), ContextReading::Unknown);
}
#[test]
fn a_running_agent_is_an_estimate_of_what_it_has_seen() {
let mut meter = Meter::default();
meter.set_kind(Some(AgentKind::Claude));
meter.observe(1, true);
meter.add((ESTIMATE_TOKEN_WINDOW * BYTES_PER_TOKEN / 4) as usize);
assert_eq!(meter.reading(), ContextReading::Estimate { percent: 25 });
}
#[test]
fn a_fresh_agent_starts_the_count_over() {
let mut meter = Meter::default();
meter.set_kind(Some(AgentKind::Claude));
meter.observe(1, true);
meter.add(400_000);
meter.observe(2, true);
assert_eq!(meter.reading(), ContextReading::Estimate { percent: 0 });
}
#[test]
fn a_stopped_agent_is_unknown_again() {
let mut meter = Meter::default();
meter.set_kind(Some(AgentKind::Claude));
meter.observe(1, true);
meter.add(400_000);
meter.observe(1, false);
assert_eq!(meter.reading(), ContextReading::Unknown);
}
#[test]
fn an_agent_with_no_documented_window_is_unknown_not_a_guess() {
let mut meter = Meter::default();
meter.set_kind(Some(AgentKind::Devin));
meter.observe(1, true);
meter.add(400_000);
assert_eq!(meter.reading(), ContextReading::Unknown);
}
#[test]
fn no_kind_set_yet_is_unknown_not_a_guess() {
let mut meter = Meter::default();
meter.observe(1, true);
meter.add(400_000);
assert_eq!(meter.reading(), ContextReading::Unknown);
}
}
-1
View File
@@ -5,7 +5,6 @@ pub mod agents;
pub mod announce;
pub mod brief;
pub mod console_supervisor;
pub mod context;
pub mod handoff;
pub mod node_check;
pub mod project;
+4 -96
View File
@@ -4,12 +4,9 @@
use std::sync::{Arc, Mutex};
use plan2code_app_lib::announce::AnnounceServer;
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentState, BeforeFresh, Sink};
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, BeforeFresh, Sink};
use plan2code_app_lib::agents::{self, AgentKind, PermissionMode};
use plan2code_app_lib::console_supervisor::{app_origin, origin_of, ConsoleSupervisor};
use plan2code_app_lib::context::claude::ClaudeReader;
use plan2code_app_lib::context::codex::CodexReader;
use plan2code_app_lib::context::{self, ContextReader, ContextReading, Meter};
use plan2code_app_lib::node_check;
use plan2code_app_lib::project::{self, ProjectDir};
use plan2code_app_lib::restart_brief;
@@ -32,8 +29,6 @@ struct AppState {
agent: Mutex<Option<Arc<AgentManager>>>,
// Where the agent's output and state changes go: the page's latest channel.
page: PageChannel,
// How much text the running agent has produced and been given, for the meter.
context: Arc<Mutex<Meter>>,
// This window's endpoint for pages the agent's `console.mjs open` wants shown here.
announce: Arc<Mutex<Option<AnnounceServer>>>,
// The Node version `main()` found before opening the window (Task 1.7 exits
@@ -83,19 +78,8 @@ fn windows_build() -> Option<u32> {
// Sends the agent's output as raw bytes and its state changes as JSON, on the
// page's latest channel. Nothing is sent while no page has registered one.
// The meter sees every output and state change too, page or no page.
fn page_sink(page: PageChannel, meter: Arc<Mutex<Meter>>) -> Sink {
fn page_sink(page: PageChannel) -> Sink {
Arc::new(move |event| {
if let Ok(mut meter) = meter.lock() {
match &event {
AgentEvent::Output(bytes) => meter.add_output(bytes),
AgentEvent::State(snapshot) => {
let running = snapshot.state == AgentState::Running;
meter.observe(snapshot.generation, running);
meter.set_kind(snapshot.kind);
}
}
}
let Ok(guard) = page.lock() else { return };
let Some(channel) = guard.as_ref() else { return };
let body = match event {
@@ -125,7 +109,7 @@ fn agent_for_project(state: &AppState) -> Result<Arc<AgentManager>, String> {
return Ok(Arc::clone(agent));
}
}
let sink = page_sink(Arc::clone(&state.page), Arc::clone(&state.context));
let sink = page_sink(Arc::clone(&state.page));
let agent = Arc::new(AgentManager::new(dir, sink));
agent.set_before_fresh(before_fresh_hook(state));
*guard = Some(Arc::clone(&agent));
@@ -217,9 +201,6 @@ fn agent_start(
#[tauri::command]
fn agent_input(state: State<'_, AppState>, data: String) -> Result<(), String> {
if let Ok(mut meter) = state.context.lock() {
meter.add(data.len());
}
match current_agent(&state) {
Some(agent) => agent.input(data.as_bytes()),
None => Ok(()),
@@ -239,14 +220,6 @@ fn agent_restart(state: State<'_, AppState>) -> Result<(), String> {
current_agent(&state).ok_or("no agent has been started")?.restart()
}
#[tauri::command]
fn agent_state(state: State<'_, AppState>) -> serde_json::Value {
match current_agent(&state) {
Some(agent) => serde_json::to_value(agent.snapshot()).unwrap_or_default(),
None => idle_snapshot_json(),
}
}
fn idle_snapshot_json() -> serde_json::Value {
serde_json::json!({ "state": "idle", "kind": null, "mode": null, "generation": 0 })
}
@@ -255,7 +228,7 @@ fn idle_snapshot_json() -> serde_json::Value {
/// agent survived it) registers its output channel here instead of through
/// `agent_start`, which would try to start a second agent. Replays the
/// current generation's recent output on it at once, so the terminal does
/// not come up blank, and returns the same shape `agent_state` does.
/// not come up blank.
#[tauri::command]
fn agent_reattach(state: State<'_, AppState>, on_output: Channel<InvokeResponseBody>) -> Result<serde_json::Value, String> {
let agent = current_agent(&state);
@@ -272,65 +245,6 @@ fn agent_reattach(state: State<'_, AppState>, on_output: Channel<InvokeResponseB
})
}
// The bar's meter, polled at most every two seconds: how full the running
// agent's context looks, labeled by how it was read.
#[tauri::command]
fn agent_context(state: State<'_, AppState>) -> serde_json::Value {
let (estimate, kind, since) = match state.context.lock() {
Ok(meter) => (meter.read(), meter.kind(), meter.since()),
Err(_) => (ContextReading::Unknown, None, None),
};
let agent = current_agent(&state);
let model = agent.as_ref().and_then(|agent| agent.model_and_effort().0);
// Claude's own transcript, or Codex's own log, is read when there is one;
// an unknown reading from either falls back to the labeled estimate.
// Nothing is read while no agent runs.
let reading = match (estimate, kind, agent, since) {
(ContextReading::Unknown, _, _, _) => ContextReading::Unknown,
(_, Some(AgentKind::Claude), Some(agent), Some(since)) => {
// `window_for` always has a window for Claude; the fallback here only
// guards against a future change to that rule.
let window = context::window_for(kind, model.as_deref()).unwrap_or(context::ESTIMATE_TOKEN_WINDOW);
let claude = ClaudeReader { projects_dir: claude_projects_dir(), folder: agent.folder().clone(), since, window };
match claude.read() {
ContextReading::Unknown => estimate,
read => read,
}
}
(_, Some(AgentKind::Codex), Some(agent), Some(since)) => {
let codex = CodexReader {
sessions_dir: codex_sessions_dir(),
folder: agent.folder().clone(),
since,
};
match codex.read() {
ContextReading::Unknown => estimate,
read => read,
}
}
_ => estimate,
};
serde_json::to_value(reading).unwrap_or_default()
}
// Claude Code's transcripts folder: `CLAUDE_CONFIG_DIR` when it is set, else `~/.claude`.
fn claude_projects_dir() -> std::path::PathBuf {
let home = std::env::var_os("CLAUDE_CONFIG_DIR")
.map(std::path::PathBuf::from)
.or_else(|| std::env::home_dir().map(|home| home.join(".claude")))
.unwrap_or_default();
home.join("projects")
}
// Codex's sessions folder: `CODEX_HOME` when it is set, else `~/.codex`.
fn codex_sessions_dir() -> std::path::PathBuf {
let home = std::env::var_os("CODEX_HOME")
.map(std::path::PathBuf::from)
.or_else(|| std::env::home_dir().map(|home| home.join(".codex")))
.unwrap_or_default();
home.join("sessions")
}
// Asks before quitting while an agent runs; "no" keeps the app open.
fn confirm_quit(app: &tauri::AppHandle) {
let app = app.clone();
@@ -379,9 +293,6 @@ fn app_state(state: State<'_, AppState>) -> serde_json::Value {
.agent
.or_else(|| settings_file.as_ref().and_then(|file| settings::load_last_agent(file)))
.or_else(project::remembered_agent);
let nudge = settings_file
.as_ref()
.map_or(settings::DEFAULT_NUDGE_PERCENT, |file| settings::load_nudge_percent(file));
let term_panel = settings_file.as_ref().map_or(
settings::TermPanelSettings {
dock: settings::DEFAULT_TERM_DOCK.to_string(),
@@ -396,7 +307,6 @@ fn app_state(state: State<'_, AppState>) -> serde_json::Value {
"projectDirSource": project.as_ref().map(|p| p.source),
"lastAgent": last_agent.map(|kind| kind.id()),
"launchModel": state.launch.model,
"contextNudgePercent": nudge,
// Task 1.7 already exits before the window opens on a missing or too-old
// Node, so this is always a pass; the checklist's Node row just names it.
"nodeVersion": state.node_version,
@@ -595,9 +505,7 @@ fn main() {
agent_input,
agent_resize,
agent_restart,
agent_state,
agent_reattach,
agent_context,
app_state,
save_term_panel,
save_first_run_done,
-44
View File
@@ -7,16 +7,11 @@ use std::path::{Path, PathBuf};
use crate::agents::AgentKind;
const LAST_AGENT_KEY: &str = "lastAgent";
const NUDGE_KEY: &str = "CONTEXT_NUDGE_PERCENT";
const TERM_DOCK_KEY: &str = "termDock";
const TERM_FRACTION_KEY: &str = "termFraction";
const TERM_COLLAPSED_KEY: &str = "termCollapsed";
const FIRST_RUN_DONE_KEY: &str = "firstRunDone";
/// The context percent at which the bar suggests a Restart, when the file
/// names no other.
pub const DEFAULT_NUDGE_PERCENT: u8 = 70;
/// The terminal pane's remembered shape: which edge it docks to, how much of
/// the window it takes (a fraction, not collapsed or maximized), and whether
/// it was left collapsed.
@@ -48,16 +43,6 @@ pub fn load_last_agent(file: &Path) -> Option<AgentKind> {
AgentKind::from_id(read(file).get(LAST_AGENT_KEY)?.as_str()?)
}
/// The context percent that triggers the Restart suggestion. A value outside
/// 1 to 100, or one that is not a number, means the default.
pub fn load_nudge_percent(file: &Path) -> u8 {
read(file)
.get(NUDGE_KEY)
.and_then(|value| value.as_u64())
.filter(|percent| (1..=100).contains(percent))
.map_or(DEFAULT_NUDGE_PERCENT, |percent| percent as u8)
}
/// Save the pick, keeping any other key the file holds.
pub fn save_last_agent(file: &Path, kind: AgentKind) -> Result<(), String> {
let mut settings = read(file);
@@ -150,35 +135,6 @@ mod tests {
let _ = std::fs::remove_dir_all(file.parent().unwrap());
}
#[test]
fn the_nudge_defaults_to_seventy() {
assert_eq!(load_nudge_percent(&temp_file("nudge-missing")), 70);
}
#[test]
fn the_nudge_reads_a_named_percent() {
let file = temp_file("nudge-set");
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
std::fs::write(&file, r#"{"CONTEXT_NUDGE_PERCENT": 85}"#).unwrap();
assert_eq!(load_nudge_percent(&file), 85);
let _ = std::fs::remove_dir_all(file.parent().unwrap());
}
#[test]
fn a_nudge_outside_one_to_one_hundred_or_not_a_number_is_the_default() {
for text in [
r#"{"CONTEXT_NUDGE_PERCENT": 0}"#,
r#"{"CONTEXT_NUDGE_PERCENT": 150}"#,
r#"{"CONTEXT_NUDGE_PERCENT": "high"}"#,
] {
let file = temp_file("nudge-bad");
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
std::fs::write(&file, text).unwrap();
assert_eq!(load_nudge_percent(&file), 70, "{text}");
let _ = std::fs::remove_dir_all(file.parent().unwrap());
}
}
#[test]
fn an_unknown_agent_is_ignored() {
let file = temp_file("unknown");
+254 -147
View File
@@ -2,16 +2,27 @@
// agent's terminal panel docked at the bottom with a drag handle.
import { mountTerminal } from './terminal.js';
import { nudgeDue } from './meter.js';
import { barNextSteps, folderName, windowTitleFor } from './meter.js';
const { invoke, Channel } = window.__TAURI__.core;
const projectDirEl = document.getElementById('project-dir');
const projectMenuBtn = document.getElementById('project-menu-button');
const projectNameEl = document.getElementById('project-name');
const projectPathEl = document.getElementById('project-path');
const projectMenu = document.getElementById('project-menu');
const agentMenuBtn = document.getElementById('agent-menu-button');
const agentMenu = document.getElementById('agent-menu');
const agentMenuHeadEl = document.getElementById('agent-menu-head');
const agentDotEl = document.getElementById('agent-dot');
const agentNameEl = document.getElementById('agent-name');
const agentEndedEl = document.getElementById('agent-ended');
const agentBypassEl = document.getElementById('agent-bypass');
const agentNoneEl = document.getElementById('agent-none');
const agentStatusEl = document.getElementById('agent-status');
const restartBtn = document.getElementById('agent-restart');
const changeAgentBtn = document.getElementById('change-agent');
const changeProjectBtn = document.getElementById('change-project');
const barRowEl = document.getElementById('bar-row');
const launchCard = document.getElementById('launch-card');
const launchAgentEl = document.getElementById('launch-agent');
const launchMissingEl = document.getElementById('launch-missing');
@@ -24,16 +35,10 @@ const launchStartBtn = document.getElementById('launch-start');
const firstRunEl = document.getElementById('first-run');
const firstRunListEl = document.getElementById('first-run-list');
const firstRunStartBtn = document.getElementById('first-run-start');
const meterSlot = document.getElementById('bar-slot-meter');
const nudgeEl = document.getElementById('context-nudge');
const nudgeRestartBtn = document.getElementById('context-restart');
const versionEl = document.getElementById('version-update');
const versionTextEl = document.getElementById('version-update-text');
const versionBtn = document.getElementById('version-update-button');
const versionRestartBtn = document.getElementById('version-update-restart');
const consoleStatusEl = document.getElementById('console-status');
const permissionsNoteEl = document.getElementById('permissions-note');
const consoleAgainBtn = document.getElementById('console-again');
const nextStepEl = document.getElementById('next-step');
const nextStepTextEl = document.getElementById('next-step-text');
const nextStepBtn = document.getElementById('next-step-button');
const nextStepMoreEl = document.getElementById('next-step-more');
const frame = document.getElementById('console-frame');
const stateBox = document.getElementById('dashboard-state');
const stateText = document.getElementById('dashboard-state-text');
@@ -46,10 +51,8 @@ const termDockBtn = document.getElementById('term-dock');
const termMaximizeBtn = document.getElementById('term-maximize');
const termCollapseBtn = document.getElementById('term-collapse');
const termBadgeEl = document.getElementById('term-badge');
const currentPageEl = document.getElementById('current-page');
const STATUS_POLL_MS = 5000;
const METER_POLL_MS = 2000;
const BADGE_POLL_MS = 2000;
const MIN_PANE = 0.10;
const MAX_PANE = 0.60;
@@ -71,12 +74,6 @@ const EFFORT_OPTIONS = {
let agent = { state: 'idle', kind: null, generation: 0 };
const agentActive = () => agent.state === 'running';
// The context percent that triggers the Restart suggestion, from the app's
// settings (main() reads it), and the agent run the suggestion was shown for:
// it appears once per run, not again after it is dismissed by a Restart.
let nudgePercent = 70;
let nudgeShownFor = null;
const terminal = await mountTerminal(document.getElementById('term'), {
onInput: (data) => {
if (agentActive()) invoke('agent_input', { data });
@@ -114,7 +111,7 @@ function applyAgentState(next, { skipReset } = {}) {
const label = AGENT_LABELS[agent.kind] || '';
const active = agentActive();
agentNameEl.textContent = active ? label : '';
const ended = agent.state === 'ended';
if (active) {
// Only ever auto-*hides* the card (the agent just started); it must
// never auto-*show* it on 'ended' or 'idle' — that is Change agent's
@@ -122,39 +119,118 @@ function applyAgentState(next, { skipReset } = {}) {
launchCard.hidden = true;
hideFirstRun();
}
// One rule throughout: Restart while running or ended (it keeps the
// previous agent, model, effort and mode); Change agent only once ended,
// when there is a real choice to make again.
restartBtn.hidden = !(active || agent.state === 'ended');
changeAgentBtn.hidden = agent.state !== 'ended';
// Checked mode needs no banner; bypass always gets one, naming the agent it
// applies to, for exactly as long as that agent runs.
// One rule throughout: New Session and the agent menu while running or
// ended (New Session keeps the previous agent, model, effort and mode);
// Change agent, in that menu, only once ended, when there is a real choice
// to make again.
restartBtn.hidden = !(active || ended);
changeAgentBtn.hidden = !ended;
// Checked mode needs no marker; bypass always gets the "checks off" badge
// on the agent, for exactly as long as that agent runs.
const bypassActive = active && agent.mode === 'bypass';
permissionsNoteEl.hidden = !bypassActive;
permissionsNoteEl.textContent = bypassActive ? `Permission checks are off for ${label || 'the running agent'}` : '';
restartBtn.title = agent.state === 'ended' ? 'Start a fresh agent on the same brief' : 'Replace the agent with a fresh one, on a fresh context window';
if (freshScreen || agent.state !== 'running') nudgeEl.hidden = true;
if (!agentActive()) renderMeter({ kind: 'unknown' });
agentMenuBtn.hidden = !(active || ended);
agentNoneEl.hidden = active || ended;
agentNameEl.textContent = active || ended ? label || 'The agent' : '';
agentDotEl.className = `agent-dot${active ? (bypassActive ? ' is-warn' : ' is-ok') : ''}`;
agentEndedEl.hidden = !ended;
agentBypassEl.hidden = !bypassActive;
renderAgentMenuHead(label || 'The agent', { active, ended, bypassActive });
if (agentMenu.hidden === false && agentMenuBtn.hidden) closeBarMenus();
restartBtn.title = ended ? 'Start a fresh agent on the same brief' : 'Replace the agent with a fresh one, on a fresh context window';
// The agent is back (a fresh generation, running): the restart message stays
// on screen (restarting() below) until its dashboard page is announced.
if (restarting && freshScreen && agent.state === 'running') {
terminal.write('\r\n\r\n[Fresh agent started. Waiting for the dashboard...]\r\n\r\n');
}
if (agent.state === 'ended') {
agentStatusEl.textContent = `${label || 'The agent'} ended: ${agent.reason}. Nothing starts until you press Restart.`;
if (ended) {
// The why sits beside the agent's menu; the menu says the rest.
setAgentStatus(agent.reason);
// A failed Restart clears the screen too, so it says so again.
if (!wasEnded || freshScreen) {
terminal.write(`\r\n[${label || 'The agent'} ended: ${agent.reason}. Press Restart in the bar to start a fresh one.]\r\n`);
terminal.write(`\r\n[${label || 'The agent'} ended: ${agent.reason}. Press New Session in the bar to start a fresh one.]\r\n`);
}
} else {
// After a Restart the bar says what it left for the dashboard, if anything.
agentStatusEl.textContent = agent.briefNote || '';
setAgentStatus(agent.briefNote || '');
}
agentStatusEl.title = agentStatusEl.textContent;
updateBadge();
}
// The short line after the agent's menu: an ended agent's reason or a
// Restart's brief note (quiet), or something that went wrong (in red).
function setAgentStatus(text, { error = false } = {}) {
agentStatusEl.textContent = text;
agentStatusEl.title = text;
agentStatusEl.classList.toggle('is-error', error && Boolean(text));
}
// The agent menu's first lines: what the agent is doing and, while it runs,
// which permission mode it started with.
function renderAgentMenuHead(label, { active, ended, bypassActive }) {
const name = document.createElement('b');
name.textContent = label;
if (active) {
const mode = document.createElement('span');
if (bypassActive) {
mode.className = 'is-warn';
mode.textContent = 'off';
} else {
mode.textContent = 'on';
}
agentMenuHeadEl.replaceChildren(name, ' is running', document.createElement('br'), 'Permission checks are ', mode);
if (bypassActive) agentMenuHeadEl.append(': it runs commands and changes files without asking');
} else if (ended) {
agentMenuHeadEl.replaceChildren(name, ` ended: ${agent.reason}`, document.createElement('br'), 'Nothing starts until you press New Session.');
} else {
agentMenuHeadEl.replaceChildren();
}
}
// The bar's two menus (project, agent). They hang outside the scrolling bar
// row, fixed under their trigger, so the row's overflow never clips them.
// Clicking anywhere else (the console frame and the terminal too), Escape,
// a resize or a scroll of the row all close them.
let openBarMenu = null;
function closeBarMenus() {
for (const [button, menu] of [[projectMenuBtn, projectMenu], [agentMenuBtn, agentMenu]]) {
menu.hidden = true;
button.setAttribute('aria-expanded', 'false');
}
openBarMenu = null;
}
function toggleBarMenu(button, menu) {
const wasOpen = openBarMenu === menu;
closeBarMenus();
if (wasOpen) return;
menu.hidden = false;
const at = button.getBoundingClientRect();
const left = Math.max(8, Math.min(at.left, window.innerWidth - menu.offsetWidth - 8));
menu.style.left = `${left}px`;
menu.style.top = `${at.bottom + 4}px`;
button.setAttribute('aria-expanded', 'true');
openBarMenu = menu;
}
projectMenuBtn.onclick = () => toggleBarMenu(projectMenuBtn, projectMenu);
agentMenuBtn.onclick = () => toggleBarMenu(agentMenuBtn, agentMenu);
document.addEventListener('pointerdown', (event) => {
if (!openBarMenu) return;
if (openBarMenu.contains(event.target) || projectMenuBtn.contains(event.target) || agentMenuBtn.contains(event.target)) return;
closeBarMenus();
});
document.addEventListener('keydown', (event) => {
if (event.key !== 'Escape' || !openBarMenu) return;
const trigger = openBarMenu === projectMenu ? projectMenuBtn : agentMenuBtn;
closeBarMenus();
trigger.focus();
});
window.addEventListener('blur', closeBarMenus);
window.addEventListener('resize', closeBarMenus);
barRowEl.addEventListener('scroll', closeBarMenus);
// True from a confirmed Restart until the fresh agent's dashboard page is
// announced (showAnnounced below): the frame stays blanked with a message the
// whole time, since the restarted agent must boot and run the skill again
@@ -167,13 +243,12 @@ function confirmRestart(onYes) {
return;
}
showState(
'Restart the agent on a fresh context window? What it was doing is not saved.',
'Restart',
'Restart the agent on a fresh context window?',
'New Session',
() => {
restarting = true;
currentUrl = null;
frameReady = false;
currentPageEl.textContent = '';
showState('The agent is restarting on a fresh context window. Please wait for the dashboard to load.');
onYes();
},
@@ -322,14 +397,14 @@ async function startAgent(event) {
const model = launchModelEl.value.trim() || null;
const effort = (EFFORT_OPTIONS[kind] || []).length > 0 ? launchEffortEl.value || null : null;
const mode = launchBypassEl.checked ? 'bypass' : 'checked';
agentStatusEl.textContent = '';
setAgentStatus('');
showState('Waiting for the agent to open the dashboard');
const { cols, rows } = terminal.size();
try {
await invoke('agent_start', { kind, model, effort, mode, cols, rows });
terminal.focus();
} catch (error) {
agentStatusEl.textContent = `Could not start the agent: ${error}`;
setAgentStatus(`Could not start the agent: ${error}`, { error: true });
showLaunchCard();
}
}
@@ -339,15 +414,17 @@ async function agentAction(command) {
await invoke(command);
terminal.focus();
} catch (error) {
agentStatusEl.textContent = String(error);
setAgentStatus(String(error), { error: true });
}
}
launchCard.addEventListener('submit', startAgent);
restartBtn.onclick = () => confirmRestart(() => agentAction('agent_restart'));
nudgeRestartBtn.onclick = () => confirmRestart(() => agentAction('agent_restart'));
// Only ever enabled once the agent has ended: nothing active to lose, so no confirm.
changeAgentBtn.onclick = () => showLaunchCard();
changeAgentBtn.onclick = () => {
closeBarMenus();
showLaunchCard();
};
// The pane's shape: which edge it docks to, its share of the window when it
// is neither collapsed nor maximized (dragging and the settings file both
@@ -455,14 +532,64 @@ function loadFrame(url) {
frame.src = url;
}
// What the console page may ask of this window. Each is a named request with
// no free text, so the page can never type anything but "continue".
window.addEventListener('message', (event) => {
if (event.source !== frame.contentWindow) return;
if (!event.data || event.data.plan2code !== 'console-ready') return;
frameReady = true;
clearTimeout(helloTimer);
hideState();
const kind = event.data && event.data.plan2code;
if (kind === 'console-ready') {
frameReady = true;
clearTimeout(helloTimer);
hideState();
} else if (kind === 'agent-continue') {
typeContinue();
} else if (kind === 'new-session') {
// The bar's own button, so the press is confirmed exactly the same way.
if (!restartBtn.hidden) restartBtn.click();
} else if (kind === 'looks') {
applyAccent(event.data.accent, { save: true });
}
});
// Its "Not running... type continue" line, pressed: the word, then Enter on
// its own a moment later, so an agent that treats one burst of input as a
// paste still reads the Enter as a submit.
const ENTER_AFTER_MS = 120;
function typeContinue() {
if (!agentActive()) return;
invoke('agent_input', { data: 'continue' })
.then(() => new Promise((resolve) => setTimeout(resolve, ENTER_AFTER_MS)))
.then(() => invoke('agent_input', { data: '\r' }))
.catch((error) => {
setAgentStatus(`Could not type continue: ${error}`, { error: true });
});
}
// The person's highlight color, as the console page last sent it (its dark
// shades: fill, soft, ink, line), so the bar's buttons light in it too. Kept
// here for the next launch, which paints the bar before any page has loaded.
const ACCENT_KEY = 'p2c-app:accent';
const ACCENT_VARS = ['--accent', '--accent-soft', '--accent-ink', '--accent-line'];
function applyAccent(shades, { save = false } = {}) {
if (!Array.isArray(shades) || shades.length !== ACCENT_VARS.length) return;
if (!shades.every((c) => typeof c === 'string' && /^#[0-9a-f]{6}$/i.test(c))) return;
ACCENT_VARS.forEach((name, i) => document.documentElement.style.setProperty(name, shades[i]));
if (!save) return;
try {
localStorage.setItem(ACCENT_KEY, JSON.stringify(shades));
} catch {
// Not remembered is fine: the stylesheet's default shows until a page loads.
}
}
try {
applyAccent(JSON.parse(localStorage.getItem(ACCENT_KEY)));
} catch {
// Nothing saved, or storage is blocked: the stylesheet's default stands.
}
// No hello in time: ask the console why, and say so with a way forward.
async function onNoHello() {
if (frameReady || !consoleKnown || restarting) return;
@@ -473,7 +600,7 @@ async function onNoHello() {
// The status check itself failed; treat it as a console that is not answering.
}
if (!status || status.state !== 'running') {
showState('The console stopped, so the page could not show.', 'Restart the console', reconnectConsole);
showState('The console stopped, so the page could not show.', 'Reconnect the console', reconnectConsole);
} else {
showState('The console is running but its page did not show in this window.', 'Reload the page', () => {
showState('Reloading the page');
@@ -512,10 +639,7 @@ async function reconnectConsole() {
} catch (error) {
showState(`The console could not be reached: ${error}`, 'Retry', reconnectConsole);
// An old console cannot be framed: the fix is the skills update, so offer it.
if (String(error).includes('too old')) {
versionTextEl.textContent = 'The installed console is too old for the app';
versionEl.hidden = false;
}
if (String(error).includes('too old')) setVersionState({ kind: 'too-old' });
}
}
@@ -545,113 +669,55 @@ async function pollConsole() {
}
}
// The meter: a bar and a percent for a real or best-effort reading, a dashed
// bar with "about N%" and an "estimate" tag for an estimate, "unknown" when
// nothing is available. Built with DOM calls, never innerHTML.
function renderMeter(reading) {
meterSlot.replaceChildren();
// Left empty, not even an "unknown" label: #bar-slot-meter:empty hides it,
// so the bar carries nothing until the reading means something.
if (reading.kind === 'unknown') return;
const label = document.createElement('span');
const track = document.createElement('span');
track.className = `meter-track ${reading.kind}`;
const fill = document.createElement('span');
fill.className = 'meter-fill';
fill.style.width = `${reading.percent}%`;
track.append(fill);
label.textContent = reading.kind === 'estimate' ? `about ${reading.percent}%` : `${reading.percent}%`;
meterSlot.append(track, label);
if (reading.kind === 'estimate') {
const tag = document.createElement('span');
tag.className = 'meter-tag';
tag.textContent = 'estimate';
meterSlot.append(tag);
meterSlot.title = 'Estimated from the text so far: the agent does not report its context size';
} else if (reading.kind === 'besteffort') {
meterSlot.title = 'Read from the agent\'s session log: undocumented, so it may stop working after an update';
} else {
meterSlot.title = 'How full the agent context is, as the agent reports it';
}
}
// Every two seconds while an agent runs: draw the meter and, once per run,
// suggest a Restart when the context reaches the nudge percent.
async function pollMeter() {
if (!agentActive()) return;
try {
// The reading may land after a Restart: only a reading for the same run counts.
const { generation, state } = agent;
const reading = await invoke('agent_context');
if (agent.generation !== generation || agent.state !== state) return;
renderMeter(reading);
if (nudgeDue(reading, nudgePercent) && state === 'running' && nudgeShownFor !== generation) {
nudgeShownFor = generation;
nudgeEl.hidden = false;
}
} catch {
// A failed read is not a reading: look again on the next tick.
}
}
// Once, at start: when the app and the installed skills are on different versions the bar
// says so and offers Update skills. Nothing runs until that button is pressed.
async function checkVersions() {
try {
const status = await invoke('version_status');
if (!status.mismatch) return;
if (status.skills_ahead) {
// The skills are ahead of this app: another Update skills run cannot help.
versionTextEl.textContent = `The installed skills are v${status.skills}, newer than this app (v${status.app}). Get the new app.`;
versionBtn.hidden = true;
} else {
versionTextEl.textContent = `Skills are v${status.skills}, this app is v${status.app}`;
versionBtn.hidden = false;
}
versionEl.hidden = false;
// Skills ahead of this app: another Update skills run cannot help, so
// that state offers no button.
setVersionState({ kind: status.skills_ahead ? 'ahead' : 'mismatch', skills: status.skills, app: status.app });
} catch {
// No version to compare is no reason to nag.
}
}
versionBtn.onclick = async () => {
versionBtn.disabled = true;
versionRestartBtn.hidden = true;
versionTextEl.textContent = 'Updating Plan2Code...';
async function updateSkills() {
setVersionState({ kind: 'updating', line: 'Updating Plan2Code...' });
const progress = new Channel();
progress.onmessage = (line) => {
if (line) versionTextEl.textContent = line;
if (line && versionState && versionState.kind === 'updating') setVersionState({ kind: 'updating', line });
};
try {
const outcome = await invoke('update_skills', { progress });
versionTextEl.textContent = outcome.status.mismatch
? `Updated, but the mismatch remains (skills v${outcome.status.skills}, app v${outcome.status.app}).`
: 'Updated. Restart the console to use the new version.';
versionBtn.hidden = true;
versionRestartBtn.hidden = outcome.status.mismatch;
setVersionState(
outcome.status.mismatch
? { kind: 'remains', skills: outcome.status.skills, app: outcome.status.app }
: { kind: 'updated' }
);
} catch (error) {
versionTextEl.textContent = String(error);
versionBtn.disabled = false;
setVersionState({ kind: 'failed', error: String(error) });
}
};
}
versionRestartBtn.onclick = async () => {
versionRestartBtn.disabled = true;
// After an update: stop the old console first, so the new skills are really
// picked up, then bring a fresh one back on the same session.
async function restartConsole() {
try {
await invoke('console_stop');
} catch {
// Nothing to stop is fine: reconnectConsole starts a fresh one either way.
}
versionEl.hidden = true;
setVersionState(null);
await reconnectConsole();
};
// A page the agent's `console.mjs open` asked this window to show.
const pageLabel = (workflow) => (workflow || '').replace(/-/g, ' ').replace(/^./, (c) => c.toUpperCase());
}
// A page the agent's `console.mjs open` asked this window to show. Which page
// it is shows inside the frame itself (the console's own badge and title),
// not repeated here.
function showAnnounced(notice) {
restarting = false;
currentPageEl.textContent = pageLabel(notice.workflow);
if (!consoleKnown) {
consoleKnown = true;
if (!pollTimer) pollTimer = setInterval(pollConsole, STATUS_POLL_MS);
@@ -665,21 +731,62 @@ function showAnnounced(notice) {
window.__TAURI__.event.listen('console-page', (event) => showAnnounced(event.payload));
// The right end of the bar: whether the console stopped answering and where
// the skills stand against this app, drawn as one next step (meter.js
// barNextSteps decides which, and its button), with the rest as "+N more".
let consoleDead = false;
let versionState = null;
const NEXT_STEP_ACTIONS = { reconnect: reconnectConsole, 'restart-console': restartConsole, update: updateSkills };
let nextStepAction = null;
function renderNextStep() {
const steps = barNextSteps({ consoleDead, version: versionState });
nextStepEl.hidden = steps.length === 0;
const [first, ...rest] = steps;
nextStepTextEl.textContent = first ? first.text : '';
nextStepTextEl.title = first ? first.title : '';
nextStepTextEl.className = first ? `is-${first.tone}${first.busy ? ' is-busy' : ''}` : '';
nextStepAction = first && first.action ? NEXT_STEP_ACTIONS[first.action] : null;
nextStepBtn.hidden = !nextStepAction;
nextStepBtn.disabled = false;
nextStepBtn.textContent = first && first.label ? first.label : '';
nextStepMoreEl.hidden = rest.length === 0;
nextStepMoreEl.textContent = `+${rest.length} more`;
nextStepMoreEl.title = rest.map((step) => step.title).join('\n');
}
function setVersionState(next) {
versionState = next;
renderNextStep();
}
function markConsoleAlive() {
consoleStatusEl.textContent = '';
consoleAgainBtn.hidden = true;
consoleDead = false;
renderNextStep();
}
function markConsoleDead() {
consoleStatusEl.textContent = 'The console stopped.';
consoleAgainBtn.hidden = false;
consoleDead = true;
renderNextStep();
}
consoleAgainBtn.onclick = () => reconnectConsole();
nextStepBtn.onclick = () => {
if (!nextStepAction) return;
// Pressed once per step: whatever it starts draws the next state itself.
nextStepBtn.disabled = true;
nextStepAction();
};
function setProjectDir(dir) {
projectDirEl.textContent = dir;
projectDirEl.title = dir;
// The bar names the folder; its menu holds the full path.
projectNameEl.textContent = folderName(dir);
projectMenuBtn.title = dir;
projectPathEl.textContent = dir;
projectMenuBtn.hidden = !dir;
// So two or more windows read apart in the taskbar without opening each
// one: a setTitle that fails (an old Tauri runtime, say) just leaves the
// static "Plan2Code" title from tauri.conf.json, never breaks the start.
window.__TAURI__.window.getCurrentWindow().setTitle(windowTitleFor(dir)).catch(() => {});
}
// The state `main()` read at startup: `pickFolder()` and the first-run
@@ -731,7 +838,6 @@ async function doChangeProject() {
restarting = false;
currentUrl = null;
frameReady = false;
currentPageEl.textContent = '';
afterProjectKnown();
} catch (error) {
showState(`Could not switch project: ${error}`, 'Try again', doChangeProject);
@@ -751,7 +857,10 @@ function changeProject() {
doChangeProject();
}
changeProjectBtn.onclick = changeProject;
changeProjectBtn.onclick = () => {
closeBarMenus();
changeProject();
};
// The launcher passed `--agent`: start it at once, on its model, with the
// same bypass flags the terminal launcher itself always runs that agent with
@@ -759,7 +868,7 @@ changeProjectBtn.onclick = changeProject;
async function autoStartAgent(state) {
launchAgentEl.value = state.autoStart;
if (typeof state.launchModel === 'string' && state.launchModel) launchModelEl.value = state.launchModel;
agentStatusEl.textContent = '';
setAgentStatus('');
showState('Starting the agent...');
const { cols, rows } = terminal.size();
try {
@@ -773,7 +882,7 @@ async function autoStartAgent(state) {
});
terminal.focus();
} catch (error) {
agentStatusEl.textContent = `Could not start the agent: ${error}`;
setAgentStatus(`Could not start the agent: ${error}`, { error: true });
showLaunchCard();
}
}
@@ -811,7 +920,6 @@ async function main() {
appState = state;
if (AGENT_LABELS[state.lastAgent]) launchAgentEl.value = state.lastAgent;
if (typeof state.launchModel === 'string' && state.launchModel) launchModelEl.value = state.launchModel;
if (Number.isInteger(state.contextNudgePercent)) nudgePercent = state.contextNudgePercent;
if (state.termPanel) {
paneDock = state.termPanel.dock === 'right' ? 'right' : 'bottom';
paneFraction = state.termPanel.fraction;
@@ -820,7 +928,6 @@ async function main() {
applyPaneLayout();
await loadAgentAvailability();
refreshLaunchCard();
setInterval(pollMeter, METER_POLL_MS);
setInterval(updateBadge, BADGE_POLL_MS);
checkVersions();
+86 -44
View File
@@ -10,30 +10,75 @@
html, body { margin: 0; height: 100%; font-family: system-ui, sans-serif; background: #1e1e1e; color: #ddd; }
body { display: flex; flex-direction: column; overflow: hidden; }
/* The console's dark tokens and its default highlight (Ocean). app.js sets
the four accent ones to the person's own highlight once the console page
says which it is, and keeps them for the next launch. */
:root {
--panel: #201d1a; --panel-2: #262220; --ink: #f0ece5; --ink-2: #b6afa3; --ink-3: #8b8376; --rule-2: #46403a;
--accent: #619fe5; --accent-soft: #1a2533; --accent-ink: #0c1117; --accent-line: #3d5978;
}
#bar { flex: none; border-bottom: 1px solid #444; }
/* The console's top bar buttons (.btn small ghost), sized to this bar:
quiet until hovered, then in the highlight color. New Session is the
one that is often the next step, so it wears the highlight outline at
rest, like the console's standby buttons. */
#bar button {
appearance: none; font: inherit; font-size: 12px; font-weight: 600; line-height: 1.2;
padding: 4px 10px; border-radius: 8px; cursor: pointer;
border: 1px solid var(--rule-2); background: var(--panel); color: var(--ink-2);
transition: background 0.12s, border-color 0.12s, color 0.12s;
}
#bar button:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); background: var(--panel-2); }
#bar button:disabled { opacity: 0.45; cursor: not-allowed; }
#bar button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
#bar #agent-restart { background: transparent; border-color: var(--accent-line); color: var(--accent); }
#bar #agent-restart:hover:not(:disabled) { background: var(--accent-soft); border-color: var(--accent); }
#bar-row { height: 34px; flex: none; display: flex; align-items: center; gap: 10px; padding: 0 10px; font-size: 12px; white-space: nowrap; overflow-x: auto; overflow-y: hidden; }
#bar-sep { flex: none; align-self: stretch; width: 1px; margin: 8px 0; background: #3a3a3a; }
#title { font-weight: 600; font-size: 13px; }
#project-dir { color: #9ab; overflow: hidden; text-overflow: ellipsis; min-width: 0; max-width: 220px; }
#current-page { color: #8c8; }
#current-page:not(:empty)::before { content: "page: "; color: #666; }
#agent-name { color: #9ab; }
#agent-name:not(:empty)::before { content: "agent: "; color: #666; }
#console-status, #agent-status { color: #d7ba7d; overflow: hidden; text-overflow: ellipsis; min-width: 0; max-width: 260px; }
#agent-restart[hidden], #change-agent[hidden] { display: none; }
.bar-slot { flex: none; }
#permissions-note { color: #888; }
#context-nudge { display: flex; align-items: center; gap: 6px; color: #d7ba7d; }
#context-nudge[hidden] { display: none; }
#version-update { display: flex; align-items: center; gap: 6px; color: #d7ba7d; }
#version-update[hidden], #version-update-button[hidden] { display: none; }
#bar-slot-meter { display: flex; align-items: center; gap: 6px; color: #9ab; }
#bar-slot-meter:empty { display: none; }
.meter-track { display: inline-block; width: 64px; height: 8px; border: 1px solid #666; border-radius: 2px; overflow: hidden; background: #2a2a2a; }
.meter-track.estimate { border-style: dashed; }
.meter-fill { display: block; height: 100%; background: #6a9955; }
.meter-track.estimate .meter-fill { background: repeating-linear-gradient(45deg, #6a9955 0 4px, transparent 4px 8px); }
.meter-tag { color: #d7ba7d; font-style: italic; }
#bar [hidden] { display: none !important; }
/* The project and agent menus' triggers: plain text until hovered, a
caret saying there is more behind them. */
#bar .bar-menu { display: inline-flex; align-items: center; gap: 6px; flex: none; border-color: transparent; background: transparent; color: var(--ink); padding: 4px 8px; }
#bar .bar-menu:hover:not(:disabled), #bar .bar-menu[aria-expanded="true"] { background: var(--panel-2); border-color: transparent; color: var(--ink); }
.bar-caret { color: var(--ink-3); font-size: 10px; }
#project-name { max-width: 220px; overflow: hidden; text-overflow: ellipsis; }
.agent-dot { flex: none; width: 8px; height: 8px; border-radius: 50%; background: #666; }
.agent-dot.is-ok { background: #6a9955; }
.agent-dot.is-warn { background: #d7ba7d; }
#agent-ended { color: var(--ink-3); font-weight: 400; }
#agent-bypass { flex: none; font-size: 11px; font-weight: 600; line-height: 1.3; padding: 0 7px; border-radius: 999px; border: 1px solid #d7ba7d; color: #d7ba7d; }
#agent-none { color: var(--ink-3); }
#agent-status { color: var(--ink-3); overflow: hidden; text-overflow: ellipsis; min-width: 0; max-width: 320px; }
#agent-status.is-error { color: #f48771; }
#bar-grow { flex: 1; min-width: 0; }
/* The one next step for the console or the skills, at the right end. */
#next-step { display: flex; align-items: center; gap: 8px; flex: none; }
#next-step-text { overflow: hidden; text-overflow: ellipsis; max-width: 320px; }
#next-step-text.is-ok { color: #6a9955; }
#next-step-text.is-warn { color: #d7ba7d; }
#next-step-text.is-err { color: #f48771; }
#next-step-text.is-busy::before {
content: ""; display: inline-block; width: 8px; height: 8px; margin-right: 6px; vertical-align: -1px;
border: 2px solid currentColor; border-right-color: transparent; border-radius: 50%; animation: bar-spin 0.8s linear infinite;
}
@keyframes bar-spin { to { transform: rotate(360deg); } }
#bar #next-step-button { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
#bar #next-step-button:hover:not(:disabled) { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); filter: brightness(1.12); }
#next-step-more { color: var(--ink-3); font-size: 11px; border-bottom: 1px dotted var(--ink-3); cursor: help; }
/* The menus sit outside the scrolling row (fixed, placed under their
trigger by app.js), so the row's overflow never clips them. */
.bar-dropdown {
position: fixed; z-index: 20; min-width: 240px; max-width: 380px; padding: 6px; box-sizing: border-box;
font-size: 12px; background: var(--panel); border: 1px solid var(--rule-2); border-radius: 8px; box-shadow: 0 10px 28px rgba(0, 0, 0, 0.45);
}
.bar-dropdown-head { margin: 0; padding: 4px 8px 8px; color: var(--ink-3); line-height: 1.45; overflow-wrap: anywhere; }
.bar-dropdown-head b { color: var(--ink); font-weight: 600; }
.bar-dropdown-head .is-warn { color: #d7ba7d; }
#bar .bar-dropdown button {
display: block; width: 100%; text-align: left; font-weight: 400; padding: 6px 8px; border: 0; border-radius: 6px;
background: transparent; color: var(--ink);
}
#bar .bar-dropdown button:hover:not(:disabled), #bar .bar-dropdown button:focus-visible { background: var(--panel-2); color: var(--accent); }
#workspace { flex: 1; min-height: 0; display: flex; flex-direction: column; }
#workspace.dock-right { flex-direction: row; }
@@ -128,30 +173,27 @@
<body>
<header id="bar">
<div id="bar-row">
<span id="title">Plan2Code</span>
<span id="project-dir"></span>
<span id="bar-slot-restart" class="bar-slot"><button id="agent-restart" hidden>Restart</button></span>
<span id="bar-slot-change-agent" class="bar-slot"><button id="change-agent" hidden>Change agent</button></span>
<span id="bar-slot-change-project" class="bar-slot"><button id="change-project">Change project</button></span>
<span id="bar-sep" aria-hidden="true"></span>
<span id="current-page" title="The page the agent opened"></span>
<span id="agent-name"></span>
<button id="project-menu-button" class="bar-menu" aria-haspopup="menu" aria-expanded="false" aria-controls="project-menu" hidden><span id="project-name"></span><span class="bar-caret" aria-hidden="true">&#9662;</span></button>
<!-- Whenever an agent exists, running or ended, just left of its menu. -->
<button id="agent-restart" hidden>New Session</button>
<button id="agent-menu-button" class="bar-menu" aria-haspopup="menu" aria-expanded="false" aria-controls="agent-menu" hidden><span id="agent-dot" class="agent-dot" aria-hidden="true"></span><span id="agent-name"></span><span id="agent-ended" hidden>ended</span><span id="agent-bypass" title="Permission checks are off: the agent runs commands and changes files without asking" hidden>checks off</span><span class="bar-caret" aria-hidden="true">&#9662;</span></button>
<span id="agent-none">No agent</span>
<span id="agent-status" role="status"></span>
<span id="console-status"></span>
<button id="console-again" hidden>Start it again</button>
<span id="context-nudge" class="bar-slot" hidden>
<span>Context is getting full: consider Restart</span>
<button id="context-restart">Restart</button>
<span id="bar-grow"></span>
<!-- The console's or the skills' one next step (meter.js barNextSteps), when there is one. -->
<span id="next-step" role="status" hidden>
<span id="next-step-text"></span>
<button id="next-step-button" hidden></button>
<span id="next-step-more" hidden></span>
</span>
<!-- Shown only when the app and the installed skills are on different versions. -->
<span id="version-update" class="bar-slot" hidden>
<span id="version-update-text"></span>
<button id="version-update-button">Update skills</button>
<button id="version-update-restart" hidden>Restart the console</button>
</span>
<span id="bar-slot-meter" class="bar-slot"></span>
<!-- Shown only while an agent is running, naming the real mode it started with. -->
<span id="permissions-note" hidden></span>
</div>
<div id="project-menu" class="bar-dropdown" role="menu" aria-label="Project" hidden>
<p class="bar-dropdown-head">Project<br><b id="project-path"></b></p>
<button id="change-project" role="menuitem">Change project...</button>
</div>
<div id="agent-menu" class="bar-dropdown" role="menu" aria-label="Agent" hidden>
<p id="agent-menu-head" class="bar-dropdown-head"></p>
<button id="change-agent" role="menuitem" hidden>Change agent...</button>
</div>
</header>
<div id="workspace">
+86 -11
View File
@@ -1,15 +1,90 @@
// The context meter's pure decisions, kept out of app.js so they can be
// imported and tested without a DOM or `window.__TAURI__` (app.js touches
// both at module scope, the same reason the web console keeps its own pure
// logic in answers.js rather than app.js).
// The bar's pure decisions, kept out of app.js so they can be imported and
// tested without a DOM or `window.__TAURI__` (app.js touches both at module
// scope, the same reason the web console keeps its own pure logic in
// answers.js rather than app.js).
// The button label for each next-step action. Both ways of reconnecting the
// console read the same, wherever they come from.
export const NEXT_STEP_LABELS = {
reconnect: 'Reconnect the console',
'restart-console': 'Reconnect the console',
update: 'Update skills',
};
/**
* Whether `reading` (what the `agent_context` command returns) should fire
* the Restart nudge at `nudgePercent`. Only a real or best-effort number
* counts, per the context policy (pathfinder Question 11): an estimate is
* not precise enough for "about 70%" to mean the window really is close to
* full, so an estimate-only agent gets the meter but never the nudge.
* What the right end of the bar offers, most pressing first: the bar shows
* the first step (short text plus its one button) and counts the rest as
* "+N more". `consoleDead` is whether the console stopped answering;
* `version` is the skills/app version state, or null when they agree:
* `{ kind: 'mismatch' | 'ahead' | 'remains', skills, app }`,
* `{ kind: 'updating', line }`, `{ kind: 'updated' }`, `{ kind: 'too-old' }`
* or `{ kind: 'failed', error }`.
*
* Only one control for "reconnect the console" is ever offered: after an
* update, its Reconnect (which stops the old console first, so the new skills
* are really picked up) covers a console that has also stopped.
*/
export function nudgeDue(reading, nudgePercent) {
return (reading.kind === 'real' || reading.kind === 'besteffort') && reading.percent >= nudgePercent;
export function barNextSteps({ consoleDead = false, version = null } = {}) {
const v = version || {};
const steps = [];
if (v.kind === 'updated') {
steps.push({ id: 'updated', text: 'Skills updated', title: 'Updated. Reconnect the console to use the new version.', tone: 'ok', action: 'restart-console' });
} else if (consoleDead) {
steps.push({ id: 'console-dead', text: 'Console stopped', title: 'The console stopped, so the dashboard cannot show.', tone: 'err', action: 'reconnect' });
}
switch (v.kind) {
case 'too-old':
steps.push({ id: 'too-old', text: 'Console too old for this app', title: 'The installed console is too old for the app. Update skills to fix it.', tone: 'warn', action: 'update' });
break;
case 'mismatch':
steps.push({ id: 'mismatch', text: `Skills v${v.skills}, app v${v.app}`, title: `The installed skills are v${v.skills}, this app is v${v.app}.`, tone: 'warn', action: 'update' });
break;
case 'updating': {
const line = v.line || 'Updating Plan2Code...';
steps.push({ id: 'updating', text: line, title: line, tone: 'warn', busy: true, action: null });
break;
}
case 'remains':
steps.push({ id: 'remains', text: `Still mismatched: skills v${v.skills}, app v${v.app}`, title: `Updated, but the mismatch remains (skills v${v.skills}, app v${v.app}).`, tone: 'warn', action: null });
break;
case 'failed':
steps.push({ id: 'failed', text: 'Update failed', title: String(v.error || 'The update did not finish.'), tone: 'err', action: 'update' });
break;
case 'ahead':
steps.push({ id: 'ahead', text: `Skills v${v.skills} are newer than this app`, title: `The installed skills are v${v.skills}, newer than this app (v${v.app}). Get the new app.`, tone: 'warn', action: null });
break;
default:
break;
}
return steps.map((step) => ({ ...step, label: step.action ? NEXT_STEP_LABELS[step.action] : null }));
}
/**
* The OS window title for a project folder: its own name (the repo's, most
* of the time) after "Plan2Code - ", so two or more windows read apart in a
* taskbar without opening each to see which project is which. Trailing
* slashes and a drive root (`C:\`, `/`) leave nothing to show, so that falls
* back to the plain title rather than a trailing "Plan2Code - ".
*/
export function windowTitleFor(dir) {
const name = lastSegment(dir);
return name ? `Plan2Code - ${name}` : "Plan2Code";
}
/**
* A project folder's own name, for the bar's project menu: the same last
* segment the window title uses, or the whole path when there is none (a
* root such as `/`), so the menu never shows an empty name.
*/
export function folderName(dir) {
return lastSegment(dir) || String(dir || "").trim();
}
function lastSegment(dir) {
return String(dir || "")
.trim()
.replace(/[\\/]+$/, "")
.split(/[\\/]/)
.filter(Boolean)
.pop();
}
+100 -13
View File
@@ -1,26 +1,113 @@
// Tests for plan2code-app/ui/meter.js. Run with: node --test scripts/test-app-meter.mjs
// Tests for plan2code-app/ui/meter.js and the app bar's own shape. Run with:
// node --test scripts/test-app-meter.mjs
//
// app.js itself cannot be imported here (it touches `document` and
// `window.__TAURI__` at module scope), which is why the nudge decision lives
// in its own pure module.
// `window.__TAURI__` at module scope), which is why the bar's pure decisions
// live in their own module and the rest is checked as plain text, the same
// way the web console's own "shape" tests work.
import test from "node:test";
import assert from "node:assert/strict";
import { nudgeDue } from "../plan2code-app/ui/meter.js";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { barNextSteps, folderName, windowTitleFor, NEXT_STEP_LABELS } from "../plan2code-app/ui/meter.js";
import { findBrowser, launchBrowser } from "./browser.mjs";
test("meter: a real reading at or past the threshold nudges", () => {
assert.equal(nudgeDue({ kind: "real", percent: 70 }, 70), true);
assert.equal(nudgeDue({ kind: "real", percent: 69 }, 70), false);
const HERE = path.dirname(fileURLToPath(import.meta.url));
const INDEX_HTML_PATH = path.join(HERE, "../plan2code-app/ui/index.html");
const APP_JS = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/app.js"), "utf8");
const INDEX_HTML = fs.readFileSync(INDEX_HTML_PATH, "utf8");
test("barNextSteps offers nothing while the console runs and the versions agree", () => {
assert.deepEqual(barNextSteps(), []);
assert.deepEqual(barNextSteps({ consoleDead: false, version: null }), []);
});
test("meter: a best-effort reading nudges the same as a real one", () => {
assert.equal(nudgeDue({ kind: "besteffort", percent: 80 }, 70), true);
test("barNextSteps puts the most pressing step first: a done update, then a stopped console, then the skills", () => {
const ids = (input) => barNextSteps(input).map((step) => step.id);
assert.deepEqual(ids({ consoleDead: true }), ["console-dead"]);
assert.deepEqual(ids({ version: { kind: "mismatch", skills: "3.0.0", app: "3.1.0" } }), ["mismatch"]);
assert.deepEqual(ids({ consoleDead: true, version: { kind: "mismatch", skills: "3.0.0", app: "3.1.0" } }), ["console-dead", "mismatch"]);
assert.deepEqual(ids({ consoleDead: true, version: { kind: "too-old" } }), ["console-dead", "too-old"]);
assert.deepEqual(ids({ version: { kind: "updated" } }), ["updated"]);
});
test("meter: an estimate never nudges, however high its percent", () => {
assert.equal(nudgeDue({ kind: "estimate", percent: 99 }, 70), false);
test("only one control for reconnecting the console is ever offered: after an update, its Reconnect covers a stopped console too", () => {
const steps = barNextSteps({ consoleDead: true, version: { kind: "updated" } });
assert.deepEqual(steps.map((step) => step.action), ["restart-console"], "the plain reconnect steps aside for the one that stops the old console first");
});
test("meter: unknown never nudges", () => {
assert.equal(nudgeDue({ kind: "unknown" }, 70), false);
test("each version state reads and acts as the old version bar did", () => {
const [mismatch] = barNextSteps({ version: { kind: "mismatch", skills: "3.0.0", app: "3.1.0" } });
assert.equal(mismatch.text, "Skills v3.0.0, app v3.1.0");
assert.equal(mismatch.label, "Update skills");
const [ahead] = barNextSteps({ version: { kind: "ahead", skills: "3.2.0", app: "3.1.0" } });
assert.equal(ahead.action, null, "another Update skills run cannot help when the skills are ahead");
assert.match(ahead.title, /newer than this app \(v3\.1\.0\)\. Get the new app\./);
const [updating] = barNextSteps({ version: { kind: "updating", line: "Installing skills (4 of 9)" } });
assert.deepEqual([updating.text, updating.busy, updating.action], ["Installing skills (4 of 9)", true, null], "no button while it runs");
const [remains] = barNextSteps({ version: { kind: "remains", skills: "3.0.0", app: "3.1.0" } });
assert.equal(remains.action, null);
assert.equal(remains.title, "Updated, but the mismatch remains (skills v3.0.0, app v3.1.0).");
const [failed] = barNextSteps({ version: { kind: "failed", error: "npm exited with code 1" } });
assert.deepEqual([failed.tone, failed.title, failed.label], ["err", "npm exited with code 1", "Update skills"], "a failed update can be tried again");
const [tooOld] = barNextSteps({ version: { kind: "too-old" } });
assert.equal(tooOld.label, "Update skills", "an old console is fixed by the skills update");
});
test("every control that reconnects the console carries the same label, never 'Restart the console' or 'Start it again'", () => {
assert.equal(NEXT_STEP_LABELS.reconnect, "Reconnect the console");
assert.equal(NEXT_STEP_LABELS["restart-console"], "Reconnect the console");
assert.doesNotMatch(APP_JS, /'Restart the console'|"Start it again"/, "no stale label text left in app.js");
});
test("app.js draws the bar's right end through barNextSteps, not a hand-rolled copy of its order", () => {
assert.match(APP_JS, /const steps = barNextSteps\(\{ consoleDead, version: versionState \}\);/);
for (const gone of ["console-again", "version-update", "permissions-note", "console-status", "project-dir"]) {
assert.ok(!INDEX_HTML.includes(`id="${gone}"`), `index.html still has #${gone}`);
}
});
test("the bar reads project menu, New Session, agent menu, with both menus outside the scrolling row", () => {
const row = INDEX_HTML.slice(INDEX_HTML.indexOf('<div id="bar-row">'), INDEX_HTML.indexOf('<div id="project-menu"'));
const at = (id) => row.indexOf(`id="${id}"`);
assert.ok(at("project-menu-button") >= 0 && at("agent-restart") > at("project-menu-button"), "New Session follows the project menu");
assert.ok(at("agent-menu-button") > at("agent-restart"), "New Session sits just left of the agent menu");
assert.ok(!row.includes('id="project-menu"') && !row.includes('id="agent-menu"'), "the menus are not inside #bar-row, whose overflow would clip them");
assert.match(INDEX_HTML, /<div id="agent-menu"[\s\S]*?<button id="change-agent" role="menuitem" hidden>/, "Change agent lives in the agent menu");
assert.match(INDEX_HTML, /<div id="project-menu"[\s\S]*?<button id="change-project" role="menuitem">/, "Change project lives in the project menu");
});
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");
assert.equal(folderName("/"), "/");
assert.equal(folderName(""), "");
});
test("the context-window meter is gone for good: no stray element, poll, or backend call left wired up", () => {
for (const needle of ["bar-slot-meter", "context-group", "context-nudge", "context-restart", "Agent context"]) {
assert.ok(!INDEX_HTML.includes(needle), `index.html still has ${needle}`);
}
for (const needle of ["agent_context", "pollMeter", "nudgeDue", "renderMeter", "nudgePercent"]) {
assert.ok(!APP_JS.includes(needle), `app.js still has ${needle}`);
}
});
test("windowTitleFor names the project folder after Plan2Code, so two or more windows read apart in a taskbar", () => {
assert.equal(windowTitleFor("C:\\git\\azw3-to-pdf"), "Plan2Code - azw3-to-pdf");
assert.equal(windowTitleFor("/home/me/projects/plan2code"), "Plan2Code - plan2code");
assert.equal(windowTitleFor("C:\\git\\azw3-to-pdf\\"), "Plan2Code - azw3-to-pdf", "a trailing slash does not leave an empty last segment");
assert.equal(windowTitleFor("/"), "Plan2Code", "a root with nothing after it has no folder name to show");
assert.equal(windowTitleFor(""), "Plan2Code");
assert.equal(windowTitleFor(null), "Plan2Code");
assert.equal(windowTitleFor(undefined), "Plan2Code");
});
test("setProjectDir sets the OS window title through windowTitleFor, with a real permission to do so", () => {
assert.match(APP_JS, /window\.__TAURI__\.window\.getCurrentWindow\(\)\.setTitle\(windowTitleFor\(dir\)\)/, "setProjectDir is the one place every project-dir change flows through");
const caps = JSON.parse(fs.readFileSync(path.join(HERE, "../plan2code-app/src-tauri/capabilities/default.json"), "utf8"));
assert.ok(caps.permissions.includes("core:window:allow-set-title"), "the capability to call setTitle must be granted, or the call is silently refused at runtime");
});
+11 -1
View File
@@ -236,9 +236,19 @@ function appJsReaders(dir) {
.filter((f) => f.endsWith(".mjs") && f !== "test-web-console-shape.mjs" && !MAY_NAME_APP_JS.has(f))
.filter((f) => {
const text = fs.readFileSync(path.join(dir, f), "utf8");
// A bare readFileSync/readFile only counts against the web console's
// own public/app.js, named somewhere in the same statement: otherwise
// this would also catch a test reading some other app.js entirely,
// such as plan2code-app/ui/app.js (the desktop app's, a different file
// with its own shape rules in its own test). publicSource() implies
// the public dir by its own name, so any app.js it is handed counts.
const oneStatement = text
.split(";")
.some((statement) => /\b(readFileSync|readFile|publicSource)\s*\(/.test(statement) && /["'/]app\.js["']/.test(statement));
.some(
(statement) =>
/["'/]app\.js["']/.test(statement) &&
(/\bpublicSource\s*\(/.test(statement) || (/\b(readFileSync|readFile)\s*\(/.test(statement) && /\bpublic\b/.test(statement)))
);
const handedToAHelper = /\w\(\s*["'](?:(?:src\/web-console\/)?public\/)?app\.js["']\s*\)/.test(text);
const publicPath = /["']public["']\s*,\s*["']app\.js["']|\bpublic\/app\.js/.test(text) && /\breadFile(Sync)?\b/.test(text);
return oneStatement || handedToAHelper || publicPath;