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
Fix "Answer in chat" target and cards left waiting by a restart
Lin (kwant bot)5d561adbd611
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex db7dc92e..9082a029 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -39,6 +39,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).unblock to review its result") could be dropped with "database is locked" while other work wassaving at the same moment. A hand-off that fails before the board sees it start now gets its cardtoo, failed so it offers Retry.+- **"Answer in chat" on a task opens the right chat.** It used to open the chat the task came from+ (usually the lead's), not the chat where the task's owner asked; on a hand-off task it was missing.+ Now it opens the owner's hand-off thread or chat where the card is.+- **Cards survive a restart.** An approval card still waiting when kwant restarted used to give an+ error when you answered it. Now Allow resumes the work in the chat that asked, and a card more than+ a day old says it expired so you can ask the bot again. Payments still ask every time.## [Mac 0.2.0] - 2026-10-28diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex f84c24a5..bd91654d 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -2859,8 +2859,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({spaceId={space.id}names={missionNames}onBack={isPhone ? () => { setShowMissions(false); setPhoneView('list'); } : undefined}- onOpenChat={(t) => {- const c = sourceChat(t);+ onOpenChat={(t, place) => {+ const c = place ?? sourceChat(t);if (!c) return;if (c.kwantId && c.threadId) return openThread(c.kwantId, c.threadId);if (!openTarget({ channel_id: c.channelId, kwant_id: c.kwantId })) pushToast('That chat no longer exists.');diff --git a/frontend/src/components/MissionBoardView.tsx b/frontend/src/components/MissionBoardView.tsxindex f40e0b93..6cee024c 100644--- a/frontend/src/components/MissionBoardView.tsx+++ b/frontend/src/components/MissionBoardView.tsx@@ -107,6 +107,8 @@ import {priorityLabel,safeHttps,sourceChat,+ answerChat,+ type ChatPlace,sourceLabel,stateLabel,untilText,@@ -1389,7 +1391,7 @@ export const TaskDetailBody: React.FC<{notice?: { text: string; error: boolean } | null;onAction: (a: TaskAction, reason?: string) => void;onApproveCheck: (c: Check) => void;- onOpenChat?: (t: Task) => void;+ onOpenChat?: (t: Task, place?: ChatPlace | null) => void;onOpenTask?: (id: string) => void;onResolveFlag?: (f: OpenFlag, choice: ResolveChoice) => void;/** Copy a verified task to redo it, with the reason typed. */@@ -1728,8 +1730,8 @@ export const TaskDetailBody: React.FC<{</button>) : null;})()- ) : chat && onOpenChat && (- <button type="button" onClick={() => onOpenChat(t)} className="px-2 py-1 rounded border border-amber-500/40 hover:bg-amber-500/10 min-h-[32px]">+ ) : onOpenChat && answerChat(t, n) && (+ <button type="button" onClick={() => onOpenChat(t, answerChat(t, n))} className="px-2 py-1 rounded border border-amber-500/40 hover:bg-amber-500/10 min-h-[32px]" data-answer-in-chat>Answer in chat</button>)}@@ -2187,7 +2189,7 @@ export const MissionBoardPage: React.FC<{spaceId: string;names: Record<string, string>;onBack?: () => void;- onOpenChat?: (t: Task) => void;+ onOpenChat?: (t: Task, place?: ChatPlace | null) => void;}> = ({ spaceId, names, onBack, onOpenChat }) => {const [tasks, setTasks] = useState<Task[] | null>(null);const [missions, setMissions] = useState<Mission[]>([]);@@ -2708,9 +2710,9 @@ export const MissionBoardPage: React.FC<{onRestoreError={restoreError}onOpenChat={onOpenChat- ? (t) => {+ ? (t, place) => {closeTask();- onOpenChat(t);+ onOpenChat(t, place);}: undefined}diff --git a/frontend/src/missions.ts b/frontend/src/missions.tsindex c41c44e4..8ad1eaf5 100644--- a/frontend/src/missions.ts+++ b/frontend/src/missions.ts@@ -54,6 +54,9 @@ export interface NeedsYouItem {kind: 'question' | 'approval' | 'human_step' | 'check_approval' | 'may_be_invalid' | 'autofix_suggested' | 'fix_needed' | 'workflow_change' | 'engine_cant_sandbox';id: string;text: string;+ /** question, approval, human_step: the chat the card is in (the owner's hand-off thread, a+ * channel or a direct chat), which may not be the chat the task came from. */+ chat?: { channel_id: string | null; kwant_id: string | null; thread_id: string | null };}export interface Claim {@@ -1583,6 +1586,15 @@ export const capabilitiesApi = {};/** Where a task came from in the app: a channel, a bot's thread, or a bot's direct chat. */+/** Where to answer a Needs-you card: the chat the card is in, else the chat the task came from. */+export function answerChat(t: Pick<Task, 'channel_id' | 'direct_kwant_id' | 'thread_id'>, n: Pick<NeedsYouItem, 'chat'>): ChatPlace | null {+ const c = n.chat;+ if (c && (c.channel_id || c.kwant_id)) return { channelId: c.channel_id, kwantId: c.channel_id ? null : c.kwant_id, threadId: c.thread_id };+ return sourceChat(t);+}++export type ChatPlace = { channelId: string | null; kwantId: string | null; threadId: string | null };+export function sourceChat(t: Pick<Task, 'channel_id' | 'direct_kwant_id' | 'thread_id'>): { channelId: string | null; kwantId: string | null; threadId: string | null } | null {if (t.channel_id) return { channelId: t.channel_id, kwantId: null, threadId: t.thread_id };if (t.direct_kwant_id) return { channelId: null, kwantId: t.direct_kwant_id, threadId: t.thread_id };diff --git a/frontend/tests/missions.test.mjs b/frontend/tests/missions.test.mjsindex fa350229..f3ecb85f 100644--- a/frontend/tests/missions.test.mjs+++ b/frontend/tests/missions.test.mjs@@ -398,6 +398,18 @@ test('sourceChat points at the channel, thread or direct chat', () => {assert.equal(m.sourceChat(task({ channel_id: null })), null);});+test("answerChat opens the chat the card is in, not the chat the task came from", () => {+ const handOff = { kind: 'question', id: 'q1', text: 'Which colour?', chat: { channel_id: null, kwant_id: 'k_lin', thread_id: 'th9' } };+ assert.deepEqual(m.answerChat(task(), handOff), { channelId: null, kwantId: 'k_lin', threadId: 'th9' });+ const inChannel = { kind: 'approval', id: 'a1', text: 'Bash', chat: { channel_id: 'c2', kwant_id: null, thread_id: null } };+ assert.deepEqual(m.answerChat(task(), inChannel), { channelId: 'c2', kwantId: null, threadId: null });+ // A delegation task has no chat of its own; its card's chat still answers it+ assert.deepEqual(m.answerChat(task({ channel_id: null }), handOff), { channelId: null, kwantId: 'k_lin', threadId: 'th9' });+ // An older server without the card's chat: the task's own chat, as before+ assert.deepEqual(m.answerChat(task(), { kind: 'question', id: 'q2', text: '?' }), { channelId: 'c1', kwantId: null, threadId: null });+ assert.equal(m.answerChat(task({ channel_id: null }), { kind: 'question', id: 'q2', text: '?' }), null);+});+test('insights strip: verified this week, false successes, blocked', () => {const html = ui.insights({ insights: insightsRow });assert.match(html, /Verified this week/);diff --git a/src/db/approval_modes.rs b/src/db/approval_modes.rsindex adc37073..8c04f949 100644--- a/src/db/approval_modes.rs+++ b/src/db/approval_modes.rs@@ -209,6 +209,36 @@ impl Database {Ok(done.rows_affected() == 1)}+ /// Records the chat a pending card is in (`{"channel_id"|"thread_id"|"direct_kwant_id": …}`),+ /// the same one [`Self::park_approval`] keeps.+ pub async fn set_approval_chat(&self, id: &str, chat: &serde_json::Value) -> Result<(), DbError> {+ sqlx::query("UPDATE approvals SET resume = ? WHERE id = ? AND status = 'pending'")+ .bind(chat.to_string())+ .bind(id)+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ /// Cards left `pending` by an earlier run of kwant: nothing waits on them any more, so they+ /// become `waiting` (answerable, a late Allow resumes the work). A card stored before its chat+ /// was recorded gets the chat of the turn that asked, else the bot's direct chat. Returns how+ /// many. Only for startup, while no turn is running.+ pub async fn park_orphaned_approvals(&self) -> Result<u64, DbError> {+ let done = sqlx::query(+ "UPDATE approvals SET status = 'waiting', resume = COALESCE(resume, \+ (SELECT CASE WHEN r.thread_id IS NOT NULL THEN json_object('thread_id', r.thread_id) \+ WHEN r.channel_id IS NOT NULL THEN json_object('channel_id', r.channel_id) \+ ELSE json_object('direct_kwant_id', COALESCE(r.direct_kwant_id, approvals.kwant_id)) END \+ FROM running_turns r WHERE r.turn_id = approvals.turn_id), \+ json_object('direct_kwant_id', kwant_id)) \+ WHERE status = 'pending'",+ )+ .execute(&self.pool)+ .await?;+ Ok(done.rows_affected())+ }+/// Answers a `waiting` card once: sets `status` and returns the ticket with its chat. `None`/// when it isn't waiting (answered, or never parked) or is older than [`WAITING_APPROVAL_HOURS`],/// which is then marked `expired`. Two answers at once: only one gets the ticket.diff --git a/src/db/missions.rs b/src/db/missions.rsindex fbd9ff7f..e88db9db 100644--- a/src/db/missions.rs+++ b/src/db/missions.rs@@ -1166,13 +1166,25 @@ impl Database {/// The bot's open question, human-step and approval cards as (kind, id, text, where): `where`/// is the chat (thread, channel or direct) for questions and steps, the turn for approvals.- pub async fn open_cards_of(&self, kwant_id: &str) -> Result<Vec<(String, String, String, Option<String>)>, DbError> {+ pub async fn open_cards_of(&self, kwant_id: &str) -> Result<Vec<OpenCard>, DbError> {+ // A card's chat: its thread (with the bot whose thread it is), else its channel, else the+ // direct chat. An approval keeps its chat in `resume`; a `waiting` one (its turn stopped+ // waiting, or kwant restarted) is still answerable for WAITING_APPROVAL_HOURS.+ let window = format!("-{} hours", super::approval_modes::WAITING_APPROVAL_HOURS);Ok(sqlx::query_as(- "SELECT 'question', id, question, COALESCE(thread_id, channel_id, direct_kwant_id) FROM questions WHERE kwant_id = ?1 AND status = 'open' \- UNION ALL SELECT 'human_step', id, reason, COALESCE(thread_id, channel_id, direct_kwant_id) FROM human_steps WHERE kwant_id = ?1 AND status = 'open' \- UNION ALL SELECT 'approval', id, tool_name, turn_id FROM approvals WHERE kwant_id = ?1 AND status = 'pending'",+ "SELECT 'question' AS kind, q.id, q.question AS text, COALESCE(q.thread_id, q.channel_id, q.direct_kwant_id) AS context, \+ q.channel_id, q.direct_kwant_id, q.thread_id, t.kwant_id AS thread_kwant_id \+ FROM questions q LEFT JOIN threads t ON t.id = q.thread_id WHERE q.kwant_id = ?1 AND q.status = 'open' \+ UNION ALL SELECT 'human_step', h.id, h.reason, COALESCE(h.thread_id, h.channel_id, h.direct_kwant_id), \+ h.channel_id, h.direct_kwant_id, h.thread_id, t.kwant_id \+ FROM human_steps h LEFT JOIN threads t ON t.id = h.thread_id WHERE h.kwant_id = ?1 AND h.status = 'open' \+ UNION ALL SELECT 'approval', a.id, a.tool_name, a.turn_id, \+ json_extract(a.resume, '$.channel_id'), json_extract(a.resume, '$.direct_kwant_id'), json_extract(a.resume, '$.thread_id'), t.kwant_id \+ FROM approvals a LEFT JOIN threads t ON t.id = json_extract(a.resume, '$.thread_id') \+ WHERE a.kwant_id = ?1 AND (a.status = 'pending' OR (a.status = 'waiting' AND a.created_at > datetime('now', ?2)))",).bind(kwant_id)+ .bind(window).fetch_all(&self.pool).await?)}@@ -1195,6 +1207,22 @@ impl Database {}}+/// An open card of a bot (see [`Database::open_cards_of`]): a question, human step or approval,+/// and the chat it is in.+#[derive(Debug, Clone, sqlx::FromRow)]+pub struct OpenCard {+ pub kind: String,+ pub id: String,+ pub text: String,+ /// The conversation it came from (a question's thread or chat; an approval's turn).+ pub context: Option<String>,+ pub channel_id: Option<String>,+ pub direct_kwant_id: Option<String>,+ pub thread_id: Option<String>,+ /// The bot whose thread `thread_id` is.+ pub thread_kwant_id: Option<String>,+}+/// What else a state move changes.#[derive(Debug, Clone)]pub struct TaskChange {diff --git a/src/serve.rs b/src/serve.rsindex a01d8fab..33352206 100644--- a/src/serve.rs+++ b/src/serve.rs@@ -50,7 +50,9 @@ pub async fn run(config: Config, shutdown: impl Future<Output = ()>) -> Result<(// Saved passwords left in a bot's folder by older versions move into the vaultcrate::server::passwords::migrate_all(&state).await;crate::server::passwords::warn_if_exposed(&state).await;- // Before anything can start a turn: say which replies the last run cut off+ // Before anything can start a turn: cards the last run waited on stay answerable, and the+ // chats say which replies it cut off+ crate::server::mcp_runtime::keep_cards_after_restart(&state).await;crate::server::routes::interrupt_running_turns(&state).await;crate::server::scheduler::spawn_background(state.clone(), cancel.clone());crate::server::engine_routes::spawn_startup_check(state.clone());diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rsindex b6671cfe..96c46c6e 100644--- a/src/server/mcp_runtime.rs+++ b/src/server/mcp_runtime.rs@@ -283,6 +283,10 @@ impl BrokerApprover {return (ApprovalOutcome::Denied, "denied", None);}};+ // Its chat is known from the start: the board links to it, and a card that outlives a+ // restart still resumes there (see `keep_cards_after_restart`)+ let chat = self.chat.clone().unwrap_or_else(|| json!({"direct_kwant_id": req.kwant_id}));+ let _ = self.db.set_approval_chat(&ticket, &chat).await;let rx = self.broker.request_approval(ApprovalRequest {@@ -329,7 +333,6 @@ impl BrokerApprover {if !self.broker.cancel(&ticket).await {return (ApprovalOutcome::Denied, "denied", Some(ticket));}- let chat = self.chat.clone().unwrap_or_else(|| json!({"direct_kwant_id": req.kwant_id}));match self.db.park_approval(&ticket, &chat).await {Ok(true) => ApprovalOutcome::Unanswered,_ => {@@ -379,6 +382,25 @@ async fn turn_chat(state: &AppState, turn_id: &str) -> Option<Value> {})}+/// At startup, before any turn runs: the cards the last run of kwant was still waiting on are+/// kept as `waiting`, like a card whose turn stopped waiting, so answering one never fails. Allow+/// starts a turn in the card's chat that makes the call again; a payment's Allow still covers+/// only that one call (D8). Must run before [`super::routes::interrupt_running_turns`], which+/// clears the turns a card's chat may be looked up in.+pub async fn keep_cards_after_restart(state: &AppState) -> u64 {+ match state.db.park_orphaned_approvals().await {+ Ok(0) => 0,+ Ok(n) => {+ tracing::info!(count = n, "kept approval cards from before the restart answerable");+ n+ }+ Err(e) => {+ tracing::warn!(error = %e, "could not keep approval cards from before the restart");+ 0+ }+ }+}+/// A late answer to a card whose turn stopped waiting (`waiting`). Deny just closes it. Allow/// lets that one call run once without a new card and starts a turn in the card's chat telling/// the bot to make it again; "always allow" also remembers the tool for that conversation.diff --git a/src/server/missions/mod.rs b/src/server/missions/mod.rsindex 1625182e..c6ba4b5b 100644--- a/src/server/missions/mod.rs+++ b/src/server/missions/mod.rs@@ -556,11 +556,27 @@ async fn owner_needs_you(state: &AppState, task: &Task) -> Vec<Value> {let cards = state.db.open_cards_of(owner).await.unwrap_or_default();cards.into_iter()- .filter(|(kind, _, _, at)| kind == "approval" || context.is_none() || at.as_deref() == context.as_deref())- .map(|(kind, id, text, _)| json!({"kind": kind, "id": id, "text": text.chars().take(200).collect::<String>()}))+ .filter(|c| c.kind == "approval" || context.is_none() || c.context.as_deref() == context.as_deref())+ .map(|c| {+ let chat = card_chat(&c, owner);+ json!({"kind": c.kind, "id": c.id, "text": c.text.chars().take(200).collect::<String>(), "chat": chat})+ }).collect()}+/// Where the person answers a card: `{"channel_id", "kwant_id", "thread_id"}` of the chat it is+/// in (the owner's hand-off thread, a channel, or a direct chat), which is not always the chat+/// the task came from. A card whose chat isn't known is in the owner's direct chat.+fn card_chat(c: &crate::db::missions::OpenCard, owner: &str) -> Value {+ if let Some(thread) = &c.thread_id {+ return json!({"channel_id": null, "kwant_id": c.thread_kwant_id.as_deref().unwrap_or(owner), "thread_id": thread});+ }+ if let Some(channel) = &c.channel_id {+ return json!({"channel_id": channel, "kwant_id": null, "thread_id": null});+ }+ json!({"channel_id": null, "kwant_id": c.direct_kwant_id.as_deref().unwrap_or(owner), "thread_id": null})+}+/// A task in review waits on the person for each required check that needs their approval/// (`{"kind": "check_approval", "id": <check id>, "text"}`). An optional check can't hold the/// task, so it never lands here; it can still be approved, and `checks_summary.needs_approval`diff --git a/src/server/routes.rs b/src/server/routes.rsindex 80d5bfae..1c1af799 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -3204,7 +3204,7 @@ pub async fn resolve_approval(State(state): State<AppState>,Path(ticket_id): Path<String>,Json(payload): Json<ResolveApprovalPayload>,-) -> Result<Json<serde_json::Value>, StatusCode> {+) -> Result<Response, StatusCode> {let decision = match payload.decision.as_str() {"allow_once" => ApprovalDecision::AllowOnce,"always_allow" => ApprovalDecision::AlwaysAllowSession,@@ -3221,15 +3221,27 @@ pub async fn resolve_approval(// keeps its status and its tool never runslet resolved = state.broker.resolve(&ticket_id, decision.clone()).await;if !resolved {- // A card whose turn stopped waiting: a late answer, and Allow resumes the work- return match super::mcp_runtime::resume_late_approval(&state, &ticket_id, decision, status_str).await {+ // A card whose turn stopped waiting (or that kwant kept over a restart): a late answer,+ // and Allow resumes the work+ let reply = super::mcp_runtime::resume_late_approval(&state, &ticket_id, decision, status_str).await;+ super::missions::listener::refresh_needs_you(&state).await;+ return match reply {Some(mut reply) => {reply["ticket_id"] = json!(ticket_id);reply["resolved"] = json!(true);reply["status"] = json!(status_str);- Ok(Json(reply))+ Ok(Json(reply).into_response())}- None => Err(StatusCode::CONFLICT),+ None => Ok((+ StatusCode::CONFLICT,+ Json(json!({+ "ticket_id": ticket_id,+ "resolved": false,+ "status": "expired",+ "error": "This card expired: the bot is no longer waiting for it. Ask the bot again.",+ })),+ )+ .into_response()),};}let _ = state.db.update_approval_status(&ticket_id, status_str).await;@@ -3240,7 +3252,8 @@ pub async fn resolve_approval("ticket_id": ticket_id,"resolved": resolved,"status": status_str- })))+ }))+ .into_response())}#[derive(Serialize)]diff --git a/tests/restart_cards_test.rs b/tests/restart_cards_test.rsnew file mode 100644index 00000000..bffdc101--- /dev/null+++ b/tests/restart_cards_test.rs@@ -0,0 +1,255 @@+//! Two filming bugs. "Answer in chat" on a task's card opens the chat the card is in (the+//! owner's hand-off thread or chat), not the chat the task came from. And a card left waiting+//! when kwant restarts is still answerable afterwards: a late Allow resumes the work in the+//! chat that asked, a payment's "always allow" still covers one call (D8), and a card that is+//! too old says plainly that it expired instead of erroring.++mod common;++use common::*;+use kwnt::broker::PermissionBroker;+use kwnt::db::continuity::RunningTurn;+use kwnt::db::models::NewApproval;+use kwnt::db::questions::QuestionPlace;+use kwnt::db::spaces::SpaceId;+use kwnt::drivers::events::RuntimeEvent;+use kwnt::mcp::{ToolApprovalRequest, ToolApprover};+use kwnt::server::mcp_runtime::{self, BrokerApprover};+use kwnt::server::missions::listener;+use serde_json::{json, Value};+use std::time::Duration;++async fn general(env: &Env) -> String {+ env.state.db.list_channels(&SpaceId::default_space()).await.unwrap().into_iter().find(|c| c.name == "general").unwrap().id+}++async fn get(env: &Env, uri: &str) -> Value {+ let (s, v) = call(&env.app, "GET", uri, None).await;+ assert!(s.is_success(), "GET {uri}: {s} {v}");+ v+}++async fn status_of(env: &Env, ticket: &str) -> String {+ env.state.db.get_approval(ticket).await.unwrap().unwrap().status+}++/// A card asked by `env.a` in its direct chat, by the kwant that ran before the restart: kept+/// in the database, unknown to this process's broker. Returns its ticket id.+async fn card_from_before_the_restart(env: &Env, args: Value) -> String {+ let old = BrokerApprover {+ db: env.state.db.clone(),+ data_dir: env.state.config.data_dir.clone(),+ broker: PermissionBroker::new(),+ events: env.state.event_sender.clone(),+ timeout: Duration::from_secs(600),+ conversation: env.a.clone(),+ chat: Some(json!({"direct_kwant_id": env.a})),+ always_ask: false,+ };+ let req = ToolApprovalRequest {+ kwant_id: env.a.clone(),+ kwant_name: "A".into(),+ turn_id: "t-before-restart".into(),+ tool_name: "Bash".into(),+ server: String::new(),+ tool: "Bash".into(),+ arguments: args,+ builtin: Some(kwnt::mcp::BuiltinCall { cwd: None, outside_folder: false }),+ smart: None,+ payment: None,+ };+ let mut events = env.state.event_sender.subscribe();+ // The asking turn never hears back: its process "stopped"+ std::mem::forget(tokio::spawn(async move { old.decide(req).await }));+ let id = tokio::time::timeout(Duration::from_secs(5), async {+ loop {+ if let Ok(RuntimeEvent::ApprovalRequired { id, .. }) = events.recv().await {+ break id;+ }+ }+ })+ .await+ .expect("a card");+ assert!(!env.state.broker.is_pending(&id).await, "this process never knew the card");+ id+}++async fn resolve(env: &Env, ticket: &str, decision: &str) -> (u16, Value) {+ let (s, v) = call(&env.app, "POST", &format!("/api/approvals/{ticket}/resolve"), Some(json!({"decision": decision}))).await;+ (s.as_u16(), v)+}++#[tokio::test]+async fn a_card_from_before_a_restart_is_still_answerable_and_resumes_the_work() {+ let env = setup().await;+ let ticket = card_from_before_the_restart(&env, json!({"command": "ls RESTART_ALLOW_MARK", "description": "list"})).await;+ assert_eq!(status_of(&env, &ticket).await, "pending");++ assert_eq!(mcp_runtime::keep_cards_after_restart(&env.state).await, 1);+ assert_eq!(status_of(&env, &ticket).await, "waiting");+ let away = get(&env, "/api/away").await;+ let item = away["waiting"].as_array().unwrap().iter().find(|i| i["id"] == ticket.as_str()).expect("card listed").clone();+ assert_eq!(item["link"]["direct_kwant_id"], env.a.as_str(), "{item}");++ let (s, v) = resolve(&env, &ticket, "allow_once").await;+ assert_eq!(s, 200, "{v}");+ assert_eq!(v["resumed"], "new_turn", "{v}");+ assert_eq!(status_of(&env, &ticket).await, "allowed_once");+ wait_for("the resumed turn", || async { !invocations_with("ls RESTART_ALLOW_MARK").is_empty() }).await;+ let prompt = invocations_with("ls RESTART_ALLOW_MARK").pop().unwrap();+ assert!(prompt.contains("[The person allowed a tool call you asked for earlier]"), "{prompt}");+}++#[tokio::test]+async fn a_card_with_no_chat_resumes_where_its_turn_was_running() {+ let env = setup().await;+ let thread = env.state.db.create_thread(&env.a, "Hand-off", "delegation", None, &env.b).await.unwrap();+ // An older kwant didn't keep the chat with a pending card; the running turn knows it+ let card = env+ .state+ .db+ .save_approval(&NewApproval {+ turn_id: "t-running".into(),+ kwant_id: env.a.clone(),+ tool_name: "Bash".into(),+ parameters: json!({"arguments": {"command": "ls"}}),+ })+ .await+ .unwrap();+ let turn = RunningTurn {+ turn_id: "t-running".into(),+ kwant_id: env.a.clone(),+ kwant_name: "A".into(),+ channel_id: None,+ direct_kwant_id: None,+ thread_id: Some(thread.id.clone()),+ started_at: chrono::Utc::now(),+ };+ env.state.db.add_running_turn(&turn).await.unwrap();+ // And one from a turn nobody recorded lands in the bot's direct chat+ let lost = env+ .state+ .db+ .save_approval(&NewApproval { turn_id: "t-lost".into(), kwant_id: env.a.clone(), tool_name: "Bash".into(), parameters: json!({}) })+ .await+ .unwrap();++ assert_eq!(mcp_runtime::keep_cards_after_restart(&env.state).await, 2);+ let away = get(&env, "/api/away").await;+ let link = |id: &str| away["waiting"].as_array().unwrap().iter().find(|i| i["id"] == id).expect("card listed")["link"].clone();+ assert_eq!(link(&card.id)["thread_id"], thread.id.as_str(), "{away}");+ assert_eq!(link(&lost.id)["direct_kwant_id"], env.a.as_str(), "{away}");+}++#[tokio::test]+async fn always_allow_on_a_payment_card_after_a_restart_covers_one_call() {+ let env = setup().await;+ let charge = "curl -X POST https://api.stripe.com/v1/charges -u sk_test_x: -d amount=100 -d currency=usd";+ let ticket = card_from_before_the_restart(&env, json!({"command": charge})).await;+ let details: Value = serde_json::from_str(&env.state.db.get_approval(&ticket).await.unwrap().unwrap().parameters).unwrap();+ assert!(details.get("payment_reason").is_some(), "a payment card: {details}");++ mcp_runtime::keep_cards_after_restart(&env.state).await;+ let (s, v) = resolve(&env, &ticket, "always_allow").await;+ assert_eq!(s, 200, "{v}");+ assert!(!env.state.broker.is_allowed_for_session(&env.a, &env.a, "Bash").await, "a payment is never remembered");+}++#[tokio::test]+async fn a_card_too_old_to_resume_says_it_expired_instead_of_erroring() {+ let env = setup().await;+ let ticket = card_from_before_the_restart(&env, json!({"command": "ls RESTART_OLD_MARK"})).await;+ mcp_runtime::keep_cards_after_restart(&env.state).await;+ env.state.db.backdate_approval_for_test(&ticket, 25).await.unwrap();++ let (s, v) = resolve(&env, &ticket, "allow_once").await;+ assert_eq!(s, 409);+ assert_eq!(v["status"], "expired", "{v}");+ assert!(v["error"].as_str().unwrap().contains("Ask the bot again"), "{v}");+ assert_eq!(status_of(&env, &ticket).await, "expired");+ tokio::time::sleep(Duration::from_millis(300)).await;+ assert!(invocations_with("ls RESTART_OLD_MARK").is_empty(), "nothing resumed");+}++/// The lead (a) plans in #general; b owns the task and works in its hand-off thread. The task's+/// cards point at b's chats, which is where "Answer in chat" goes.+#[tokio::test]+async fn a_tasks_cards_say_which_chat_answers_them() {+ let env = setup().await;+ call(&env.app, "POST", "/api/settings", Some(json!({"mission_board": true}))).await;+ let general = general(&env).await;+ let body = json!({"title": "Ship it", "goal": "a release", "lead_kwant_id": env.a, "budget_tokens": 900_000,+ "channel_id": general, "tasks": [{"title": "A", "owner": env.b}]});+ let (s, m) = call(&env.app, "POST", "/api/missions", Some(body)).await;+ assert!(s.is_success(), "{m}");+ let detail = get(&env, &format!("/api/missions/{}", m["id"].as_str().unwrap())).await;+ let tid = detail["tasks"][0]["id"].as_str().unwrap().to_string();+ env.state.db.claim_task(&tid, &env.b, None, None, 600_000, false, &env.b).await.unwrap().unwrap();++ let thread = env.state.db.create_thread(&env.b, "Hand-off", "delegation", None, &env.a).await.unwrap();+ let place = QuestionPlace { kwant_id: env.b.clone(), channel_id: None, direct_kwant_id: None, thread_id: Some(thread.id.clone()), turn_id: None };+ let question = env.state.db.create_question(&place, "Which colour?", &[]).await.unwrap();+ let card = card_by(&env, &env.b).await;+ listener::refresh_needs_you(&env.state).await;++ let t = get(&env, &format!("/api/tasks/{tid}")).await;+ assert_eq!(t["task"]["state"], "needs_you", "{t}");+ assert_eq!(t["task"]["channel_id"], general.as_str(), "the task came from #general");+ let items = t["task"]["needs_you"].as_array().unwrap();+ let item = |id: &str| items.iter().find(|i| i["id"] == id).unwrap_or_else(|| panic!("{id} in {t}")).clone();+ let asked = item(&question.id);+ assert_eq!(asked["chat"], json!({"channel_id": null, "kwant_id": env.b, "thread_id": thread.id}), "{asked}");+ let approval = item(&card);+ assert_eq!(approval["chat"]["kwant_id"], env.b.as_str(), "{approval}");+ assert_eq!(approval["chat"]["channel_id"], Value::Null);++ // A card left waiting (its turn stopped) still holds the task; answering it lets go+ tokio::time::sleep(Duration::from_millis(400)).await;+ assert_eq!(status_of(&env, &card).await, "waiting");+ env.state.db.close_question(&question.id, "answered", Some("red")).await.unwrap();+ listener::refresh_needs_you(&env.state).await;+ let t = get(&env, &format!("/api/tasks/{tid}")).await;+ assert_eq!(t["task"]["needs_you"].as_array().unwrap().len(), 1, "{t}");+ assert_eq!(t["task"]["state"], "needs_you");+ let (s, v) = resolve(&env, &card, "deny").await;+ assert_eq!(s, 200, "{v}");+ let t = get(&env, &format!("/api/tasks/{tid}")).await;+ assert_eq!(t["task"]["state"], "working", "{t}");+}++/// A card `kwant` asks in its direct chat that nobody answers in time. Returns its ticket id.+async fn card_by(env: &Env, kwant: &str) -> String {+ let a = BrokerApprover {+ db: env.state.db.clone(),+ data_dir: env.state.config.data_dir.clone(),+ broker: env.state.broker.clone(),+ events: env.state.event_sender.clone(),+ timeout: Duration::from_millis(200),+ conversation: kwant.to_string(),+ chat: Some(json!({"direct_kwant_id": kwant})),+ always_ask: false,+ };+ let req = ToolApprovalRequest {+ kwant_id: kwant.to_string(),+ kwant_name: "B".into(),+ turn_id: "t-card".into(),+ tool_name: "Bash".into(),+ server: String::new(),+ tool: "Bash".into(),+ arguments: json!({"command": "ls CARD_CHAT_MARK"}),+ builtin: None,+ smart: None,+ payment: None,+ };+ let mut events = env.state.event_sender.subscribe();+ tokio::spawn(async move { a.decide(req).await });+ tokio::time::timeout(Duration::from_secs(5), async {+ loop {+ if let Ok(RuntimeEvent::ApprovalRequired { id, .. }) = events.recv().await {+ break id;+ }+ }+ })+ .await+ .expect("a card")+}