Drafts in every chat, factory chat overlay, factory main switch

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Richard ZinkandClaude Sonnet 5.5 committed 2026-11-20 12:14:04 +01:00
1 parent 58475ce65e
commit 171b87b766
48 files changed
+754 -10

No files matched your search

+51
View File
@@ -96,6 +96,7 @@ pub fn router(app: AppState) -> Router {
.route("/sessions/{id}/compact", post(compact))
.route("/sessions/{id}/rewind", post(rewind))
.route("/sessions/{id}/job-draft", post(job_draft))
.route("/sessions/{id}/composer-draft", get(get_composer_draft).put(put_composer_draft))
.route("/projects/overview", get(project_overview))
.route("/sessions/{id}/project-defaults", get(get_project_defaults).put(put_project_defaults).delete(delete_project_defaults))
.route("/sessions/{id}/check", get(get_check).put(put_check))
@@ -169,6 +170,7 @@ pub fn router(app: AppState) -> Router {
.route("/account/factory/test", post(test_factory))
.route("/factory/overview", get(factory_overview))
.route("/factory/backlog", get(factory_backlog))
.route("/factory/power", post(factory_power))
.route("/factory/backlog/enqueue", post(factory_enqueue))
.route("/factory/poll", post(factory_poll))
.route("/factory/issues/restart", post(factory_restart))
@@ -1660,6 +1662,27 @@ async fn reply_permission(Extension(user): Extension<User>, State(app): State<Ap
}
/// Instructions for an automation drafted from this chat (small model); the client creates the job.
/// The unsent message of this chat (typed on any device).
async fn get_composer_draft(Extension(user): Extension<User>, State(app): State<AppState>, Path(id): Path<String>) -> ApiResult {
writable(&app, &user, &id)?;
let d = app.store.chat_draft(&id, &user.id)?;
Ok(Json(json!({"text": d.as_ref().map(|x| x.0.as_str()).unwrap_or(""), "updated_at": d.map(|x| x.1).unwrap_or(0)})))
}
#[derive(Deserialize)]
struct ComposerDraft {
text: String,
}
async fn put_composer_draft(Extension(user): Extension<User>, State(app): State<AppState>, Path(id): Path<String>, Json(b): Json<ComposerDraft>) -> ApiResult {
writable(&app, &user, &id)?;
if b.text.len() > 200_000 {
return Err(ApiError(StatusCode::PAYLOAD_TOO_LARGE, "the draft is too long".into()));
}
let at = app.store.chat_draft_set(&id, &user.id, &b.text)?;
Ok(Json(json!({"updated_at": at})))
}
async fn job_draft(Extension(user): Extension<User>, State(app): State<AppState>, Path(id): Path<String>) -> ApiResult {
let s = writable(&app, &user, &id)?;
let (name, prompt) = runner::draft_job(&app, &s).await.map_err(|e| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}")))?;
@@ -2751,11 +2774,39 @@ async fn factory_overview(Extension(user): Extension<User>, State(app): State<Ap
"area": app.factory_dir().is_some(),
"repos": repos,
"issues": app.store.factory_issues(&user.id)?,
"power": factory_power_json(&app, &user),
"runs": app.store.factory_runs(&user.id, None, None, 300)?,
"releases": app.store.factory_releases(&user.id, 10)?,
})))
}
fn factory_power_json(app: &App, user: &User) -> Value {
let on = app.store.user_setting::<crate::factory::Power>(&user.id, "factory_power").unwrap_or_default().on;
let active = app.store.factory_active(&user.id).unwrap_or(0);
json!({"on": on, "active": active, "state": crate::factory::power_state(on, active)})
}
#[derive(Deserialize)]
struct PowerBody {
on: bool,
}
/// The master switch: stop = no new agent starts (running ones finish), start = take up work again right away.
async fn factory_power(Extension(user): Extension<User>, State(app): State<AppState>, headers: axum::http::HeaderMap, Json(b): Json<PowerBody>) -> ApiResult {
app.store.set_user_setting(&user.id, "factory_power", &crate::factory::Power { on: b.on })?;
app.audit(Some(&user), if b.on { "factory.start" } else { "factory.stop" }, "", &crate::auth::client_ip(&headers));
if b.on {
let (app2, user2) = (app.clone(), user.clone());
tokio::spawn(async move {
let s: crate::factory::FactorySettings = app2.store.user_setting(&user2.id, "factory").unwrap_or_default();
for cfg in s.repos.iter().filter(|r| r.enabled).map(|r| s.resolve(r)).filter(|r| !r.token.is_empty()) {
let _ = crate::factory::poll_repo(&app2, &user2, &cfg).await;
}
});
}
Ok(Json(factory_power_json(&app, &user)))
}
/// Open issues per repository as the forge lists them; cached for a minute so that the board can ask often.
static BACKLOG_CACHE: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, (std::time::Instant, Vec<Value>)>>> = std::sync::OnceLock::new();
+35 -3
View File
@@ -17,6 +17,28 @@ pub const FACTORY_FOLDER: &str = "Factory";
pub const PHASES: [&str; 3] = ["review", "build", "qa"];
/// The master switch of a user's factory. Switched off, no new agent starts (a soft stop: agents that
/// are running finish their phase); the poller still keeps the board up to date.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Power {
pub on: bool,
}
impl Default for Power {
fn default() -> Self {
Self { on: true }
}
}
/// "running" (on), "stopping" (off, agents still working) or "stopped" (off, nobody working).
pub fn power_state(on: bool, active: i64) -> &'static str {
match (on, active) {
(true, _) => "running",
(false, 0) => "stopped",
(false, _) => "stopping",
}
}
/// Status labels of an issue, in the order of the workflow.
pub const STATUS_LABELS: [(&str, &str); 9] = [
("factory", "0e8a16"),
@@ -1478,6 +1500,7 @@ pub async fn poll_repo(app: &Arc<App>, user: &User, cfg: &RepoCfg) -> Result<()>
allowed.push(g.login().await?);
}
let issues = g.issues(&cfg.label).await?;
let power_on = app.store.user_setting::<Power>(&user.id, "factory_power").unwrap_or_default().on;
for issue in issues {
let n = issue_no(&issue);
let author = issue["user"]["login"].as_str().unwrap_or("");
@@ -1498,7 +1521,7 @@ pub async fn poll_repo(app: &Arc<App>, user: &User, cfg: &RepoCfg) -> Result<()>
}
"approved" | "rework" => {
let feedback = if state == "rework" { row["note"].as_str().unwrap_or("").to_string() } else { String::new() };
if app.store.factory_running(&cfg.url)? < cfg.max_parallel as i64 {
if power_on && app.store.factory_running(&cfg.url)? < cfg.max_parallel as i64 {
let comments = g.comments(n as u64).await.unwrap_or_default();
app.store.factory_issue_set(&cfg.url, n, &[("title", json!(title)), ("state", json!("building"))])?;
tokio::spawn(build(app.clone(), user.clone(), cfg.clone(), issue, comments, feedback));
@@ -1506,7 +1529,7 @@ pub async fn poll_repo(app: &Arc<App>, user: &User, cfg: &RepoCfg) -> Result<()>
continue;
}
"qa" => {
if app.store.factory_running(&cfg.url)? < cfg.max_parallel as i64 {
if power_on && app.store.factory_running(&cfg.url)? < cfg.max_parallel as i64 {
app.store.factory_issue_set(&cfg.url, n, &[("title", json!(title))])?;
// Mark the run before it starts so the next poll does not take it up again.
app.store.factory_issue_set(&cfg.url, n, &[("state", json!("testing"))])?;
@@ -1516,7 +1539,7 @@ pub async fn poll_repo(app: &Arc<App>, user: &User, cfg: &RepoCfg) -> Result<()>
}
_ => false,
};
if !start || app.store.factory_running(&cfg.url)? >= cfg.max_parallel as i64 {
if !start || !power_on || app.store.factory_running(&cfg.url)? >= cfg.max_parallel as i64 {
continue;
}
if comments.is_empty() {
@@ -1907,6 +1930,15 @@ pub async fn create_project(app: &Arc<App>, user: &User, settings: &mut FactoryS
mod tests {
use super::*;
#[test]
fn power_states() {
assert_eq!(power_state(true, 0), "running");
assert_eq!(power_state(true, 3), "running");
assert_eq!(power_state(false, 2), "stopping");
assert_eq!(power_state(false, 0), "stopped");
assert!(Power::default().on);
}
#[test]
fn backlog_skips_tracked_and_queued_issues() {
let cfg = repo("https://git.example.org/o/r.git");
+67 -1
View File
@@ -125,6 +125,13 @@ impl Store {
last_status TEXT,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS chat_drafts (
session_id TEXT NOT NULL,
user_id TEXT NOT NULL,
text TEXT NOT NULL,
updated_at INTEGER NOT NULL,
PRIMARY KEY (session_id, user_id)
);
CREATE TABLE IF NOT EXISTS user_settings (
user_id TEXT NOT NULL,
key TEXT NOT NULL,
@@ -1569,13 +1576,42 @@ impl Store {
Ok(rows.filter_map(|r| r.ok()).collect())
}
/// The unsent message of a chat, kept on the server so that it can be continued on another device.
pub fn chat_draft(&self, session: &str, user: &str) -> Result<Option<(String, i64)>> {
Ok(self.conn.lock().unwrap().query_row("SELECT text, updated_at FROM chat_drafts WHERE session_id = ?1 AND user_id = ?2", params![session, user], |r| Ok((r.get(0)?, r.get(1)?))).optional()?)
}
/// Store the unsent message (an empty text deletes it).
pub fn chat_draft_set(&self, session: &str, user: &str, text: &str) -> Result<i64> {
let conn = self.conn.lock().unwrap();
let now = crate::types::now_ms();
if text.trim().is_empty() {
conn.execute("DELETE FROM chat_drafts WHERE session_id = ?1 AND user_id = ?2", params![session, user])?;
} else {
conn.execute("INSERT INTO chat_drafts (session_id, user_id, text, updated_at) VALUES (?1,?2,?3,?4) ON CONFLICT(session_id, user_id) DO UPDATE SET text = ?3, updated_at = ?4", params![session, user, text, now])?;
}
Ok(now)
}
pub fn factory_issues(&self, owner: &str) -> Result<Vec<Value>> {
let nums: Vec<(String, i64)> = {
let conn = self.conn.lock().unwrap();
let mut st = conn.prepare("SELECT repo_url, number FROM factory_issues WHERE owner_id = ?1 ORDER BY updated_at DESC")?;
st.query_map([owner], |r| Ok((r.get(0)?, r.get(1)?)))?.filter_map(|r| r.ok()).collect()
};
Ok(nums.into_iter().filter_map(|(r, n)| self.factory_issue(&r, n).ok().flatten()).collect())
let mut rows: Vec<Value> = nums.into_iter().filter_map(|(r, n)| self.factory_issue(&r, n).ok().flatten()).collect();
// The newest phase chat that still exists, for the "open chat" button of the card.
let conn = self.conn.lock().unwrap();
if let Ok(mut chat) = conn.prepare("SELECT r.session_id, r.phase FROM factory_runs r WHERE r.repo_url = ?1 AND r.issue = ?2 AND EXISTS (SELECT 1 FROM sessions s WHERE s.id = r.session_id) ORDER BY r.started_at DESC LIMIT 1") {
for row in rows.iter_mut() {
let (repo, n) = (row["repo"].as_str().unwrap_or("").to_string(), row["number"].as_i64().unwrap_or(0));
if let Ok((sid, phase)) = chat.query_row(params![repo, n], |x| Ok((x.get::<_, String>(0)?, x.get::<_, String>(1)?))) {
row["chat_session"] = json!(sid);
row["chat_phase"] = json!(phase);
}
}
}
Ok(rows)
}
pub fn factory_run_add(&self, id: &str, owner: &str, repo: &str, issue: i64, phase: &str, round: i64, session: &str, model: &str) -> Result<()> {
@@ -1597,6 +1633,11 @@ impl Store {
Ok(self.conn.lock().unwrap().query_row("SELECT COUNT(*) FROM factory_issues WHERE repo_url = ?1 AND state IN ('review', 'building', 'testing')", [repo], |r| r.get(0))?)
}
/// Phases of this user that are running right now (any repository).
pub fn factory_active(&self, owner: &str) -> Result<i64> {
Ok(self.conn.lock().unwrap().query_row("SELECT COUNT(*) FROM factory_issues WHERE owner_id = ?1 AND state IN ('review', 'building', 'testing')", [owner], |r| r.get(0))?)
}
/// Runs with token and cost totals (joined from the usage table).
pub fn factory_runs(&self, owner: &str, repo: Option<&str>, issue: Option<i64>, limit: i64) -> Result<Vec<Value>> {
let conn = self.conn.lock().unwrap();
@@ -2022,3 +2063,28 @@ mod link_tests {
std::fs::remove_dir_all(&dir).unwrap();
}
}
#[cfg(test)]
mod draft_tests {
use super::*;
#[test]
fn drafts_are_kept_per_chat_and_user_and_cleared_when_empty() {
let dir = std::env::temp_dir().join(format!("cc-drafts-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let store = Store::open(&dir.join("t.db")).unwrap();
assert!(store.chat_draft("s1", "u1").unwrap().is_none());
store.chat_draft_set("s1", "u1", "half a message").unwrap();
store.chat_draft_set("s1", "u2", "someone else").unwrap();
store.chat_draft_set("s2", "u1", "other chat").unwrap();
assert_eq!(store.chat_draft("s1", "u1").unwrap().unwrap().0, "half a message");
store.chat_draft_set("s1", "u1", "continued on another device").unwrap();
assert_eq!(store.chat_draft("s1", "u1").unwrap().unwrap().0, "continued on another device");
assert_eq!(store.chat_draft("s1", "u2").unwrap().unwrap().0, "someone else");
// Sending clears it.
store.chat_draft_set("s1", "u1", " \n").unwrap();
assert!(store.chat_draft("s1", "u1").unwrap().is_none());
assert_eq!(store.chat_draft("s2", "u1").unwrap().unwrap().0, "other chat");
let _ = std::fs::remove_dir_all(&dir);
}
}