From 73684253ce0703550146e5c9cdbef951c9229891 Mon Sep 17 00:00:00 2001 From: Richard Zink Date: Thu, 19 Nov 2026 13:42:49 +0100 Subject: [PATCH] Terminal client: steer server chats and the factory Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 6 + README.md | 9 ++ cli/src/app.rs | 313 +++++++++++++++++++++++++++++++++++++++++++- cli/src/main.rs | 1 + cli/src/remote.rs | 278 +++++++++++++++++++++++++++++++++++++++ web/src/whatsnew.ts | 4 + 6 files changed, 604 insertions(+), 7 deletions(-) create mode 100644 cli/src/remote.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 5277742..f292177 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,12 @@ All notable changes to CodeCraft. Versions follow [Semantic Versioning](https://semver.org/); until 1.0, minor versions may contain breaking changes. +## [Unreleased] + +### Added + +- **Terminal client: steer the server.** `/projects` lists your chats on the server and opens one in the terminal – the agent keeps running on the server; you read along, send messages, answer permissions and questions, interrupt and compact. `/factory` shows the factory board and lets you merge pull requests, close, restart or remove issues and open the chat of any run; `/factory check` polls for new issues. `/local` returns to the local chat. + ## [v202611-00065] – 2026-11-19 ### Added diff --git a/README.md b/README.md index 34120fa..91908bc 100644 --- a/README.md +++ b/README.md @@ -210,6 +210,15 @@ codecraft login # server URL, user name, password → creates an API codecraft # start in the current folder; /help lists the commands ``` +Signed in to a server, the terminal also steers the server itself: + +- `/projects` lists your chats on the server; open one and follow it – the agent keeps running **on the + server**, in the server's folder – and answer its permission requests and questions, send messages, interrupt + it (Esc) and `/compact` it. `/local` returns to a local chat. The view refreshes every second or two. +- `/factory` shows the factory board (issues by phase with their latest run, totals and cost) and offers per + issue: open the chat of a run, merge the pull request (merge, squash or rebase), close the issue, restart it at + the review, build or acceptance, or remove it from the board. `/factory check` looks for new issues right away. + The Docker image ships static binaries for Linux x86_64, aarch64 and riscv64; the server offers them for download (*Settings → Account*) and `codecraft update` fetches new versions from it. Other platforms: `cargo install --locked --git https://git.familie-zink.org/zink/codecraft codecraft-cli`. diff --git a/cli/src/app.rs b/cli/src/app.rs index 7a8cf92..145bada 100644 --- a/cli/src/app.rs +++ b/cli/src/app.rs @@ -3,6 +3,7 @@ use crate::agent::{Env, Reply, UiEvent}; use crate::editor::Editor; use crate::i18n::t; +use crate::remote::{self, Remote, Snapshot}; use crate::session::LocalSession; use crate::theme::{self, Theme}; use anyhow::Result; @@ -61,6 +62,11 @@ enum PickKind { Permission, Effort, Lang, + /// Chats of the server. + Remote, + /// Issues of the factory board / the actions for one issue. + FactoryIssue, + FactoryAction, } struct Picker { @@ -129,6 +135,14 @@ pub struct App { /// Running setup action (login / provider test): Ok(message) or error. pending_setup: Option>>, pending_env: Option>>, + /// A chat of the server that this terminal follows (instead of the local session). + remote: Option, + pending_snapshot: Option>>, + pending_open: Option>>, + pending_pick: Option)>>>, + pending_note: Option>>, + /// The factory issue ("repo#number") whose actions are open. + factory_key: String, } const SPINNER: &[&str] = &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]; @@ -317,6 +331,12 @@ impl App { pending_detect: None, pending_setup: None, pending_env: None, + remote: None, + pending_snapshot: None, + pending_open: None, + pending_pick: None, + pending_note: None, + factory_key: String::new(), }; app.rebuild_items(); app @@ -446,6 +466,10 @@ impl App { return; } let text = self.expand_command(&trimmed).unwrap_or(trimmed); + if self.remote.is_some() { + self.send_remote(text); + return; + } if self.busy { self.queue.push_back(text); self.status = format!("{} ({})", t("queued"), self.queue.len()); @@ -527,6 +551,9 @@ impl App { ("setup", "add model providers or sign in to a server"), ("memory", "show the project memory"), ("jobs", "automations on the server"), + ("projects", "chats on the server: open and steer them"), + ("factory", "software factory of the server: board and actions"), + ("local", "back to a local chat"), ("quit", "exit"), ] } @@ -545,6 +572,21 @@ impl App { } self.dialog = Dialog::Text { title: t("help").into(), body }; } + "projects" | "server" => self.fetch_pick(PickKind::Remote), + "factory" if arg == "check" => { + if let Some(server) = self.env.server.clone() { + let (tx, rx) = oneshot::channel(); + tokio::spawn(async move { + let _ = tx.send(remote::factory_poll(&server).await); + }); + self.pending_note = Some(rx); + } else { + self.items.push(Item::Error("not signed in to a server".into())); + } + } + "factory" => self.fetch_pick(PickKind::FactoryIssue), + "local" => self.leave_remote(), + "model" | "mode" | "permissions" | "effort" if self.remote.is_some() => self.items.push(Item::Info("this chat runs on the server – change this in the web interface (/local returns to a local chat)".into())), "model" => self.open_picker(PickKind::Model), "mode" => { if arg.is_empty() { @@ -558,7 +600,18 @@ impl App { "theme" => self.open_picker(PickKind::Theme), "lang" => self.open_picker(PickKind::Lang), "resume" | "sessions" => self.open_picker(PickKind::Session), + "compact" if self.remote.is_some() => { + if let (Some(server), Some(r)) = (self.env.server.clone(), &self.remote) { + let id = r.id.clone(); + let (tx, rx) = oneshot::channel(); + tokio::spawn(async move { + let _ = tx.send(remote::compact(&server, &id).await.map(|_| "compacting on the server…".to_string())); + }); + self.pending_note = Some(rx); + } + } "new" | "clear" => { + self.remote = None; let _ = self.cmd.send(Cmd::New); self.session = LocalSession::new(&self.session.cwd, &self.session.model, &self.session.mode, &self.session.permission_mode); self.items.clear(); @@ -638,6 +691,7 @@ impl App { PickKind::Effort => ("Effort".into(), ["low", "medium", "high", "max"].iter().map(|e| (e.to_string(), e.to_string(), "next message only".into())).collect()), PickKind::Theme => (t("choose_theme").into(), theme::names().into_iter().flat_map(|n| ["auto", "dark", "light"].map(|m| (format!("{n}:{m}"), format!("{n} ({m})"), String::new()))).collect()), PickKind::Lang => ("Language".into(), vec![("en".into(), "English".into(), String::new()), ("de".into(), "Deutsch".into(), String::new())]), + PickKind::Remote | PickKind::FactoryIssue | PickKind::FactoryAction => return, PickKind::Session => ( t("choose_session").into(), crate::session::list(None) @@ -682,6 +736,12 @@ impl App { cfg.lang = Some(key); let _ = cfg.save(); } + PickKind::Remote => self.open_remote(&key), + PickKind::FactoryIssue => { + self.factory_key = key.clone(); + self.fetch_actions(&key); + } + PickKind::FactoryAction => self.factory_action(&key), PickKind::Session => { if let Ok(s) = LocalSession::load(&key) { self.session = s.clone(); @@ -694,6 +754,245 @@ impl App { } } + // --- server: remote chats and the factory ---------------------------------------------- + + fn abort_current(&mut self) { + if let (Some(server), Some(r)) = (self.env.server.clone(), &self.remote) { + let id = r.id.clone(); + tokio::spawn(async move { + let _ = remote::abort(&server, &id).await; + }); + } else if let Some(c) = &self.cancel { + c.cancel(); + } + } + + /// Fetch the entries of a server picker in the background; the picker opens when they arrive. + fn fetch_pick(&mut self, kind: PickKind) { + let Some(server) = self.env.server.clone() else { + self.items.push(Item::Error("not signed in to a server – run: codecraft login".into())); + return; + }; + let (tx, rx) = oneshot::channel(); + self.status = "loading…".into(); + tokio::spawn(async move { + let res = match kind { + PickKind::Remote => remote::sessions(&server).await.map(|items| (kind, "Chats on the server".to_string(), items)), + _ => remote::factory_board(&server).await.map(|(summary, items)| (kind, summary, items)), + }; + let _ = tx.send(res); + }); + self.pending_pick = Some(rx); + } + + fn fetch_actions(&mut self, key: &str) { + let Some(server) = self.env.server.clone() else { return }; + let key = key.to_string(); + let (tx, rx) = oneshot::channel(); + tokio::spawn(async move { + let _ = tx.send(remote::factory_actions(&server, &key).await.map(|(title, acts)| (PickKind::FactoryAction, title, acts))); + }); + self.pending_pick = Some(rx); + } + + fn factory_action(&mut self, action: &str) { + if let Some(id) = action.strip_prefix("chat:") { + self.open_remote(id); + return; + } + let Some(server) = self.env.server.clone() else { return }; + let (key, action) = (self.factory_key.clone(), action.to_string()); + let (tx, rx) = oneshot::channel(); + tokio::spawn(async move { + let _ = tx.send(remote::factory_do(&server, &key, &action).await); + }); + self.pending_note = Some(rx); + } + + fn open_remote(&mut self, id: &str) { + let Some(server) = self.env.server.clone() else { return }; + let id = id.to_string(); + let (tx, rx) = oneshot::channel(); + tokio::spawn(async move { + let _ = tx.send(remote::open(&server, &id).await); + }); + self.pending_open = Some(rx); + } + + fn leave_remote(&mut self) { + if self.remote.take().is_some() { + self.items.clear(); + self.todos = Value::Null; + self.busy = false; + self.rebuild_items(); + self.status = "local chat".into(); + } + } + + fn send_remote(&mut self, text: String) { + let (Some(server), Some(r)) = (self.env.server.clone(), &self.remote) else { return }; + let id = r.id.clone(); + let (tx, rx) = oneshot::channel(); + tokio::spawn(async move { + let _ = tx.send(remote::prompt(&server, &id, &text).await.map(|_| String::new())); + }); + self.pending_note = Some(rx); + self.busy = true; + self.busy_since = Instant::now(); + self.scroll = 0; + } + + /// Items of messages (shared by the local and the remote view). + fn items_of(messages: &[codecraft_core::types::Message], open: &std::collections::HashSet) -> Vec { + let mut items = Vec::new(); + for m in messages { + for p in &m.parts { + match (&m.role, p) { + (Role::User, Part::Text { text }) => items.push(Item::User(text.clone(), 0)), + (Role::User, Part::Summary { .. }) => items.push(Item::Info("— conversation compacted —".into())), + (_, Part::Text { text }) => items.push(Item::Assistant(text.clone())), + (_, Part::Reasoning { text, .. }) if !text.trim().is_empty() => items.push(Item::Thinking(text.clone(), false)), + (_, Part::ToolCall { id, name, input, .. }) => items.push(Item::Tool { id: id.clone(), name: name.clone(), title: tool_title(name, input), state: ToolState::Running, output: String::new(), diff: None, open: open.contains(id) }), + (_, Part::ToolResult { call_id, content, is_error, meta, .. }) => { + if let Some(Item::Tool { state, output, diff, .. }) = items.iter_mut().rev().find(|i| matches!(i, Item::Tool { id, .. } if id == call_id)) { + *state = if *is_error { ToolState::Err } else { ToolState::Ok }; + *output = content.clone(); + *diff = meta.as_ref().and_then(|m| m["diff"].as_str().map(String::from)); + } + } + _ => {} + } + } + } + items + } + + /// Poll the followed server chat every ~1.5 s and take up the results of background requests. + fn poll_remote(&mut self) { + if let Some(rx) = &mut self.pending_pick { + if let Ok(res) = rx.try_recv() { + self.pending_pick = None; + self.status.clear(); + match res { + Ok((kind, title, items)) if items.is_empty() => { + let _ = kind; + self.items.push(Item::Info(format!("{title}: nothing to show"))); + } + Ok((kind, title, items)) => self.dialog = Dialog::Picker(Picker { kind, title, items, filter: String::new(), sel: 0 }), + Err(e) => self.items.push(Item::Error(format!("{e:#}"))), + } + } + } + if let Some(rx) = &mut self.pending_note { + if let Ok(res) = rx.try_recv() { + self.pending_note = None; + match res { + Ok(msg) if !msg.is_empty() => self.items.push(Item::Info(msg)), + Ok(_) => {} + Err(e) => self.items.push(Item::Error(format!("{e:#}"))), + } + } + } + if let Some(rx) = &mut self.pending_open { + if let Ok(res) = rx.try_recv() { + self.pending_open = None; + match res { + Ok(r) => { + self.items.clear(); + self.items.push(Item::Info(format!("server chat: {} · {} · {} · {} – /local returns", r.title, r.agent, r.model, r.cwd))); + self.todos = Value::Null; + self.busy = false; + self.dialog = Dialog::None; + self.remote = Some(r); + self.pending_snapshot = None; + } + Err(e) => self.items.push(Item::Error(format!("{e:#}"))), + } + } + } + let Some(server) = self.env.server.clone() else { return }; + let Some(r) = &mut self.remote else { return }; + if let Some(rx) = &mut self.pending_snapshot { + if let Ok(res) = rx.try_recv() { + self.pending_snapshot = None; + match res { + Ok(snap) => { + let open: std::collections::HashSet = self.items.iter().filter_map(|i| if let Item::Tool { id, open: true, .. } = i { Some(id.clone()) } else { None }).collect(); + let was_busy = self.busy; + let at_end = self.scroll == 0; + let mut items = Self::items_of(&snap.messages, &open); + // Tool calls without a result are still running only while the chat is busy. + if !snap.busy { + for i in items.iter_mut() { + if let Item::Tool { state, .. } = i { + if matches!(state, ToolState::Running) { + *state = ToolState::Err; + } + } + } + } + let head = self.items.first().filter(|i| matches!(i, Item::Info(s) if s.starts_with("server chat:"))).map(|i| if let Item::Info(s) = i { s.clone() } else { String::new() }); + self.items = head.map(Item::Info).into_iter().chain(items).collect(); + self.busy = snap.busy; + if snap.busy && !was_busy { + self.busy_since = Instant::now(); + } + self.todos = snap.todos.clone(); + if !snap.title.is_empty() { + r.title = snap.title.clone(); + } + if at_end { + self.scroll = 0; + } + // Requests that wait for an answer (permissions and questions of this chat). + if matches!(self.dialog, Dialog::None) { + if let Some(ev) = snap.pending.iter().find(|e| e["id"].as_str().is_some_and(|id| !r.answered.contains(id))) { + let id = ev["id"].as_str().unwrap_or("").to_string(); + r.answered.insert(id.clone()); + if ev["type"] == "permission_request" { + let (tx, rx) = oneshot::channel::(); + let srv = server.clone(); + tokio::spawn(async move { + if let Ok(reply) = rx.await { + let (kind, msg) = match reply { + Reply::Once => ("once", None), + Reply::Always => ("always", None), + Reply::Reject(m) => ("reject", m), + }; + let _ = remote::reply_permission(&srv, &id, kind, msg).await; + } + }); + self.dialog = Dialog::Permission { tool: ev["tool"].as_str().unwrap_or("").into(), title: ev["title"].as_str().unwrap_or("").into(), diff: ev["diff"].as_str().map(String::from), input: ev["input"].clone(), reply: Some(tx), feedback: None }; + } else if ev["type"] == "question_request" { + let questions: Vec = serde_json::from_value(ev["questions"].clone()).unwrap_or_default(); + if !questions.is_empty() { + let (tx, rx) = oneshot::channel::>>(); + let srv = server.clone(); + tokio::spawn(async move { + if let Ok(answers) = rx.await { + let _ = remote::answer_question(&srv, &id, answers).await; + } + }); + self.dialog = Dialog::Question { questions, idx: 0, sel: 0, custom: String::new(), answers: Default::default(), reply: Some(tx) }; + } + } + } + } + } + Err(e) => self.status = format!("server: {e:#}"), + } + } + } else if r.last_poll.elapsed() >= Duration::from_millis(1500) { + r.last_poll = Instant::now(); + let id = r.id.clone(); + let (tx, rx) = oneshot::channel(); + tokio::spawn(async move { + let _ = tx.send(remote::snapshot(&server, &id).await); + }); + self.pending_snapshot = Some(rx); + } + } + // --- setup wizard --------------------------------------------------------------- fn open_setup(&mut self) { @@ -771,9 +1070,7 @@ impl App { match (k.code, ctrl) { (KeyCode::Char('c'), true) => { if self.busy { - if let Some(c) = &self.cancel { - c.cancel(); - } + self.abort_current(); self.items.push(Item::Info(t("aborted").into())); } else if !self.editor.is_empty() { self.editor.clear(); @@ -787,9 +1084,7 @@ impl App { (KeyCode::Char('d'), true) if self.editor.is_empty() => self.quit = true, (KeyCode::Esc, _) => { if self.busy { - if let Some(c) = &self.cancel { - c.cancel(); - } + self.abort_current(); self.queue.clear(); self.items.push(Item::Info(t("aborted").into())); } @@ -1147,6 +1442,7 @@ impl App { } fn poll_pending(&mut self) { + self.poll_remote(); if let Some(rx) = &mut self.pending_detect { if let Ok(found) = rx.try_recv() { self.pending_detect = None; @@ -1398,7 +1694,10 @@ impl App { // Status line. let ctx_pct = self.env.catalog.find(&self.session.model).and_then(|m| m.config.context).filter(|c| *c > 0).map(|c| format!("{} {}%", t("context"), self.context * 100 / c)).unwrap_or_default(); let cost = if self.session.cost > 0.0 { format!(" · {:.3} {}", self.session.cost, self.env.catalog.currency) } else { String::new() }; - let left = format!(" {} · {} ", self.model_label(), self.session.permission_mode); + let left = match &self.remote { + Some(r) => format!(" server · {} · {} ", r.model, r.agent), + None => format!(" {} · {} ", self.model_label(), self.session.permission_mode), + }; let right = format!("{ctx_pct}{cost} · Shift+Tab {} · /help ", t("mode")); let pad = (area.width as usize).saturating_sub(left.chars().count() + right.chars().count()); f.render_widget(Paragraph::new(Line::from(vec![Span::styled(left, Style::default().fg(th.fg3)), Span::raw(" ".repeat(pad)), Span::styled(right, Style::default().fg(th.muted))])).style(Style::default().bg(th.bg1)), status); diff --git a/cli/src/main.rs b/cli/src/main.rs index e8f3ada..3d082ae 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -9,6 +9,7 @@ mod conf; mod editor; mod i18n; mod models; +mod remote; mod server; mod session; mod stats; diff --git a/cli/src/remote.rs b/cli/src/remote.rs new file mode 100644 index 0000000..70daab8 --- /dev/null +++ b/cli/src/remote.rs @@ -0,0 +1,278 @@ +//! Remote control of the server: chats that run on the CodeCraft server (`/projects`) and the +//! software factory board (`/factory`). Everything goes through the server's REST API with the +//! login's token; the chat view polls every second or two instead of holding a socket open. + +use crate::server::Server; +use anyhow::{Context, Result, bail}; +use codecraft_core::types::Message; +use serde_json::{Value, json}; +use std::collections::HashSet; +use std::time::Instant; + +/// How many messages of a remote chat are loaded (its end; older ones stay on the server). +const WINDOW: usize = 300; + +/// A chat of the server that this terminal follows. +pub struct Remote { + pub id: String, + pub title: String, + pub cwd: String, + pub agent: String, + pub model: String, + pub last_poll: Instant, + /// Requests already answered here (the server confirms them with the next poll). + pub answered: HashSet, +} + +/// State of a remote chat at one moment. +pub struct Snapshot { + pub messages: Vec, + pub busy: bool, + pub title: String, + pub todos: Value, + /// Open permission and question requests of this chat (and its subagents). + pub pending: Vec, +} + +fn short(s: &str, n: usize) -> String { + let t: String = s.chars().take(n).collect(); + if s.chars().count() > n { format!("{t}…") } else { t } +} + +pub fn ago(ms: i64) -> String { + let d = (chrono::Utc::now().timestamp_millis() - ms).max(0) / 1000; + match d { + 0..=89 => "now".into(), + 90..=5399 => format!("{} min ago", d / 60), + 5400..=129_599 => format!("{} h ago", d / 3600), + _ => format!("{} d ago", d / 86_400), + } +} + +/// The user's chats on the server as picker entries: (id, title, description). Busy chats first. +pub async fn sessions(server: &Server) -> Result> { + let v = server.get("/sessions").await?; + let mut list: Vec = v.as_array().cloned().unwrap_or_default().into_iter().filter(|s| s["parent_id"].is_null() && s["archived"] != true).collect(); + list.sort_by_key(|s| (!s["busy"].as_bool().unwrap_or(false), std::cmp::Reverse(s["updated_at"].as_i64().unwrap_or(0)))); + Ok(list + .into_iter() + .take(200) + .map(|s| { + let title = s["title"].as_str().filter(|t| !t.is_empty()).unwrap_or("(untitled)").to_string(); + let folder = s["folder"].as_str().filter(|f| !f.is_empty()).map(|f| format!("[{f}] ")).unwrap_or_default(); + let cwd = s["cwd"].as_str().unwrap_or("").rsplit('/').next().unwrap_or("").to_string(); + let state = if s["busy"].as_bool().unwrap_or(false) { "working · " } else { "" }; + (s["id"].as_str().unwrap_or("").to_string(), format!("{folder}{title}"), format!("{state}{cwd} · {} · {}", s["agent"].as_str().unwrap_or(""), ago(s["updated_at"].as_i64().unwrap_or(0)))) + }) + .collect()) +} + +/// Load a chat: its end, whether it is working, its task list and what waits for an answer. +pub async fn snapshot(server: &Server, id: &str) -> Result { + let path = format!("/sessions/{id}?limit={WINDOW}"); + let (s, pending) = tokio::join!(server.get(&path), server.get("/pending")); + let s = s?; + let messages: Vec = serde_json::from_value(s["messages"].clone()).unwrap_or_default(); + let pending = pending + .ok() + .and_then(|p| p.as_array().cloned()) + .unwrap_or_default() + .into_iter() + .filter(|e| e["session_id"].as_str() == Some(id) || e["root_session_id"].as_str() == Some(id)) + .collect(); + Ok(Snapshot { messages, busy: s["busy"].as_bool().unwrap_or(false), title: s["session"]["title"].as_str().unwrap_or("").to_string(), todos: s["session"]["todos"].clone(), pending }) +} + +pub async fn open(server: &Server, id: &str) -> Result { + let s = server.get(&format!("/sessions/{id}?limit=1")).await?; + let s = &s["session"]; + if s["id"].as_str().is_none() { + bail!("unknown chat"); + } + Ok(Remote { + id: id.to_string(), + title: s["title"].as_str().unwrap_or("").to_string(), + cwd: s["cwd"].as_str().unwrap_or("").to_string(), + agent: s["agent"].as_str().unwrap_or("").to_string(), + model: s["model"].as_str().unwrap_or("").to_string(), + last_poll: Instant::now(), + answered: HashSet::new(), + }) +} + +pub async fn prompt(server: &Server, id: &str, text: &str) -> Result<()> { + server.post(&format!("/sessions/{id}/prompt"), json!({"text": text})).await.map(|_| ()) +} + +pub async fn abort(server: &Server, id: &str) -> Result<()> { + server.post(&format!("/sessions/{id}/abort"), json!({})).await.map(|_| ()) +} + +pub async fn compact(server: &Server, id: &str) -> Result<()> { + server.post(&format!("/sessions/{id}/compact"), json!({})).await.map(|_| ()) +} + +/// Answer a permission request. reply: once, always, project, reject. +pub async fn reply_permission(server: &Server, id: &str, reply: &str, message: Option) -> Result<()> { + server.post(&format!("/permissions/{id}"), json!({"reply": reply, "message": message})).await.map(|_| ()) +} + +pub async fn answer_question(server: &Server, id: &str, answers: Option>) -> Result<()> { + server.post(&format!("/questions/{id}"), json!({"answers": answers})).await.map(|_| ()) +} + +// --- software factory ------------------------------------------------------------------------ + +/// Column of the board for an issue state. +pub fn column(state: &str) -> &'static str { + match state { + "new" | "review" => "Review", + "question" => "Question", + "approved" => "Approved", + "building" | "rework" => "Build", + "qa" | "testing" => "Acceptance", + "failed" | "rejected" => "Failed", + "done" => "Done", + "closed" => "Closed", + _ => "Other", + } +} + +pub fn repo_name(url: &str) -> String { + url.trim_end_matches(".git").rsplit('/').take(2).collect::>().into_iter().rev().collect::>().join("/") +} + +/// The board as picker entries (key "repo#number") and a summary line for the title. +pub async fn factory_board(server: &Server) -> Result<(String, Vec<(String, String, String)>)> { + let v = server.get("/factory/overview").await?; + let issues = v["issues"].as_array().cloned().unwrap_or_default(); + let runs = v["runs"].as_array().cloned().unwrap_or_default(); + let running = issues.iter().filter(|i| matches!(i["state"].as_str(), Some("review" | "building" | "testing"))).count(); + let done = issues.iter().filter(|i| i["state"] == "done").count(); + let cost: f64 = runs.iter().map(|r| r["cost"].as_f64().unwrap_or(0.0)).sum(); + let summary = format!("Factory · {} issues · {running} running · {done} done · {} runs · ${cost:.2}", issues.iter().filter(|i| i["state"] != "closed").count(), runs.len()); + let order = ["Question", "Failed", "Build", "Acceptance", "Review", "Approved", "Done"]; + let mut rows: Vec<(usize, String, String, String)> = issues + .iter() + .filter(|i| i["state"] != "closed") + .map(|i| { + let state = i["state"].as_str().unwrap_or(""); + let col = column(state); + let key = format!("{}#{}", i["repo"].as_str().unwrap_or(""), i["number"].as_i64().unwrap_or(0)); + let latest = runs.iter().find(|r| r["repo"] == i["repo"] && r["issue"] == i["number"]); + let run = latest.map(|r| format!(" · {} {}", r["phase"].as_str().unwrap_or(""), if r["ended_at"].is_null() { "running" } else { r["status"].as_str().unwrap_or("") })).unwrap_or_default(); + let ver = i["version"].as_str().filter(|v| !v.is_empty()).map(|v| format!(" v{v}")).unwrap_or_default(); + ( + order.iter().position(|c| *c == col).unwrap_or(order.len()), + key, + format!("{col:<10} {} #{} {}", repo_name(i["repo"].as_str().unwrap_or("")), i["number"].as_i64().unwrap_or(0), short(i["title"].as_str().unwrap_or(""), 60)), + format!("{}{run}{ver}", short(i["note"].as_str().unwrap_or("").replace('\n', " ").as_str(), 80)), + ) + }) + .collect(); + rows.sort_by_key(|r| r.0); + Ok((summary, rows.into_iter().map(|(_, k, l, d)| (k, l, d)).collect())) +} + +/// Split a board key "repo#number". +pub fn split_key(key: &str) -> Result<(String, i64)> { + let (repo, n) = key.rsplit_once('#').context("invalid issue")?; + Ok((repo.to_string(), n.parse()?)) +} + +/// What can be done with an issue in this state: (action key, label, description). +pub async fn factory_actions(server: &Server, key: &str) -> Result<(String, Vec<(String, String, String)>)> { + let (repo, n) = split_key(key)?; + let v = server.get("/factory/overview").await?; + let issue = v["issues"].as_array().and_then(|a| a.iter().find(|i| i["number"] == n && i["repo"] == repo)).cloned().context("the issue is gone")?; + let state = issue["state"].as_str().unwrap_or("").to_string(); + let busy = matches!(state.as_str(), "review" | "building" | "testing"); + let title = format!("{} #{n} – {} [{}]", repo_name(&repo), short(issue["title"].as_str().unwrap_or(""), 50), column(&state)); + let mut acts: Vec<(String, String, String)> = Vec::new(); + // The chats of its runs. + for r in v["runs"].as_array().into_iter().flatten().filter(|r| r["issue"] == n && (r["repo"] == repo)).take(6) { + acts.push((format!("chat:{}", r["session_id"].as_str().unwrap_or("")), format!("Open the {} chat", r["phase"].as_str().unwrap_or("")), format!("{} · {}", r["model"].as_str().unwrap_or(""), if r["ended_at"].is_null() { "running".to_string() } else { r["status"].as_str().unwrap_or("").to_string() }))); + } + if state == "done" { + if let Ok(p) = server.get(&format!("/factory/issues/pr?repo={}&number={n}", urlenc(&repo))).await { + if let Some(pr) = p["pr"].as_object() { + if pr.get("state").and_then(|s| s.as_str()) == Some("open") { + let num = pr.get("number").and_then(|x| x.as_i64()).unwrap_or(0); + for (m, d) in [("merge", "merge commit"), ("squash", "squash into one commit"), ("rebase", "rebase onto the base branch")] { + acts.push((format!("merge:{num}:{m}"), format!("Merge pull request #{num} ({m})"), d.to_string())); + } + } + } + } + acts.push(("close".into(), "Close the issue".into(), "comments and closes it on the forge".into())); + } + if !busy { + for (to, label) in [("new", "Restart at the review"), ("approved", "Restart at the build"), ("qa", "Restart at the acceptance")] { + acts.push((format!("restart:{to}"), label.into(), String::new())); + } + acts.push(("remove".into(), "Remove from the board".into(), "the issue on the forge stays as it is".into())); + } + Ok((title, acts)) +} + +fn urlenc(s: &str) -> String { + s.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect() +} + +/// Run an action chosen in `factory_actions` (everything except opening a chat). Returns a message. +pub async fn factory_do(server: &Server, key: &str, action: &str) -> Result { + let (repo, number) = split_key(key)?; + let (verb, arg) = action.split_once(':').unwrap_or((action, "")); + match verb { + "restart" => { + server.post("/factory/issues/restart", json!({"repo": repo, "number": number, "to": arg})).await?; + Ok(format!("#{number} restarted")) + } + "remove" => { + server.post("/factory/issues/remove", json!({"repo": repo, "number": number})).await?; + Ok(format!("#{number} removed from the board")) + } + "close" => { + server.post("/factory/issues/close", json!({"repo": repo, "number": number, "comment": "Closed from the terminal."})).await?; + Ok(format!("#{number} closed")) + } + "merge" => { + let (pr, method) = arg.split_once(':').context("invalid merge")?; + server.post("/factory/issues/pr/merge", json!({"repo": repo, "number": number, "pr": pr.parse::()?, "method": method})).await?; + Ok(format!("pull request #{pr} merged ({method})")) + } + _ => bail!("unknown action"), + } +} + +pub async fn factory_poll(server: &Server) -> Result { + let v = server.post("/factory/poll", json!({})).await?; + let errs = v["errors"].as_array().map(|a| a.len()).unwrap_or(0); + Ok(if errs == 0 { "checked for new issues".into() } else { format!("checked – {errs} repository error(s)") }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn board_columns_and_keys() { + assert_eq!(column("rework"), "Build"); + assert_eq!(column("testing"), "Acceptance"); + assert_eq!(column("rejected"), "Failed"); + assert_eq!(repo_name("https://git.example.org/acme/demo-shop.git"), "acme/demo-shop"); + let (repo, n) = split_key("https://git.example.org/acme/demo-shop.git#12").unwrap(); + assert_eq!((repo.as_str(), n), ("https://git.example.org/acme/demo-shop.git", 12)); + assert!(split_key("nonsense").is_err()); + assert_eq!(urlenc("https://a/b c"), "https%3A%2F%2Fa%2Fb%20c"); + } + + #[test] + fn relative_times() { + let now = chrono::Utc::now().timestamp_millis(); + assert_eq!(ago(now), "now"); + assert_eq!(ago(now - 10 * 60_000), "10 min ago"); + assert_eq!(ago(now - 5 * 3_600_000), "5 h ago"); + assert_eq!(ago(now - 3 * 86_400_000), "3 d ago"); + } +} diff --git a/web/src/whatsnew.ts b/web/src/whatsnew.ts index 05b207e..2fcda31 100644 --- a/web/src/whatsnew.ts +++ b/web/src/whatsnew.ts @@ -3,6 +3,10 @@ * under "unreleased"; scripts/release.sh renames the key to the release version. */ export const WHATS_NEW: Record = { + unreleased: { + en: ["Terminal client: /projects steers chats on the server, /factory manages the factory board"], + de: ["Terminal-Client: /projects steuert Chats auf dem Server, /factory verwaltet das Factory-Board"], + }, "202611-00065": { en: ["Terminal client now also for Linux riscv64"], de: ["Terminal-Client jetzt auch für Linux riscv64"],