Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

Mission spend lands when the bot hands its task in

Lin (kwant bot)7efbf5c6e674
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6e005605..9dc05209 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
and blocked work. Turn it on in Settings → Mission board. It works on phone and desktop.
### Changed
+- **A task's spend shows up the moment it is verified.** When a bot hands a task in partway through
+ its turn, the tokens used so far land on the task and mission right away; the rest of the turn is
+ added when it ends, so nothing is counted twice. Before, a just-verified task showed 0 tokens for a
+ few seconds. Engines that report usage only at the end (Codex, Grok, custom CLIs) still add it then.
- **Deciding for you costs fewer tokens.** Before deciding a choice itself, a bot now hears at most one
teammate, and only when the choice or an open check names that teammate.
diff --git a/src/db/missions.rs b/src/db/missions.rs
index d91c6c82..3c1ce802 100644
--- a/src/db/missions.rs
+++ b/src/db/missions.rs
@@ -860,14 +860,15 @@ impl Database {
Ok(())
}
- /// Adds `tokens` to the task and its mission.
+ /// Adds `tokens` to the task and its mission. A negative amount takes back an overcount (a
+ /// mid-turn usage report the turn's final one came in under); neither goes below 0.
pub async fn spend_on_task(&self, task_id: &str, tokens: i64) -> Result<(), DbError> {
- if tokens <= 0 {
+ if tokens == 0 {
return Ok(());
}
let mut tx = self.pool.begin().await?;
- sqlx::query("UPDATE tasks SET spent_tokens = spent_tokens + ? WHERE id = ?").bind(tokens).bind(task_id).execute(&mut *tx).await?;
- sqlx::query("UPDATE missions SET spent_tokens = spent_tokens + ?, updated_at = ? WHERE id = (SELECT mission_id FROM tasks WHERE id = ?)")
+ sqlx::query("UPDATE tasks SET spent_tokens = MAX(0, spent_tokens + ?) WHERE id = ?").bind(tokens).bind(task_id).execute(&mut *tx).await?;
+ sqlx::query("UPDATE missions SET spent_tokens = MAX(0, spent_tokens + ?), updated_at = ? WHERE id = (SELECT mission_id FROM tasks WHERE id = ?)")
.bind(tokens)
.bind(Utc::now())
.bind(task_id)
diff --git a/src/drivers/api.rs b/src/drivers/api.rs
index 2b970d0c..b225fb38 100644
--- a/src/drivers/api.rs
+++ b/src/drivers/api.rs
@@ -761,6 +761,13 @@ struct ChatRequest<'a> {
turn_usage: std::sync::Mutex<Option<super::TurnUsage>>,
}
+impl ChatRequest<'_> {
+ /// Fresh tokens of the turn's calls so far; `None` until one reports usage.
+ fn fresh_so_far(&self) -> Option<u64> {
+ self.turn_usage.lock().unwrap_or_else(|e| e.into_inner()).map(|u| u.fresh())
+ }
+}
+
/// The bot and conversation a turn's calls are recorded for (see `crate::db::usage`).
#[derive(Clone, Copy)]
struct UsageSink<'a> {
@@ -1114,6 +1121,10 @@ impl ApiDriver {
}
let purpose = if round == 0 { crate::db::usage::PURPOSE_REPLY } else { crate::db::usage::PURPOSE_TOOL_ROUND };
record_call(request, purpose, usage, &body).await;
+ // A tool this round may hand the bot's task in: the turn so far is known now
+ if let Some(fresh) = request.fresh_so_far() {
+ let _ = event_tx.send(RuntimeEvent::UsageSoFar { fresh }).await;
+ }
if let Some(thinking) = reply_reasoning(&reply) {
let _ = event_tx.send(RuntimeEvent::ThinkingDelta(thinking)).await;
}
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rs
index d185c893..2adbf9d4 100644
--- a/src/drivers/cli.rs
+++ b/src/drivers/cli.rs
@@ -722,6 +722,13 @@ struct ClaudeStream {
last_progress: Option<Instant>,
/// Thinking arrived as partial deltas, so the whole `thinking` blocks repeat it.
thinking_streamed: bool,
+ /// Usage of each model call so far, by message id: fresh input, cache writes, output (each the
+ /// largest reported, since a message's usage repeats and grows as it streams).
+ calls: std::collections::HashMap<String, [u64; 3]>,
+ /// The message `message_delta` usage belongs to.
+ current_call: Option<String>,
+ /// Fresh tokens last sent as [`RuntimeEvent::UsageSoFar`].
+ fresh_reported: u64,
}
impl ClaudeStream {
@@ -742,6 +749,15 @@ impl ClaudeStream {
match v["type"].as_str() {
Some("result") => self.result_line = Some(line.to_string()),
Some("stream_event") => {
+ match v["event"]["type"].as_str() {
+ Some("message_start") => {
+ let id = v["event"]["message"]["id"].as_str().map(String::from);
+ self.current_call = id.clone();
+ events.extend(self.saw_usage(id, &v["event"]["message"]["usage"]));
+ }
+ Some("message_delta") => events.extend(self.saw_usage(self.current_call.clone(), &v["event"]["usage"])),
+ _ => {}
+ }
let delta = &v["event"]["delta"];
if v["event"]["type"] == "content_block_delta" && delta["type"] == "thinking_delta" {
if let Some(text) = delta["thinking"].as_str().filter(|t| !t.is_empty()) {
@@ -751,6 +767,7 @@ impl ClaudeStream {
}
}
Some("assistant") => {
+ events.extend(self.saw_usage(v["message"]["id"].as_str().map(String::from), &v["message"]["usage"]));
if !self.thinking_streamed {
for b in blocks.iter().filter(|b| b["type"] == "thinking") {
if let Some(text) = b["thinking"].as_str().filter(|t| !t.trim().is_empty()) {
@@ -791,6 +808,22 @@ impl ClaudeStream {
events
}
+ /// Takes one model call's usage (a `message_start`, `message_delta` or `assistant` line) and
+ /// returns a [`RuntimeEvent::UsageSoFar`] when the turn's fresh total grew.
+ fn saw_usage(&mut self, id: Option<String>, usage: &serde_json::Value) -> Option<RuntimeEvent> {
+ let (id, usage) = (id?, usage.as_object()?);
+ let n = |k: &str| usage.get(k).and_then(serde_json::Value::as_u64).unwrap_or(0);
+ let call = self.calls.entry(id).or_default();
+ for (slot, value) in call.iter_mut().zip([n("input_tokens"), n("cache_creation_input_tokens"), n("output_tokens")]) {
+ *slot = (*slot).max(value);
+ }
+ let fresh: u64 = self.calls.values().flatten().sum();
+ (fresh > self.fresh_reported).then(|| {
+ self.fresh_reported = fresh;
+ RuntimeEvent::UsageSoFar { fresh }
+ })
+ }
+
fn progress(&mut self, now: Instant) -> Vec<RuntimeEvent> {
if self.last_progress.is_some_and(|at| now.duration_since(at) < CLAUDE_PROGRESS_EVERY) {
return Vec::new();
@@ -1400,6 +1433,25 @@ mod tests {
use super::*;
use crate::db::models::{Kwant, Message};
+ #[test]
+ fn claude_stream_reports_usage_so_far() {
+ let mut stream = ClaudeStream::default();
+ let now = Instant::now();
+ let so_far = |events: Vec<RuntimeEvent>| events.into_iter().find_map(|e| match e {
+ RuntimeEvent::UsageSoFar { fresh } => Some(fresh),
+ _ => None,
+ });
+ let start = r#"{"type":"stream_event","event":{"type":"message_start","message":{"id":"m1","usage":{"input_tokens":5,"cache_creation_input_tokens":100,"cache_read_input_tokens":9000,"output_tokens":1}}}}"#;
+ assert_eq!(so_far(stream.line(start, now)), Some(106), "cache reads don't count");
+ let delta = r#"{"type":"stream_event","event":{"type":"message_delta","usage":{"output_tokens":40}}}"#;
+ assert_eq!(so_far(stream.line(delta, now)), Some(145));
+ // The whole message repeats its usage: no double count, no new report
+ let whole = r#"{"type":"assistant","message":{"id":"m1","content":[],"usage":{"input_tokens":5,"cache_creation_input_tokens":100,"output_tokens":40}}}"#;
+ assert_eq!(so_far(stream.line(whole, now)), None);
+ let next = r#"{"type":"assistant","message":{"id":"m2","content":[],"usage":{"input_tokens":3,"output_tokens":7}}}"#;
+ assert_eq!(so_far(stream.line(next, now)), Some(155), "a second model call adds up");
+ }
+
#[test]
fn claude_result_usage_is_split_into_fresh_and_cached() {
let stdout = include_str!("../../tests/fixtures/claude/result_with_usage.jsonl");
diff --git a/src/drivers/events.rs b/src/drivers/events.rs
index b463d4b2..ca2188b6 100644
--- a/src/drivers/events.rs
+++ b/src/drivers/events.rs
@@ -18,6 +18,11 @@ pub enum RuntimeEvent {
/// A driver is still working: it printed something that isn't reply text or a tool call.
/// Only feeds the turn's stall watchdog; it is never broadcast.
Progress,
+ /// The turn's fresh tokens so far (see `TurnUsage::fresh`), when the engine reports usage
+ /// mid-turn, so a task the bot hands in during the turn can pay for it then. Never broadcast.
+ UsageSoFar {
+ fresh: u64,
+ },
ApprovalRequired {
id: String,
tool_name: String,
diff --git a/src/server/missions/mod.rs b/src/server/missions/mod.rs
index 96c0dd11..1fab60ec 100644
--- a/src/server/missions/mod.rs
+++ b/src/server/missions/mod.rs
@@ -366,9 +366,13 @@ pub fn checks_summary(task: &Task, checks: &[OutcomeCheck]) -> Value {
/// holds for it there (a hand-off, a routine run), else its own claim. A claim taken in `turn_id`
/// or released since `turn_started_ms` counts too, so a bot that finishes its task inside the turn
/// (`task_update review` releases the claim) still pays for that turn. Renews an open lease, and
-/// blocks the task when it goes over its own budget.
-pub async fn spend(state: &AppState, kwant_id: &str, context_id: &str, turn_id: Option<&str>, turn_started_ms: i64, fresh: u64) {
- if fresh == 0 {
+/// blocks the task when it goes over its own budget. `booked` of the turn's tokens already landed
+/// when the bot handed its task in ([`spend_at_hand_in`]), so only the rest is added here; when the
+/// engine's mid-turn count ran ahead of its final one, the difference is taken back, so the turn
+/// adds up to exactly `fresh`.
+pub async fn spend(state: &AppState, kwant_id: &str, context_id: &str, turn_id: Option<&str>, turn_started_ms: i64, fresh: u64, booked: u64) {
+ let due = i64::try_from(fresh).unwrap_or(i64::MAX).saturating_sub(i64::try_from(booked).unwrap_or(i64::MAX));
+ if due == 0 {
return;
}
let Ok(claims) = state.db.spend_claims(kwant_id, turn_id, turn_started_ms).await else { return };
@@ -378,8 +382,7 @@ pub async fn spend(state: &AppState, kwant_id: &str, context_id: &str, turn_id:
.find(|c| c.system && c.context_id.as_deref() == Some(context_id))
.or_else(|| claims.iter().filter(here).find(|c| !c.system));
let Some(claim) = claim else { return };
- let tokens = i64::try_from(fresh).unwrap_or(i64::MAX);
- if state.db.spend_on_task(&claim.task_id, tokens).await.is_err() {
+ if state.db.spend_on_task(&claim.task_id, due).await.is_err() {
return;
}
let _ = state.db.renew_claim(&claim.task_id, lease_ms(state).await).await;
@@ -400,6 +403,28 @@ pub async fn spend(state: &AppState, kwant_id: &str, context_id: &str, turn_id:
}
}
+/// When the bot hands its task in during a turn (`task_update`), the turn's tokens its engine
+/// reported so far land on the task right away, so a task verified in-turn never shows 0 spend
+/// until the turn ends. [`spend`] adds only the rest at turn end. Engines that report usage only
+/// at the end (codex, grok, custom CLIs) book nothing here.
+pub async fn spend_at_hand_in(state: &AppState, task_id: &str, turn_id: Option<&str>) {
+ let Some(turn_id) = turn_id else { return };
+ let due = state.turns.book_usage(turn_id);
+ if due == 0 {
+ return;
+ }
+ let tokens = i64::try_from(due).unwrap_or(i64::MAX);
+ if state.db.spend_on_task(task_id, tokens).await.is_err() {
+ return;
+ }
+ if let Ok(Some(task)) = state.db.get_task(task_id).await {
+ emit_task(state, &task).await;
+ if let Some(m) = &task.mission_id {
+ emit_mission(state, m).await;
+ }
+ }
+}
+
/// Working tasks whose lease ran out go back to ready (one attempt used).
pub async fn sweep_leases(state: &AppState) -> usize {
let mut n = 0;
diff --git a/src/server/missions/tools.rs b/src/server/missions/tools.rs
index 55b7b0e0..2ad79fe6 100644
--- a/src/server/missions/tools.rs
+++ b/src/server/missions/tools.rs
@@ -313,6 +313,8 @@ async fn update(state: &AppState, scope: &SelfScope, task: &Task, args: &Value)
Ok(t) => t,
Err(e) => return fail(format!("Not moved: {e}.")),
};
+ // Handed in: the turn so far pays now, before its checks can verify it
+ super::spend_at_hand_in(state, &task.id, scope.turn_id.as_deref()).await;
if task.state != "review" {
return ok(json!({"task": brief(&task)}));
}
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 00d05353..237ec54c 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -2218,6 +2218,8 @@ async fn run_kwant_turn_inner(
}
// Only resets the stall clock (above)
Some(RuntimeEvent::Progress) => {}
+ // Lets a task handed in during the turn pay for it then (see `super::missions::spend_at_hand_in`)
+ Some(RuntimeEvent::UsageSoFar { fresh }) => state.turns.saw_usage(&tag.turn_id, fresh),
Some(event) => {
if let RuntimeEvent::ToolCallPending { name, args, .. } = &event {
if name == super::questions::NATIVE_ASK_TOOL {
@@ -2424,7 +2426,9 @@ async fn run_kwant_turn_inner(
state.turns.add_job_tokens(&scope.job_id, fresh);
// …and toward the task the bot holds, if any (see `super::missions`)
let turn_started_ms = chrono::Utc::now().timestamp_millis() - turn_start.elapsed().as_millis() as i64;
- super::missions::spend(state, &target_kwant.id, &scope.context_id(target_kwant), Some(&tag.turn_id), turn_started_ms, fresh).await;
+ // (less what a task the bot handed in mid-turn already paid for)
+ let booked = state.turns.take_booked(&tag.turn_id);
+ super::missions::spend(state, &target_kwant.id, &scope.context_id(target_kwant), Some(&tag.turn_id), turn_started_ms, fresh, booked).await;
let mut reply_text = output.text.clone();
let saved = match &opts.discussion {
diff --git a/src/server/turns.rs b/src/server/turns.rs
index f0e499a2..9fcbfcf5 100644
--- a/src/server/turns.rs
+++ b/src/server/turns.rs
@@ -52,6 +52,15 @@ pub struct ActiveTurn {
struct Inner {
jobs: HashMap<String, Job>,
turns: HashMap<String, ActiveTurn>,
+ /// Usage the engine reported so far in a running turn, by turn id (see [`TurnRegistry::book_usage`]).
+ meters: HashMap<String, Meter>,
+}
+
+/// One turn's fresh tokens: reported by the engine so far, and already booked onto a task.
+#[derive(Default, Clone, Copy)]
+struct Meter {
+ seen: u64,
+ booked: u64,
}
/// Jobs, their cancel tokens and the turns they run.
@@ -160,7 +169,32 @@ impl TurnRegistry {
}
pub fn end_turn(&self, turn_id: &str) {
- self.lock().turns.remove(turn_id);
+ let mut inner = self.lock();
+ inner.turns.remove(turn_id);
+ inner.meters.remove(turn_id);
+ }
+
+ /// Notes the fresh tokens a running turn used so far, as its engine reports them.
+ pub fn saw_usage(&self, turn_id: &str, fresh: u64) {
+ let mut inner = self.lock();
+ let m = inner.meters.entry(turn_id.to_string()).or_default();
+ m.seen = m.seen.max(fresh);
+ }
+
+ /// Fresh tokens of the turn not booked yet, now marked booked: what a task the bot hands in
+ /// mid-turn pays for at that moment.
+ pub fn book_usage(&self, turn_id: &str) -> u64 {
+ let mut inner = self.lock();
+ let Some(m) = inner.meters.get_mut(turn_id) else { return 0 };
+ let due = m.seen.saturating_sub(m.booked);
+ m.booked = m.booked.max(m.seen);
+ due
+ }
+
+ /// Tokens of the turn already booked mid-turn; forgets the turn's meter. At turn end only
+ /// `fresh − booked` is still due, so the turn is counted once.
+ pub fn take_booked(&self, turn_id: &str) -> u64 {
+ self.lock().meters.remove(turn_id).map_or(0, |m| m.booked)
}
/// Running and waiting turns, oldest first.
@@ -361,6 +395,23 @@ impl Limiter {
#[cfg(test)]
mod tests {
+ #[test]
+ fn usage_booked_mid_turn_is_counted_once() {
+ let reg = TurnRegistry::default();
+ assert_eq!(reg.book_usage("t"), 0, "nothing reported, nothing booked");
+ reg.saw_usage("t", 100);
+ reg.saw_usage("t", 80); // an older report never shrinks the count
+ assert_eq!(reg.book_usage("t"), 100);
+ assert_eq!(reg.book_usage("t"), 0, "booking twice books nothing new");
+ reg.saw_usage("t", 150);
+ assert_eq!(reg.book_usage("t"), 50, "a second hand-in pays only what came since");
+ assert_eq!(reg.take_booked("t"), 150, "turn end subtracts what was booked");
+ assert_eq!(reg.take_booked("t"), 0, "…and forgets the turn");
+ reg.saw_usage("u", 10);
+ reg.end_turn("u");
+ assert_eq!(reg.book_usage("u"), 0, "an ended turn keeps no meter");
+ }
+
use super::*;
#[test]
diff --git a/tests/mission_spend_test.rs b/tests/mission_spend_test.rs
index 314ad2c5..390f31d2 100644
--- a/tests/mission_spend_test.rs
+++ b/tests/mission_spend_test.rs
@@ -1,8 +1,10 @@
-//! Mission Control spend through the real end-of-turn path: the mission runner starts a turn on a
-//! fake claude CLI, which calls `task_update review` through the turn's own MCP server (so the
-//! claim is released inside the turn), then reports its usage. The turn's tokens must still land
-//! on the task and the mission, and the mission budget must use that number. Its own test binary:
-//! it changes PATH and listens on a real port the CLI calls back on.
+//! Mission Control spend through the real turn path: the mission runner starts a turn on a fake
+//! claude CLI, which streams its usage so far, writes the task's outcome and calls `task_update
+//! review` through the turn's own MCP server (so the claim is released and the check verifies the
+//! task inside the turn), and only then ends with its final usage. The usage known at hand-in must
+//! be on the task the moment it is Verified, the turn must add up to its final usage exactly (no
+//! double count), and the mission budget must use that number. Its own test binary: it changes
+//! PATH and listens on a real port the CLI calls back on.
use axum::{
body::{to_bytes, Body},
@@ -23,11 +25,12 @@ use std::sync::OnceLock;
use std::time::Duration;
use tower::ServiceExt;
-/// On a Mission Control prompt, moves the task it holds to review through the kwant tools in its
-/// `--mcp-config`, then reports 12 new input, 8,211 cache-write, 83,544 cache-read and 487 output
-/// tokens: 8,710 fresh.
+/// On a Mission Control prompt: streams one model call's usage so far (12 new input, 8,211
+/// cache-write, 83,544 cache-read, 300 output: 8,523 fresh), writes notes.md, moves the task it
+/// holds to review through the kwant tools in its `--mcp-config`, works on for a while, then
+/// reports the turn's final usage: 487 output, so 8,710 fresh.
const FAKE_CLAUDE: &str = r#"#!/usr/bin/env python3
-import json, re, sys, urllib.request
+import json, re, sys, time, urllib.request
args = sys.argv[1:]
if args[:1] == ["auth"]:
print('{"loggedIn":true}')
@@ -35,6 +38,13 @@ if args[:1] == ["auth"]:
prompt = args[-1] if args else ""
held = re.search(r"You hold task (\S+) of", prompt)
if held and "--mcp-config" in args:
+ start = {"type": "message_start", "message": {"id": "msg_1", "usage": {"input_tokens": 12,
+ "cache_creation_input_tokens": 8211, "cache_read_input_tokens": 83544, "output_tokens": 1}}}
+ print(json.dumps({"type": "stream_event", "event": start}), flush=True)
+ print(json.dumps({"type": "stream_event", "event": {"type": "message_delta", "usage": {"output_tokens": 300}}}), flush=True)
+ time.sleep(0.5)
+ with open("notes.md", "w") as f:
+ f.write("done")
with open(args[args.index("--mcp-config") + 1]) as f:
servers = json.load(f).get("mcpServers", {})
for s in servers.values():
@@ -44,6 +54,7 @@ if held and "--mcp-config" in args:
headers = dict(s.get("headers", {}), **{"content-type": "application/json"})
req = urllib.request.Request(s["url"], data=json.dumps(call).encode(), headers=headers)
urllib.request.urlopen(req, timeout=30).read()
+ time.sleep(3)
print(json.dumps({"type": "result", "is_error": False, "num_turns": 1, "result": "done, sent for review",
"total_cost_usd": 0.42,
"usage": {"input_tokens": 12, "cache_creation_input_tokens": 8211,
@@ -51,6 +62,8 @@ print(json.dumps({"type": "result", "is_error": False, "num_turns": 1, "result":
"modelUsage": {"claude-opus-5-5": {"outputTokens": 487}}}))
"#;
+/// Fresh tokens the CLI reported before it handed the task in.
+const FRESH_AT_HAND_IN: i64 = 12 + 8_211 + 300;
const FRESH_PER_TURN: i64 = 12 + 8_211 + 487;
fn fake_cli() {
@@ -86,7 +99,7 @@ async fn ok(app: &Router, method: &str, uri: &str, body: Option<Value>) -> Value
}
#[tokio::test]
-async fn a_turn_that_finishes_its_task_still_pays_for_itself() {
+async fn a_task_verified_in_turn_pays_at_hand_in_and_the_turn_counts_once() {
fake_cli();
let tmp = tempfile::tempdir().unwrap();
// The CLI reaches its kwant tools over HTTP, so kwant listens for real
@@ -119,7 +132,8 @@ async fn a_turn_that_finishes_its_task_still_pays_for_itself() {
let channel = ok(&app, "POST", "/api/channels", Some(json!({"name": "desk", "lead_kwant_id": ann, "member_kwants": []}))).await;
let channel = channel["id"].as_str().unwrap().to_string();
let body = json!({"title": "Ship it", "goal": "a release", "lead_kwant_id": ann, "budget_tokens": 10_000, "channel_id": channel,
- "tasks": [{"title": "A", "owner": ann, "budget_tokens": 9_000},
+ "tasks": [{"title": "A", "owner": ann, "budget_tokens": 9_000,
+ "checks": [{"kind": "file_contains", "spec": {"path": "notes.md", "text": "done"}}]},
{"title": "B", "owner": ann, "budget_tokens": 2_000}]});
let m = ok(&app, "POST", "/api/missions", Some(body)).await;
let mid = m["id"].as_str().unwrap().to_string();
@@ -132,18 +146,30 @@ async fn a_turn_that_finishes_its_task_still_pays_for_itself() {
let other = if started == a { b.clone() } else { a.clone() };
assert_eq!(started, a, "the runner starts the first task: {run}");
- // The turn moves A to review (releasing its claim) and then ends with its usage
+ // The turn hands A in and its check verifies it, while the turn is still running
let mut t = Value::Null;
for _ in 0..300 {
t = ok(&app, "GET", &format!("/api/tasks/{a}"), None).await;
- if t["task"]["spent_tokens"].as_i64().unwrap_or(0) > 0 {
+ if t["task"]["state"] == "verified" {
break;
}
- tokio::time::sleep(Duration::from_millis(100)).await;
+ tokio::time::sleep(Duration::from_millis(50)).await;
}
- assert_eq!(t["task"]["state"], "review", "the bot sent it for review inside the turn: {t}");
+ assert_eq!(t["task"]["state"], "verified", "the bot handed it in and its check passed inside the turn: {t}");
assert!(t["task"]["claim"].is_null(), "review released the claim: {t}");
- assert_eq!(t["task"]["spent_tokens"], FRESH_PER_TURN, "the turn's tokens land on the task: {t}");
+ assert_eq!(t["task"]["spent_tokens"], FRESH_AT_HAND_IN, "the usage known at hand-in is on the task the moment it is Verified: {t}");
+ let detail = ok(&app, "GET", &format!("/api/missions/{mid}"), None).await;
+ assert_eq!(detail["mission"]["spent_tokens"], FRESH_AT_HAND_IN, "…and on the mission: {detail}");
+
+ // At turn end only the rest is added: the turn counts exactly once
+ for _ in 0..300 {
+ t = ok(&app, "GET", &format!("/api/tasks/{a}"), None).await;
+ if t["task"]["spent_tokens"] != FRESH_AT_HAND_IN {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ assert_eq!(t["task"]["spent_tokens"], FRESH_PER_TURN, "the turn's final usage, not hand-in plus final: {t}");
let released = t["events"].as_array().unwrap().iter().any(|ev| ev["to_state"] == "review");
assert!(released, "{t}");
let detail = ok(&app, "GET", &format!("/api/missions/{mid}"), None).await;