Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -849,7 +849,7 @@
"visibility": "documented",
"rustPath": "api::insights_api::cancel_insights_generation",
"sourceFile": "src/apps/desktop/src/api/insights_api.rs",
"signature": "fn cancel_insights_generation() -> Result<(), String>",
"signature": "fn cancel_insights_generation( request: Option<CancelInsightsRequest>, ) -> Result<(), String>",
"remoteWorkspacePolicy": "LocalOnly"
},
{
Expand Down
44 changes: 38 additions & 6 deletions src/apps/desktop/src/api/insights_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use serde::Deserialize;
pub struct GenerateInsightsRequest {
pub days: Option<u32>,
pub model_id: Option<String>,
pub generation_id: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
Expand All @@ -15,6 +16,12 @@ pub struct LoadInsightsReportRequest {
pub path: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelInsightsRequest {
pub generation_id: Option<String>,
}

#[tauri::command]
pub async fn generate_insights(request: GenerateInsightsRequest) -> Result<InsightsReport, String> {
let days = request.days.unwrap_or(30);
Expand All @@ -24,7 +31,7 @@ pub async fn generate_insights(request: GenerateInsightsRequest) -> Result<Insig
days, model_id
);

InsightsService::generate(days, model_id)
InsightsService::generate(days, model_id, request.generation_id)
.await
.map_err(|e| {
error!("Failed to generate insights: {}", e);
Expand Down Expand Up @@ -62,9 +69,34 @@ pub async fn has_insights_data(request: GenerateInsightsRequest) -> Result<bool,
}

#[tauri::command]
pub async fn cancel_insights_generation() -> Result<(), String> {
InsightsService::cancel().await.map_err(|e| {
error!("Failed to cancel insights generation: {}", e);
e
})
pub async fn cancel_insights_generation(
request: Option<CancelInsightsRequest>,
) -> Result<(), String> {
let generation_id = request.and_then(|request| request.generation_id);
InsightsService::cancel(generation_id.as_deref())
.await
.map_err(|e| {
error!("Failed to cancel insights generation: {}", e);
e
})
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn accepts_legacy_generation_requests_and_correlated_requests() {
let legacy: GenerateInsightsRequest =
serde_json::from_value(serde_json::json!({ "days": 7, "modelId": "primary" })).unwrap();
assert_eq!(legacy.days, Some(7));
assert_eq!(legacy.model_id.as_deref(), Some("primary"));
assert_eq!(legacy.generation_id, None);

let current: GenerateInsightsRequest =
serde_json::from_value(serde_json::json!({ "generationId": "run-new" })).unwrap();
let cancel: CancelInsightsRequest =
serde_json::from_value(serde_json::json!({ "generationId": "run-new" })).unwrap();
assert_eq!(current.generation_id, cancel.generation_id);
}
}
110 changes: 77 additions & 33 deletions src/crates/assembly/core/src/agentic/insights/cancellation.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,43 @@
use log::{debug, info, warn};
use crate::{OpenBitFunError, OpenBitFunResult};
use log::{debug, info};
use std::future::Future;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio_util::sync::CancellationToken;

#[derive(Clone)]
pub struct Registration {
pub id: u64,
pub token: CancellationToken,
pub client_id: Option<String>,
}

type Slot = Arc<Mutex<Option<Registration>>>;

static SLOT: std::sync::OnceLock<Slot> = std::sync::OnceLock::new();
static SLOT: Mutex<Option<Registration>> = Mutex::const_new(None);
static NEXT_ID: AtomicU64 = AtomicU64::new(1);

fn get_slot() -> Slot {
SLOT.get_or_init(|| Arc::new(Mutex::new(None))).clone()
/// One pipeline at a time, including the publication of its final report.
pub static PIPELINE: Mutex<()> = Mutex::const_new(());

pub async fn run_until_cancelled<T>(
token: &CancellationToken,
work: impl Future<Output = OpenBitFunResult<T>>,
) -> OpenBitFunResult<T> {
tokio::select! {
biased;
_ = token.cancelled() => Err(OpenBitFunError::service("Insights generation cancelled")),
result = work => result,
}
}

/// Registers a new insights generation task, cancelling any previous one.
pub async fn register() -> Registration {
pub async fn register(client_id: Option<String>) -> Registration {
let token = CancellationToken::new();
let registration = Registration {
id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
token: token.clone(),
token,
client_id,
};
let arc = get_slot();
let mut slot = arc.lock().await;
let mut slot = SLOT.lock().await;
if let Some(old) = slot.take() {
old.token.cancel();
debug!("Cancelled previous insights generation");
Expand All @@ -37,49 +47,83 @@ pub async fn register() -> Registration {
}

/// Cancels the current insights generation task.
pub async fn cancel() -> Result<(), String> {
let arc = get_slot();
let mut slot = arc.lock().await;
match slot.take() {
Some(token) => {
token.token.cancel();
info!("Insights generation cancelled by user");
Ok(())
}
None => {
warn!("No insights generation in progress to cancel");
Err("No insights generation in progress".into())
}
}
pub async fn cancel(client_id: Option<&str>) -> Result<(), String> {
let slot = SLOT.lock().await;
let current = slot
.as_ref()
.filter(|current| client_id.is_none() || current.client_id.as_deref() == client_id)
.ok_or_else(|| "No matching insights generation in progress".to_string())?;
current.token.cancel();
info!("Insights generation cancelled by user");
Ok(())
}

/// Unregisters the current task (call on completion).
pub async fn unregister(registration_id: u64) {
let arc = get_slot();
let mut slot = arc.lock().await;
/// Only the still-current, uncancelled generation may publish a report.
pub async fn claim_completion(id: u64) -> bool {
let mut slot = SLOT.lock().await;
if slot
.as_ref()
.is_some_and(|current| current.id == registration_id)
.is_some_and(|current| current.id == id && !current.token.is_cancelled())
{
*slot = None;
true
} else {
false
}
}

pub async fn unregister(id: u64) {
let mut slot = SLOT.lock().await;
if slot.as_ref().is_some_and(|current| current.id == id) {
*slot = None;
}
}

#[cfg(test)]
mod tests {
use super::*;

#[tokio::test]
async fn cancelling_pipeline_drops_in_flight_work_without_waiting_for_a_model() {
struct InFlight<'a>(&'a std::sync::atomic::AtomicUsize);
impl Drop for InFlight<'_> {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::SeqCst);
}
}

let token = CancellationToken::new();
let active = std::sync::atomic::AtomicUsize::new(0);
let calls = async {
active.fetch_add(1, Ordering::SeqCst);
let _request = InFlight(&active);
std::future::pending::<OpenBitFunResult<()>>().await
};
let mut pipeline = Box::pin(run_until_cancelled(&token, calls));
let mut context = std::task::Context::from_waker(std::task::Waker::noop());
assert!(pipeline.as_mut().poll(&mut context).is_pending());
assert_eq!(active.load(Ordering::SeqCst), 1);
token.cancel();
assert!(pipeline.await.is_err());
assert_eq!(active.load(Ordering::SeqCst), 0);
}

#[tokio::test]
async fn old_task_cannot_unregister_a_new_generation() {
let old = register().await;
let current = register().await;
let old = register(Some("old".to_string())).await;
let current = register(Some("current".to_string())).await;
assert!(old.token.is_cancelled());

unregister(old.id).await;
cancel()
assert!(cancel(Some("old")).await.is_err());
assert!(!current.token.is_cancelled());
assert!(!claim_completion(old.id).await);
cancel(Some("current"))
.await
.expect("current generation remains registered");

assert!(current.token.is_cancelled());
assert!(!claim_completion(current.id).await);
unregister(current.id).await;
}
}
15 changes: 12 additions & 3 deletions src/crates/assembly/core/src/agentic/insights/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ impl InsightsCollector {
duration_minutes,
unix_ms_to_iso(first_activity_ms),
);
transcript.workspace_path = Some(workspace_path.to_string_lossy().to_string());
transcript.session_storage_scope = Some(ws_path.to_string_lossy().into_owned());
transcript.last_activity_unix_secs = last_activity_ms / 1000;

update_date_bounds(&mut base_stats, first_activity_ms, last_activity_ms);
Expand All @@ -222,8 +222,13 @@ impl InsightsCollector {
message_count,
duration_millis,
);
let execution_workspace_id = session
.config
.workspace_id
.as_deref()
.unwrap_or(&target.workspace_id);
for path in
accumulate_code_stats(&mut base_stats, &target.workspace_id, &selected_turns)
accumulate_code_stats(&mut base_stats, execution_workspace_id, &selected_turns)
.await
{
modified_files.insert((target.workspace_id.clone(), path));
Expand Down Expand Up @@ -331,7 +336,7 @@ impl InsightsCollector {
session_id: session_id.to_string(),
agent_type: session.agent_type.clone(),
session_name: session.session_name.clone(),
workspace_path: None,
session_storage_scope: None,
last_activity_unix_secs: 0,
duration_minutes,
message_count: message_count as u32,
Expand Down Expand Up @@ -387,6 +392,10 @@ impl InsightsCollector {
let dt = DateTime::<Local>::from(UNIX_EPOCH + Duration::from_millis(turn.start_time));
let hour = dt.format("%H").to_string().parse::<u32>().unwrap_or(0);
*base_stats.hour_counts.entry(hour).or_insert(0) += 1;
*base_stats
.activity_by_utc_minute
.entry(turn.start_time / 60_000)
.or_default() += 1;

if let Some(previous_end_ms) = previous_end_ms {
let response_ms = turn.start_time.saturating_sub(previous_end_ms);
Expand Down
Loading
Loading