Start New Session's fresh agent on a console session of its own

AI Assisted
This commit is contained in:
jparkerweb committed 2026-10-25 12:48:14 -07:00
1 parent c1f41e4a82
commit 442904e6f2
5 files changed
+125 -35

No files matched your search

+12
View File
@@ -228,6 +228,15 @@ impl AnnounceServer {
self.current.lock().ok().and_then(|slot| slot.clone())
}
/// Forget the page most recently announced, so the next agent's `open`
/// starts a session of its own instead of joining that one. New Session
/// does this: a fresh agent's session meter starts over with it.
pub fn forget_current(&self) {
if let Ok(mut slot) = self.current.lock() {
*slot = None;
}
}
/// What goes on the agent's process so its `console.mjs open` shows pages
/// here. Every value belongs to this window. `embed_origin` is the origin of
/// the app page, so a console the agent starts allows being framed by it.
@@ -361,5 +370,8 @@ mod tests {
assert!(ask(server.token()).contains(r#""sid":"s1""#));
assert!(ask("wrong").starts_with("HTTP/1.1 403"));
assert_eq!(server.current().unwrap().workflow, "plan");
server.forget_current();
assert!(ask(server.token()).ends_with("null"), "forgotten: the next open starts its own session");
assert_eq!(server.current(), None);
}
}
+50 -8
View File
@@ -4,7 +4,7 @@
use std::sync::{Arc, Mutex};
use plan2code_app_lib::announce::AnnounceServer;
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentState, Sink};
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentState, 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;
@@ -35,7 +35,7 @@ struct AppState {
// 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: Mutex<Option<AnnounceServer>>,
announce: Arc<Mutex<Option<AnnounceServer>>>,
// The Node version `main()` found before opening the window (Task 1.7 exits
// cleanly on anything else, so this is always a passing version once the
// window exists), and which binary that was, with `resolved_path`'s PATH
@@ -127,16 +127,32 @@ fn agent_for_project(state: &AppState) -> Result<Arc<AgentManager>, String> {
}
let sink = page_sink(Arc::clone(&state.page), Arc::clone(&state.context));
let agent = Arc::new(AgentManager::new(dir, sink));
// A Restart leaves the brief for the dashboard, from the console that is running now.
let console = Arc::clone(&state.console);
agent.set_before_fresh(Arc::new(move || {
let sid = console.lock().ok()?.as_ref()?.session().sid.clone();
restart_brief::note_for_restart(&sid)
}));
agent.set_before_fresh(before_fresh_hook(state));
*guard = Some(Arc::clone(&agent));
Ok(agent)
}
// What New Session does before the fresh agent starts. It leaves the brief for
// the dashboard, from the console session running now, then forgets that
// session, so the fresh agent's `open` starts one of its own: a session that
// joined the old one would carry its meter along, still red after the very
// press the red meter asks for. The old console is left to shut itself down
// once the frame moves on to the new page.
fn before_fresh_hook(state: &AppState) -> BeforeFresh {
let console = Arc::clone(&state.console);
let announce = Arc::clone(&state.announce);
Arc::new(move || {
let sid = console.lock().ok().and_then(|guard| guard.as_ref().map(|sup| sup.session().sid.clone()));
let note = sid.and_then(|sid| restart_brief::note_for_restart(&sid));
if let Ok(guard) = announce.lock() {
if let Some(server) = guard.as_ref() {
server.forget_current();
}
}
note
})
}
fn current_agent(state: &AppState) -> Option<Arc<AgentManager>> {
state.agent.lock().ok().and_then(|guard| guard.clone())
}
@@ -691,6 +707,32 @@ mod tests {
assert!(!Arc::ptr_eq(&first, &second), "project-a's manager must never stand in for project-b's");
}
#[test]
fn new_session_forgets_the_windows_session_so_the_fresh_agent_starts_its_own() {
let state = state_for("project-a");
let server = AnnounceServer::start(Arc::new(|_| {})).unwrap();
let port: u16 = server.url().rsplit_once(':').unwrap().1.trim_end_matches("/page").parse().unwrap();
*state.announce.lock().unwrap() = Some(server);
let body = r#"{"url":"http://127.0.0.1:5000/s/abc/","sid":"s1","workflow":"plan"}"#;
let mut stream = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap();
let token = state.announce.lock().unwrap().as_ref().unwrap().token().to_string();
use std::io::{Read, Write};
write!(
stream,
"POST /page HTTP/1.1\r\nHost: 127.0.0.1\r\nx-plan2code-token: {token}\r\ncontent-length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
.unwrap();
let mut answer = String::new();
stream.read_to_string(&mut answer).unwrap();
assert!(answer.starts_with("HTTP/1.1 204"), "the page was announced: {answer}");
assert_eq!(state.announce.lock().unwrap().as_ref().unwrap().current().map(|n| n.sid), Some("s1".to_string()));
// No console supervised here, so no brief to write: only the forgetting.
assert_eq!(before_fresh_hook(&state)(), None);
assert_eq!(state.announce.lock().unwrap().as_ref().unwrap().current(), None, "the fresh agent's open must not join s1");
}
#[test]
fn the_same_folder_reuses_the_same_manager() {
let state = state_for("project-a");
+60 -26
View File
@@ -19,20 +19,23 @@ pub const READY_NOTE: &str = "Brief ready on the dashboard";
/// has not picked it up, so unused briefs do not pile up as chips.
static LAST_BRIEF: Mutex<Option<String>> = Mutex::new(None);
/// The skill named on a handoff record for a workflow `brief::skill_for_workflow`
/// does not map, such as `dashboard`: the console's own name for that pseudo-skill.
const UNMAPPED_SKILL: &str = "plan2code";
/// Write the brief for session `sid` as a handoff. A workflow with no mapped
/// skill (a dashboard, or one not yet known) still gets a short, honest chip
/// rather than nothing. Returns the handoff's id, or `None` when there is
/// truly nothing to write (the session names no worktree is an error, not a
/// `None`, since that is a broken session rather than an empty one).
/// Write the brief for session `sid` as a handoff. Returns the handoff's id,
/// or `None` when there is nothing worth picking up: a workflow with no mapped
/// skill (the dashboard, or one not yet known), whose only next step would be
/// "Open the dashboard" where the fresh agent lands anyway, and a session that
/// finished, whose finished screen already named what comes next, and one
/// that has posted nothing yet (no spec, progress, activity or questions),
/// whose brief would only repeat the skill's name. A session
/// that names no worktree is an error, not a `None`, since that is a broken
/// session rather than an empty one.
pub fn leave_brief(console_home: &Path, handoffs: &Path, sid: &str, when: DateTime<Local>) -> Result<Option<String>, String> {
let session = session_reader::load(console_home, sid).map_err(|e| e.to_string())?;
let state = &session.state;
let workflow = text(state, "workflow").unwrap_or("");
let skill = brief::skill_for_workflow(workflow);
let Some(skill) = brief::skill_for_workflow(workflow) else { return Ok(None) };
if finished(state) || empty(state) {
return Ok(None);
}
let worktree = text(state, "worktree").ok_or("the session names no worktree")?;
let project = text(state, "project").unwrap_or(worktree);
let spec = text(state, "specDir").filter(|s| valid_spec(s));
@@ -40,14 +43,11 @@ pub fn leave_brief(console_home: &Path, handoffs: &Path, sid: &str, when: DateTi
let git = brief::git_summary(Path::new(worktree));
let events = session_reader::read_ndjson(&session.dir.join("events.ndjson"));
let body = brief::build_brief(state, spec_dir.as_deref(), git.as_ref(), &events);
let title = match skill {
Some(skill) => match spec {
Some(spec) => format!("Restart of {skill} on {spec}"),
None => format!("Restart of {skill}"),
},
None => format!("Restart while on {workflow}"),
let title = match spec {
Some(spec) => format!("Restart of {skill} on {spec}"),
None => format!("Restart of {skill}"),
};
let record = handoff::Record { title: &title, worktree, project, spec, workflow, skill: skill.unwrap_or(UNMAPPED_SKILL) };
let record = handoff::Record { title: &title, worktree, project, spec, workflow, skill };
handoff::write(handoffs, when, &record, &body).map(Some)
}
@@ -73,6 +73,22 @@ fn text<'a>(state: &'a Value, key: &str) -> Option<&'a str> {
state.get(key).and_then(Value::as_str).filter(|s| !s.is_empty())
}
/// The session posted a `finish` that is not a pause. A pause's headline starts
/// with "Paused" (the page's `finishPaused`) and keeps a place worth picking up.
fn finished(state: &Value) -> bool {
let Some(finish) = state.get("finish").filter(|f| f.is_object()) else { return false };
let headline = finish.get("headline").and_then(Value::as_str).unwrap_or("").trim_start();
!headline.get(..6).is_some_and(|word| word.eq_ignore_ascii_case("paused"))
}
/// Nothing a fresh agent could pick up beyond the skill's name.
fn empty(state: &Value) -> bool {
let stage = state.get("headline").and_then(|h| text(h, "stage"));
let activity = state.get("agent").and_then(|a| text(a, "activity")).filter(|a| !a.trim().is_empty());
let items = state.get("items").and_then(Value::as_array).is_some_and(|items| !items.is_empty());
text(state, "specDir").is_none() && stage.is_none() && activity.is_none() && !items
}
fn valid_spec(spec: &str) -> bool {
spec.strip_prefix("specs/").is_some_and(|name| !name.is_empty() && name != "." && name != ".." && !name.contains(['/', '\\']))
}
@@ -135,16 +151,34 @@ mod tests {
}
#[test]
fn a_dashboard_session_still_leaves_a_chip() {
fn a_dashboard_session_leaves_nothing() {
let (home, _, handoffs) = session("dashboard", "dashboard", None);
let id = leave_brief(&home, &handoffs, "s1", when()).unwrap().expect("a handoff");
let record: Value = serde_json::from_str(&fs::read_to_string(handoffs.join(format!("{id}.json"))).unwrap()).unwrap();
assert_eq!(record["title"], "Restart while on dashboard");
assert_eq!(record["skill"], "plan2code");
assert_eq!(record["workflow"], "dashboard");
let doc = fs::read_to_string(handoffs.join(format!("{id}.md"))).unwrap();
assert!(doc.contains("- Workflow: `dashboard`"));
assert!(doc.contains("## Next task\n\nOpen the dashboard"));
assert_eq!(leave_brief(&home, &handoffs, "s1", when()).unwrap(), None);
assert!(!handoffs.exists());
}
#[test]
fn a_skill_that_has_posted_nothing_leaves_nothing() {
let (home, _, handoffs) = session("blank", "quick-task", None);
let file = home.join("sessions").join("s1").join("state.json");
let mut state: Value = serde_json::from_str(&fs::read_to_string(&file).unwrap()).unwrap();
state["headline"] = Value::Null;
fs::write(&file, state.to_string()).unwrap();
assert_eq!(leave_brief(&home, &handoffs, "s1", when()).unwrap(), None);
}
#[test]
fn a_finished_session_leaves_nothing_but_a_paused_one_does() {
let (home, _, handoffs) = session("finished", "implement", Some("specs/feature"));
let file = home.join("sessions").join("s1").join("state.json");
let mut state: Value = serde_json::from_str(&fs::read_to_string(&file).unwrap()).unwrap();
state["finish"] = serde_json::json!({ "headline": "Phase 5 is built", "dashboard": true });
fs::write(&file, state.to_string()).unwrap();
assert_eq!(leave_brief(&home, &handoffs, "s1", when()).unwrap(), None);
state["finish"] = serde_json::json!({ "headline": "Paused at Phase 5" });
fs::write(&file, state.to_string()).unwrap();
assert!(leave_brief(&home, &handoffs, "s1", when()).unwrap().is_some());
}
#[test]