Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Mission Control B1: Idempotency-Key on resolving a flag, so a double Redo makes one fork
Lin (kwant bot)149377c3ddd8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex edcd642f..020de5ce 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,7 +20,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).that directly depend on it as "may be invalid". Their state never changes, and only you decide:still valid, redo, or cancel. Redo forks the task, so verified history stays untouched. Newendpoints serve the mission's graph (`/api/missions/:id/graph`), flags, forks and an on-demand drift- scan. Fork and retry accept an `Idempotency-Key`. The board UI follows separately.+ scan. Fork, retry and resolving a flag accept an `Idempotency-Key`, so a double Redo makes one+ copy. The board UI follows separately.- **Mission Control (preview, off by default).** One task board for everything bots work on: plannedmissions, team hand-offs, routine runs, Loose Ends you take on and work-ahead posts. A task counts as**verified** only when an outcome check passes (a command, a URL, a file, a teammate's review withdiff --git a/docs/mission-control.md b/docs/mission-control.mdindex 6f803419..87ae5ebf 100644--- a/docs/mission-control.md+++ b/docs/mission-control.md@@ -380,7 +380,7 @@ What else happens:### Idempotency-Key-The header works on `POST /api/tasks/:id/fork` and `POST /api/tasks/:id/retry`. Keys are 1–200 characters.+The header works on `POST /api/tasks/:id/fork`, `POST /api/tasks/:id/retry` and `POST /api/tasks/:id/flags/:flag_id/resolve` (so two Redo clicks from two tabs make one fork; the route includes the flag id). Keys are 1–200 characters.- The same key on the same route (method plus path, task id included) returns the stored response with `idempotent-replayed: true`, and nothing runs again.- The same key on another route gets 422.- Only successful responses are stored. Keyed requests run one at a time.diff --git a/src/server/missions/graph.rs b/src/server/missions/graph.rsindex 567a6529..a85656bc 100644--- a/src/server/missions/graph.rs+++ b/src/server/missions/graph.rs@@ -333,10 +333,12 @@ pub struct ResolveBody {note: Option<String>,}-/// `POST /api/tasks/:id/flags/:flag_id/resolve` (person-only).+/// `POST /api/tasks/:id/flags/:flag_id/resolve` (person-only; `Idempotency-Key` optional, so+/// two Redo clicks from two tabs make one fork).pub async fn resolve_flag(State(state): State<AppState>,RawQuery(q): RawQuery,+ headers: HeaderMap,Path((id, flag_id)): Path<(String, String)>,Json(p): Json<ResolveBody>,) -> Response {@@ -344,76 +346,67 @@ pub async fn resolve_flag(return bad("resolution must be still_valid, redo or cancelled");}let note = p.note.as_deref().map(str::trim).filter(|n| !n.is_empty()).map(|n| n.chars().take(500).collect::<String>());- let t = match load_task(&state, q.as_deref(), &id).await {- Ok(t) => t,- Err(r) => return r,- };- let flag = match state.db.get_flag(&flag_id).await {- Ok(Some(f)) if f.task_id == t.id => f,- Ok(_) => return not_found("flag"),- Err(e) => return internal(e),- };- if flag.resolved_at.is_some() {- return conflict("this flag is already resolved");- }- let mut fork_out = None;- let mut extra = json!({});- match (p.resolution.as_str(), t.state.as_str()) {- ("still_valid", _) => {}- ("redo", "working" | "needs_you") => return conflict("it's running; resolve when it stops"),- ("redo", "cancelled") => return conflict("the task is cancelled; fork it to redo it"),- ("redo", "verified") => {- let reason = note.clone().unwrap_or_else(|| "redo: it may no longer hold".into());- match fork(&state, &t, &reason).await {- Ok(f) => {- extra = json!({"fork_id": f.id});- fork_out = Some(f);- }- Err(r) => return r,- }+ let route = format!("POST /api/tasks/{id}/flags/{flag_id}/resolve");+ idempotent(&state, &headers, route, || async {+ let t = load_task(&state, q.as_deref(), &id).await?;+ let flag = match state.db.get_flag(&flag_id).await {+ Ok(Some(f)) if f.task_id == t.id => f,+ Ok(_) => return Err(not_found("flag")),+ Err(e) => return Err(internal(e)),+ };+ if flag.resolved_at.is_some() {+ return Err(conflict("this flag is already resolved"));}- ("redo", from @ ("review" | "failed")) => {- let change = TaskChange { reason: Some("redo: it may no longer hold".into()), detail: Some(json!({"flag_id": flag.id})), ..Default::default() };- if let Err(r) = moved(transition(&state, &t.id, from, "ready", Actor::Person, "person", change).await) {- return r;+ let mut fork_out = None;+ let mut extra = json!({});+ match (p.resolution.as_str(), t.state.as_str()) {+ ("still_valid", _) => {}+ ("redo", "working" | "needs_you") => return Err(conflict("it's running; resolve when it stops")),+ ("redo", "cancelled") => return Err(conflict("the task is cancelled; fork it to redo it")),+ ("redo", "verified") => {+ let reason = note.clone().unwrap_or_else(|| "redo: it may no longer hold".into());+ let f = fork(&state, &t, &reason).await?;+ extra = json!({"fork_id": f.id});+ fork_out = Some(f);}- let _ = state.db.reset_attempts(&t.id).await;- }- ("redo", "blocked") => {- let change = TaskChange { reason: Some("redo: it may no longer hold".into()), detail: Some(json!({"flag_id": flag.id})), ..Default::default() };- match moved(transition(&state, &t.id, "blocked", "backlog", Actor::Person, "person", change).await) {- Ok(t) => super::promote_one(&state, &t).await,- Err(r) => return r,+ ("redo", from @ ("review" | "failed")) => {+ let change = TaskChange { reason: Some("redo: it may no longer hold".into()), detail: Some(json!({"flag_id": flag.id})), ..Default::default() };+ moved(transition(&state, &t.id, from, "ready", Actor::Person, "person", change).await)?;+ let _ = state.db.reset_attempts(&t.id).await;}- }- // backlog or ready: it runs again anyway- ("redo", _) => {}- ("cancelled", "verified") => return conflict("a verified task can't be cancelled; choose still_valid or redo"),- ("cancelled", "cancelled") => {}- ("cancelled", from) => {- let change = TaskChange { reason: Some("cancelled by the person: it may no longer hold".into()), ..Default::default() };- if let Err(r) = moved(transition(&state, &t.id, from, "cancelled", Actor::Person, "person", change).await) {- return r;+ ("redo", "blocked") => {+ let change = TaskChange { reason: Some("redo: it may no longer hold".into()), detail: Some(json!({"flag_id": flag.id})), ..Default::default() };+ let t = moved(transition(&state, &t.id, "blocked", "backlog", Actor::Person, "person", change).await)?;+ super::promote_one(&state, &t).await;+ }+ // backlog or ready: it runs again anyway+ ("redo", _) => {}+ ("cancelled", "verified") => return Err(conflict("a verified task can't be cancelled; choose still_valid or redo")),+ ("cancelled", "cancelled") => {}+ ("cancelled", from) => {+ let change = TaskChange { reason: Some("cancelled by the person: it may no longer hold".into()), ..Default::default() };+ moved(transition(&state, &t.id, from, "cancelled", Actor::Person, "person", change).await)?;}+ _ => return Err(bad("resolution must be still_valid, redo or cancelled")),}- _ => return bad("resolution must be still_valid, redo or cancelled"),- }- match state.db.resolve_flag(&flag.id, &p.resolution, note.as_deref(), Some(&extra)).await {- Ok(true) => {}- Ok(false) => return conflict("this flag is already resolved"),- Err(e) => return internal(e),- }- let t = state.db.get_task(&t.id).await.ok().flatten().unwrap_or(t);- emit_task(&state, &t).await;- if let Some(mid) = &t.mission_id {- emit_mission(&state, mid).await;- }- let flag = state.db.get_flag(&flag.id).await.ok().flatten().unwrap_or(flag);- let fork_json = match &fork_out {- Some(f) => task_json(&state, f).await,- None => Value::Null,- };- Json(json!({"flag": flag_json(&flag), "task": task_json(&state, &t).await, "fork": fork_json})).into_response()+ match state.db.resolve_flag(&flag.id, &p.resolution, note.as_deref(), Some(&extra)).await {+ Ok(true) => {}+ Ok(false) => return Err(conflict("this flag is already resolved")),+ Err(e) => return Err(internal(e)),+ }+ let t = state.db.get_task(&t.id).await.ok().flatten().unwrap_or(t);+ emit_task(&state, &t).await;+ if let Some(mid) = &t.mission_id {+ emit_mission(&state, mid).await;+ }+ let flag = state.db.get_flag(&flag.id).await.ok().flatten().unwrap_or(flag);+ let fork_json = match &fork_out {+ Some(f) => task_json(&state, f).await,+ None => Value::Null,+ };+ Ok(json!({"flag": flag_json(&flag), "task": task_json(&state, &t).await, "fork": fork_json}))+ })+ .await}/// `GET /api/tasks/:id/flags` (open ones; `?all=1` adds resolved ones).diff --git a/tests/mission_graph_test.rs b/tests/mission_graph_test.rsindex d64415ef..439ce175 100644--- a/tests/mission_graph_test.rs+++ b/tests/mission_graph_test.rs@@ -481,6 +481,55 @@ async fn an_idempotency_key_forks_once_and_belongs_to_one_route() {assert_eq!(e.state.db.forks_of(&ids[0]).await.unwrap().len(), 2, "a new key is a new fork");}+#[tokio::test]+async fn an_idempotency_key_resolves_a_redo_once_and_belongs_to_one_flag() {+ let e = setup().await;+ let (mid, ids) = graph_mission(&e, &[("a", &[]), ("b", &["a"])]).await;+ do_task(&e, &mid, &ids[0], "a").await;+ do_task(&e, &mid, &ids[1], "b").await;+ drift(&e, &mid, "a").await;+ scan(&e, &mid).await;+ let fa = id(&flags(&task(&e, &ids[0]).await)[0]);+ let fb = id(&flags(&task(&e, &ids[1]).await)[0]);+ let resolve = |t: &str, f: &str| format!("/api/tasks/{t}/flags/{f}/resolve");+ let send = |uri: String, key: Option<&'static str>| {+ let app = e.app.clone();+ async move {+ let mut req = Request::builder().method("POST").uri(uri).header("content-type", "application/json");+ if let Some(k) = key {+ req = req.header("idempotency-key", k);+ }+ let resp = app.oneshot(req.body(Body::from(json!({"resolution": "redo"}).to_string())).unwrap()).await.unwrap();+ let status = resp.status();+ let replayed = resp.headers().get("idempotent-replayed").is_some();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (status, replayed, serde_json::from_slice::<Value>(&bytes).unwrap_or(Value::Null))+ }+ };++ // Two Redo clicks (two tabs) with one key: one fork, the second reply is the first one replayed+ let (s1, r1, first) = send(resolve(&ids[0], &fa), Some("redo-a-1")).await;+ let (s2, r2, second) = send(resolve(&ids[0], &fa), Some("redo-a-1")).await;+ assert!(s1.is_success() && s2.is_success(), "{first} {second}");+ assert!(!r1 && r2, "only the second reply is replayed");+ assert!(first["fork"]["id"].is_string(), "{first}");+ assert_eq!(first["fork"]["id"], second["fork"]["id"]);+ assert_eq!(e.state.db.forks_of(&ids[0]).await.unwrap().len(), 1, "one fork for one key");++ // The same key on another flag is refused and changes nothing+ let (s3, _, v) = send(resolve(&ids[1], &fb), Some("redo-a-1")).await;+ assert_eq!(s3, StatusCode::UNPROCESSABLE_ENTITY, "{v}");+ assert!(flags(&task(&e, &ids[1]).await).iter().any(|f| id(f) == fb), "B's flag is still open");+ assert!(e.state.db.forks_of(&ids[1]).await.unwrap().is_empty());++ // Without a key nothing changes: the first resolve forks, a second one is 409+ let (s4, r4, v) = send(resolve(&ids[1], &fb), None).await;+ assert!(s4.is_success() && !r4, "{v}");+ let (s5, _, v) = send(resolve(&ids[1], &fb), None).await;+ assert_eq!(s5, StatusCode::CONFLICT, "{v}");+ assert_eq!(e.state.db.forks_of(&ids[1]).await.unwrap().len(), 1);+}+// 10#[tokio::test]async fn a_scan_reads_nothing_outside_the_task_folder() {