From 0355fc4283ea8b1d4958db280f46391c03c54b6f Mon Sep 17 00:00:00 2001 From: barath-dev Date: Mon, 23 Nov 2026 12:14:47 +0530 Subject: [PATCH] Teams of sub-agents, the Simple layout, and a reload keeps your place - Team page: Team (a Claude Code session's details, or its right-click menu in Finder) draws the session as a team. The session leads; its members are Claude Code agent files in /.claude/agents, each in its model's colour, lit up while running, with every sub-agent the session started listed under the drawing. Members are added, edited (other front matter such as tools is kept) and removed (moved into Paddock's removed-agents folder) from the page. A session with no team says so, and offers the Report review template as a link. - Run the team: claude --bg with the team's brief and the work to do, on the lead's chosen model. A closed session is continued; for one open in a terminal the team starts as a new background session in the same folder, which the page then follows. A session waiting for an answer offers Open in a terminal. - Teams in the Finder sidebar counts the teams working now, and shows every session whose sub-agents worked in the last day (/api/teams). - Simple layout (/simple, Settings > Appearance > Layout): a card for each project folder with its sessions and one button each, account chips, today's tokens, and the teams working. Its script is all inside one function, so nothing in it replaces a browser function. - Fixed: closing one session from Finder did nothing since 2.5.0. Its tick box is not shown, so the sheet found none ticked and sent nothing. - Fixed: Finder's Open team, and Team in its menu, opened nothing. The page's own open() takes the place of window.open; they use links now. - A reload stays where it was: Finder keeps its place and selected session in the address (#teams, #f=, #a=, &s=), Simple its search, opened cards and scroll for the tab, and / hands the # on. - Transcripts the team views read are indexed once and cached by size and time, as they are asked for every few seconds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013DS9XhJVN73JGnZEqrX89o --- README.md | 61 +++++- src/history.rs | 2 +- src/main.rs | 1 + src/server.rs | 74 +++++++ src/team.rs | 461 +++++++++++++++++++++++++++++++++++++++ tests/e2e.rs | 6 + ui/app.js | 10 +- ui/concept.css | 83 +++++++ ui/concept.js | 175 ++++++++++++++- ui/icons.js | 1 + ui/settings.js | 9 +- ui/simple.css | 221 +++++++++++++++++++ ui/simple.html | 34 +++ ui/simple.js | 570 +++++++++++++++++++++++++++++++++++++++++++++++++ ui/team.css | 230 ++++++++++++++++++++ ui/team.html | 40 ++++ ui/team.js | 513 ++++++++++++++++++++++++++++++++++++++++++++ ui/theme.js | 7 +- 18 files changed, 2479 insertions(+), 19 deletions(-) create mode 100644 src/team.rs create mode 100644 ui/simple.css create mode 100644 ui/simple.html create mode 100644 ui/simple.js create mode 100644 ui/team.css create mode 100644 ui/team.html create mode 100644 ui/team.js diff --git a/README.md b/README.md index 7372acb..9e4f564 100644 --- a/README.md +++ b/README.md @@ -170,7 +170,28 @@ files in them, accounts as tags in the sidebar. day (or move to it with the arrow keys and press Enter) to see its tokens by kind, hour and account, how it compares with its week and the year, and the sessions that used them. -### Both layouts +### Simple layout + +A card for each project folder, and nothing else to learn. Pick it in Settings › +Appearance › Layout; the page then opens on it (`/simple`). + +- **Cards**: each shows the folder, the accounts used in it, how it is doing (`2 need you`, + `1 working`, or when it was last used) and its sessions, needing you first, then + working, then the latest. **+ N more** opens the rest of a card's sessions. Projects + that need you come first, then working, then pinned, then the most recently used; + ones not used for 30 days fold under **Show older projects**. +- **One button per session**: **Open** for a running one, **Resume** for a saved one. Its + **⋯** menu has Rename, Pin, Copy command, Team, Open in your editor and Close. A + card's **⋯** pins the project to the top or opens it in your editor. +- **Account chips** show one account's projects (the choice is remembered), the line under + them counts **today's tokens**, and **Teams working** appears while a team is running, + each opening its Team page. +- **Search** (`/` to start, Esc to clear) finds projects by folder, session names and + prompts. + +The templates, theme and primary colour from Settings apply here as on the other layouts. + +### Every layout - **Rename** a session with the pencil on its row, by double-clicking its name, or with Enter in the Finder layout. The name is kept by Paddock and shown in the page and on @@ -197,6 +218,40 @@ a terminal, doing nothing), `Done` (background task finished, not closed), `Clos A Codex account's name is shown with a small **Codex** mark where the name does not already say so. +### Teams + +**Team**, in a Claude Code session's details, opens a page that draws the session as a +team: the session itself leads, at the top, and its members, the sub-agents it can hand +work to, sit under it, each in the colour of its model (Opus, Sonnet, Haiku). A member's +box lights up and the line to it moves while it is running, and the list under the +drawing shows every sub-agent the session started, with its task, model and tokens. +Sub-agents it started that are not members, such as Claude Code's own `Explore`, are +drawn on a row of their own. + +- **Add a member** with a name, a model and one sentence on what it does, which the lead + reads to decide when to hand work over. Instructions are optional. Members are Claude + Code agent files, `/.claude/agents/.md`, so any session started in that + folder can use them; one already running in a terminal sees a new member once it is resumed. Editing + a file keeps what else its front matter says, such as `tools`. +- **Report review** sets up a team in one click: the lead analyses the report, `scorer` + on Sonnet scores it and `answer-checker` on Haiku checks the answers. +- **Run the team**: say what the team should work on and pick the lead's model (Opus by + default). Claude Code runs it in the background (`claude --bg`): a closed session is + continued, and for one open in a terminal the team starts as a new session in the same + folder, which the page then follows. Either way Claude Code starts afresh, so it sees + the members as they are now. The folder must be one you have trusted in Claude Code. + If the lead stops to ask you something, its box says so and opens it in a terminal. + **Copy the prompt instead** gives the same brief to paste into a session yourself. +- **Remove** moves the member's file into Paddock's `removed-agents` folder rather than + deleting it. + +**Teams**, in the Finder sidebar, watches every team at once. It counts the teams working +right now, and its view shows each Claude Code session whose sub-agents worked in the last +day: the lead with its model and how it is doing, and each sub-agent with its model and +what it is working on, pulsing while it runs. Sub-agents that are not members of the team +have a dashed outline. Working teams come first. It updates every few seconds, and +**Open team** opens that team's page. + ## What it never does - It never deletes or moves anything under an account folder. The test suite checks this @@ -207,6 +262,8 @@ already say so. - Renaming an account or its shortcut changes nothing inside the account folder. - Renaming or pinning a session changes nothing in its transcript. Names and pins are kept in `titles.json` and `pins.json`. +- The one place it writes outside its own folder is a project's `.claude/agents`, when you + add or change a team member. What the lead does is kept in `teams.json`. - Its own records are rewritten in place with the previous version kept as `.bak`. The only files it removes are its own launchers: its pid file, a command link it created @@ -281,6 +338,8 @@ In the settings folder above: | `closed.json` | Sessions closed through the tool. | | `titles.json` | Names you gave to sessions. | | `pins.json` | Sessions and folders you pinned. | +| `teams.json` | What each team's lead does, as written on the Team page. | +| `removed-agents/` | Team members' files, moved here when they are removed from a team. | | `history-cache.json` | Rebuildable index of saved conversations, with their token counts. | | `ui-token` | Access key for the web app (readable only by you). | | `ui.pid`, `ui.log` | The running server's pid and its log. | diff --git a/src/history.rs b/src/history.rs index 1759b18..33910ff 100644 --- a/src/history.rs +++ b/src/history.rs @@ -283,7 +283,7 @@ pub fn note_prompt(entry: &mut Entry, typed: &mut Vec, prompt: &str) { } /// Read one saved conversation into a small summary. Never writes to it. -fn index_transcript(path: &Path) -> Entry { +pub fn index_transcript(path: &Path) -> Entry { let mut entry = Entry { session_id: path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(), ..Entry::default() diff --git a/src/main.rs b/src/main.rs index bc9d742..b5c03ee 100644 --- a/src/main.rs +++ b/src/main.rs @@ -25,6 +25,7 @@ mod sessions; mod setup; mod shell; mod store; +mod team; mod titles; mod tools; mod update; diff --git a/src/server.rs b/src/server.rs index 32c0e12..a2573c0 100644 --- a/src/server.rs +++ b/src/server.rs @@ -28,6 +28,7 @@ use crate::report; use crate::resume::{self, Target}; use crate::sessions::{self, Session}; use crate::store::{state_dir, state_file}; +use crate::team; use crate::titles; use crate::update; use crate::util::{err, expand_tilde, log_stamp, now_ms, setting, tilde, Error, Result}; @@ -60,6 +61,12 @@ const UI: &[(&str, &str, &[u8])] = &[ ("/concept", "text/html; charset=utf-8", include_bytes!("../ui/concept.html")), ("/concept.js", "text/javascript; charset=utf-8", include_bytes!("../ui/concept.js")), ("/concept.css", "text/css; charset=utf-8", include_bytes!("../ui/concept.css")), + ("/simple", "text/html; charset=utf-8", include_bytes!("../ui/simple.html")), + ("/simple.js", "text/javascript; charset=utf-8", include_bytes!("../ui/simple.js")), + ("/simple.css", "text/css; charset=utf-8", include_bytes!("../ui/simple.css")), + ("/team", "text/html; charset=utf-8", include_bytes!("../ui/team.html")), + ("/team.js", "text/javascript; charset=utf-8", include_bytes!("../ui/team.js")), + ("/team.css", "text/css; charset=utf-8", include_bytes!("../ui/team.css")), ]; pub fn port() -> u16 { @@ -355,6 +362,58 @@ impl App { Ok(json!({ "sessions": found.into_iter().take(50).map(|(_, row)| row).collect::>() })) } + /// The folder an open session runs in, as Claude Code reports it. + fn running_in(&self, account: &str, session_id: &str) -> Result> { + let listing = self.sessions(false)?; + Ok(listing.0.iter().find(|s| s.open && s.account == account && s.session_id == session_id).map(|s| s.cwd.clone())) + } + + /// A session's team, for the team page: `?account=&session=`. + fn team(&self, query: &str) -> Result { + let param = |name: &str| query.split('&').find_map(|pair| pair.strip_prefix(name)?.strip_prefix('=')).unwrap_or(""); + self.team_of(&self.sessions(false)?.0, param("account"), param("session")) + } + + fn team_of(&self, listing: &[Session], account: &str, session_id: &str) -> Result { + let session = listing.iter().find(|s| s.account == account && s.session_id == session_id); + let title = match session { + Some(sess) => Some(sess.name.clone()), + None => titles::Titles::load()?.get(&accounts::get_account(account)?.dir, session_id).map(String::from), + }; + let running_in = session.filter(|s| s.open).map(|s| s.cwd.as_str()); + let mut team = team::team(account, session_id, running_in, title)?; + // How the lead is doing, and what the page asks for to open it in a terminal. + if let (Some(sess), Some(fields)) = (session, team.as_object_mut()) { + fields.insert("status".into(), json!(sess.status)); + fields.insert("key".into(), json!(sess.key)); + } + Ok(team) + } + + /// Every team that has worked in the last day, the most recently busy first, for + /// the Teams view. One that cannot be read is left out rather than failing the rest. + fn teams(&self) -> Result { + let listing = self.sessions(false)?; + let since = now_ms() - 24 * 3_600_000; + let teams: Vec = team::recent(since)? + .iter() + .take(40) + .filter_map(|(account, session_id)| self.team_of(&listing.0, account, session_id).ok()) + .collect(); + Ok(json!({ "teams": teams })) + } + + /// Start the team in the background, and say which session it runs as. + fn run_team(&self, account: &str, session_id: &str, body: &Value) -> Result { + let text = |field: &str| body.get(field).and_then(Value::as_str).unwrap_or(""); + let running_in = self.running_in(account, session_id)?; + let id = team::run(account, session_id, running_in.as_deref(), text("prompt"), text("model"))?; + self.invalidate(false); + let listing = self.sessions(true)?; + let started = listing.0.iter().find(|s| s.account == account && s.id == id); + Ok(json!({ "ok": true, "id": id, "sessionId": started.map_or(session_id, |s| s.session_id.as_str()) })) + } + // -- actions fn close(&self, keys: &[String]) -> Result { @@ -516,6 +575,17 @@ impl App { "/api/pins" => self.pin(body, body.get("pinned").and_then(Value::as_bool).unwrap_or(true)), "/api/history/resume" => self.resume_history(need("account")?, need("sessionId")?), "/api/editor/open" => self.open_in_editor(need("editor")?, body), + "/api/team/run" => self.run_team(need("account")?, need("sessionId")?, body), + "/api/team/member" | "/api/team/remove" | "/api/team/lead" => { + let (account, session_id) = (need("account")?, need("sessionId")?); + let running_in = self.running_in(account, session_id)?; + let running_in = running_in.as_deref(); + match path { + "/api/team/member" => team::save_member(account, session_id, running_in, body.get("member").unwrap_or(&Value::Null)), + "/api/team/remove" => team::remove_member(account, session_id, running_in, need("file")?), + _ => team::set_lead(account, session_id, running_in, text("job").unwrap_or("")), + } + } "/api/update/check" => { // A failed check is shown in the status, not as a failed request. let _ = update::check(); @@ -628,6 +698,8 @@ fn static_file(path: &str) -> Option<(&'static str, Vec)> { let name = match path { "/" => "index.html", "/finder" | "/concept" => "concept.html", + "/team" => "team.html", + "/simple" => "simple.html", _ => &path[1..], }; if let Ok(bytes) = fs::read(PathBuf::from(dir).join(name)) { @@ -671,6 +743,8 @@ fn handle(app: &App, mut request: Request) { "/api/history" => app.history(), "/api/usage" => app.usage(), "/api/usage/sessions" => app.usage_sessions(&query), + "/api/team" => app.team(&query), + "/api/teams" => app.teams(), "/api/diagnostics" => Ok(report::diagnostics()), "/api/editors" => Ok(json!({ "editors": editors::installed().iter().map(|e| json!({ "id": e.id, "name": e.name })).collect::>() })), _ => return respond_json(request, 404, &json!({ "error": "Not found." })), diff --git a/src/team.rs b/src/team.rs new file mode 100644 index 0000000..4d4e058 --- /dev/null +++ b/src/team.rs @@ -0,0 +1,461 @@ +//! A session's team: the sub-agents it can hand work to, and the ones it has run. +//! +//! Members are Claude Code's own agent files, `/.claude/agents/.md`, +//! so the session sees them as it sees any other. What the lead (the session itself) +//! is for is only a note for the page, kept in the tool's own records. The runs +//! are read from the session's `subagents/` folder, read-only. + +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::time::{Duration, UNIX_EPOCH}; + +use serde_json::{json, Map, Value}; + +use crate::accounts::{self, Account}; +use crate::history::{self, Entry, Tokens}; +use crate::proc; +use crate::store::{self, state_file}; +use crate::tools::{self, Tool}; +use crate::util::{err, now_ms, path_str, squash, Result}; + +const MAX_NAME: usize = 48; +const MAX_JOB: usize = 400; +const MAX_INSTRUCTIONS: usize = 20_000; +const MAX_PROMPT: usize = 100_000; +/// What a member may run on: Claude Code's aliases, or a model's full id. +const MODELS: [&str; 4] = ["opus", "sonnet", "haiku", "inherit"]; + +pub fn teams_file() -> PathBuf { + state_file("teams.json") +} + +fn key(account_dir: &str, session_id: &str) -> String { + format!("{account_dir}|{session_id}") +} + +/// The account, the session's transcript (none before its first prompt) and the folder it runs in. +struct Place { + account: Account, + transcript: Option, + cwd: PathBuf, +} + +/// `running_in` is the folder Claude Code reports for a running session, for one +/// whose transcript does not say yet: it holds nothing but a title until the first prompt. +fn find(account: &str, session_id: &str, running_in: Option<&str>) -> Result<(Place, Entry)> { + let account = accounts::get_account(account)?; + if account.tool != Tool::Claude { + return err("Teams are made of Claude Code sub-agents, so only Claude Code sessions have one."); + } + if session_id.is_empty() || !session_id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') { + return err("That is not a session id."); + } + let file = format!("{session_id}.jsonl"); + let transcript = fs::read_dir(Path::new(&account.dir).join("projects")) + .ok() + .into_iter() + .flatten() + .flatten() + .map(|folder| folder.path().join(&file)) + .find(|path| path.is_file()); + let entry = transcript.as_deref().map(indexed).unwrap_or_default(); + let cwd = entry.cwd.clone().or_else(|| running_in.filter(|c| !c.is_empty()).map(String::from)); + let Some(cwd) = cwd else { + return err("This session does not say which folder it runs in yet. Send it a prompt first."); + }; + Ok((Place { account, transcript, cwd: PathBuf::from(cwd) }, entry)) +} + +fn agents_dir(cwd: &Path) -> PathBuf { + cwd.join(".claude").join("agents") +} + +/// The model that wrote most, as the one a conversation runs on. +fn main_model(models: &BTreeMap) -> Option { + models.iter().max_by_key(|(_, t)| t.output).map(|(m, _)| m.clone()) +} + +// ------------------------------------------------------------------ reading + +/// The team of a session: who leads it, its members and what they have run. +/// `running_in` is set while the session is open, so a run it never finished can +/// be told from one still going. +pub fn team(account: &str, session_id: &str, running_in: Option<&str>, title: Option) -> Result { + let open = running_in.is_some(); + let (place, entry) = find(account, session_id, running_in)?; + let job = load_leads()?.get(&key(&place.account.dir, session_id)).and_then(Value::as_str).map(String::from); + let members = members(&place.cwd); + let runs = runs(&place, open); + Ok(json!({ + "account": place.account.name, + "sessionId": session_id, + "title": title.or(entry.title).unwrap_or_else(|| session_id.to_string()), + "cwd": path_str(&place.cwd), + "open": open, + "agentsDir": path_str(&agents_dir(&place.cwd)), + "lead": { "model": main_model(&entry.models), "job": job, "tokens": entry.tokens }, + "members": members, + "runs": runs, + })) +} + +fn members(cwd: &Path) -> Vec { + let Ok(files) = fs::read_dir(agents_dir(cwd)) else { return Vec::new() }; + let mut found: Vec = files + .flatten() + .map(|f| f.path()) + .filter(|p| p.extension().is_some_and(|x| x == "md") && p.is_file()) + .filter_map(|path| { + let text = fs::read_to_string(&path).ok()?; + let (fields, body) = split(&text); + let field = |name: &str| fields.iter().find(|(k, _)| k == name).map(|(_, v)| value_of(v)); + let file = path.file_stem()?.to_string_lossy().into_owned(); + Some(json!({ + "file": file, + "name": field("name").filter(|n| !n.is_empty()).unwrap_or_else(|| file.clone()), + "job": field("description").unwrap_or_default(), + "model": field("model").filter(|m| !m.is_empty()).unwrap_or_else(|| "inherit".into()), + "tools": field("tools"), + "instructions": body.trim(), + })) + }) + .collect(); + found.sort_by(|a, b| a["name"].as_str().cmp(&b["name"].as_str())); + found +} + +fn mtime_ms(meta: &fs::Metadata) -> Option { + Some(meta.modified().ok()?.duration_since(UNIX_EPOCH).ok()?.as_millis()) +} + +/// A transcript, indexed. Each is read again only when it has changed, as the +/// pages ask every few seconds. +fn indexed(path: &Path) -> Entry { + static SEEN: Mutex> = Mutex::new(BTreeMap::new()); + let stamp = fs::metadata(path).ok().and_then(|m| Some((m.len(), mtime_ms(&m)?))); + let mut seen = SEEN.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if let (Some((size, at, entry)), Some(stamp)) = (seen.get(path), stamp) { + if (*size, *at) == stamp { + return entry.clone(); + } + } + let entry = history::index_transcript(path); + if let Some((size, at)) = stamp { + seen.insert(path.to_path_buf(), (size, at, entry.clone())); + } + entry +} + +/// What each sub-agent the session started did, oldest first. +fn runs(place: &Place, open: bool) -> Vec { + let Some(transcript) = &place.transcript else { return Vec::new() }; + let dir = transcript.with_extension("").join("subagents"); + let mut files = Vec::new(); + agent_files(&dir, &mut files); + let mut found: Vec<(i64, Value)> = files + .into_iter() + .filter_map(|path| { + let mtime = mtime_ms(&fs::metadata(&path).ok()?)?; + let entry = indexed(&path); + let about = store::read_json_or_null(&path.with_extension("meta.json")); + let text = |name: &str| about.get(name).and_then(Value::as_str).unwrap_or("").to_string(); + let finished = about.get("finished").and_then(Value::as_bool).unwrap_or(false); + let started = entry.started_at.unwrap_or(mtime as i64); + let id = path.file_stem()?.to_string_lossy().trim_start_matches("agent-").to_string(); + Some((started, json!({ + "id": id, + "type": Some(text("agentType")).filter(|t| !t.is_empty()).unwrap_or_else(|| "general-purpose".into()), + "task": text("description"), + "model": main_model(&entry.models), + "depth": about.get("spawnDepth").and_then(Value::as_u64).unwrap_or(1), + "state": if finished { "done" } else if open { "running" } else { "stopped" }, + "tokens": entry.tokens, + "startedAt": started, + "lastAt": mtime as i64, + }))) + }) + .collect(); + found.sort_by_key(|(at, _)| *at); + found.into_iter().map(|(_, run)| run).collect() +} + +/// The Claude Code sessions whose sub-agents have worked since `since` (ms since +/// 1970), as (account name, session id), the most recently busy first. +pub fn recent(since: i64) -> Result> { + let mut found: Vec<(u128, String, String)> = Vec::new(); + for acc in accounts::load_accounts(false)?.into_iter().filter(|a| a.tool == Tool::Claude) { + let Ok(projects) = fs::read_dir(Path::new(&acc.dir).join("projects")) else { continue }; + for session in projects.flatten().filter_map(|p| fs::read_dir(p.path()).ok()).flatten().flatten() { + let mut files = Vec::new(); + agent_files(&session.path().join("subagents"), &mut files); + let last = files.iter().filter_map(|f| mtime_ms(&fs::metadata(f).ok()?)).max(); + if let Some(last) = last.filter(|at| *at as i64 >= since) { + found.push((last, acc.name.clone(), session.file_name().to_string_lossy().into_owned())); + } + } + } + found.sort_by_key(|(at, ..)| std::cmp::Reverse(*at)); + Ok(found.into_iter().map(|(_, account, session)| (account, session)).collect()) +} + +/// `agent-*.jsonl` under a session's `subagents/`, a workflow's a folder further down. +fn agent_files(dir: &Path, found: &mut Vec) { + let Ok(files) = fs::read_dir(dir) else { return }; + for file in files.flatten() { + let path = file.path(); + let name = file.file_name().to_string_lossy().into_owned(); + match file.file_type() { + Ok(t) if t.is_dir() => agent_files(&path, found), + Ok(t) if t.is_file() && name.starts_with("agent-") && name.ends_with(".jsonl") => found.push(path), + _ => {} + } + } +} + +// ----------------------------------------------------------- agent files + +/// Front matter as `(key, lines)` in order, a key's lines being its own and any +/// that continue it, and the text after it. A file without any is all text. +fn split(text: &str) -> (Vec<(String, Vec)>, String) { + let text = text.strip_prefix('\u{feff}').unwrap_or(text); + let Some(rest) = text.strip_prefix("---\n").or_else(|| text.strip_prefix("---\r\n")) else { + return (Vec::new(), text.to_string()); + }; + let mut fields: Vec<(String, Vec)> = Vec::new(); + let mut read = 0; + for line in rest.split_inclusive('\n') { + read += line.len(); + let bare = line.trim_end_matches(['\n', '\r']); + if bare == "---" { + return (fields, rest[read..].to_string()); + } + match fields.last_mut() { + Some((_, kept)) if bare.is_empty() || bare.starts_with([' ', '\t']) => kept.push(bare.to_string()), + _ => fields.push((bare.split(':').next().unwrap_or("").trim().to_string(), vec![bare.to_string()])), + } + } + // Never closed: not front matter after all. + (Vec::new(), text.to_string()) +} + +/// A member's file name, as the page sends it back: one name, no folders. +fn plain_file(file: &str) -> bool { + !file.is_empty() && !file.contains(['/', '\\']) && !file.starts_with('.') +} + +/// A field's value: on its line, quoted or not, or folded from the lines under it. +fn value_of(lines: &[String]) -> String { + let first = lines.first().map(String::as_str).unwrap_or(""); + let value = first.split_once(':').map(|(_, v)| v.trim()).unwrap_or(""); + if matches!(value, "|" | ">" | "|-" | ">-" | "") && lines.len() > 1 { + return squash(&lines[1..].join(" ")); + } + if value.starts_with('"') { + if let Ok(Value::String(s)) = serde_json::from_str::(value) { + return s; + } + } + if let Some(inner) = value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')) { + return inner.replace("''", "'"); + } + value.to_string() +} + +fn valid_name(name: &str) -> bool { + let mut chars = name.chars(); + name.len() <= MAX_NAME + && chars.next().is_some_and(|c| c.is_ascii_lowercase()) + && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') +} + +fn valid_model(model: &str) -> bool { + MODELS.contains(&model) + || (model.starts_with("claude-") && model.len() <= 64 && model.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | '[' | ']'))) +} + +/// The file's text with `name`, `description` and `model` set, keeping whatever +/// else its front matter says (tools, colour, ...) as it was. +fn render(old: Option<&str>, name: &str, job: &str, model: &str, instructions: &str) -> String { + let (mut fields, _) = old.map(split).unwrap_or_default(); + let quoted = serde_json::to_string(job).unwrap_or_default(); + for (field, line) in [("name", format!("name: {name}")), ("description", format!("description: {quoted}")), ("model", format!("model: {model}"))] { + match fields.iter_mut().find(|(k, _)| k == field) { + Some((_, lines)) => *lines = vec![line], + None => fields.push((field.to_string(), vec![line])), + } + } + let head: Vec = fields.into_iter().flat_map(|(_, lines)| lines).collect(); + format!("---\n{}\n---\n\n{}\n", head.join("\n"), instructions.trim()) +} + +/// Written when no instructions are given, so the member knows its place. +fn default_instructions(name: &str, job: &str) -> String { + format!( + "You are {name}, one member of a team. The lead (the main session) hands you work.\n\n\ + What you do: {job}\n\n\ + Do only that, then report back to the lead: what you found, and anything you could not do." + ) +} + +/// Add a member, or change one (`file` is the one being changed; a new name renames it). +pub fn save_member(account: &str, session_id: &str, running_in: Option<&str>, member: &Value) -> Result { + let (place, _) = find(account, session_id, running_in)?; + let text = |field: &str| member.get(field).and_then(Value::as_str).unwrap_or("").trim().to_string(); + let (name, model, file) = (text("name"), text("model"), text("file")); + let job = squash(&text("job")); + let instructions = text("instructions"); + if !valid_name(&name) { + return err("A name is lowercase letters, digits and dashes, starting with a letter, like 'scorer'."); + } + if job.is_empty() || job.chars().count() > MAX_JOB { + return err(format!("Say in a sentence what {name} does (up to {MAX_JOB} characters). The lead reads it to decide when to hand work over.")); + } + let model = if model.is_empty() { "inherit".to_string() } else { model }; + if !valid_model(&model) { + return err("The model is opus, sonnet, haiku, inherit, or a model's full id."); + } + if instructions.len() > MAX_INSTRUCTIONS { + return err("The instructions are too long."); + } + if !file.is_empty() && !plain_file(&file) { + return err("That member could not be found."); + } + let dir = agents_dir(&place.cwd); + let path = dir.join(format!("{name}.md")); + let previous = (!file.is_empty()).then(|| dir.join(format!("{file}.md"))); + if previous.as_ref() != Some(&path) && path.exists() { + return err(format!("There is already a member called {name}.")); + } + let old = previous.as_ref().and_then(|p| fs::read_to_string(p).ok()); + let instructions = if instructions.is_empty() { default_instructions(&name, &job) } else { instructions }; + store::write_text(&path, &render(old.as_deref(), &name, &job, &model, &instructions), false)?; + if let Some(previous) = previous.filter(|p| *p != path && p.exists()) { + fs::remove_file(previous)?; + } + Ok(json!({ "ok": true, "path": path_str(&path) })) +} + +/// Take a member off the team. Its file is moved into the tool's own records, not deleted. +pub fn remove_member(account: &str, session_id: &str, running_in: Option<&str>, file: &str) -> Result { + let (place, _) = find(account, session_id, running_in)?; + if !plain_file(file) { + return err("That member could not be found."); + } + let path = agents_dir(&place.cwd).join(format!("{file}.md")); + if !path.is_file() { + return err("That member could not be found. It may have been removed already."); + } + let kept = state_file("removed-agents").join(format!("{}-{file}.md", now_ms())); + fs::create_dir_all(kept.parent().unwrap_or(Path::new(".")))?; + if fs::rename(&path, &kept).is_err() { + fs::copy(&path, &kept)?; + fs::remove_file(&path)?; + } + Ok(json!({ "ok": true, "keptAt": path_str(&kept) })) +} + +// ---------------------------------------------------------------- running + +/// Set the team to work: Claude Code runs the session in the background (`claude --bg`), +/// so the team page can follow it. A closed session is continued; one open in a terminal +/// is left alone, and the team starts as a new session beside it, in the same folder. +/// Returns the background session's short id, as `claude agents` lists it. +pub fn run(account: &str, session_id: &str, running_in: Option<&str>, prompt: &str, model: &str) -> Result { + let (place, _) = find(account, session_id, running_in)?; + let prompt = prompt.trim(); + if prompt.is_empty() || prompt.len() > MAX_PROMPT { + return err("Say what the team should work on."); + } + if model == "inherit" || !valid_model(model) { + return err("The lead runs on opus, sonnet, haiku, or a model's full id."); + } + let mut cmd = tools::command(&place.account)?; + cmd.current_dir(&place.cwd).args(["--bg", "--model", model]); + if running_in.is_none() && place.transcript.is_some() { + cmd.args(["--resume", session_id]); + } + cmd.args(["--", prompt]); + let output = proc::run(&mut cmd, Duration::from_secs(60))?; + match backgrounded(&output.stdout) { + Some(id) => Ok(id), + None => err(format!("Claude Code did not start it: {}", output.last_line())), + } +} + +/// The id in `claude --bg`'s "backgrounded · ". +fn backgrounded(stdout: &str) -> Option { + let line = stdout.lines().find(|l| l.trim_start().starts_with("backgrounded"))?; + let id = line.rsplit([' ', '\u{b7}']).find(|w| !w.is_empty())?; + id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-').then(|| id.to_string()) +} + +// --------------------------------------------------------------- the lead + +fn load_leads() -> Result> { + Ok(store::read_json(&teams_file())?.and_then(|data| data.get("leads").and_then(Value::as_object).cloned()).unwrap_or_default()) +} + +/// What the lead is for, as the page shows it. Empty forgets it. +pub fn set_lead(account: &str, session_id: &str, running_in: Option<&str>, job: &str) -> Result { + let (place, _) = find(account, session_id, running_in)?; + let job: String = squash(job).chars().take(MAX_JOB).collect(); + store::locked(|| { + let mut leads = load_leads()?; + match job.is_empty() { + true => leads.remove(&key(&place.account.dir, session_id)), + false => leads.insert(key(&place.account.dir, session_id), json!(job)), + }; + store::write_json(&teams_file(), &json!({ "version": 1, "leads": leads }), true) + })?; + Ok(json!({ "ok": true })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_front_matter() { + let text = "---\nname: scorer\ndescription: \"Scores: the report\"\nmodel: sonnet\ntools: Read, Grep\ncolor: blue\n---\n\nYou score.\n"; + let (fields, body) = split(text); + assert_eq!(fields.iter().map(|(k, _)| k.as_str()).collect::>(), ["name", "description", "model", "tools", "color"]); + assert_eq!(value_of(&fields[1].1), "Scores: the report"); + assert_eq!(body.trim(), "You score."); + let folded = "---\nname: x\ndescription: >\n one\n two\n---\nbody"; + let (fields, body) = split(folded); + assert_eq!(value_of(&fields[1].1), "one two"); + assert_eq!(body, "body"); + assert!(split("no front matter").0.is_empty()); + assert!(split("---\nname: never closed\n").0.is_empty()); + } + + #[test] + fn keeps_what_it_does_not_change() { + let old = "---\nname: scorer\ndescription: >\n old\n job\ntools: Read\ncolor: blue\n---\nold body\n"; + let new = render(Some(old), "grader", "Scores \"it\"", "haiku", "New body"); + assert_eq!(new, "---\nname: grader\ndescription: \"Scores \\\"it\\\"\"\ntools: Read\ncolor: blue\nmodel: haiku\n---\n\nNew body\n"); + let (fields, body) = split(&new); + assert_eq!(value_of(&fields[1].1), "Scores \"it\""); + assert_eq!(body.trim(), "New body"); + } + + #[test] + fn reads_the_background_id() { + assert_eq!(backgrounded("backgrounded \u{b7} eeda6102\n claude agents list sessions\n").as_deref(), Some("eeda6102")); + assert_eq!(backgrounded("Workspace not trusted. Run `claude` in /x once"), None); + } + + #[test] + fn names_and_models() { + assert!(valid_name("answer-checker")); + assert!(!valid_name("Answer")); + assert!(!valid_name("../x")); + assert!(!valid_name("-x")); + assert!(valid_model("haiku")); + assert!(valid_model("claude-sonnet-5-5")); + assert!(!valid_model("gpt-5")); + assert!(!valid_model("sonnet\nmalicious: true")); + } +} diff --git a/tests/e2e.rs b/tests/e2e.rs index ed8a8c6..108fbe5 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -1009,6 +1009,12 @@ fn server_guards_and_disconnect() { assert_eq!(m.get("/api/state", Some(&token), Some("evil.example")).0, 403, "wrong host"); assert_eq!(m.get("/", None, Some("evil.example")).0, 403, "wrong host for the page"); assert_eq!(m.get("/", None, None).0, 200, "the page itself needs no token"); + // The Simple layout is served like the others, and refused like them. + for page in ["/simple", "/simple.js", "/simple.css"] { + assert_eq!(m.get(page, None, None).0, 200, "{page}"); + } + assert!(m.get("/simple", None, None).1.contains("/simple.js"), "the Simple page loads its script"); + assert_eq!(m.get("/simple", None, Some("evil.example")).0, 403, "wrong host for the Simple page"); assert_eq!(m.post("/api/refresh", &token, "Content-Type: application/json\r\nOrigin: http://evil.example\r\n", "{}").0, 403); assert_eq!(m.post("/api/refresh", &token, "Content-Type: text/plain\r\n", "{}").0, 415); assert_eq!(m.post("/api/refresh", &token, "Content-Type: application/json\r\n", "{}").0, 200); diff --git a/ui/app.js b/ui/app.js index ae78b7c..19b047a 100644 --- a/ui/app.js +++ b/ui/app.js @@ -1196,6 +1196,13 @@ function renderPanel(entries) { panelKey = e.key; } +// A Claude Code session's sub-agents, drawn as a team, on a page of their own. +function teamButton(e, cls) { + if (!e.sessionId || toolOf(e.account) !== 'claude') return null; + const url = `/team?account=${encodeURIComponent(e.account)}&session=${encodeURIComponent(e.sessionId)}`; + return h('button', { type: 'button', class: cls, title: 'Its sub-agents, as a team', onclick: () => window.open(url, '_blank') }, icon('users'), 'Team'); +} + function entryDetails(e, where) { const { session: s, item } = e; const account = state.data.accounts.find((a) => a.name === e.account) || {}; @@ -1209,7 +1216,8 @@ function entryDetails(e, where) { onclick: () => copyText(e.command) }, icon('copy'), 'Copy command'), editorButton(e), e.sessionId && h('button', { type: 'button', class: 'btn btn-small', onclick: () => startRename(e, where) }, icon('pencil'), 'Rename'), - pinButton(e)), + pinButton(e), + teamButton(e, 'btn btn-small')), h('dl', { class: 'facts' }, [ ['Account', `${e.account}${account.email ? ` (${account.email})` : ''}`], ['Tool', toolLabel(toolOf(e.account))], diff --git a/ui/concept.css b/ui/concept.css index 65bc1e8..dd3b5cb 100644 --- a/ui/concept.css +++ b/ui/concept.css @@ -22,6 +22,15 @@ --idle: #8e8e93; --done: #23893f; --closed: #7b8794; + /* Models, for teams: one colour each, as on the team page. */ + --opus: #b4532a; + --opus-soft: #f8e7df; + --sonnet: #2f6fd0; + --sonnet-soft: #e1ebfa; + --haiku: #23874f; + --haiku-soft: #dff1e6; + --other: #64768a; + --other-soft: #e8ecf0; --folder-tab: #5fa8ea; --folder-body: #7bbef4; @@ -63,6 +72,14 @@ --idle: #9a9aa0; --done: #4cc06a; --closed: #6f7c8a; + --opus: #f08a5d; + --opus-soft: #3d2519; + --sonnet: #6aa6ff; + --sonnet-soft: #1a2a44; + --haiku: #5fd08e; + --haiku-soft: #16331f; + --other: #9fb0c2; + --other-soft: #2a3038; --folder-tab: #3f8fd8; --folder-body: #5aa9ec; --folder-shine: #8cc7f5; @@ -97,6 +114,14 @@ --idle: #9a9aa0; --done: #4cc06a; --closed: #6f7c8a; + --opus: #f08a5d; + --opus-soft: #3d2519; + --sonnet: #6aa6ff; + --sonnet-soft: #1a2a44; + --haiku: #5fd08e; + --haiku-soft: #16331f; + --other: #9fb0c2; + --other-soft: #2a3038; --folder-tab: #3f8fd8; --folder-body: #5aa9ec; --folder-shine: #8cc7f5; @@ -467,3 +492,61 @@ button, input, select { font: inherit; color: inherit; } .search input { width: 100%; } .tb .tb-settings { display: inline-flex; } } + +/* ------------------------------------------------------------------ teams */ + +.tone-opus { --tone: var(--opus); --soft: var(--opus-soft); } +.tone-sonnet { --tone: var(--sonnet); --soft: var(--sonnet-soft); } +.tone-haiku { --tone: var(--haiku); --soft: var(--haiku-soft); } +.tone-other { --tone: var(--other); --soft: var(--other-soft); } + +.teams { display: flex; flex-direction: column; gap: 1.4rem; max-width: 72rem; } +.teams-h { display: flex; align-items: center; gap: 0.5rem; margin: 0 0 0.6rem; font-size: 13px; font-weight: 600; color: var(--muted); } +.teams-count { font-weight: 500; color: var(--faint); } +.teams-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(22rem, 1fr)); gap: 0.9rem; } + +.team-card { display: flex; flex-direction: column; gap: 0.75rem; padding: 0.85rem 0.95rem; border: 1px solid var(--line); border-radius: 10px; background: var(--window); } +.team-card.is-working { border-color: color-mix(in srgb, var(--working) 45%, var(--line)); box-shadow: 0 0 0 3px color-mix(in srgb, var(--working) 12%, transparent); } +.tc-head { display: flex; align-items: flex-start; gap: 0.6rem; } +.tc-title { min-width: 0; flex: 1; } +.tc-title h3 { margin: 0; font-size: 14px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.tc-where { margin: 0.1rem 0 0; color: var(--muted); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.tc-where .tagdot { margin-left: 0; } +.tc-when { color: var(--faint); font-size: 12px; white-space: nowrap; } + +/* The lead on the left, its members down the right, joined like a tree. */ +.tc-flow { display: grid; grid-template-columns: auto 1fr; gap: 0 1.4rem; align-items: center; } +.tc-lead { position: relative; display: flex; flex-direction: column; gap: 0.3rem; padding: 0.5rem 0.65rem; border: 1px solid var(--line); border-top: 3px solid var(--tone); border-radius: 8px; font-size: 12px; } +.tc-lead::after { content: ""; position: absolute; left: 100%; top: 50%; width: 0.7rem; border-top: 1.5px solid var(--line); } +.tc-role { font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--faint); } +.tc-chip { align-self: flex-start; padding: 0 0.45rem; border-radius: 999px; background: var(--soft); color: var(--tone); font-size: 11.5px; font-weight: 600; white-space: nowrap; } +.tc-members { list-style: none; margin: 0; padding: 0 0 0 0.7rem; border-left: 1.5px solid var(--line); display: flex; flex-direction: column; gap: 0.35rem; min-width: 0; } +.tc-members:empty { display: none; } +/* Dot, name and model on one line; what it is doing under them. */ +.tc-node { position: relative; display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 0.1rem 0.45rem; padding: 0.3rem 0.5rem; border-radius: 6px; background: var(--stripe); font-size: 12.5px; min-width: 0; } +.tc-node .tc-task { grid-column: 2 / -1; font-size: 12px; } +.tc-node::before { content: ""; position: absolute; right: 100%; top: 50%; width: 0.7rem; border-top: 1.5px solid var(--line); } +.tc-node[data-state="running"] { background: var(--soft); } +.tc-node[data-state="running"]::before { border-top: 1.5px dashed var(--tone); } +.tc-dot { width: 0.5rem; height: 0.5rem; border-radius: 50%; background: var(--idle); } +.tc-node[data-state="done"] .tc-dot { background: var(--done); } +.tc-node[data-state="running"] .tc-dot { background: var(--tone); animation: tc-pulse 1.2s ease-in-out infinite; } +@keyframes tc-pulse { 50% { opacity: 0.25; } } +.tc-name { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; } +/* Started by the session but not one of its members, such as Claude Code's own Explore. */ +.tc-node.is-other { background: transparent; border: 1px dashed var(--line); } +.tc-task { color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; } +.tc-node[data-state="running"] .tc-task { color: var(--ink); } +a.btn { text-decoration: none; color: inherit; } +a.btn-primary { color: var(--on-accent); } +.tc-foot { display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap; } +.tc-used { flex: 1; color: var(--muted); font-size: 12px; } + +@media (max-width: 640px) { + .teams-grid { grid-template-columns: 1fr; } + .tc-flow { grid-template-columns: 1fr; gap: 0.6rem; } + .tc-lead::after { display: none; } +} +@media (prefers-reduced-motion: reduce) { + .tc-node[data-state="running"] .tc-dot { animation: none; } +} diff --git a/ui/concept.js b/ui/concept.js index b64ac60..e8092c0 100644 --- a/ui/concept.js +++ b/ui/concept.js @@ -50,7 +50,7 @@ const ART = { }; // Sidebar and toolbar icons, from icons.js, by what they stand for here. const GLYPHS = { - recents: 'clock', needs: 'bell', loops: 'rotate-ccw', open: 'circle-play', usage: 'chart-column', home: 'house', all: 'folders', folder: 'folder', + recents: 'clock', needs: 'bell', loops: 'rotate-ccw', open: 'circle-play', teams: 'users', usage: 'chart-column', home: 'house', all: 'folders', folder: 'folder', icons: 'layout-grid', list: 'list', columns: 'columns-3', back: 'chevron-left', forward: 'chevron-right', search: 'search', settings: 'settings', }; const glyph = (name) => { @@ -96,7 +96,7 @@ function toast(message, kind = 'ok') { let token = new URLSearchParams(location.search).get('t'); if (token) { store('cc-token', token); - history.replaceState(null, '', location.pathname); + history.replaceState(null, '', location.pathname + location.hash); } else { token = store('cc-token') || ''; } @@ -131,17 +131,20 @@ const SORTS = { }; +// The places in the sidebar that are not a folder or an account. +const PLACES = ['recents', 'needs', 'loops', 'open', 'teams', 'usage']; + const S = { data: null, history: null, - place: { kind: 'folder', id: '' }, + place: fromAddress().place, // where the page was, from the address, so a reload comes back to it back: [], forward: [], view: ['icons', 'list', 'columns'].includes(store('cc-concept-view')) ? store('cc-concept-view') : 'icons', sort: SORTS[store('cc-concept-sort')] ? store('cc-concept-sort') : 'active', sortDir: ['asc', 'desc'].includes(store('cc-concept-sort-dir')) ? store('cc-concept-sort-dir') : null, // null: the column's own way scale: Number(store('cc-concept-scale')) || 1, - selected: null, // an item key: 'f:' or a session's key + selected: fromAddress().selected, // an item key: 'f:' or a session's key expanded: new Set(), // folders opened in the list view q: '', renaming: null, // the key of the session whose name is being typed @@ -219,10 +222,14 @@ function accountColor(name) { return (index >= 0 && accounts[index].color) || COLORS[(index < 0 ? 0 : index) % COLORS.length]; } +function toolOf(account) { + const found = S.data && S.data.accounts.find((a) => a.name === account); + return (found && found.tool) || 'claude'; +} + // What the tool an account belongs to is called: Claude Code, or Codex. function toolName(account) { - const found = S.data && S.data.accounts.find((a) => a.name === account); - const tool = (found && found.tool) || 'claude'; + const tool = toolOf(account); return window.ccTools ? window.ccTools.label(tool) : tool; } @@ -268,6 +275,7 @@ function placeName(place = S.place) { if (place.kind === 'loops') return 'Worth a look'; if (place.kind === 'open') return 'Open now'; if (place.kind === 'usage') return 'Usage'; + if (place.kind === 'teams') return 'Teams'; if (place.kind === 'tag') return place.account; const node = tree.byId.get(place.id); return node ? node.label : 'All folders'; @@ -277,6 +285,29 @@ function samePlace(a, b) { return a.kind === b.kind && a.id === b.id && a.account === b.account; } +// Where the page is, in the address: #teams, #f=, #a=, with &s=. +// A reload, or the link copied, opens the same place again. +function toAddress() { + const place = S.place; + const where = PLACES.includes(place.kind) ? place.kind + : place.kind === 'tag' ? `a=${encodeURIComponent(place.account)}` + : place.id ? `f=${encodeURIComponent(place.id)}` : ''; + const parts = [where, S.selected && `s=${encodeURIComponent(S.selected)}`].filter(Boolean); + return parts.length ? `#${parts.join('&')}` : ''; +} +function fromAddress() { + const found = { place: { kind: 'folder', id: '' }, selected: null }; + try { + for (const part of location.hash.slice(1).split('&').filter(Boolean)) { + if (PLACES.includes(part)) found.place = { kind: part }; + else if (part.startsWith('f=')) found.place = { kind: 'folder', id: decodeURIComponent(part.slice(2)) }; + else if (part.startsWith('a=')) found.place = { kind: 'tag', account: decodeURIComponent(part.slice(2)) }; + else if (part.startsWith('s=')) found.selected = decodeURIComponent(part.slice(2)); + } + } catch { /* a mangled address opens at the start */ } + return found; +} + function go(place, { remember = true } = {}) { if (samePlace(place, S.place)) return; if (remember) { @@ -363,7 +394,7 @@ function itemsIn(place = S.place, { search = S.q } = {}) { sessions = entries.filter(needsYou); } else if (place.kind === 'open') { sessions = entries.filter((e) => e.open); - } else if (place.kind === 'usage') { + } else if (place.kind === 'usage' || place.kind === 'teams') { return []; } else { sessions = entries.filter((e) => e.account === place.account); @@ -405,6 +436,8 @@ function render() { renderPath(); renderStatus(); if (S.quickLook) renderQuickLook(); + const address = toAddress(); + if (address !== location.hash) history.replaceState(null, '', location.pathname + address); } function sbItem({ place, icon, label, count, hot, color }) { @@ -424,6 +457,8 @@ function renderSidebar() { // Sessions that may be going round in circles, once any session is big enough to be judged. entries.some((e) => loopOf(e) && loopOf(e).measured) && sbItem({ place: { kind: 'loops' }, icon: 'loops', label: 'Worth a look', count: entries.filter(worthALook).length }), sbItem({ place: { kind: 'open' }, icon: 'open', label: 'Open now', count: entries.filter((e) => e.open).length }), + // Counts the teams working now; its view also shows the ones that worked today. + sbItem({ place: { kind: 'teams' }, icon: 'teams', label: 'Teams', count: S.teams ? S.teams.filter(teamWorking).length : null, hot: true }), sbItem({ place: { kind: 'usage' }, icon: 'usage', label: 'Usage' }), h('div', { class: 'sb-head' }, 'Favourites'), home && sbItem({ place: { kind: 'folder', id: home }, icon: 'home', label: 'Home' }), @@ -459,7 +494,7 @@ function renderToolbar() { h('button', { type: 'button', class: 'btn tb-settings', 'aria-label': 'Settings', title: 'Settings (⌘,)', onclick: () => window.ccSettings.open() }, glyph('settings'))); } // The usage view has its own controls. - tb.classList.toggle('is-usage', S.place.kind === 'usage'); + tb.classList.toggle('is-usage', S.place.kind === 'usage' || S.place.kind === 'teams'); $('#back').disabled = !S.back.length; $('#forward').disabled = !S.forward.length; $('#title').textContent = S.q.trim() ? `Searching “${S.q.trim()}” in ${placeName()}` : placeName(); @@ -526,6 +561,14 @@ function renderContent() { if (focused && SKY.canvas && SKY.canvas.isConnected) SKY.canvas.focus({ preventScroll: true }); return; } + if (S.place.kind === 'teams') { + const scroll = content.scrollTop; + content.classList.remove('is-columns'); + content.removeAttribute('aria-activedescendant'); + content.replaceChildren(teamsView()); + content.scrollTop = scroll; + return; + } const items = itemsIn(); content.setAttribute('aria-activedescendant', S.selected && items.some((i) => i.key === S.selected) ? cellId(S.selected) : ''); if (!items.length && S.view !== 'columns') { @@ -663,6 +706,10 @@ function renderPath() { } function renderStatus() { + if (S.place.kind === 'teams') { + $('#statusbar').replaceChildren(h('span', {}, 'Claude Code sessions whose sub-agents worked in the last day. Updates every few seconds.')); + return; + } if (S.place.kind === 'usage') { $('#statusbar').replaceChildren(h('span', {}, 'Counted from the conversations Claude Code and Codex keep on this computer')); return; @@ -723,9 +770,27 @@ function actionButtons(e) { e.command && h('button', { type: 'button', class: 'btn', onclick: () => copy(e.command) }, window.ccIcon('copy'), 'Copy command'), e.sessionId && h('button', { type: 'button', class: 'btn', onclick: () => { hideQuickLook(); startRename(e); } }, window.ccIcon('pencil'), 'Rename'), e.sessionId && h('button', { type: 'button', class: 'btn', onclick: () => pin(e) }, window.ccIcon(e.pinned ? 'pin-off' : 'pin'), e.pinned ? 'Unpin' : 'Pin'), + hasTeam(e) && h('button', { type: 'button', class: 'btn', title: 'Its sub-agents, as a team', onclick: () => openTeam(e) }, window.ccIcon('users'), 'Team'), ]; } +// A Claude Code session's sub-agents, drawn as a team, on a page of their own. +const teamUrl = (account, sessionId) => `/team?account=${encodeURIComponent(account)}&session=${encodeURIComponent(sessionId)}`; + +// A page in a new tab, through a link: this page's own open() (for sessions) takes the +// place of window.open, as a function declared in a script does. +function newTab(url) { + const link = h('a', { href: url, target: '_blank', rel: 'noopener' }); + document.body.append(link); + link.click(); + link.remove(); +} + +const hasTeam = (e) => Boolean(e.sessionId) && toolOf(e.account) === 'claude'; +function openTeam(e) { + newTab(teamUrl(e.account, e.sessionId)); +} + function renderQuickLook() { const e = findItem(S.selected); if (!e || e.kind !== 'session') return hideQuickLook(); @@ -746,6 +811,94 @@ function hideQuickLook() { $('#content').focus({ preventScroll: true }); } +// --------------------------------------------------------------------- teams + +const teamWorking = (t) => t.runs.some((run) => run.state === 'running'); + +async function loadTeams() { + if (S.stopped || S.teamsLoading) return; + S.teamsLoading = true; + try { + const teams = (await api('/api/teams')).teams; + S.teamsAt = Date.now(); + const changed = JSON.stringify(teams) !== JSON.stringify(S.teams); + S.teams = teams; + if (changed && $('#menu').hidden && !S.renaming) render(); + } catch (err) { + if (S.place.kind === 'teams') toast(`Could not read the teams: ${err.message}`, 'error'); + } + S.teamsLoading = false; +} + +// "opus", "claude-sonnet-5-5" and the like, as a colour and a short name. +function modelTone(model) { + const id = String(model || '').toLowerCase(); + const family = ['opus', 'sonnet', 'haiku'].find((f) => id.includes(f)); + if (!family) return { tone: 'other', label: model ? model.replace(/^claude-/, '') : '…' }; + const numbers = id.replace(/\[.*\]$/, '').replace(/-\d{8}$/, '').replace(family, '').split('-').filter((p) => /^\d+$/.test(p)); + return { tone: family, label: `${family[0].toUpperCase()}${family.slice(1)}${numbers.length ? ` ${numbers.join('.')}` : ''}` }; +} + +const LEAD_STATUS = { working: 'Working', blocked: 'Waiting for you', idle: 'Idle', done: 'Done', closed: 'Closed' }; + +function teamCard(t) { + const lead = modelTone(t.lead.model); + const status = LEAD_STATUS[t.status] ? t.status : t.open ? 'idle' : 'closed'; + // Members first, as the team page draws them, then whatever else the session started. + const names = [...t.members.map((m) => m.name), ...new Set(t.runs.map((run) => run.type))].filter((n, i, all) => all.indexOf(n) === i); + const nodes = names.map((name) => { + const member = t.members.find((m) => m.name === name); + const runs = t.runs.filter((run) => run.type === name); + const used = runs.map((run) => run.model).find(Boolean); + const model = modelTone(member && member.model !== 'inherit' ? member.model : used || t.lead.model); + const state = runs.some((run) => run.state === 'running') ? 'running' : runs.length ? 'done' : 'idle'; + const last = runs[runs.length - 1]; + return h('li', { class: `tc-node tone-${model.tone}${member ? '' : ' is-other'}`, 'data-state': state, + title: `${member ? '' : 'Not on the team. '}${last ? last.task : 'Not used yet'}` }, + h('span', { class: 'tc-dot' }), + h('span', { class: 'tc-name' }, name), + h('span', { class: 'tc-chip' }, model.label), + h('span', { class: 'tc-task' }, state === 'running' ? last.task : runs.length ? `${runs.length === 1 ? 'Ran once' : `Ran ${runs.length} times`}` : 'Not used yet')); + }); + const used = t.runs.reduce((sum, run) => sum + tokenSum(run.tokens), 0); + const last = Math.max(0, ...t.runs.map((run) => run.lastAt)); + return h('article', { class: `team-card${teamWorking(t) ? ' is-working' : ''}` }, + h('header', { class: 'tc-head' }, + h('div', { class: 'tc-title' }, + h('h3', {}, t.title), + h('p', { class: 'tc-where' }, h('span', { class: 'tagdot', style: { '--acct': accountColor(t.account) } }), ` ${t.account} · `, t.cwd.replace(/^\/Users\/[^/]+/, '~'))), + h('span', { class: 'tc-when', title: fullDate(last) }, ago(last))), + h('div', { class: 'tc-flow' }, + h('div', { class: `tc-lead tone-${lead.tone}`, 'data-status': status }, + h('span', { class: 'tc-role' }, 'Lead'), + h('span', { class: 'tc-chip' }, t.lead.model ? lead.label : 'No replies yet'), + h('span', { class: 'st', 'data-status': status }, LEAD_STATUS[status])), + h('ul', { class: 'tc-members' }, nodes)), + h('footer', { class: 'tc-foot' }, + h('span', { class: 'tc-used' }, `${plural(t.runs.length, 'sub-agent run')} · ${tokens(used)} tokens`), + status === 'blocked' && t.key && h('button', { type: 'button', class: 'btn', onclick: () => act(() => api('/api/sessions/resume', { key: t.key }), 'Opened in a terminal.') }, + window.ccIcon('square-terminal'), 'Open in a terminal'), + h('a', { class: 'btn btn-primary', href: teamUrl(t.account, t.sessionId), target: '_blank', rel: 'noopener' }, window.ccIcon('users'), 'Open team'))); +} + +function teamsView() { + if (!S.teams) { + loadTeams(); + return h('p', { class: 'empty' }, 'Looking for teams…'); + } + if (!S.teams.length) { + return h('p', { class: 'empty' }, 'No team has worked in the last day. To set one up, right-click a Claude Code session and choose Team.'); + } + const working = S.teams.filter(teamWorking); + const earlier = S.teams.filter((t) => !teamWorking(t)); + const section = (title, list) => list.length > 0 && h('section', { class: 'teams-section' }, + h('h2', { class: 'teams-h' }, title, h('span', { class: 'teams-count' }, String(list.length))), + h('div', { class: 'teams-grid' }, list.map(teamCard))); + return h('div', { class: 'teams' }, + section('Working now', working), + section(working.length ? 'Earlier today' : 'In the last day', earlier)); +} + // --------------------------------------------------------------------- usage const METRICS = { @@ -1404,7 +1557,8 @@ function closeSessions(sessions) { const confirm = h('button', { type: 'submit', class: 'btn btn-danger' }, one ? 'Close session' : 'Close ticked sessions'); sheet.replaceChildren(h('form', { method: 'dialog', onsubmit: async (event) => { event.preventDefault(); - const keys = [...sheet.querySelectorAll('input:checked')].map((box) => box.value); + // From the boxes themselves: a single session's is ticked but never shown, so it is not in the sheet. + const keys = boxes.map((label) => label.querySelector('input')).filter((box) => box.checked).map((box) => box.value); sheet.close(); if (!keys.length) return; const result = await act(() => api('/api/sessions/close', { keys })); @@ -1479,6 +1633,7 @@ function showMenu(x, y, item) { e.command && entryButton(e.open ? 'Open in a terminal' : 'Resume', () => resume(e), '⌘O', false, e.open ? 'square-terminal' : 'play'), editorFor(e) && entryButton(`Open in ${editorFor(e)}`, () => openInEditor(e), '⌘E', false, 'square-code'), e.command && entryButton('Copy command', () => copy(e.command), null, false, 'copy'), + hasTeam(e) && entryButton('Team', () => openTeam(e), null, false, 'users'), h('hr'), e.sessionId && entryButton('Rename', () => startRename(e), '↩', false, 'pencil'), e.sessionId && entryButton(e.pinned ? 'Unpin' : 'Pin to the top', () => pin(e), null, false, e.pinned ? 'pin-off' : 'pin'), @@ -1635,5 +1790,7 @@ refresh().then(loadHistory); setInterval(() => { if (!document.hidden) refresh(); }, 5000); setInterval(() => { if (!document.hidden) loadHistory(); }, 20000); setInterval(() => { if (!document.hidden && S.place.kind === 'usage') loadUsage(); }, 60000); +// Teams: every few seconds while looking at them, else now and then for the sidebar's count. +setInterval(() => { if (!document.hidden && (S.place.kind === 'teams' || Date.now() - (S.teamsAt || 0) > 30000)) loadTeams(); }, 4000); setInterval(() => { if (!document.hidden && $('#menu').hidden && !S.renaming) render(); }, 60000); $('#content').focus(); diff --git a/ui/icons.js b/ui/icons.js index df23995..5efa2b2 100644 --- a/ui/icons.js +++ b/ui/icons.js @@ -40,6 +40,7 @@ 'clock': '', 'columns-3': '', 'copy': '', + 'ellipsis': '', 'eye': '', 'filter-x': '', 'folder-open': '', diff --git a/ui/settings.js b/ui/settings.js index 5de53b4..e31f53d 100644 --- a/ui/settings.js +++ b/ui/settings.js @@ -8,7 +8,7 @@ // it in settings.css (one for light, one for dark). (() => { const TEMPLATES = [ - { id: '', name: 'Each view’s own', note: 'Classic looks classic, Finder looks like a Mac.' }, + { id: '', name: 'Each view’s own', note: 'Classic looks classic, Finder and Simple look like a Mac.' }, { id: 'mac', name: 'Mac', note: 'System font, soft greys, rounded corners.', light: ['#f2f2f4', '#ffffff', '#1d1d1f', '#6b6b70', '#0a6cdc'], dark: ['#1c1c1e', '#242426', '#e8e8ea', '#a1a1a6', '#2f8cff'] }, { id: 'classic', name: 'Classic', note: 'The original look: cool blue-greys.', @@ -190,12 +190,12 @@ const radio = (name, value, current, label, onchange, glyph) => h('label', { class: 'st-choice' }, h('input', { type: 'radio', name, value, 'data-fk': `${name}:${value}`, checked: value === current, onchange }), glyph && icon(glyph), h('span', {}, label)); // Which page shows the sessions. Picking the other one goes there, and Settings opens again on it. - const layout = location.pathname === '/' ? 'classic' : 'finder'; + const layout = location.pathname === '/' ? 'classic' : location.pathname === '/simple' ? 'simple' : 'finder'; const switchTo = (value) => { store('cc-view', value); if (value === layout) return; try { sessionStorage.setItem('cc-settings-reopen', 'appearance'); } catch { /* it just doesn't reopen */ } - location.replace(value === 'finder' ? '/finder' : '/'); + location.replace({ finder: '/finder', simple: '/simple' }[value] || '/'); }; // A small picture of each template, in the current light or dark. @@ -215,7 +215,8 @@ h('h4', {}, 'Layout'), h('div', { class: 'st-choices', role: 'radiogroup', 'aria-label': 'Layout' }, radio('st-layout', 'classic', layout, 'Classic: one list, with details beside it', () => switchTo('classic'), 'rows-3'), - radio('st-layout', 'finder', layout, 'Finder: folders you open, like a Mac', () => switchTo('finder'), 'folder-open')), + radio('st-layout', 'finder', layout, 'Finder: folders you open, like a Mac', () => switchTo('finder'), 'folder-open'), + radio('st-layout', 'simple', layout, 'Simple: a card for each project', () => switchTo('simple'), 'layout-grid')), h('p', { class: 'st-hint' }, 'The page opens in this layout from now on.')), h('section', { class: 'st-group' }, h('h4', {}, 'Theme'), diff --git a/ui/simple.css b/ui/simple.css new file mode 100644 index 0000000..3827a2c --- /dev/null +++ b/ui/simple.css @@ -0,0 +1,221 @@ +/* The Simple layout: a card for each project. Its colours use the names the other + pages share (--window, --ink, --line, ...), so the templates and the primary + colour in settings.css apply here too. Account colours come from simple.js as --acct. */ +:root { + --page: #f6f5f7; + --window: #ffffff; + --stripe: #f5f5f7; + --ink: #1d1d1f; + --muted: #6e6e73; + --faint: #8e8e93; + --line: #dcdce0; + --hover: rgb(0 0 0 / 0.05); + --accent: #0a6cdc; + --on-accent: #ffffff; + --danger: #c4322b; + --on-danger: #ffffff; + --shadow: 0 1px 2px rgb(0 0 0 / 0.05), 0 3px 12px rgb(0 0 0 / 0.05); + + --working: #0a6cdc; + --blocked: #c27406; + --idle: #8e8e93; + --done: #23893f; + --closed: #7b8794; + + --opus: #b4532a; + --opus-soft: #f8e7df; + --sonnet: #2f6fd0; + --sonnet-soft: #e1ebfa; + --haiku: #23874f; + --haiku-soft: #dff1e6; + --other: #64768a; + --other-soft: #e8ecf0; + + --radius: 10px; + --sans: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", system-ui, sans-serif; + --mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace; + color-scheme: light; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + --page: #18181a; + --window: #232325; + --stripe: #2a2a2c; + --ink: #e8e8ea; + --muted: #a1a1a6; + --faint: #8a8a8f; + --line: #3a3a3d; + --hover: rgb(255 255 255 / 0.05); + --accent: #2f8cff; + --on-accent: #0b1424; + --danger: #ff6961; + --on-danger: #1a0d0c; + --shadow: 0 1px 2px rgb(0 0 0 / 0.4), 0 3px 12px rgb(0 0 0 / 0.25); + --working: #4c9dff; + --blocked: #f0a83c; + --idle: #9a9aa0; + --done: #4cc06a; + --closed: #6f7c8a; + --opus: #f08a5d; + --opus-soft: #3d2519; + --sonnet: #6aa6ff; + --sonnet-soft: #1a2a44; + --haiku: #5fd08e; + --haiku-soft: #16331f; + --other: #9fb0c2; + --other-soft: #2a3038; + color-scheme: dark; + } +} + +:root[data-theme="dark"] { + --page: #18181a; + --window: #232325; + --stripe: #2a2a2c; + --ink: #e8e8ea; + --muted: #a1a1a6; + --faint: #8a8a8f; + --line: #3a3a3d; + --hover: rgb(255 255 255 / 0.05); + --accent: #2f8cff; + --on-accent: #0b1424; + --danger: #ff6961; + --on-danger: #1a0d0c; + --shadow: 0 1px 2px rgb(0 0 0 / 0.4), 0 3px 12px rgb(0 0 0 / 0.25); + --working: #4c9dff; + --blocked: #f0a83c; + --idle: #9a9aa0; + --done: #4cc06a; + --closed: #6f7c8a; + --opus: #f08a5d; + --opus-soft: #3d2519; + --sonnet: #6aa6ff; + --sonnet-soft: #1a2a44; + --haiku: #5fd08e; + --haiku-soft: #16331f; + --other: #9fb0c2; + --other-soft: #2a3038; + color-scheme: dark; +} + +/* A template's page colour, where it has one. */ +:root[data-template] { --page: var(--ground, var(--side, #f6f5f7)); } + +* { box-sizing: border-box; } +[hidden] { display: none !important; } +body { margin: 0; background: var(--page); color: var(--ink); font: 14px/1.45 var(--sans); } +button, input { font: inherit; color: inherit; } +.cc-icon { width: 16px; height: 16px; flex: none; } +:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } + +/* ------------------------------------------------------------------ header */ + +.top { position: sticky; top: 0; z-index: 3; display: flex; align-items: center; gap: 16px; padding: 12px 24px; background: color-mix(in srgb, var(--window) 88%, transparent); backdrop-filter: blur(12px); border-bottom: 1px solid var(--line); } +.brand { margin: 0; font-size: 17px; font-weight: 700; letter-spacing: -0.01em; } +.search { flex: 1; max-width: 520px; margin-left: auto; padding: 8px 12px; border: 1px solid var(--line); border-radius: 999px; background: var(--page); } +.search::placeholder { color: var(--faint); } +.icon-btn { display: inline-grid; place-items: center; width: 36px; height: 36px; border: 1px solid transparent; border-radius: 50%; background: none; color: var(--muted); cursor: pointer; } +.icon-btn:hover { background: var(--hover); color: var(--ink); } +.icon-btn .cc-icon { width: 18px; height: 18px; } + +.page { max-width: 1240px; margin: 0 auto; padding: 18px 24px 64px; display: flex; flex-direction: column; gap: 14px; } + +/* --------------------------------------------------- accounts, today, teams */ + +.filters { display: flex; flex-wrap: wrap; gap: 8px; } +.chip { display: inline-flex; align-items: center; gap: 7px; padding: 5px 12px; border: 1px solid var(--line); border-radius: 999px; background: var(--window); cursor: pointer; } +.chip:hover { border-color: var(--faint); } +.chip[aria-pressed="true"] { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 10%, var(--window)); color: var(--ink); font-weight: 600; } +.chip .count { color: var(--faint); font-weight: 500; font-variant-numeric: tabular-nums; } +.dot { display: inline-block; width: 9px; height: 9px; border-radius: 50%; background: var(--acct, var(--faint)); flex: none; } + +.today { margin: 0; color: var(--muted); } +.today b { color: var(--ink); font-weight: 650; } + +.teams { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 10px 12px; border: 1px solid color-mix(in srgb, var(--working) 40%, var(--line)); border-radius: var(--radius); background: color-mix(in srgb, var(--working) 6%, var(--window)); } +.teams-label { font-weight: 600; margin-right: 4px; } +.team { display: inline-flex; align-items: center; gap: 8px; padding: 5px 10px; border: 1px solid var(--line); border-radius: 999px; background: var(--window); color: inherit; text-decoration: none; } +.team:hover { border-color: var(--working); } +.team { max-width: 100%; min-width: 0; } +.team b { font-weight: 600; min-width: 0; max-width: 24rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.member { flex: none; white-space: nowrap; display: inline-flex; align-items: center; gap: 5px; padding: 0 7px; border-radius: 999px; background: var(--soft); color: var(--tone); font-size: 12px; font-weight: 600; } +.member::before { content: ""; width: 6px; height: 6px; border-radius: 50%; background: var(--tone); animation: pulse 1.2s ease-in-out infinite; } +.tone-opus { --tone: var(--opus); --soft: var(--opus-soft); } +.tone-sonnet { --tone: var(--sonnet); --soft: var(--sonnet-soft); } +.tone-haiku { --tone: var(--haiku); --soft: var(--haiku-soft); } +.tone-other { --tone: var(--other); --soft: var(--other-soft); } + +/* ------------------------------------------------------------------- cards */ + +.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(19rem, 1fr)); gap: 14px; align-items: start; } +.card { display: flex; flex-direction: column; gap: 10px; padding: 14px 14px 10px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--window); box-shadow: var(--shadow); min-width: 0; } +.card.needs { border-color: color-mix(in srgb, var(--blocked) 55%, var(--line)); } +.card.busy { border-color: color-mix(in srgb, var(--working) 45%, var(--line)); } +.card-head { display: flex; align-items: flex-start; gap: 8px; } +.card-title { min-width: 0; flex: 1; } +.card-title h2 { margin: 0; font-size: 15.5px; font-weight: 650; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.card-title p { margin: 1px 0 0; color: var(--faint); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.pin-mark { color: var(--accent); } +.dots { display: inline-flex; gap: 4px; padding-top: 5px; } +.state { display: flex; align-items: center; gap: 7px; font-size: 13px; color: var(--muted); } +.state b { font-weight: 600; } +.state[data-state="needs"] b { color: var(--blocked); } +.state[data-state="working"] b { color: var(--working); } + +.rows { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; } +.row { display: grid; grid-template-columns: auto minmax(0, 1fr) auto auto; align-items: center; gap: 8px; padding: 6px 0; border-top: 1px solid var(--line); } +.row:first-child { border-top: 0; } +.status { width: 9px; height: 9px; border-radius: 50%; background: none; box-shadow: inset 0 0 0 1.5px var(--closed); } +.status[data-status="working"] { background: var(--working); box-shadow: none; animation: pulse 1.6s ease-in-out infinite; } +.status[data-status="blocked"] { background: var(--blocked); box-shadow: none; } +.status[data-status="idle"] { background: var(--idle); box-shadow: none; } +.status[data-status="done"] { background: var(--done); box-shadow: none; } +.who { min-width: 0; } +.who .name { display: block; font-weight: 550; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.who .meta { display: block; color: var(--faint); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.row[data-status="blocked"] .meta { color: var(--blocked); } +.rename { width: 100%; padding: 2px 6px; border: 1px solid var(--accent); border-radius: 6px; background: var(--window); } + +.btn { display: inline-flex; align-items: center; justify-content: center; gap: 6px; padding: 5px 12px; border: 1px solid var(--line); border-radius: 7px; background: var(--window); cursor: pointer; white-space: nowrap; text-decoration: none; } +.btn:hover { border-color: var(--faint); } +.btn-primary { background: var(--accent); border-color: var(--accent); color: var(--on-accent); } +.btn-primary:hover { border-color: var(--accent); filter: brightness(1.06); } +.btn-danger { background: var(--danger); border-color: var(--danger); color: var(--on-danger); } +.more-btn { width: 30px; height: 30px; } +.card-foot { display: flex; justify-content: center; } +.link { border: 0; background: none; padding: 4px 6px; color: var(--accent); cursor: pointer; } +.older { justify-self: center; grid-column: 1 / -1; } +.empty { grid-column: 1 / -1; padding: 4rem 1rem; color: var(--muted); text-align: center; } + +@keyframes pulse { 50% { opacity: 0.3; } } + +/* ------------------------------------------------------ menu, sheet, toasts */ + +.menu { position: fixed; z-index: 10; min-width: 200px; padding: 5px; border: 1px solid var(--line); border-radius: 9px; background: var(--window); box-shadow: 0 10px 30px rgb(0 0 0 / 0.18); } +.menu button { display: flex; align-items: center; gap: 9px; width: 100%; padding: 6px 10px; border: 0; border-radius: 6px; background: none; text-align: left; cursor: pointer; } +.menu button:hover, .menu button:focus-visible { background: var(--accent); color: var(--on-accent); outline: none; } +.menu button.danger { color: var(--danger); } +.menu button.danger:hover, .menu button.danger:focus-visible { background: var(--danger); color: var(--on-danger); } +.menu hr { margin: 4px 6px; border: 0; border-top: 1px solid var(--line); } + +.sheet { width: min(440px, calc(100vw - 32px)); padding: 0; border: 1px solid var(--line); border-radius: 12px; background: var(--window); color: var(--ink); box-shadow: 0 20px 60px rgb(0 0 0 / 0.25); } +.sheet::backdrop { background: rgb(0 0 0 / 0.3); } +.sheet form { display: flex; flex-direction: column; gap: 12px; padding: 20px 22px; } +.sheet h2 { margin: 0; font-size: 16px; } +.sheet p { margin: 0; color: var(--muted); } +.sheet-actions { display: flex; justify-content: flex-end; gap: 8px; } + +.toasts { position: fixed; bottom: 18px; left: 50%; transform: translateX(-50%); z-index: 20; display: flex; flex-direction: column; gap: 8px; } +.toast { max-width: 90vw; padding: 8px 14px; border-radius: 8px; background: var(--ink); color: var(--window); box-shadow: var(--shadow); } +.toast-error { background: var(--danger); color: var(--on-danger); } + +@media (max-width: 640px) { + .top { padding: 10px 16px; gap: 10px; } + .brand { font-size: 16px; } + .page { padding: 14px 16px 48px; } + .cards { grid-template-columns: 1fr; } +} +@media (prefers-reduced-motion: reduce) { + .member::before, .status[data-status="working"] { animation: none; } +} diff --git a/ui/simple.html b/ui/simple.html new file mode 100644 index 0000000..cc51797 --- /dev/null +++ b/ui/simple.html @@ -0,0 +1,34 @@ + + + + + + + Paddock + + + + + + + + + +
+

Paddock

+ + +
+ +
+
+ + +
+
+ + + +
+ + diff --git a/ui/simple.js b/ui/simple.js new file mode 100644 index 0000000..f19824e --- /dev/null +++ b/ui/simple.js @@ -0,0 +1,570 @@ +'use strict'; + +// The Simple layout: a card for each project folder, its sessions in it, one button +// each. It reads and acts through the same server calls as the other pages. All of it +// is inside one function, so none of its names takes the place of a browser one (a +// script's own open() replaces window.open). +(() => { + const $ = (selector) => document.querySelector(selector); + const DAY = 24 * 60 * 60 * 1000; + const OLD = 30 * DAY; // projects not used for this long are folded away + const SHOWN = 3; // sessions on a card before "more" + const MOST = 20; // sessions on an opened card + const COLORS = ['#0f9488', '#7c56d8', '#d0661c', '#c2417c', '#2f6fd0', '#4a8f2f', '#b08412', '#64768a']; + const STATUS = { working: 'Working', blocked: 'Needs you', idle: 'Open, idle', done: 'Done', closed: 'Closed' }; + + // What this tab was showing, so a reload comes back to it: the search, the cards + // opened, older projects shown, and how far down the page it was. + const KEPT = 'cc-simple-view'; + const kept = (() => { + try { return JSON.parse(sessionStorage.getItem(KEPT)) || {}; } catch { return {}; } + })(); + + const S = { + data: null, // /api/state + history: null, // /api/history items + teams: null, // /api/teams + usage: null, // /api/usage + account: store('cc-simple-account') || '', + q: typeof kept.q === 'string' ? kept.q : '', + opened: new Set(Array.isArray(kept.opened) ? kept.opened : []), // cards showing all their sessions + older: kept.older === true, // projects not used lately are shown + renaming: null, // the key of the session whose name is being typed + stopped: false, + }; + let shown = ''; + + // ---------------------------------------------------------------- utilities + + function h(tag, props = {}, ...children) { + const el = document.createElement(tag); + for (const [key, value] of Object.entries(props)) { + if (value == null || value === false) continue; + if (key === 'class') el.className = value; + else if (key === 'style') for (const [name, v] of Object.entries(value)) el.style.setProperty(name, v); + else if (key.startsWith('on')) el.addEventListener(key.slice(2), value); + else if (key in el) el[key] = value; + else el.setAttribute(key, value); + } + el.append(...children.flat(Infinity).filter((child) => child != null && child !== false)); + return el; + } + + function store(key, value) { + try { + if (value === undefined) return localStorage.getItem(key); + localStorage.setItem(key, value); + } catch { /* private window */ } + return null; + } + + // Put children in an element, as h() does: lists flattened, false and null left out. + const fill = (el, ...children) => el.replaceChildren(...children.flat(Infinity).filter((child) => child != null && child !== false)); + const icon = (name) => window.ccIcon(name); + const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`; + + function toast(message, kind = 'ok') { + const report = kind === 'error' && window.ccReport; + if (report) report.noteError(message); + const el = h('div', { class: `toast toast-${kind}` }, message); + $('#toasts').append(el); + setTimeout(() => el.remove(), kind === 'error' ? 9000 : 4500); + } + + function ago(ms) { + if (!ms) return ''; + const s = Math.max(0, (Date.now() - ms) / 1000); + if (s < 60) return 'just now'; + if (s < 3600) return `${Math.floor(s / 60)} min ago`; + if (s < 86400) return `${Math.floor(s / 3600)} h ago`; + if (s < 7 * 86400) return `${Math.floor(s / 86400)} d ago`; + return new Date(ms).toLocaleDateString(undefined, { day: 'numeric', month: 'short' }); + } + + function tokens(n) { + if (n >= 1e9) return `${(n / 1e9).toFixed(1)}B`; + if (n >= 1e6) return `${(n / 1e6).toFixed(n >= 1e7 ? 0 : 1)}M`; + if (n >= 1e3) return `${(n / 1e3).toFixed(n >= 1e4 ? 0 : 1)}k`; + return String(n); + } + + // A page in a new tab, through a link. + function newTab(url) { + const link = h('a', { href: url, target: '_blank', rel: 'noopener' }); + document.body.append(link); + link.click(); + link.remove(); + } + + async function copy(text) { + try { + await navigator.clipboard.writeText(text); + toast('Copied.'); + } catch { + toast('The browser would not copy it.', 'error'); + } + } + + // ---------------------------------------------------------------------- API + + let token = new URLSearchParams(location.search).get('t'); + if (token) { + store('cc-token', token); + history.replaceState(null, '', location.pathname); + } else { + token = store('cc-token') || ''; + } + window.ccToken = token; // for Settings, which talks to the server too + + async function api(path, body) { + const response = await fetch(path, { + method: body ? 'POST' : 'GET', + headers: { 'X-CC-Token': token, ...(body ? { 'Content-Type': 'application/json' } : {}) }, + body: body ? JSON.stringify(body) : undefined, + }); + const data = await response.json().catch(() => ({})); + if (response.status === 401) throw new Error('Open Paddock from the terminal once, so this page has its key.'); + if (!response.ok) throw new Error(data.error || `Request failed (${response.status}).`); + return data; + } + + // Run an action, say how it went, and read the sessions again. + async function act(run, done) { + try { + const result = await run(); + if (done) toast(typeof done === 'function' ? done(result) : done); + return result; + } catch (err) { + toast(err.message, 'error'); + return null; + } finally { + refresh(); + } + } + + // ------------------------------------------------------------------ the data + + const folderId = (cwd) => { + const parts = String(cwd || '').split(/[\\/]+/).filter(Boolean); + return parts.length ? `/${parts.join('/')}` : '?'; + }; + const folderPath = (id) => (!id || id === '?' ? '' : /^\/(~|[A-Za-z]:)/.test(id) ? id.slice(1) : id); + const accountOf = (name) => (S.data ? S.data.accounts.find((a) => a.name === name) : null) || {}; + function accountColor(name) { + const accounts = S.data ? S.data.accounts : []; + const index = accounts.findIndex((a) => a.name === name); + return (index >= 0 && accounts[index].color) || COLORS[(index < 0 ? 0 : index) % COLORS.length]; + } + + // Running sessions and saved conversations, one entry each, as the other pages make them. + function entries() { + const saved = new Map((S.history || []).map((item) => [`${item.account}|${item.sessionId}`, item])); + const list = S.data.sessions.map((s) => { + const id = `${s.account}|${s.sessionId}`; + const item = s.sessionId ? saved.get(id) : undefined; + saved.delete(id); + return entry(s, item); + }); + for (const item of saved.values()) list.push(entry(null, item)); + // Opened and never used: nothing to go back to. + return list.filter((e) => e.session || e.item.prompts > 0); + } + + function entry(s, item) { + const { account, sessionId } = s || item; + const cwd = (s && s.cwd) || (item && item.cwd) || ''; + return { + key: sessionId ? `${account}|${sessionId}` : `s:${s.key}`, + session: s, + item, + account, + sessionId, + name: s ? s.name : item.title, + renamed: (s || item).renamed, + pinned: Boolean((s && s.pinned) || (item && item.pinned)), + cwd, + status: s ? s.status : 'closed', + open: Boolean(s && s.open), + at: Math.max((s && (s.closedAt || s.updatedAt)) || 0, (item && item.lastActivity) || 0), + command: (s && s.resumeCommand) || (item && item.resumeCommand) || '', + search: `${s ? s.name : item.title} ${cwd} ${account} ${(item && item.promptText) || ''}`.toLowerCase(), + }; + } + + const needsYou = (e) => e.open && (e.status === 'blocked' || (e.status === 'done' && Date.now() - e.at < DAY)); + const working = (e) => e.open && e.status === 'working'; + // Within a card: what needs you, then what is working, open, pinned, then the latest. + const rank = (e) => (needsYou(e) ? 0 : working(e) ? 1 : e.open ? 2 : e.pinned ? 3 : 4); + + // The projects to show: sessions grouped by folder, for the chosen account and search. + function projects() { + const needle = S.q.trim().toLowerCase(); + const pinned = new Set((S.data.pinnedFolders || []).map(folderId)); + const byFolder = new Map(); + for (const e of entries()) { + if (S.account && e.account !== S.account) continue; + const id = folderId(e.cwd); + if (!byFolder.has(id)) byFolder.set(id, []); + byFolder.get(id).push(e); + } + const list = []; + for (const [id, all] of byFolder) { + const path = folderPath(id); + const name = id === '?' ? 'No folder' : id === '/~' ? 'Home' : id.split('/').pop(); + const matches = needle && !`${name} ${path}`.toLowerCase().includes(needle) ? all.filter((e) => e.search.includes(needle)) : all; + if (!matches.length) continue; + matches.sort((a, b) => rank(a) - rank(b) || b.at - a.at); + list.push({ + id, + path, + name, + parent: path.slice(0, Math.max(0, path.length - name.length - 1)), + sessions: matches, + accounts: [...new Set(all.map((e) => e.account))], + needs: all.filter(needsYou).length, + working: all.filter(working).length, + open: all.filter((e) => e.open).length, + pinned: pinned.has(id), + at: Math.max(...all.map((e) => e.at)), + }); + } + const order = (p) => (p.needs ? 0 : p.working ? 1 : p.pinned ? 2 : p.open ? 3 : 4); + return list.sort((a, b) => order(a) - order(b) || b.at - a.at); + } + + // ------------------------------------------------------------------ drawing + + function render(force = false) { + if (!S.data || S.stopped) return; + // Leave the page be while something on it is being used. + if (!force && (!$('#menu').hidden || S.renaming || document.querySelector('dialog[open]'))) return; + const list = projects(); + const signature = JSON.stringify([list.map((p) => [p.id, p.needs, p.working, p.pinned, p.sessions.map((e) => [e.key, e.name, e.status, e.pinned, Math.round(e.at / 60000)])]), + S.account, S.opened.size, S.older, S.teams, S.usage && S.usage.at, S.data.accounts.map((a) => [a.name, a.color])]); + if (!force && signature === shown) return; + shown = signature; + const waiting = list.reduce((n, p) => n + p.needs, 0); + document.title = `${waiting ? `(${waiting}) ` : ''}Paddock`; + drawFilters(); + drawToday(); + drawTeams(); + drawCards(list); + keep(); + // Back to where the page was, once the cards it was showing are there. + if (S.history && kept.scroll && !keep.restored) { + keep.restored = true; + window.scrollTo(0, kept.scroll); + } + } + + function keep() { + try { + // Until the page is back where it was, the place it was is still the one to keep. + const scroll = keep.restored || !kept.scroll ? Math.round(window.scrollY) : kept.scroll; + sessionStorage.setItem(KEPT, JSON.stringify({ q: S.q, opened: [...S.opened], older: S.older, scroll })); + } catch { /* nothing kept: a reload starts at the top */ } + } + + function drawFilters() { + const all = entries(); + const accounts = S.data.accounts.filter((a) => !a.removed && all.some((e) => e.account === a.name)); + if (S.account && !accounts.some((a) => a.name === S.account)) S.account = ''; + const chip = (name, label, count, color) => h('button', { type: 'button', class: 'chip', 'aria-pressed': String(S.account === name), + onclick: () => { S.account = name; store('cc-simple-account', name); render(true); } }, + color && h('span', { class: 'dot', style: { '--acct': color } }), label, h('span', { class: 'count' }, String(count))); + fill($('#filters'), + chip('', 'All', all.length), + accounts.length > 1 && accounts.map((a) => chip(a.name, a.name, all.filter((e) => e.account === a.name).length, accountColor(a.name)))); + } + + // Today's tokens, on this browser's own day, for the chosen account or all of them. + function drawToday() { + const el = $('#today'); + if (!S.usage) { el.hidden = true; return; } + const start = new Date(); + start.setHours(0, 0, 0, 0); + const from = start.getTime(); + const per = []; + for (const [name, data] of Object.entries(S.usage.accounts)) { + if (S.account && name !== S.account) continue; + const sum = data.hours.filter((row) => row[0] * 3600000 >= from).reduce((n, row) => n + row[1] + row[2] + row[3] + row[4], 0); + if (sum) per.push([name, sum]); + } + const total = per.reduce((n, [, sum]) => n + sum, 0); + el.hidden = !total; + if (!total) return; + fill(el, 'Today: ', h('b', {}, `${tokens(total)} tokens`), + per.length > 1 && per.sort((a, b) => b[1] - a[1]).map(([name, sum]) => [' · ', h('span', { class: 'dot', style: { '--acct': accountColor(name) } }), ` ${name} ${tokens(sum)}`])); + } + + function modelTone(model) { + const id = String(model || '').toLowerCase(); + const family = ['opus', 'sonnet', 'haiku'].find((f) => id.includes(f)); + return { tone: family || 'other', label: family ? family[0].toUpperCase() + family.slice(1) : (model || '').replace(/^claude-/, '') }; + } + + // Teams working now, each opening its team page. + function drawTeams() { + const el = $('#teams'); + const live = (S.teams || []).filter((t) => (!S.account || t.account === S.account) && t.runs.some((run) => run.state === 'running')); + el.hidden = !live.length; + if (!live.length) return; + fill(el, h('span', { class: 'teams-label' }, icon('users'), ' Teams working'), + live.map((t) => { + const running = [...new Map(t.runs.filter((run) => run.state === 'running').map((run) => [run.type, run])).values()]; + return h('a', { class: 'team', href: `/team?account=${encodeURIComponent(t.account)}&session=${encodeURIComponent(t.sessionId)}`, target: '_blank', rel: 'noopener', title: 'Open the team' }, + h('b', {}, t.title), + running.map((run) => { + const member = t.members.find((m) => m.name === run.type); + const model = modelTone(member && member.model !== 'inherit' ? member.model : run.model); + return h('span', { class: `member tone-${model.tone}` }, `${run.type} · ${model.label}`); + })); + })); + } + + function drawCards(list) { + const cutoff = Date.now() - OLD; + const recent = list.filter((p) => S.older || S.q.trim() || p.open || p.pinned || p.at >= cutoff); + const folded = list.length - recent.length; + const cards = $('#cards'); + if (!S.history && !list.length) return cards.replaceChildren(h('p', { class: 'empty' }, 'Reading your sessions…')); + if (!list.length) { + return cards.replaceChildren(h('p', { class: 'empty' }, S.q.trim() ? `Nothing matches “${S.q.trim()}”.` : 'No sessions yet. Start Claude Code or Codex in a project and it shows up here.')); + } + fill(cards, recent.map(card), + folded > 0 && h('button', { type: 'button', class: 'link older', onclick: () => { S.older = true; render(true); } }, `Show ${plural(folded, 'older project')}`), + S.older && !S.q.trim() && h('button', { type: 'button', class: 'link older', onclick: () => { S.older = false; render(true); } }, 'Hide older projects')); + } + + function card(p) { + const opened = S.opened.has(p.id); + const rows = p.sessions.slice(0, opened ? MOST : SHOWN); + const hidden = p.sessions.length - rows.length; + const state = p.needs ? h('div', { class: 'state', 'data-state': 'needs' }, h('span', { class: 'status', 'data-status': 'blocked' }), h('b', {}, `${p.needs} need${p.needs === 1 ? 's' : ''} you`)) + : p.working ? h('div', { class: 'state', 'data-state': 'working' }, h('span', { class: 'status', 'data-status': 'working' }), h('b', {}, `${p.working} working`)) + : h('div', { class: 'state' }, h('span', { class: 'status', 'data-status': p.open ? 'idle' : 'closed' }), p.open ? `${p.open} open` : `Last used ${ago(p.at)}`); + return h('article', { class: `card${p.needs ? ' needs' : p.working ? ' busy' : ''}`, 'aria-label': p.name }, + h('header', { class: 'card-head' }, + h('div', { class: 'card-title' }, + h('h2', { title: p.path }, p.pinned && h('span', { class: 'pin-mark', title: 'Pinned' }, '● '), p.name), + h('p', { title: p.path }, p.parent || ' ')), + h('span', { class: 'dots' }, p.accounts.map((name) => h('span', { class: 'dot', title: name, style: { '--acct': accountColor(name) } }))), + h('button', { type: 'button', class: 'icon-btn more-btn', 'aria-label': `More for ${p.name}`, 'aria-haspopup': 'menu', + onclick: (event) => showMenu(event.currentTarget, projectMenu(p)) }, icon('ellipsis'))), + state, + h('ul', { class: 'rows' }, rows.map(row)), + (hidden > 0 || opened) && h('div', { class: 'card-foot' }, + h('button', { type: 'button', class: 'link', onclick: () => { if (opened) S.opened.delete(p.id); else S.opened.add(p.id); render(true); } }, + opened ? 'Show fewer' : `+ ${hidden} more`))); + } + + function row(e) { + const meta = needsYou(e) ? (e.status === 'blocked' ? 'Needs you' : `Finished ${ago(e.at)}`) + : e.open ? `${STATUS[e.status] || e.status} · ${ago(e.at)}` : ago(e.at); + const first = e.item && e.item.firstPrompt; + const primary = e.open ? h('button', { type: 'button', class: `btn${needsYou(e) ? ' btn-primary' : ''}`, onclick: () => resume(e) }, 'Open') + : e.command ? h('button', { type: 'button', class: 'btn', onclick: () => resume(e) }, 'Resume') : null; + return h('li', { class: 'row', 'data-status': e.status }, + h('span', { class: 'status', 'data-status': e.open ? e.status : 'closed', title: STATUS[e.status] || e.status }), + h('span', { class: 'who' }, + S.renaming === e.key ? renameBox(e) : h('span', { class: 'name', title: first || e.name }, e.name), + h('span', { class: 'meta' }, accountsShown() && [h('span', { class: 'dot', style: { '--acct': accountColor(e.account) } }), ' '], meta)), + primary || h('span'), + h('button', { type: 'button', class: 'icon-btn more-btn', 'aria-label': `More for ${e.name}`, 'aria-haspopup': 'menu', + onclick: (event) => showMenu(event.currentTarget, sessionMenu(e)) }, icon('ellipsis'))); + } + + // Each session's account is marked only where more than one shows. + const accountsShown = () => !S.account && S.data.accounts.filter((a) => !a.removed).length > 1; + + // -------------------------------------------------------------------- menus + + function sessionMenu(e) { + const editor = window.ccEditor && window.ccEditor.current(); + const claude = (accountOf(e.account).tool || 'claude') === 'claude'; + return [ + e.sessionId && ['Rename', 'pencil', () => { S.renaming = e.key; render(true); const box = $('.rename'); if (box) { box.focus(); box.select(); } }], + e.sessionId && [e.pinned ? 'Unpin' : 'Pin to the top', e.pinned ? 'pin-off' : 'pin', () => pin(e)], + e.command && ['Copy command', 'copy', () => copy(e.command)], + e.sessionId && claude && ['Team', 'users', () => newTab(`/team?account=${encodeURIComponent(e.account)}&session=${encodeURIComponent(e.sessionId)}`)], + editor && e.cwd && [`Open in ${editor.name}`, 'square-code', () => act(() => window.ccEditor.open(e.session ? { key: e.session.key } : { account: e.account, sessionId: e.sessionId }), (name) => `Opened ${e.name} in ${name}.`)], + e.open && 'hr', + e.open && ['Close session…', 'circle-stop', () => closeSession(e), true], + ]; + } + + function projectMenu(p) { + const editor = window.ccEditor && window.ccEditor.current(); + return [ + p.id !== '?' && [p.pinned ? 'Unpin project' : 'Pin project to the top', p.pinned ? 'pin-off' : 'pin', + () => act(() => api('/api/pins', { folder: p.path, pinned: !p.pinned }), p.pinned ? `Unpinned ${p.name}.` : `Pinned ${p.name} to the top.`)], + editor && p.id !== '?' && [`Open in ${editor.name}`, 'square-code', () => act(() => window.ccEditor.open({ folder: p.path }), (name) => `Opened ${p.name} in ${name}.`)], + p.path && ['Copy folder path', 'copy', () => copy(p.path)], + ]; + } + + function showMenu(anchor, items) { + const menu = $('#menu'); + menu.replaceChildren(...items.filter(Boolean).map((item) => item === 'hr' ? h('hr') + : h('button', { type: 'button', role: 'menuitem', class: item[3] ? 'danger' : null, onclick: () => { hideMenu(); item[2](); } }, icon(item[1]), item[0]))); + if (!menu.firstChild) return; + menu.hidden = false; + const at = anchor.getBoundingClientRect(); + const box = menu.getBoundingClientRect(); + menu.style.setProperty('left', `${Math.max(8, Math.min(at.right - box.width, innerWidth - box.width - 8))}px`); + menu.style.setProperty('top', `${at.bottom + box.height + 8 > innerHeight ? Math.max(8, at.top - box.height - 4) : at.bottom + 4}px`); + menu.querySelector('button').focus(); + menu.anchor = anchor; + } + + function hideMenu() { + const menu = $('#menu'); + if (menu.hidden) return; + menu.hidden = true; + if (menu.anchor && menu.anchor.isConnected) menu.anchor.focus(); + render(); + } + + // ------------------------------------------------------------------ actions + + function resume(e) { + return e.session + ? act(() => api('/api/sessions/resume', { key: e.session.key }), (r) => `Opened ${e.name} in ${r.terminal}.`) + : act(() => api('/api/history/resume', { account: e.account, sessionId: e.sessionId }), (r) => `Opened ${e.name} in ${r.terminal}.`); + } + + async function pin(e) { + await act(() => api('/api/pins', { account: e.account, sessionId: e.sessionId, pinned: !e.pinned }), e.pinned ? 'Unpinned.' : 'Pinned to the top.'); + loadHistory(); + } + + function renameBox(e) { + let done = false; + const finish = async (save) => { + if (done) return; + done = true; + const value = box.value.trim(); + S.renaming = null; + render(true); + if (!save || value === e.name || (!value && !e.renamed)) return; + await act(() => api('/api/sessions/rename', { account: e.account, sessionId: e.sessionId, title: value }), + value ? `Renamed to ${value}.` : 'Back to its own title.'); + loadHistory(); + }; + const box = h('input', { type: 'text', class: 'rename', value: e.name, 'aria-label': 'Session name', spellcheck: false, + onkeydown: (event) => { + if (event.key === 'Enter') finish(true); + else if (event.key === 'Escape') finish(false); + }, + onblur: () => finish(box.isConnected) }); + return box; + } + + function closeSession(e) { + const sheet = $('#sheet'); + const confirm = h('button', { type: 'submit', class: 'btn btn-danger' }, 'Close session'); + sheet.replaceChildren(h('form', { method: 'dialog', onsubmit: async (event) => { + event.preventDefault(); + sheet.close(); + const result = await act(() => api('/api/sessions/close', { keys: [e.session.key] })); + const outcome = result && result.results[0]; + if (outcome && outcome.ok) toast('Closed. The conversation is kept.'); + else if (outcome) toast(`Could not close it: ${outcome.message}`, 'error'); + } }, + h('h2', { id: 'sheet-title' }, `Close “${e.name}”?`), + h('p', {}, 'It stops, and its conversation is kept, so you can resume it later.'), + h('div', { class: 'sheet-actions' }, h('button', { type: 'button', class: 'btn', onclick: () => sheet.close() }, 'Cancel'), confirm))); + sheet.showModal(); + confirm.focus(); + } + + // -------------------------------------------------------------------- data + + async function refresh() { + if (S.stopped) return; + try { + S.data = await api('/api/state'); + } catch (err) { + if (!S.data) $('#cards').replaceChildren(h('p', { class: 'empty' }, err.message)); + return; + } + // A new version (the server updated itself) reloads the page; after one, says what's new. + if (window.ccUpdates) window.ccUpdates.seen(S.data); + render(); + } + + async function loadHistory() { + if (S.stopped) return; + try { + S.history = (await api('/api/history')).items; + } catch (err) { + toast(`Could not read saved conversations: ${err.message}`, 'error'); + } + render(); + } + + async function loadTeams() { + if (S.stopped) return; + try { + S.teams = (await api('/api/teams')).teams; + render(); + } catch { /* the strip waits for the next try */ } + } + + async function loadUsage() { + if (S.stopped) return; + try { + S.usage = { ...(await api('/api/usage')), at: Date.now() }; + render(); + } catch { /* the line waits for the next try */ } + } + + // ------------------------------------------------------------------- start + + $('#settings').append(icon('settings')); + $('#settings').addEventListener('click', () => window.ccSettings.open()); + $('#search').value = S.q; + $('#search').addEventListener('input', (event) => { S.q = event.target.value; render(true); }); + let scrolling = 0; + window.addEventListener('scroll', () => { + clearTimeout(scrolling); + scrolling = setTimeout(keep, 200); + }, { passive: true }); + document.addEventListener('click', (event) => { + if (!$('#menu').hidden && !event.target.closest('#menu') && !event.target.closest('.more-btn')) hideMenu(); + }); + document.addEventListener('keydown', (event) => { + if (document.querySelector('dialog[open]') || S.renaming) return; + const menu = $('#menu'); + if (!menu.hidden) { + const buttons = [...menu.querySelectorAll('button')]; + const at = buttons.indexOf(document.activeElement); + if (event.key === 'Escape') hideMenu(); + else if (event.key === 'ArrowDown') buttons[(at + 1) % buttons.length].focus(); + else if (event.key === 'ArrowUp') buttons[(at + buttons.length - 1) % buttons.length].focus(); + else return; + event.preventDefault(); + return; + } + const typing = event.target instanceof Element && event.target.closest('input, textarea'); + if (event.key === '/' && !typing) { + event.preventDefault(); + $('#search').focus(); + } else if (event.key === 'Escape' && event.target === $('#search')) { + $('#search').value = ''; + S.q = ''; + render(true); + } + }); + window.addEventListener('cc-settings-changed', () => { shown = ''; refresh(); }); + window.addEventListener('cc-stopped', () => { + S.stopped = true; + $('#cards').replaceChildren(h('p', { class: 'empty' }, 'Paddock has stopped. Run it again from a terminal to come back here.')); + }); + + refresh().then(() => { loadHistory(); loadTeams(); loadUsage(); }); + setInterval(() => { if (!document.hidden) refresh(); }, 5000); + setInterval(() => { if (!document.hidden) loadTeams(); }, 5000); + setInterval(() => { if (!document.hidden) loadHistory(); }, 20000); + setInterval(() => { if (!document.hidden) loadUsage(); }, 60000); +})(); diff --git a/ui/team.css b/ui/team.css new file mode 100644 index 0000000..5394243 --- /dev/null +++ b/ui/team.css @@ -0,0 +1,230 @@ +/* A session's team: the lead at the top, its members under it, joined the way + work is handed down. Each model has a colour of its own (--opus and so on). */ +:root { + --page: #f6f5f7; + --card: #ffffff; + --ink: #1d1d1f; + --muted: #6e6e73; + --faint: #8e8e93; + --line: #dcdce0; + --wire: #a9a9b0; + --hover: rgb(0 0 0 / 0.04); + --accent: #0a6cdc; + --on-accent: #ffffff; + --danger: #c4322b; + --ok: #23893f; + --shadow: 0 1px 2px rgb(0 0 0 / 0.06), 0 4px 14px rgb(0 0 0 / 0.06); + + --opus: #b4532a; + --opus-soft: #f8e7df; + --sonnet: #2f6fd0; + --sonnet-soft: #e1ebfa; + --haiku: #23874f; + --haiku-soft: #dff1e6; + --other: #64768a; + --other-soft: #e8ecf0; + + --sans: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", system-ui, sans-serif; + --mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace; + color-scheme: light; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + --page: #18181a; + --card: #232325; + --ink: #e8e8ea; + --muted: #a1a1a6; + --faint: #8a8a8f; + --line: #3a3a3d; + --wire: #5d5d63; + --hover: rgb(255 255 255 / 0.05); + --accent: #2f8cff; + --on-accent: #0b1424; + --danger: #ff6961; + --ok: #4cc06a; + --shadow: 0 1px 2px rgb(0 0 0 / 0.4), 0 4px 14px rgb(0 0 0 / 0.3); + --opus: #f08a5d; + --opus-soft: #3d2519; + --sonnet: #6aa6ff; + --sonnet-soft: #1a2a44; + --haiku: #5fd08e; + --haiku-soft: #16331f; + --other: #9fb0c2; + --other-soft: #2a3038; + color-scheme: dark; + } +} + +:root[data-theme="dark"] { + --page: #18181a; + --card: #232325; + --ink: #e8e8ea; + --muted: #a1a1a6; + --faint: #8a8a8f; + --line: #3a3a3d; + --wire: #5d5d63; + --hover: rgb(255 255 255 / 0.05); + --accent: #2f8cff; + --on-accent: #0b1424; + --danger: #ff6961; + --ok: #4cc06a; + --shadow: 0 1px 2px rgb(0 0 0 / 0.4), 0 4px 14px rgb(0 0 0 / 0.3); + --opus: #f08a5d; + --opus-soft: #3d2519; + --sonnet: #6aa6ff; + --sonnet-soft: #1a2a44; + --haiku: #5fd08e; + --haiku-soft: #16331f; + --other: #9fb0c2; + --other-soft: #2a3038; + color-scheme: dark; +} + +/* The primary colour picked in Settings. */ +:root[data-accent] { --accent: var(--accent-user); --on-accent: var(--on-accent-user); } + +* { box-sizing: border-box; } +body { margin: 0; background: var(--page); color: var(--ink); font: 14px/1.45 var(--sans); } +button, input, select, textarea { font: inherit; color: inherit; } +.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; } +.cc-icon { width: 16px; height: 16px; flex: none; } +.card.add .cc-icon { width: 22px; height: 22px; } + +/* ------------------------------------------------------------------ header */ + +.top { display: flex; align-items: center; gap: 14px; padding: 14px 24px; border-bottom: 1px solid var(--line); background: var(--card); position: sticky; top: 0; z-index: 2; } +.back { display: inline-flex; align-items: center; gap: 4px; color: var(--muted); text-decoration: none; font-size: 13px; } +.back:hover { color: var(--ink); } +.heading { min-width: 0; flex: 1; } +.heading h1 { margin: 0; font-size: 17px; font-weight: 650; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.where { margin: 1px 0 0; color: var(--muted); font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.top-actions { display: flex; gap: 8px; flex-wrap: wrap; justify-content: flex-end; } + +.btn { display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; border-radius: 7px; border: 1px solid var(--line); background: var(--card); cursor: pointer; white-space: nowrap; } +.btn:hover { background: var(--hover); } +.btn-primary { background: var(--accent); border-color: var(--accent); color: var(--on-accent); } +.btn-primary:hover { background: var(--accent); filter: brightness(1.06); } +.btn-danger { color: var(--danger); } +.btn:disabled, .btn-primary:disabled { opacity: 0.55; cursor: default; background: var(--card); border-color: var(--line); color: var(--muted); filter: none; } +.btn:focus-visible, .card:focus-visible, .link:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +.link { border: 0; background: none; padding: 0; color: var(--accent); cursor: pointer; text-align: left; } +.link.job { color: var(--ink); } +.link.job.empty { color: var(--accent); font-style: normal; } + +.page { max-width: 1120px; margin: 0 auto; padding: 28px 24px 64px; } + +/* ----------------------------------------------------------------- diagram */ + +.board { background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 28px 20px 18px; box-shadow: var(--shadow); + background-image: radial-gradient(circle, var(--line) 1px, transparent 1.2px); background-size: 18px 18px; } +.diagram { position: relative; } +.wires { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; overflow: visible; } +.wire { fill: none; stroke: var(--wire); stroke-width: 1.6; } +.wire.dashed { stroke-dasharray: 4 4; } +.wire.live { stroke: var(--tone); stroke-width: 2; stroke-dasharray: 6 6; animation: flow 0.9s linear infinite; } +@keyframes flow { to { stroke-dashoffset: -12; } } +.arrow { fill: var(--wire); } +.arrow.live { fill: var(--tone); } + +.tier { position: relative; display: flex; justify-content: center; align-items: flex-start; flex-wrap: wrap; gap: 22px 28px; } +.tier + .tier { margin-top: 64px; } +.tier-label { width: 100%; text-align: center; color: var(--faint); font-size: 12px; margin-bottom: -8px; } + +.card { position: relative; width: 236px; text-align: left; background: var(--card); border: 1px solid var(--line); border-top: 3px solid var(--tone); border-radius: 10px; padding: 12px 14px; box-shadow: var(--shadow); cursor: pointer; display: flex; flex-direction: column; gap: 6px; } +.card:hover { border-color: var(--tone); } +.card.lead { width: 300px; border-top-width: 4px; } +.card.other { border-style: dashed; border-top-style: solid; box-shadow: none; cursor: default; opacity: 0.92; } +.card.running { box-shadow: 0 0 0 3px color-mix(in srgb, var(--tone) 22%, transparent), var(--shadow); } +.card.add { border: 1.5px dashed var(--line); box-shadow: none; background: transparent; align-items: center; justify-content: center; color: var(--muted); min-height: 128px; width: 150px; align-self: stretch; } +.card.add:hover { color: var(--ink); border-color: var(--muted); } +.card.empty-team { width: 380px; cursor: default; border-top-color: var(--line); border-style: dashed; box-shadow: none; } +.card.empty-team:hover { border-color: var(--line); } +.template-line { margin: 2px 0 0; color: var(--muted); font-size: 12.5px; } + +.card-top { display: flex; align-items: center; gap: 6px; justify-content: space-between; } +.role { font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--faint); } +.name { font-weight: 650; font-size: 15px; overflow-wrap: anywhere; } +.job { color: var(--ink); opacity: 0.86; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; } +.job.empty { color: var(--faint); font-style: italic; } +.facts { color: var(--muted); font-size: 12px; display: flex; gap: 4px 10px; flex-wrap: wrap; } + +.chip { display: inline-flex; align-items: center; gap: 5px; padding: 1px 8px; border-radius: 999px; font-size: 12px; font-weight: 600; background: var(--soft); color: var(--tone); white-space: nowrap; } +.tone-opus { --tone: var(--opus); --soft: var(--opus-soft); } +.tone-sonnet { --tone: var(--sonnet); --soft: var(--sonnet-soft); } +.tone-haiku { --tone: var(--haiku); --soft: var(--haiku-soft); } +.tone-other { --tone: var(--other); --soft: var(--other-soft); } + +.state { display: inline-flex; align-items: center; gap: 5px; font-size: 12px; color: var(--muted); } +.state::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: var(--faint); } +.state[data-state="running"] { color: var(--tone); font-weight: 600; } +.state[data-state="running"]::before { background: var(--tone); animation: pulse 1.2s ease-in-out infinite; } +.state[data-state="done"]::before { background: var(--ok); } +.state[data-state="stopped"]::before { background: var(--danger); } +@keyframes pulse { 50% { opacity: 0.25; } } + +.lead-job { border: 1px solid var(--line); border-radius: 6px; padding: 4px 8px; width: 100%; background: var(--card); } +.card-actions { display: flex; gap: 8px; margin-top: 4px; flex-wrap: wrap; } + +.note { margin: 22px 0 0; text-align: center; color: var(--muted); font-size: 12.5px; } +.note code, .sheet code { font-family: var(--mono); font-size: 12px; } + +/* --------------------------------------------------------------- run box */ + +section.launch { margin-top: 30px; } +.run-box { background: var(--card); border: 1px solid var(--line); border-radius: 10px; padding: 14px; display: flex; flex-direction: column; gap: 10px; box-shadow: var(--shadow); } +.run-box textarea { width: 100%; border: 1px solid var(--line); border-radius: 7px; padding: 8px 10px; background: var(--page); resize: vertical; min-height: 84px; } +.run-row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; } +.run-row .models { align-items: center; } +.run-row .spacer { flex: 1; } + +/* -------------------------------------------------------------------- runs */ + +.runs { margin-top: 30px; } +.section-title { font-size: 14px; font-weight: 650; margin: 0 0 10px; } +.run-list { background: var(--card); border: 1px solid var(--line); border-radius: 10px; overflow: hidden; } +.run { display: grid; grid-template-columns: 92px 170px 1fr auto auto; gap: 12px; align-items: center; padding: 9px 14px; border-top: 1px solid var(--line); } +.run:first-child { border-top: 0; } +.run .when { color: var(--muted); font-size: 12.5px; } +.run .who { display: flex; flex-direction: column; gap: 2px; min-width: 0; } +.run .who .chip { align-self: flex-start; } +.run .who b { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.run .task { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.run .used { color: var(--muted); font-size: 12.5px; font-variant-numeric: tabular-nums; } +.run.nested .who { padding-left: 14px; border-left: 2px solid var(--line); } +.empty-runs { color: var(--muted); background: var(--card); border: 1px dashed var(--line); border-radius: 10px; padding: 18px; text-align: center; } + +@media (max-width: 720px) { + .top { padding: 12px 16px; flex-wrap: wrap; } + .page { padding: 18px 16px 48px; } + .card, .card.lead, .card.empty-team { width: 100%; } + .run { grid-template-columns: 1fr auto; } + .run .when, .run .task { grid-column: 1 / -1; } +} + +/* ---------------------------------------------------------- editor, toasts */ + +.sheet { border: 1px solid var(--line); border-radius: 12px; padding: 0; width: min(520px, calc(100vw - 32px)); background: var(--card); color: var(--ink); box-shadow: 0 20px 60px rgb(0 0 0 / 0.25); } +.sheet::backdrop { background: rgb(0 0 0 / 0.3); } +.sheet form { padding: 20px 22px; display: flex; flex-direction: column; gap: 14px; } +.sheet h2 { margin: 0; font-size: 16px; } +.field { display: flex; flex-direction: column; gap: 5px; } +.field > span { font-weight: 600; font-size: 13px; } +.field input, .field textarea { border: 1px solid var(--line); border-radius: 7px; padding: 7px 9px; background: var(--page); } +.field textarea { min-height: 120px; resize: vertical; font-family: var(--mono); font-size: 12.5px; } +.hint { color: var(--muted); font-size: 12px; margin: 0; } +.models { display: flex; gap: 8px; flex-wrap: wrap; border: 0; padding: 0; margin: 0; } +.models legend { font-weight: 600; font-size: 13px; padding: 0; margin-bottom: 5px; } +.models label { display: inline-flex; align-items: center; gap: 6px; padding: 5px 10px; border: 1px solid var(--line); border-radius: 999px; cursor: pointer; } +.models label:has(input:checked) { border-color: var(--tone, var(--accent)); background: var(--soft, var(--hover)); color: var(--tone, var(--ink)); font-weight: 600; } +.models input { margin: 0; accent-color: var(--tone, var(--accent)); } +.sheet-actions { display: flex; gap: 8px; justify-content: flex-end; align-items: center; } +.sheet-actions .spacer { flex: 1; } + +.toasts { position: fixed; bottom: 18px; left: 50%; transform: translateX(-50%); display: flex; flex-direction: column; gap: 8px; z-index: 10; } +.toast { background: var(--ink); color: var(--card); padding: 8px 14px; border-radius: 8px; box-shadow: var(--shadow); max-width: 90vw; } +.toast-error { background: var(--danger); color: #fff; } + +@media (prefers-reduced-motion: reduce) { + .wire.live, .state[data-state="running"]::before { animation: none; } +} diff --git a/ui/team.html b/ui/team.html new file mode 100644 index 0000000..1ec6ae3 --- /dev/null +++ b/ui/team.html @@ -0,0 +1,40 @@ + + + + + + + Team · Paddock + + + + + + + +
+ +
+

Team

+

+
+
+
+ +
+
+

How the team works

+
+

+
+
+
+

What the team did

+
+
+
+ + +
+ + diff --git a/ui/team.js b/ui/team.js new file mode 100644 index 0000000..9078900 --- /dev/null +++ b/ui/team.js @@ -0,0 +1,513 @@ +'use strict'; + +// A session's team, drawn the way work flows: the session itself leads, at the +// top, and hands work down to its members, Claude Code sub-agents defined in the +// project. Each box lights up while that member is running. Members are edited +// here; what they did is read from the session's transcripts. + +const $ = (selector) => document.querySelector(selector); +const POLL_MS = 4000; +const params = new URLSearchParams(location.search); +const ACCOUNT = params.get('account') || ''; +let SESSION = params.get('session') || ''; +// The team from the sketch this page was made for: one reads, one scores, one checks. +const TEMPLATE = { + title: 'Report review', + lead: 'Analyse the report', + members: [ + { name: 'scorer', model: 'sonnet', short: 'scores it', job: 'Scores the report against the criteria the lead gives, with a short reason for each score.' }, + { name: 'answer-checker', model: 'haiku', short: 'checks the answers', job: 'Checks the answers in the report for mistakes and says which are right, which are wrong, and why.' }, + ], +}; + +let team = null; +let shown = ''; +let editingLead = false; + +// ------------------------------------------------------------------ utilities + +function h(tag, props = {}, ...children) { + const el = document.createElement(tag); + for (const [key, value] of Object.entries(props)) { + if (value == null || value === false) continue; + if (key === 'class') el.className = value; + else if (key === 'style') for (const [name, v] of Object.entries(value)) el.style.setProperty(name, v); + else if (key.startsWith('on')) el.addEventListener(key.slice(2), value); + else if (key in el) el[key] = value; + else el.setAttribute(key, value); + } + el.append(...children.flat(Infinity).filter((child) => child != null && child !== false)); + return el; +} + +function svg(tag, attrs = {}) { + const el = document.createElementNS('http://www.w3.org/2000/svg', tag); + for (const [key, value] of Object.entries(attrs)) el.setAttribute(key, value); + return el; +} + +function store(key, value) { + try { + if (value === undefined) return localStorage.getItem(key); + localStorage.setItem(key, value); + } catch { /* private window */ } + return null; +} + +const icon = (name) => window.ccIcon(name); + +function toast(message, kind = 'ok') { + const el = h('div', { class: `toast toast-${kind}` }, message); + $('#toasts').append(el); + setTimeout(() => el.remove(), kind === 'error' ? 9000 : 4000); +} + +function ago(ms) { + if (!ms) return ''; + const s = Math.max(0, (Date.now() - ms) / 1000); + if (s < 60) return 'just now'; + if (s < 3600) return `${Math.floor(s / 60)} min ago`; + if (s < 86400) return `${Math.floor(s / 3600)} h ago`; + return new Date(ms).toLocaleDateString(undefined, { day: 'numeric', month: 'short' }); +} + +function tokens(n) { + if (n >= 1e6) return `${(n / 1e6).toFixed(n >= 1e7 ? 0 : 1)}M`; + if (n >= 1e3) return `${(n / 1e3).toFixed(n >= 1e4 ? 0 : 1)}k`; + return String(n); +} +const tokenSum = (t) => (t ? t.input + t.output + t.cacheWrite + t.cacheRead : 0); + +// ----------------------------------------------------------------------- API + +let token = params.get('t'); +if (token) { + store('cc-token', token); + params.delete('t'); + history.replaceState(null, '', `${location.pathname}?${params}`); +} else { + token = store('cc-token') || ''; +} + +async function api(path, body) { + const response = await fetch(path, { + method: body ? 'POST' : 'GET', + headers: { 'X-CC-Token': token, ...(body ? { 'Content-Type': 'application/json' } : {}) }, + body: body ? JSON.stringify(body) : undefined, + }); + const data = await response.json().catch(() => ({})); + if (response.status === 401) throw new Error('Open Paddock from the terminal once, so this page has its key.'); + if (!response.ok) throw new Error(data.error || `Request failed (${response.status}).`); + return data; +} + +const send = (path, body) => api(path, { account: ACCOUNT, sessionId: SESSION, ...body }); + +// -------------------------------------------------------------------- models + +// "opus", "claude-opus-5-5" or "claude-3-5-haiku-20241022" as a colour and a name. +function modelOf(model) { + const id = String(model || '').toLowerCase(); + const family = ['opus', 'sonnet', 'haiku', 'fable'].find((f) => id.includes(f)); + const tone = family === 'fable' ? 'other' : family || 'other'; + if (!family) return { tone, label: model || 'Unknown' }; + const numbers = id.replace(/\[.*\]$/, '').replace(/-\d{8}$/, '').replace(family, '').split('-').filter((p) => /^\d+$/.test(p)); + const name = family[0].toUpperCase() + family.slice(1); + return { tone, label: numbers.length ? `${name} ${numbers.join('.')}` : name }; +} + +// A member's model: its own, or the lead's when it runs on whatever the lead does. +function memberModel(member) { + if (member.model !== 'inherit') return { ...modelOf(member.model), inherit: false }; + const lead = modelOf(team.lead.model); + return { tone: lead.tone, label: team.lead.model ? lead.label : 'Lead’s model', inherit: true }; +} + +function chip(model, extra) { + return h('span', { class: `chip tone-${model.tone}`, title: extra || null }, model.label); +} + +// ------------------------------------------------------------------- drawing + +function runsOf(type) { + return team.runs.filter((run) => run.type === type); +} + +function stateOf(runs) { + if (runs.some((run) => run.state === 'running')) return ['running', 'Running']; + if (runs.length) return ['done', `Ran ${runs.length === 1 ? 'once' : `${runs.length} times`}`]; + return ['idle', 'Not used yet']; +} + +function usedFacts(runs) { + if (!runs.length) return []; + const used = runs.reduce((sum, run) => sum + tokenSum(run.tokens), 0); + const last = Math.max(...runs.map((run) => run.lastAt)); + return [h('span', {}, `${tokens(used)} tokens`), h('span', {}, ago(last))]; +} + +function leadCard() { + const model = team.lead.model ? modelOf(team.lead.model) : { tone: 'other', label: 'No replies yet' }; + const job = editingLead + ? h('input', { class: 'lead-job', value: team.lead.job || '', placeholder: 'What the lead does, like “Analyse the report”', 'aria-label': 'What the lead does', + onkeydown: (event) => { + if (event.key === 'Enter') saveLead(event.target.value); + if (event.key === 'Escape') { editingLead = false; draw(true); } + }, + onblur: (event) => saveLead(event.target.value) }) + : h('button', { type: 'button', class: `link job${team.lead.job ? '' : ' empty'}`, title: 'Change what the lead does', + onclick: () => { editingLead = true; draw(true); } }, team.lead.job || 'Say what the lead does…'); + return h('div', { class: `card lead tone-${model.tone}`, id: 'lead' }, + h('div', { class: 'card-top' }, h('span', { class: 'role' }, 'Lead · this session'), chip(model)), + h('div', { class: 'name' }, 'Main session'), + job, + h('div', { class: 'facts' }, + h('span', { class: 'state', 'data-state': LEAD_STATES[leadStatus()][0] }, LEAD_STATES[leadStatus()][1]), + tokenSum(team.lead.tokens) > 0 && h('span', {}, `${tokens(tokenSum(team.lead.tokens))} tokens of its own`)), + leadStatus() === 'blocked' && team.key && h('div', { class: 'card-actions' }, + h('button', { type: 'button', class: 'btn', onclick: openLead }, icon('square-terminal'), 'Open in a terminal'))); +} + +// How the session is doing, as Paddock lists it: [the dot's state, what it says]. +const LEAD_STATES = { + working: ['running', 'Working'], + blocked: ['stopped', 'Waiting for you'], + idle: ['idle', 'Open, idle'], + done: ['done', 'Done'], + closed: ['idle', 'Closed'], +}; +const leadStatus = () => (LEAD_STATES[team.status] ? team.status : team.open ? 'idle' : 'closed'); + +function memberCard(member) { + const model = memberModel(member); + const runs = runsOf(member.name); + const [state, label] = stateOf(runs); + return h('button', { type: 'button', class: `card member tone-${model.tone}${state === 'running' ? ' running' : ''}`, 'data-member': member.name, 'data-tone': model.tone, + 'aria-label': `${member.name}, ${model.label}. ${member.job}. ${label}. Edit`, onclick: () => editMember(member) }, + h('div', { class: 'card-top' }, h('span', { class: 'role' }, 'Member'), chip(model, model.inherit ? 'Runs on the lead’s model' : null)), + h('div', { class: 'name' }, member.name), + h('div', { class: `job${member.job ? '' : ' empty'}` }, member.job || 'No description: the lead will not know when to use it.'), + h('div', { class: 'facts' }, h('span', { class: 'state', 'data-state': state }, label), usedFacts(runs))); +} + +// Sub-agents the session ran that are not members: Claude Code's own, or another folder's. +function otherCard(type) { + const runs = runsOf(type); + const model = modelOf(runs.map((run) => run.model).find(Boolean)); + const [state, label] = stateOf(runs); + return h('div', { class: `card other tone-${model.tone}${state === 'running' ? ' running' : ''}`, 'data-member': type, 'data-tone': model.tone }, + h('div', { class: 'card-top' }, h('span', { class: 'role' }, 'Sub-agent'), chip(model)), + h('div', { class: 'name' }, type), + h('div', { class: 'job' }, runs[runs.length - 1].task || ''), + h('div', { class: 'facts' }, h('span', { class: 'state', 'data-state': state }, label), usedFacts(runs))); +} + +// A session with no team yet: what it has, and how to start one. The template is only offered, never drawn as a team. +function emptyCard() { + const folder = team.cwd.split('/').filter(Boolean).pop() || team.cwd; + const used = [...new Set(team.runs.map((run) => run.type))]; + return h('div', { class: 'card empty-team' }, + h('div', { class: 'card-top' }, h('span', { class: 'role' }, 'No team yet')), + h('div', { class: 'name' }, folder), + h('div', { class: 'job' }, + `Members belong to this folder, so every session in ${folder} shares them. `, + used.length ? `This session has started ${used.join(', ')} on its own, without a team.` : 'This session has not started any sub-agents.'), + h('div', { class: 'card-actions' }, h('button', { type: 'button', class: 'btn btn-primary', onclick: () => editMember(null) }, icon('user-plus'), 'Add the first member')), + h('p', { class: 'template-line' }, 'Or use a template: ', + h('button', { type: 'button', class: 'link', onclick: useTemplate, + title: TEMPLATE.members.map((m) => `${m.name} on ${modelOf(m.model).label}: ${m.job}`).join('\n') }, + `${TEMPLATE.title} (adds ${TEMPLATE.members.map((m) => m.name).join(' and ')})`))); +} + +function addCard() { + return h('button', { type: 'button', class: 'card add', onclick: () => editMember(null) }, icon('user-plus'), 'Add a member'); +} + +function draw(force = false) { + const signature = JSON.stringify(team); + if (!force && signature === shown) return; + // Typing in the lead's box: leave it be until it is saved. + if (!force && document.activeElement && document.activeElement.classList.contains('lead-job')) return; + shown = signature; + + document.title = `Team · ${team.title}`; + $('#title').textContent = team.title; + $('#where').textContent = `${team.cwd} · ${team.account}`; + $('#top-actions').replaceChildren( + h('button', { type: 'button', class: 'btn', onclick: () => editMember(null) }, icon('user-plus'), 'Add a member')); + drawRunBox(); + + const names = new Set(team.members.map((m) => m.name)); + const others = [...new Set(team.runs.map((run) => run.type))].filter((type) => !names.has(type)); + const diagram = $('#diagram'); + diagram.replaceChildren(...[ + svg('svg', { class: 'wires', id: 'wires', 'aria-hidden': 'true' }), + h('div', { class: 'tier' }, leadCard()), + h('div', { class: 'tier' }, team.members.map(memberCard), team.members.length ? addCard() : emptyCard()), + others.length > 0 && h('div', { class: 'tier' }, h('div', { class: 'tier-label' }, 'Also started by this session, not on the team'), others.map(otherCard)), + ].filter(Boolean)); + if (editingLead) diagram.querySelector('.lead-job').focus(); + + const lead = modelOf(team.lead.model); + const wantsOpus = team.members.length > 0 && Boolean(team.lead.model) && lead.tone !== 'opus'; + $('#note').replaceChildren(h('span', {}, + 'Members are Claude Code agent files in ', h('code', {}, team.agentsDir), ', so any session in this folder can use them. ', + 'Running the team from here starts Claude Code afresh, so it always sees the members as they are now.', + wantsOpus && [h('br'), `The lead runs on ${lead.label}. To lead on Opus, type `, h('code', {}, '/model opus'), ' in the session.'])); + wires(); + drawRuns(); +} + +// Lines from the lead down to each member: down, across, down, as on paper. +function wires() { + const diagram = $('#diagram'); + const layer = $('#wires'); + const lead = $('#lead'); + if (!layer || !lead) return; + const box = diagram.getBoundingClientRect(); + const rect = (el) => { + const r = el.getBoundingClientRect(); + return { x: r.left - box.left, y: r.top - box.top, w: r.width, h: r.height }; + }; + const from = rect(lead); + const fx = from.x + from.w / 2; + const fy = from.y + from.h; + const paths = []; + const arrows = []; + for (const card of diagram.querySelectorAll('[data-member]')) { + const to = rect(card); + const tx = to.x + to.w / 2; + const ty = to.y; + const mid = card.classList.contains('other') ? ty - 22 : fy + (ty - fy) / 2; + const r = Math.min(8, Math.abs(tx - fx) / 2); + const turn = tx === fx ? '' : `Q ${fx} ${mid} ${fx + Math.sign(tx - fx) * r} ${mid} L ${tx - Math.sign(tx - fx) * r} ${mid} Q ${tx} ${mid} ${tx} ${mid + r}`; + const live = card.classList.contains('running') ? ` live tone-${card.dataset.tone}` : ''; + paths.push(svg('path', { class: `wire${live}${card.classList.contains('other') ? ' dashed' : ''}`, + d: `M ${fx} ${fy} L ${fx} ${mid - (tx === fx ? 0 : r)} ${turn} L ${tx} ${ty - 7}` })); + arrows.push(svg('path', { class: `arrow${live}`, d: `M ${tx - 5} ${ty - 8} L ${tx + 5} ${ty - 8} L ${tx} ${ty - 1} Z` })); + } + layer.replaceChildren(...paths, ...arrows); +} + +function drawRuns() { + const runs = [...team.runs].reverse(); + if (!runs.length) { + $('#runs').replaceChildren(h('p', { class: 'empty-runs' }, 'No sub-agents yet. When the session hands work to one, it shows here and its box lights up.')); + return; + } + const members = new Map(team.members.map((m) => [m.name, m])); + $('#runs').replaceChildren(h('div', { class: 'run-list' }, runs.map((run) => { + const model = modelOf(run.model); + const states = { running: 'Running', done: 'Done', stopped: 'Stopped' }; + return h('div', { class: `run tone-${model.tone}${run.depth > 1 ? ' nested' : ''}` }, + h('span', { class: 'when', title: new Date(run.startedAt).toLocaleString() }, ago(run.startedAt)), + h('span', { class: 'who' }, h('b', { title: members.has(run.type) ? 'On the team' : 'Not on the team' }, run.type), run.model && chip(model)), + h('span', { class: 'task', title: run.task }, run.depth > 1 ? `${run.task} (started by a sub-agent)` : run.task), + h('span', { class: 'used' }, `${tokens(tokenSum(run.tokens))} tokens`), + h('span', { class: 'state', 'data-state': run.state }, states[run.state] || run.state)); + }))); +} + +// ------------------------------------------------------------------- actions + +async function load() { + try { + team = await api(`/api/team?account=${encodeURIComponent(ACCOUNT)}&session=${encodeURIComponent(SESSION)}`); + draw(); + } catch (error) { + if (!team) { + $('#title').textContent = 'No team to show'; + $('#where').textContent = error.message; + } else { + toast(error.message, 'error'); + } + } +} + +async function saveLead(job) { + if (!editingLead) return; + editingLead = false; + if (job.trim() === (team.lead.job || '')) return draw(true); + try { + await send('/api/team/lead', { job }); + } catch (error) { + toast(error.message, 'error'); + } + await load(); + draw(true); +} + +// The box that sets the team to work. Drawn once, so polling never touches what is being typed. +function drawRunBox() { + const box = $('#run'); + if (!box.firstChild) { + box.append( + h('h2', { class: 'section-title', id: 'run-title' }, 'Run the team'), + h('form', { class: 'run-box', onsubmit: (event) => { event.preventDefault(); runTeam(); } }, + h('textarea', { id: 'run-task', rows: 4, 'aria-labelledby': 'run-title', + placeholder: 'What should the team work on? Paste the report, or say which file it is in.' }), + h('div', { class: 'run-row' }, + h('fieldset', { class: 'models' }, h('legend', { class: 'sr-only' }, 'The lead runs on'), h('span', { class: 'hint' }, 'Lead on'), + [['opus', 'Opus'], ['sonnet', 'Sonnet'], ['haiku', 'Haiku']].map(([id, label]) => h('label', { class: `tone-${id}` }, + h('input', { type: 'radio', name: 'lead-model', value: id, checked: id === 'opus' }), label))), + h('span', { class: 'spacer' }), + h('button', { type: 'button', class: 'link', onclick: copyPrompt }, 'Copy the prompt instead'), + h('button', { type: 'submit', class: 'btn btn-primary', id: 'run-go' }, icon('play'), 'Run the team')), + h('p', { class: 'hint', id: 'run-hint' }))); + } + $('#run-go').disabled = !team.members.length || running; + $('#run-hint').textContent = !team.members.length ? 'Add a member first: the team runs with the members of this folder.' + : team.open ? 'This session is open, so the team starts as a new background session in the same folder, and this page follows it.' + : 'Claude Code continues this session in the background with the team. Watch the boxes light up as each member works.'; +} + +let running = false; + +async function runTeam() { + const task = $('#run-task').value.trim(); + if (!task) { + toast('Say what the team should work on.', 'error'); + return $('#run-task').focus(); + } + const model = (document.querySelector('input[name="lead-model"]:checked') || {}).value || 'opus'; + running = true; + drawRunBox(); + try { + const started = await send('/api/team/run', { prompt: teamPrompt(task), model }); + $('#run-task').value = ''; + if (started.sessionId && started.sessionId !== SESSION) { + SESSION = started.sessionId; + params.set('session', SESSION); + history.replaceState(null, '', `${location.pathname}?${params}`); + toast(`The team is running as a new background session (${started.id}). Following it here.`); + } else { + toast(`The team is running in the background (${started.id}).`); + } + } catch (error) { + toast(error.message, 'error'); + } + running = false; + await load(); + drawRunBox(); +} + +async function openLead() { + try { + await api('/api/sessions/resume', { key: team.key }); + toast('Opened in a terminal.'); + } catch (error) { + toast(error.message, 'error'); + } +} + +function teamPrompt(task) { + const lead = team.lead.job ? `${team.lead.job.replace(/[.\s]+$/, '')}.` : 'Lead this piece of work.'; + return [ + lead, + '', + 'You lead a team. Hand work to its members with the Agent tool, by name:', + ...team.members.map((m) => `- ${m.name} (${memberModel(m).label}): ${m.job}`), + '', + 'If a member is not among your agent types yet, start a general-purpose agent on that member’s model instead, and give it the member’s job.', + 'Start members whose work does not depend on each other at the same time. Then bring their results together and give me one answer.', + ...(task ? ['', 'The work:', task] : []), + ].join('\n'); +} + +async function copyPrompt() { + try { + await navigator.clipboard.writeText(teamPrompt($('#run-task').value.trim())); + toast('Copied. Paste it into the session to start the team.'); + } catch { + toast('The browser would not copy. Select the text in the next window instead.', 'error'); + } +} + +async function useTemplate() { + try { + for (const member of TEMPLATE.members) { + if (team.members.some((m) => m.name === member.name)) continue; + await send('/api/team/member', { member }); + } + if (!team.lead.job) await send('/api/team/lead', { job: TEMPLATE.lead }); + toast(`${TEMPLATE.title} is set up. Say what to review below and run the team.`); + } catch (error) { + toast(error.message, 'error'); + } + await load(); +} + +const MODEL_CHOICES = [['opus', 'Opus'], ['sonnet', 'Sonnet'], ['haiku', 'Haiku'], ['inherit', 'Same as the lead']]; + +function editMember(member) { + const sheet = $('#sheet'); + const model = member ? member.model : 'sonnet'; + const choices = MODEL_CHOICES.some(([id]) => id === model) ? MODEL_CHOICES : [...MODEL_CHOICES, [model, modelOf(model).label]]; + let armed = false; + const field = (label, input, hint) => h('label', { class: 'field' }, h('span', {}, label), input, hint && h('p', { class: 'hint' }, hint)); + const form = h('form', { method: 'dialog', + onsubmit: async (event) => { + event.preventDefault(); + const data = new FormData(event.target); + try { + await send('/api/team/member', { member: { + file: member ? member.file : '', + name: String(data.get('name')).trim(), + model: String(data.get('model')), + job: String(data.get('job')), + instructions: String(data.get('instructions')), + } }); + sheet.close(); + toast(member ? 'Saved.' : 'Added to the team.'); + await load(); + } catch (error) { + toast(error.message, 'error'); + } + } }, + h('h2', { id: 'sheet-title' }, member ? `Edit ${member.name}` : 'Add a member'), + field('Name', h('input', { name: 'name', required: true, value: member ? member.name : '', placeholder: 'scorer', pattern: '[a-z][a-z0-9\\-]*', maxLength: 48, autocomplete: 'off', spellcheck: false }), + 'Lowercase letters, digits and dashes. The lead calls it by this name.'), + h('fieldset', { class: 'models' }, h('legend', {}, 'Model'), + choices.map(([id, label]) => h('label', { class: `tone-${id === 'inherit' ? modelOf(team.lead.model).tone : modelOf(id).tone}` }, + h('input', { type: 'radio', name: 'model', value: id, checked: id === model }), label))), + field('What it does', h('input', { name: 'job', required: true, value: member ? member.job : '', maxLength: 400, placeholder: 'Checks the answers in the report' }), + 'One sentence. The lead reads it to decide when to hand work over.'), + field('Instructions', h('textarea', { name: 'instructions', value: member ? member.instructions : '', placeholder: 'Left empty, Paddock writes a short brief from what it does.' }), + member && member.tools ? `It can use: ${member.tools}. That is kept as it is.` : 'What it is told before it starts. It can use the same tools as the lead.'), + h('div', { class: 'sheet-actions' }, + member && h('button', { type: 'button', class: 'btn btn-danger', + onclick: async (event) => { + if (!armed) { + armed = true; + event.currentTarget.textContent = 'Click again to remove'; + return; + } + try { + await send('/api/team/remove', { file: member.file }); + sheet.close(); + toast(`${member.name} is off the team. Its file is kept in Paddock’s folder.`); + await load(); + } catch (error) { + toast(error.message, 'error'); + } + } }, 'Remove'), + h('span', { class: 'spacer' }), + h('button', { type: 'button', class: 'btn', onclick: () => sheet.close() }, 'Cancel'), + h('button', { type: 'submit', class: 'btn btn-primary' }, member ? 'Save' : 'Add'))); + sheet.replaceChildren(form); + sheet.showModal(); +} + +// ---------------------------------------------------------------------- start + +$('#back').replaceChildren(icon('chevron-left'), 'Sessions'); +if (!ACCOUNT || !SESSION) { + $('#title').textContent = 'No session chosen'; + $('#where').textContent = 'Open a session in Paddock and choose Team.'; +} else { + load(); + setInterval(() => { + if (!document.hidden && !$('#sheet').open) load(); + }, POLL_MS); +} +new ResizeObserver(() => wires()).observe($('#diagram')); diff --git a/ui/theme.js b/ui/theme.js index 31f39cf..0730e08 100644 --- a/ui/theme.js +++ b/ui/theme.js @@ -2,7 +2,7 @@ // Loaded before the page paints, so the chosen theme, template and primary // colour never flash the defaults first, and the classic page hands over to the -// Finder view straight away when that was the last one used. +// Finder or Simple layout straight away when that was the last one used. (() => { // Settings keeps choices in memory as well, for browsers that keep no storage. const memory = window.ccMemory || (window.ccMemory = {}); @@ -11,8 +11,9 @@ try { return localStorage.getItem(key); } catch { return null; } }; - if (read('cc-view') === 'finder' && location.pathname === '/') { - location.replace(`/finder${location.search}`); + const start = { finder: '/finder', simple: '/simple' }[read('cc-view')]; + if (start && location.pathname === '/') { + location.replace(`${start}${location.search}${location.hash}`); } // White or near-black, whichever reads better on the colour.