The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(chat): keep context breakdown aligned with final call
Steven Enamakel7f2940c0d7fd
diff --git a/app/src/features/conversations/aui/ContextUsage.test.tsx b/app/src/features/conversations/aui/ContextUsage.test.tsxindex 35a20d0063..f33347d15a 100644--- a/app/src/features/conversations/aui/ContextUsage.test.tsx+++ b/app/src/features/conversations/aui/ContextUsage.test.tsx@@ -119,7 +119,7 @@ describe('ContextUsage', () => {await waitFor(() => expect(popover).toHaveTextContent('Tool schemas'));expect(popover).not.toHaveTextContent('Tool usage');expect(popover).not.toHaveTextContent('Thinking tokens');- expect(popover).toHaveTextContent('Output');+ expect(popover).not.toHaveTextContent('Output');expect(popover).toHaveTextContent('Your input');expect(popover).toHaveTextContent('System prompt');// Individual system-prompt headings are folded into one stable bucket.@@ -229,7 +229,6 @@ describe('contextBreakdownSegments', () => {expect(segments.map(s => [s.label, s.tokens])).toEqual([['System prompt', 30],['Tool schemas', 100],- ['Output', 0],['Your input', 0],]);});@@ -245,16 +244,15 @@ describe('contextBreakdownSegments', () => {context_window: 1_000_000,},t,- { lastTurnContextUsed: 100_000, lastTurnOutputTokens: 30_000 }+ { lastTurnContextUsed: 100_000 });- // 100k context = 10k prompt + 20k schemas + 30k of this turn's replies +- // 40k of conversation. The summed 5.7M input never enters the partition.+ // 100k context = 10k prompt + 20k schemas + 70k of conversation. The+ // turn-wide output total is excluded because earlier replies may be gone.expect(segments.map(s => [s.label, s.tokens])).toEqual([['System prompt', 10_000],['Tool schemas', 20_000],- ['Output', 30_000],- ['Your input', 40_000],+ ['Your input', 70_000],]);expect(segments.reduce((sum, s) => sum + s.tokens, 0)).toBe(100_000);});diff --git a/app/src/features/conversations/aui/ContextUsage.tsx b/app/src/features/conversations/aui/ContextUsage.tsxindex 388786193a..b3ccbccf13 100644--- a/app/src/features/conversations/aui/ContextUsage.tsx+++ b/app/src/features/conversations/aui/ContextUsage.tsx@@ -66,7 +66,7 @@ type BreakdownState =export function contextBreakdownSegments(data: ContextBreakdownData,t: (key: string) => string,- usage: Pick<SessionTokenUsage, 'lastTurnContextUsed' | 'lastTurnOutputTokens'> = EMPTY_USAGE+ usage: Pick<SessionTokenUsage, 'lastTurnContextUsed'> = EMPTY_USAGE): readonly ContextSegment[] {let systemPrompt = 0;let toolSchemas = 0;@@ -85,13 +85,12 @@ export function contextBreakdownSegments(systemPrompt += section.est_tokens;}}- // Partition the context the last turn ended with. Every reply the turn- // produced is in that context (each one is input to the next call), so the- // turn's output is a share of it and the rest is the conversation.- const output = Math.min(usage.lastTurnOutputTokens, usage.lastTurnContextUsed);+ // The turn-wide output total includes replies from earlier calls that may+ // have been trimmed or compacted out of the final request. Keep the final+ // context partition limited to its fixed prompt and remaining conversation.const yourInput = Math.max(0,- usage.lastTurnContextUsed - output - systemPrompt - toolSchemas - hiddenToolUsage+ usage.lastTurnContextUsed - systemPrompt - toolSchemas - hiddenToolUsage);return [{@@ -104,7 +103,6 @@ export function contextBreakdownSegments(tokens: toolSchemas,tint: 'bg-violet-500',},- { label: t('conversations.composer.context.output'), tokens: output, tint: 'bg-emerald-500' },{label: t('conversations.composer.context.section.yourInput'),tokens: yourInput,diff --git a/crates/openhuman-core/src/agent/context_breakdown.rs b/crates/openhuman-core/src/agent/context_breakdown.rsindex 274ab966d7..cf2fb78069 100644--- a/crates/openhuman-core/src/agent/context_breakdown.rs+++ b/crates/openhuman-core/src/agent/context_breakdown.rs@@ -132,7 +132,11 @@ async fn cached_report(agent_id: &str, config: &Config) -> Result<PromptSizeRepo/// recorded usage. Silent no-op (no section added) on any lookup failure —/// a context breakdown must never fail just because the optional history/// enrichment couldn't be computed.-async fn history_section(thread_id: &str) -> Option<ContextSection> {+fn history_tokens(context_tokens: usize, fixed_prompt_tokens: usize) -> usize {+ context_tokens.saturating_sub(fixed_prompt_tokens)+}++async fn history_section(thread_id: &str, fixed_prompt_tokens: usize) -> Option<ContextSection> {let outcome = crate::threads::ops::token_usage(crate::threads::ops::ThreadTokenUsageRequest {thread_id: thread_id.to_string(),})@@ -145,7 +149,7 @@ async fn history_section(thread_id: &str) -> Option<ContextSection> {// Tokens, not bytes, is what `token_usage` actually recorded — reverse// the module's own byte-per-token estimate so `bytes` stays a consistent// (if approximate) unit across every section in the response.- let est = usage.last_turn_context_tokens as usize;+ let est = history_tokens(usage.last_turn_context_tokens as usize, fixed_prompt_tokens);let bytes = est.saturating_mul(crate::agent::debug::prompt_size::EST_BYTES_PER_TOKEN);Some(ContextSection {label: "history".to_string(),@@ -191,6 +195,7 @@ pub async fn context_breakdown(let mut sections: Vec<ContextSection> =report.sections.iter().map(section_from_prompt).collect();sections.push(tools_section(&report.tools));+ let fixed_prompt_tokens = sections.iter().map(|section| section.est_tokens).sum();if let Some(thread_id) = params.thread_id@@ -198,7 +203,7 @@ pub async fn context_breakdown(.map(str::trim).filter(|s| !s.is_empty()){- if let Some(history) = history_section(thread_id).await {+ if let Some(history) = history_section(thread_id, fixed_prompt_tokens).await {sections.push(history);}}diff --git a/crates/openhuman-core/src/agent/context_breakdown_tests.rs b/crates/openhuman-core/src/agent/context_breakdown_tests.rsindex fcb9ebdf92..eb000d37f6 100644--- a/crates/openhuman-core/src/agent/context_breakdown_tests.rs+++ b/crates/openhuman-core/src/agent/context_breakdown_tests.rs@@ -49,6 +49,12 @@ fn est_tokens_divides_by_the_shared_bytes_per_token_constant() {assert_eq!(est_tokens(0), 0);}+#[test]+fn history_section_excludes_prompt_and_tool_tokens_already_listed() {+ assert_eq!(history_tokens(100_000, 30_000), 70_000);+ assert_eq!(history_tokens(20_000, 30_000), 0);+}+#[test]fn config_fingerprint_changes_when_config_content_changes() {// `workspace_dir` is `#[serde(skip)]` on `Config` (a runtime path, not@@ -84,7 +90,7 @@ async fn history_section_is_none_for_an_unknown_thread() {// `has_usage: false` (or the RPC itself fails) and this must degrade to// `None` rather than propagating an error — the breakdown must still// answer with just the prompt/tools sections.- let section = history_section("context-breakdown-unknown-thread-id").await;+ let section = history_section("context-breakdown-unknown-thread-id", 0).await;assert!(section.is_none());}diff --git a/crates/openhuman-core/src/agent/session_host/driver.rs b/crates/openhuman-core/src/agent/session_host/driver.rsindex a884a4169d..a2bfc485fb 100644--- a/crates/openhuman-core/src/agent/session_host/driver.rs+++ b/crates/openhuman-core/src/agent/session_host/driver.rs@@ -461,7 +461,7 @@ fn final_call_tokens([repair, close].into_iter().flatten()- .find(|usage| usage.last_call_input_tokens > 0)+ .find(|usage| usage.last_call_input_tokens > 0 || usage.last_call_output_tokens > 0).map(|usage| (usage.last_call_input_tokens, usage.last_call_output_tokens)).or(loop_last_call).unwrap_or_default()diff --git a/crates/openhuman-core/src/agent/session_host/driver/grounded_close.rs b/crates/openhuman-core/src/agent/session_host/driver/grounded_close.rsindex cbf2d029ab..9708e04396 100644--- a/crates/openhuman-core/src/agent/session_host/driver/grounded_close.rs+++ b/crates/openhuman-core/src/agent/session_host/driver/grounded_close.rs@@ -38,11 +38,13 @@ pub(super) struct RepairUsage {}impl RepairUsage {- fn record(&mut self, usage: Option<BilledUsage>) {+ fn record(&mut self, usage: Option<BilledUsage>, measures_context: bool) {self.model_calls += 1;if let Some(usage) = usage {- self.last_call_input_tokens = usage.input_tokens;- self.last_call_output_tokens = usage.output_tokens;+ if measures_context {+ self.last_call_input_tokens = usage.input_tokens;+ self.last_call_output_tokens = usage.output_tokens;+ }self.input_tokens += usage.input_tokens;self.output_tokens += usage.output_tokens;self.cached_input_tokens += usage.cached_input_tokens();@@ -105,7 +107,7 @@ pub(super) async fn repair_required_output(let (candidate, candidate_usage) =completion(source, model, temperature, thread_id, prompt_history).await;let mut usage = RepairUsage::default();- usage.record(candidate_usage);+ usage.record(candidate_usage, true);let candidate = candidate.trim().to_owned();let candidate_is_usable = !candidate.is_empty()&& !contains_tool_call(dispatcher, &candidate)@@ -281,7 +283,7 @@ wherelet mut prompt = instruction.clone();for attempt in 0..2 {let (candidate, candidate_usage) = ask(prompt).await;- usage.record(candidate_usage);+ usage.record(candidate_usage, true);let candidate = candidate.trim().to_owned();let violation = if candidate.is_empty() {Some(CloseViolation::NoReply)@@ -289,7 +291,9 @@ whereSome(CloseViolation::QuotedHarnessText)} else {let (violation, verify_usage) = verify(candidate.clone()).await;- usage.record(verify_usage);+ // The verifier sees one synthetic prompt, not the conversation+ // context that will be resumed, so it must not replace the gauge.+ usage.record(verify_usage, false);violation};let Some(violation) = violation else {diff --git a/crates/openhuman-core/src/agent/session_host/driver_tests.rs b/crates/openhuman-core/src/agent/session_host/driver_tests.rsindex 0ade713d73..c27a702313 100644--- a/crates/openhuman-core/src/agent/session_host/driver_tests.rs+++ b/crates/openhuman-core/src/agent/session_host/driver_tests.rs@@ -230,6 +230,10 @@ fn final_call_tokens_prefer_the_newest_call_that_reached_the_provider() {final_call_tokens(loop_last, Some(&call(95_000, 300)), None),(95_000, 300));+ assert_eq!(+ final_call_tokens(loop_last, Some(&call(0, 300)), None),+ (0, 300)+ );assert_eq!(final_call_tokens(loop_last,diff --git a/docs/gitbooks/en/developing/architecture/agent-harness.md b/docs/gitbooks/en/developing/architecture/agent-harness.mdindex 0f09c66ede..0bfc2a7c6c 100644--- a/docs/gitbooks/en/developing/architecture/agent-harness.md+++ b/docs/gitbooks/en/developing/architecture/agent-harness.md@@ -502,9 +502,10 @@ New/extended socket events (bridged from `DomainEvent` onto `WebChannelEvent` by- `ts` (epoch ms) is stamped on every event by `publish_web_channel_event` when the producer left it unset, so the frontend can order/measure latency without guessing at receive time.- `chat_done.timing`: `{ first_token_ms, first_tool_ms, total_ms, tokens_per_second }`, threaded from the progress bridge's per-turn `TurnTiming` through `ProgressBridgeHandle::timing_snapshot()`. `tokens_per_second` is derived from `output_tokens / (total_ms / 1000)` when both are known and `total_ms > 0`.+- `chat_done.usage.context_tokens`: input plus output tokens from the root agent's final model call. It feeds the context-window gauge and excludes earlier calls and sub-agents; `input_tokens` and `output_tokens` remain summed turn spend.- `chat_cancelled`: `{ thread_id, client_id, request_id, cancel_reason: "user_stop" | "superseded", superseded_by }`. Emitted alongside (not instead of) the existing `chat_error{error_type:"cancelled"}`, on both the unscoped/scoped stop path and the superseded-by-a-newer-request path, and on the parallel-turn cooperative-cancel path (which previously published no terminal event at all).- `chat_error{error_type:"guardrail"}`: carries a `guardrail: { verdict, score, reasons: [{code,message}] }` payload when `start_chat` rejects a message via `StartChatError::Guardrail` (the prompt-injection/security guardrail). Every other rejection stays `error_type:"inference"`. The RPC surface (`channel.web_chat`'s `Result<_, String>`) encodes the same structured verdict as a `GUARDRAIL:<json>` sentinel string (`web_chat::ops::start_chat::{GUARDRAIL_ERROR_PREFIX, is_guardrail_error_message}`, mirroring the existing `BACKEND_UNAVAILABLE:` pattern).-- `turn_cost`: live per-turn cost readout from `AgentProgress::TurnCostUpdated`, throttled to at most one emission per 750ms per turn (the first update always emits immediately): `{ thread_id, client_id, request_id, round, usage: { input_tokens, output_tokens, cached_input_tokens, cost_usd, context_window, subagents } }`. `subagents` is always empty on this live event (it is the parent's cumulative rollup only); per-sub-agent attribution still only shows up on the terminal `chat_done.usage`.+- `turn_cost`: live per-turn cost readout from `AgentProgress::TurnCostUpdated`, throttled to at most one emission per 750ms per turn (the first update always emits immediately): `{ thread_id, client_id, request_id, round, usage: { input_tokens, output_tokens, cached_input_tokens, cost_usd, context_window, context_tokens, subagents } }`. `context_tokens` is the root agent's final-call input plus output, for its context-window gauge; it is not summed over calls or sub-agents. `subagents` is always empty on this live event (it is the parent's cumulative rollup only); per-sub-agent attribution still only shows up on the terminal `chat_done.usage`.- `approval_decided` / `plan_review_decided`: bridged from `DomainEvent::ApprovalDecided` / `PlanReviewDecided`, which gained `thread_id`, `client_id`, `tool_call_id`, and `resolution` (`"expired"` on TTL/sweep, `"cancelled"` on a dropped decision channel, `None` for an ordinary user decision, carried on the wire as the existing `cancel_reason` field). Only surfaced when the original park had both `thread_id` and `client_id` (chat-routed).- `run_mode_changed`: `{ thread_id, client_id: "", message: "plan" | "build" }`, bridged from `DomainEvent::ThreadRunModeChanged`, published by `agent::tinyagents::run_mode::set_mode`.- `thread_todos_changed`, `queue_item_queued` / `queue_item_delivered` / `queue_item_removed`, `queue_item` carries `{ id, lane, text_preview }`.@@ -514,6 +515,7 @@ New/extended socket events (bridged from `DomainEvent` onto `WebChannelEvent` byNew RPCs:- `agent.set_run_mode { thread_id, mode }` / `agent.get_run_mode { thread_id }`, read/flip a thread's Plan/Build `RunModeHandle`. `channel.web_chat` also accepts an optional `run_mode: "plan" | "build"` param (mirroring the socket `chat:start` payload) so a turn can start with the thread already in the requested mode instead of racing a separate RPC call; unrecognized values are logged and ignored.+- `threads.token_usage { thread_id }`: returns persisted thread spend totals plus `last_turn_context_tokens`, the root agent's final-call input plus output used by the context-window gauge. Older turns without per-call usage fall back to their summed input plus output.- `threads.goal_get` / `threads.todos_get`: read a thread's current goal/todo state directly .- `threads.edit_message { thread_id, message_id, content, client_id? }` / `threads.regenerate { thread_id, message_id?, client_id? }`, both return `{ request_id }`. They cancel the thread's in-flight turn, fork the session transcript at a cut point via `TranscriptLocator::truncate_into_next_generation` (the sealed generation the fork was cut from is never touched, same "compaction never erases" guarantee), truncate the conversation-store message log and the turn-state snapshots for every dropped turn, then restart the turn with the edited content (`edit_message`) or the original prompt (`regenerate`). See `threads::ops::edit`'s module doc for the full UI-message-id -> transcript-cut-point mapping.- `channel.web_queue_remove { client_id, thread_id, item_id }`, remove one specific queued item from a thread's run queue.diff --git a/gitbooks/developing/architecture/agent-harness.md b/gitbooks/developing/architecture/agent-harness.mdindex a9f7f0d45a..e443da8ae1 100644--- a/gitbooks/developing/architecture/agent-harness.md+++ b/gitbooks/developing/architecture/agent-harness.md@@ -555,9 +555,10 @@ New/extended socket events (bridged from `DomainEvent` onto `WebChannelEvent` by- `ts` (epoch ms) is stamped on every event by `publish_web_channel_event` when the producer left it unset, so the frontend can order/measure latency without guessing at receive time.- `chat_done.timing`: `{ first_token_ms, first_tool_ms, total_ms, tokens_per_second }`, threaded from the progress bridge's per-turn `TurnTiming` through `ProgressBridgeHandle::timing_snapshot()`. `tokens_per_second` is derived from `output_tokens / (total_ms / 1000)` when both are known and `total_ms > 0`.+- `chat_done.usage.context_tokens`: input plus output tokens from the root agent's final model call. It feeds the context-window gauge and excludes earlier calls and sub-agents; `input_tokens` and `output_tokens` remain summed turn spend.- `chat_cancelled`: `{ thread_id, client_id, request_id, cancel_reason: "user_stop" | "superseded", superseded_by }`. Emitted alongside (not instead of) the existing `chat_error{error_type:"cancelled"}`, on both the unscoped/scoped stop path and the superseded-by-a-newer-request path, and on the parallel-turn cooperative-cancel path (which previously published no terminal event at all).- `chat_error{error_type:"guardrail"}`: carries a `guardrail: { verdict, score, reasons: [{code,message}] }` payload when `start_chat` rejects a message via `StartChatError::Guardrail` (the prompt-injection/security guardrail). Every other rejection stays `error_type:"inference"`. The RPC surface (`channel.web_chat`'s `Result<_, String>`) encodes the same structured verdict as a `GUARDRAIL:<json>` sentinel string (`web_chat::ops::start_chat::{GUARDRAIL_ERROR_PREFIX, is_guardrail_error_message}`, mirroring the existing `BACKEND_UNAVAILABLE:` pattern).-- `turn_cost`: live per-turn cost readout from `AgentProgress::TurnCostUpdated`, throttled to at most one emission per 750ms per turn (the first update always emits immediately): `{ thread_id, client_id, request_id, round, usage: { input_tokens, output_tokens, cached_input_tokens, cost_usd, context_window, subagents } }`. `subagents` is always empty on this live event (it is the parent's cumulative rollup only); per-sub-agent attribution still only shows up on the terminal `chat_done.usage`.+- `turn_cost`: live per-turn cost readout from `AgentProgress::TurnCostUpdated`, throttled to at most one emission per 750ms per turn (the first update always emits immediately): `{ thread_id, client_id, request_id, round, usage: { input_tokens, output_tokens, cached_input_tokens, cost_usd, context_window, context_tokens, subagents } }`. `context_tokens` is the root agent's final-call input plus output, for its context-window gauge; it is not summed over calls or sub-agents. `subagents` is always empty on this live event (it is the parent's cumulative rollup only); per-sub-agent attribution still only shows up on the terminal `chat_done.usage`.- `approval_decided` / `plan_review_decided`: bridged from `DomainEvent::ApprovalDecided` / `PlanReviewDecided`, which gained `thread_id`, `client_id`, `tool_call_id`, and `resolution` (`"expired"` on TTL/sweep, `"cancelled"` on a dropped decision channel, `None` for an ordinary user decision, carried on the wire as the existing `cancel_reason` field). Only surfaced when the original park had both `thread_id` and `client_id` (chat-routed).- `run_mode_changed`: `{ thread_id, client_id: "", message: "plan" | "build" }`, bridged from `DomainEvent::ThreadRunModeChanged`, published by `agent::tinyagents::run_mode::set_mode`.- `thread_todos_changed`, `queue_item_queued` / `queue_item_delivered` / `queue_item_removed`, `queue_item` carries `{ id, lane, text_preview }`.@@ -568,6 +569,7 @@ New RPCs:- `agent.set_run_mode { thread_id, mode }` / `agent.get_run_mode { thread_id }`, read/flip a thread's Plan/Build `RunModeHandle`. `channel.web_chat` also accepts an optional `run_mode: "plan" | "build"` param (mirroring the socket `chat:start` payload) so a turn can start with the thread already in the requested mode instead of racing a separate RPC call; unrecognized values are logged and ignored.- `threads.goal_get` / `threads.todos_get`: read a thread's current goal/todo state directly .+- `threads.token_usage { thread_id }`: returns persisted thread spend totals plus `last_turn_context_tokens`, the root agent's final-call input plus output used by the context-window gauge. Older turns without per-call usage fall back to their summed input plus output.- `threads.edit_message { thread_id, message_id, content, client_id? }` / `threads.regenerate { thread_id, message_id?, client_id? }`, both return `{ request_id }`. They cancel the thread's in-flight turn, fork the session transcript at a cut point via `TranscriptLocator::truncate_into_next_generation` (the sealed generation the fork was cut from is never touched, same "compaction never erases" guarantee), truncate the conversation-store message log and the turn-state snapshots for every dropped turn, then restart the turn with the edited content (`edit_message`) or the original prompt (`regenerate`). See `threads::ops::edit`'s module doc for the full UI-message-id -> transcript-cut-point mapping.- `channel.web_queue_remove { client_id, thread_id, item_id }`, remove one specific queued item from a thread's run queue.- `agent.context_breakdown { agent_id?, thread_id? }`, a UI-friendly view over the agent's rendered prompt size (system/tools/history split) for the composer's context-usage indicator.diff --git a/tests/json_rpc_e2e.rs b/tests/json_rpc_e2e.rsindex d9d41d1d77..fdaa478944 100644--- a/tests/json_rpc_e2e.rs+++ b/tests/json_rpc_e2e.rs@@ -2452,6 +2452,7 @@ fn json_rpc_protocol_auth_and_agent_hello() {async fn json_rpc_protocol_auth_and_agent_hello_inner() {let _env_lock = json_rpc_e2e_env_lock_async().await;+ let _scripted_fifo_guard = ScriptedFifoGuard;let tmp = tempdir().expect("tempdir");let home = tmp.path();let openhuman_home = home.join(".openhuman");@@ -2536,6 +2537,10 @@ async fn json_rpc_protocol_auth_and_agent_hello_inner() {let thread_id = "thread-1";let events_url = format!("{}/events?client_id={}", rpc_base, client_id);let sse_task = tokio::spawn(async move { read_terminal_web_chat_event(&events_url).await });+ push_forced_chat_completion_when(+ "Hello from web channel",+ forced_text_completion("Hello from e2e mock agent"),+ );let web_chat = post_json_rpc(&rpc_base,@@ -2566,6 +2571,13 @@ async fn json_rpc_protocol_auth_and_agent_hello_inner() {sse_event.get("thread_id").and_then(Value::as_str),Some(thread_id));+ assert_eq!(+ sse_event+ .pointer("/usage/context_tokens")+ .and_then(Value::as_u64),+ Some(20),+ "chat_done carries the final call's input plus output token count: {sse_event}"+ );assert!(!sse_event.get("full_response")