mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 20:45:33 -08:00
Rebuild the desktop app's top bar and drop its context meter
AI Assisted
This commit is contained in:
1 parent
442904e6f2
commit
efc96e91c2
15 files changed
+606
-1247
No files matched your search
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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,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,
|
||||
|
||||
@@ -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");
|
||||
|
||||
Reference in new issue
Block a user