Skip to content

Commit a1988e7

Browse files
wspwsp
authored andcommitted
fix(context): Estimate composition on demand
Compute current context composition when the panel opens so compressed and forked sessions no longer depend on the latest request snapshot. Reuse each estimate for numeric breakdowns and content previews. Stop writing usage-context.json and per-request contextComposition. Keep legacy reads, usage accounting and runtime recovery data intact. Expose the additive query through Desktop and CLI Peer adapters, and show unavailable states when current context cannot be reconstructed. Cover compression, forks, read-only inspection, legacy payloads and UI refresh behavior with focused regression tests.
1 parent 242b615 commit a1988e7

44 files changed

Lines changed: 1082 additions & 1959 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/features/session-runtime-usage-report-design.md‎

Lines changed: 0 additions & 1763 deletions
This file was deleted.

‎src/apps/cli/src/dispatch/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -421,6 +421,7 @@ async fn query_in_store(
421421
remote_ssh_host: None,
422422
include_system_prompt_preview: false,
423423
context_preview_category: None,
424+
context_estimate: None,
424425
include_hidden_subagents: false,
425426
},
426427
)

‎src/apps/cli/src/management.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -572,6 +572,7 @@ pub(crate) async fn print_usage_report(session_id: Option<&str>) -> Result<()> {
572572
remote_ssh_host: None,
573573
include_system_prompt_preview: false,
574574
context_preview_category: None,
575+
context_estimate: None,
575576
include_hidden_subagents: true,
576577
})
577578
.await

‎src/apps/cli/src/modes/chat/selection.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,7 @@ impl ChatMode {
316316
remote_ssh_host: None,
317317
include_system_prompt_preview: false,
318318
context_preview_category: None,
319+
context_estimate: None,
319320
include_hidden_subagents: true,
320321
})
321322
.await

‎src/apps/cli/src/peer_host/commands/session.rs‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1128,6 +1128,7 @@ pub(crate) async fn get_session_usage_report(
11281128
include_hidden_subagents: options.include_hidden_subagents,
11291129
include_system_prompt_preview: options.include_system_prompt_preview,
11301130
context_preview_category: options.context_preview_category,
1131+
context_estimate: options.context_estimate,
11311132
})
11321133
.await
11331134
.map_err(|error| {
@@ -1147,6 +1148,7 @@ struct UsageReportOptions {
11471148
include_hidden_subagents: bool,
11481149
include_system_prompt_preview: bool,
11491150
context_preview_category: Option<openbitfun_core_types::UsageContextCategory>,
1151+
context_estimate: Option<openbitfun_core_types::UsageContextEstimateRequest>,
11501152
}
11511153

11521154
/// Reads the Desktop `GetSessionUsageReportRequest` option fields with the
@@ -1166,6 +1168,13 @@ fn usage_report_options(request: &Value) -> Result<UsageReportOptions, String> {
11661168
include_system_prompt_preview: optional_bool(request, "includeSystemPromptPreview")
11671169
.unwrap_or(false),
11681170
context_preview_category,
1171+
context_estimate: ["contextEstimate", "context_estimate"]
1172+
.iter()
1173+
.find_map(|key| request.get(*key))
1174+
.filter(|value| !value.is_null())
1175+
.map(|value| serde_json::from_value(value.clone()))
1176+
.transpose()
1177+
.map_err(|error| format!("Invalid context estimate options: {error}"))?,
11691178
})
11701179
}
11711180

@@ -1226,6 +1235,7 @@ mod tests {
12261235
include_hidden_subagents: true,
12271236
include_system_prompt_preview: false,
12281237
context_preview_category: None,
1238+
context_estimate: None,
12291239
}
12301240
);
12311241
let snake = json!({
@@ -1239,6 +1249,7 @@ mod tests {
12391249
include_hidden_subagents: false,
12401250
include_system_prompt_preview: true,
12411251
context_preview_category: Some(UsageContextCategory::ToolDefinitions),
1252+
context_estimate: None,
12421253
}
12431254
);
12441255
// A category a newer controller knows maps to Unknown instead of failing.
@@ -1249,6 +1260,19 @@ mod tests {
12491260
.context_preview_category,
12501261
Some(UsageContextCategory::Unknown)
12511262
);
1263+
for key in ["contextEstimate", "context_estimate"] {
1264+
let options = super::usage_report_options(
1265+
&json!({key: {"includeContents": true, "contextOnly": true}}),
1266+
)
1267+
.unwrap();
1268+
assert_eq!(
1269+
options.context_estimate,
1270+
Some(openbitfun_core_types::UsageContextEstimateRequest {
1271+
include_contents: true,
1272+
context_only: true,
1273+
})
1274+
);
1275+
}
12521276
assert!(super::usage_report_options(&json!({ "context_preview_category": 3 })).is_err());
12531277
}
12541278

‎src/apps/desktop/AGENTS.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,3 +463,7 @@ Use `-- --include-ignored` with `latexmk`, pdfLaTeX, and XeLaTeX on PATH to
463463
exercise a multi-file paper build, error diagnostics, and temporary output.
464464
The POSIX build test checks the remote command in a local shell. Verify live
465465
SSH, container, and peer routing separately.
466+
467+
For additive on-demand context-estimate requests and legacy payload defaults:
468+
`cargo test --locked -p openbitfun-desktop --no-default-features --lib context_estimate_request_tests`.
469+
This verifies the Desktop boundary, not a live Peer or remote workspace.

‎src/apps/desktop/src/api/session_api.rs‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,8 @@ pub struct GetSessionUsageReportRequest {
242242
pub include_system_prompt_preview: bool,
243243
#[serde(default, skip_serializing_if = "Option::is_none")]
244244
pub context_preview_category: Option<openbitfun_core_types::UsageContextCategory>,
245+
#[serde(default)]
246+
pub context_estimate: Option<openbitfun_core_types::UsageContextEstimateRequest>,
245247
}
246248

247249
fn default_include_hidden_subagents() -> bool {
@@ -567,6 +569,7 @@ pub async fn get_session_usage_report(
567569
request.include_hidden_subagents,
568570
request.include_system_prompt_preview,
569571
request.context_preview_category,
572+
request.context_estimate,
570573
)
571574
.await
572575
.map_err(|error| {
@@ -970,3 +973,25 @@ mod catalog_request_tests {
970973
assert_eq!(serde_json::to_value(request).unwrap(), current);
971974
}
972975
}
976+
977+
#[cfg(test)]
978+
mod context_estimate_request_tests {
979+
use super::*;
980+
981+
#[test]
982+
fn current_context_estimate_preserves_legacy_request_defaults() {
983+
let legacy = serde_json::json!({"session_id": "session-1", "workspace_id": "workspace-1"});
984+
let request: GetSessionUsageReportRequest = serde_json::from_value(legacy.clone()).unwrap();
985+
assert!(request.context_estimate.is_none());
986+
assert!(request.include_hidden_subagents);
987+
let mut current = legacy;
988+
current["context_estimate"] =
989+
serde_json::json!({"includeContents": true, "contextOnly": true});
990+
let request: GetSessionUsageReportRequest = serde_json::from_value(current).unwrap();
991+
let restored: GetSessionUsageReportRequest =
992+
serde_json::from_value(serde_json::to_value(request).unwrap()).unwrap();
993+
let options = restored.context_estimate.unwrap();
994+
assert!(options.include_contents);
995+
assert!(options.context_only);
996+
}
997+
}

‎src/apps/desktop/src/runtime/session_application.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -606,6 +606,7 @@ impl DesktopSessionApplication {
606606
include_hidden_subagents: bool,
607607
include_system_prompt_preview: bool,
608608
context_preview_category: Option<openbitfun_core_types::UsageContextCategory>,
609+
context_estimate: Option<openbitfun_core_types::UsageContextEstimateRequest>,
609610
) -> DesktopSessionApplicationResult<SessionUsageReport> {
610611
let scope = self.resolved_scope(request).await?;
611612
let storage_path = self.storage_path(&scope);
@@ -620,6 +621,7 @@ impl DesktopSessionApplication {
620621
include_hidden_subagents,
621622
include_system_prompt_preview,
622623
context_preview_category,
624+
context_estimate,
623625
})
624626
.await
625627
.map_err(|error| DesktopSessionApplicationError::Runtime(error.into_message()))?;

‎src/crates/assembly/core/src/agentic/coordination/coordinator.rs‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2861,6 +2861,48 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet
28612861
.await
28622862
}
28632863

2864+
/// Resolve prompt sources after the caller has released the session read permit.
2865+
pub(crate) async fn estimate_session_context(
2866+
&self,
2867+
inputs: crate::agentic::session::session_manager::ContextEstimateInputs,
2868+
options: &openbitfun_core_types::UsageContextEstimateRequest,
2869+
) -> OpenBitFunResult<openbitfun_core_types::UsageContextEstimate> {
2870+
let workspace = Self::build_workspace_binding(&inputs.session.config)
2871+
.await
2872+
.ok_or_else(|| {
2873+
OpenBitFunError::validation(
2874+
"Session workspace is unavailable for context inspection",
2875+
)
2876+
})?;
2877+
let services = Self::build_workspace_services(&Some(workspace.clone())).await?;
2878+
let restrictions = runtime_tool_restrictions_for_session_lifetime(
2879+
miniapp_agent_run_tool_restrictions(
2880+
inputs.turn_metadata.as_ref(),
2881+
inputs.session.created_by.as_deref(),
2882+
),
2883+
self.session_manager
2884+
.is_transient_session(&inputs.session.session_id),
2885+
);
2886+
let mut context_vars = HashMap::new();
2887+
copy_turn_control_context(&mut context_vars, inputs.turn_metadata.as_ref());
2888+
Self::copy_output_schema_context(&mut context_vars, inputs.turn_metadata.as_ref());
2889+
if metadata_bool(inputs.turn_metadata.as_ref(), "acp_transport") == Some(true) {
2890+
context_vars.insert("acp_transport".into(), "true".into());
2891+
}
2892+
self.execution_engine
2893+
.estimate_current_context(
2894+
inputs,
2895+
workspace,
2896+
services,
2897+
self.terminal_port.get(),
2898+
self.remote_exec_port.get(),
2899+
restrictions,
2900+
context_vars,
2901+
options,
2902+
)
2903+
.await
2904+
}
2905+
28642906
pub async fn retry_model_pool_member(&self, model_id: &str) -> OpenBitFunResult<()> {
28652907
self.execution_engine
28662908
.model_pools

‎src/crates/assembly/core/src/agentic/execution/AGENTS.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -432,3 +432,13 @@ cargo test --locked -p openbitfun-core --no-default-features --features agent-ru
432432

433433
This delayed loopback HTTP fixture separates response headers, metadata and model
434434
output. It does not exercise a real provider or remote host.
435+
436+
For on-demand context composition, compression/fork recovery without display
437+
snapshots, and request-ledger independence:
438+
439+
```bash
440+
cargo test --locked -p openbitfun-core --no-default-features --features agent-runtime,git --lib -- current_context_estimate context_composition account_attempt_ledger_keeps_failed_usage_actual_accounts_and_idempotent_events
441+
```
442+
443+
These local fixtures cover read-only persistence and typed estimates, not live
444+
remote workspace, Peer, relay, or detached transports.

0 commit comments

Comments
 (0)