diff --git a/docs/interactive-capabilities/technical/tauri-command-map.json b/docs/interactive-capabilities/technical/tauri-command-map.json index 7f4026a0a5..98d8f037f6 100644 --- a/docs/interactive-capabilities/technical/tauri-command-map.json +++ b/docs/interactive-capabilities/technical/tauri-command-map.json @@ -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, ) -> Result<(), String>", "remoteWorkspacePolicy": "LocalOnly" }, { diff --git a/src/apps/desktop/src/api/insights_api.rs b/src/apps/desktop/src/api/insights_api.rs index dd96e1f37f..e291e32f68 100644 --- a/src/apps/desktop/src/api/insights_api.rs +++ b/src/apps/desktop/src/api/insights_api.rs @@ -7,6 +7,7 @@ use serde::Deserialize; pub struct GenerateInsightsRequest { pub days: Option, pub model_id: Option, + pub generation_id: Option, } #[derive(Debug, Clone, Deserialize)] @@ -15,6 +16,12 @@ pub struct LoadInsightsReportRequest { pub path: String, } +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CancelInsightsRequest { + pub generation_id: Option, +} + #[tauri::command] pub async fn generate_insights(request: GenerateInsightsRequest) -> Result { let days = request.days.unwrap_or(30); @@ -24,7 +31,7 @@ pub async fn generate_insights(request: GenerateInsightsRequest) -> Result Result Result<(), String> { - InsightsService::cancel().await.map_err(|e| { - error!("Failed to cancel insights generation: {}", e); - e - }) +pub async fn cancel_insights_generation( + request: Option, +) -> 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); + } } diff --git a/src/crates/assembly/core/src/agentic/insights/cancellation.rs b/src/crates/assembly/core/src/agentic/insights/cancellation.rs index 0870977110..f1b9900212 100644 --- a/src/crates/assembly/core/src/agentic/insights/cancellation.rs +++ b/src/crates/assembly/core/src/agentic/insights/cancellation.rs @@ -1,6 +1,7 @@ -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; @@ -8,26 +9,35 @@ use tokio_util::sync::CancellationToken; pub struct Registration { pub id: u64, pub token: CancellationToken, + pub client_id: Option, } -type Slot = Arc>>; - -static SLOT: std::sync::OnceLock = std::sync::OnceLock::new(); +static SLOT: Mutex> = 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( + token: &CancellationToken, + work: impl Future>, +) -> OpenBitFunResult { + 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) -> 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"); @@ -37,31 +47,35 @@ 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; } } @@ -69,17 +83,47 @@ pub async fn unregister(registration_id: u64) { 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::>().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; } } diff --git a/src/crates/assembly/core/src/agentic/insights/collector.rs b/src/crates/assembly/core/src/agentic/insights/collector.rs index d4482ff7b0..b8a630c262 100644 --- a/src/crates/assembly/core/src/agentic/insights/collector.rs +++ b/src/crates/assembly/core/src/agentic/insights/collector.rs @@ -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); @@ -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)); @@ -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, @@ -387,6 +392,10 @@ impl InsightsCollector { let dt = DateTime::::from(UNIX_EPOCH + Duration::from_millis(turn.start_time)); let hour = dt.format("%H").to_string().parse::().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); diff --git a/src/crates/assembly/core/src/agentic/insights/facet_cache.rs b/src/crates/assembly/core/src/agentic/insights/facet_cache.rs index d7e4219f1f..1cf541dbdf 100644 --- a/src/crates/assembly/core/src/agentic/insights/facet_cache.rs +++ b/src/crates/assembly/core/src/agentic/insights/facet_cache.rs @@ -4,6 +4,7 @@ use crate::agentic::insights::types::{SessionFacet, SessionTranscript}; use crate::infrastructure::get_path_manager_arc; use crate::util::errors::OpenBitFunResult; use log::debug; +use openbitfun_services_core::json_store::JsonFileStore; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use tokio::fs; @@ -16,19 +17,29 @@ struct CachedFacetFile { facet: SessionFacet, } -pub fn compute_fingerprint(transcript: &SessionTranscript) -> String { +fn compute_fingerprint( + transcript: &SessionTranscript, + model_identity: &[&str], + prompt: &str, +) -> String { let mut hasher = Sha256::new(); - if let Some(workspace_path) = transcript.workspace_path.as_deref() { - hasher.update(workspace_path.as_bytes()); + hasher.update(transcript.last_activity_unix_secs.to_be_bytes()); + hasher.update(transcript.turn_count.to_be_bytes()); + for part in [ + "insights-facet-v2", + transcript + .session_storage_scope + .as_deref() + .unwrap_or_default(), + &transcript.session_id, + ] + .into_iter() + .chain(model_identity.iter().copied()) + .chain(std::iter::once(prompt)) + { + hasher.update((part.len() as u64).to_be_bytes()); + hasher.update(part.as_bytes()); } - hasher.update(b"|"); - hasher.update(transcript.session_id.as_bytes()); - hasher.update(b"|"); - hasher.update(transcript.last_activity_unix_secs.to_string().as_bytes()); - hasher.update(b"|"); - hasher.update(transcript.turn_count.to_string().as_bytes()); - hasher.update(b"|"); - hasher.update(transcript.transcript.as_bytes()); format!("{:x}", hasher.finalize()) } @@ -40,7 +51,7 @@ fn cache_file_path(transcript: &SessionTranscript) -> OpenBitFunResult|".contains(c) { '_' } else { c }) .collect::(); let mut workspace_hasher = Sha256::new(); - if let Some(workspace_path) = transcript.workspace_path.as_deref() { + if let Some(workspace_path) = transcript.session_storage_scope.as_deref() { workspace_hasher.update(workspace_path.as_bytes()); } let workspace_hash = format!("{:x}", workspace_hasher.finalize()); @@ -52,6 +63,8 @@ fn cache_file_path(transcript: &SessionTranscript) -> OpenBitFunResult OpenBitFunResult> { let path = match cache_file_path(transcript) { Ok(p) => p, @@ -65,7 +78,7 @@ pub async fn try_load_cached_facet( Ok(v) => v, Err(_) => return Ok(None), }; - let want = compute_fingerprint(transcript); + let want = compute_fingerprint(transcript, model_identity, prompt); if parsed.fingerprint != want { return Ok(None); } @@ -75,17 +88,21 @@ pub async fn try_load_cached_facet( pub async fn save_cached_facet( transcript: &SessionTranscript, facet: &SessionFacet, + model_identity: &[&str], + prompt: &str, ) -> OpenBitFunResult<()> { let path = cache_file_path(transcript)?; if let Some(parent) = path.parent() { fs::create_dir_all(parent).await?; } let payload = CachedFacetFile { - fingerprint: compute_fingerprint(transcript), + fingerprint: compute_fingerprint(transcript, model_identity, prompt), facet: facet.clone(), }; - let json = serde_json::to_string_pretty(&payload)?; - fs::write(&path, json).await?; + JsonFileStore + .write_atomic_strict(&path, &payload) + .await + .map_err(|error| crate::OpenBitFunError::io(error.to_string()))?; debug!("Saved facet cache {}", path.display()); Ok(()) } @@ -99,7 +116,7 @@ mod tests { session_id: "same-session".to_string(), agent_type: "Standard".to_string(), session_name: "Session".to_string(), - workspace_path: Some(workspace_path.to_string()), + session_storage_scope: Some(workspace_path.to_string()), last_activity_unix_secs: 10, duration_minutes: 1, message_count: 2, @@ -111,11 +128,24 @@ mod tests { } } + #[test] + fn changing_model_language_or_template_invalidates_the_fingerprint() { + let transcript = transcript("workspace-a"); + let baseline = compute_fingerprint(&transcript, &["model-a"], "Analyze in English"); + for (model, prompt) in [ + ("model-b", "Analyze in English"), + ("model-a", "Analyze in Chinese"), + ("model-a", "Summarize in English"), + ] { + assert_ne!(baseline, compute_fingerprint(&transcript, &[model], prompt)); + } + } + #[test] fn fingerprint_is_scoped_by_workspace() { assert_ne!( - compute_fingerprint(&transcript("workspace-a")), - compute_fingerprint(&transcript("workspace-b")) + compute_fingerprint(&transcript("workspace-a"), &["model"], "prompt"), + compute_fingerprint(&transcript("workspace-b"), &["model"], "prompt") ); } } diff --git a/src/crates/assembly/core/src/agentic/insights/html.rs b/src/crates/assembly/core/src/agentic/insights/html.rs index 104dfe657d..8807c84e3f 100644 --- a/src/crates/assembly/core/src/agentic/insights/html.rs +++ b/src/crates/assembly/core/src/agentic/insights/html.rs @@ -1,9 +1,11 @@ use crate::agentic::insights::types::*; +use crate::service::i18n::LocaleId; /// All user-visible labels in the HTML report, supporting i18n. pub struct HtmlLabels { pub title: &'static str, pub subtitle_template: &'static str, // "{msgs} messages across {sessions} sessions ({analyzed} analyzed) | {start} to {end}" + pub partial_report: &'static str, pub at_a_glance: &'static str, pub whats_working: &'static str, pub whats_hindering: &'static str, @@ -52,6 +54,7 @@ pub struct HtmlLabels { pub no_friction: &'static str, pub no_horizon: &'static str, pub md_additions: &'static str, + pub copy: &'static str, pub copy_all_checked: &'static str, pub features_to_try: &'static str, pub usage_patterns: &'static str, @@ -64,11 +67,11 @@ pub struct HtmlLabels { } impl HtmlLabels { - pub fn for_locale(locale: &str) -> Self { - if locale.starts_with("zh") { - Self::zh() - } else { - Self::en() + pub fn for_locale(locale: LocaleId) -> Self { + match locale { + LocaleId::EnUS => Self::en(), + LocaleId::ZhCN => Self::zh(), + LocaleId::ZhTW => Self::zh_tw(), } } @@ -76,6 +79,7 @@ impl HtmlLabels { HtmlLabels { title: "OpenBitFun Insights", subtitle_template: "{msgs} messages across {sessions} sessions ({analyzed} analyzed) | {start} to {end}", + partial_report: "Partial report. {failed} report sections failed.", at_a_glance: "At a Glance", whats_working: "What's working:", whats_hindering: "What's hindering you:", @@ -124,6 +128,7 @@ impl HtmlLabels { no_friction: "No significant friction points found.", no_horizon: "No horizon workflows identified.", md_additions: "OPENBITFUN.md Additions", + copy: "Copy", copy_all_checked: "Copy All Checked", features_to_try: "Features to Try", usage_patterns: "Usage Patterns", @@ -141,6 +146,7 @@ impl HtmlLabels { title: "OpenBitFun 洞察", subtitle_template: "{msgs} 条消息,{sessions} 个会话({analyzed} 个已分析)| {start} 至 {end}", + partial_report: "报告部分生成。{failed} 个报告章节生成失败。", at_a_glance: "概览", whats_working: "做得好的:", whats_hindering: "遇到的阻碍:", @@ -189,6 +195,7 @@ impl HtmlLabels { no_friction: "未发现明显摩擦点。", no_horizon: "暂未识别到未来工作流。", md_additions: "OPENBITFUN.md 补充", + copy: "复制", copy_all_checked: "复制选中项", features_to_try: "推荐功能", usage_patterns: "使用模式", @@ -200,9 +207,76 @@ impl HtmlLabels { stat_files: "文件", } } + + fn zh_tw() -> Self { + HtmlLabels { + title: "OpenBitFun 洞察", + subtitle_template: + "{msgs} 則訊息,{sessions} 個會話({analyzed} 個已分析)| {start} 至 {end}", + partial_report: "報告部分產生。{failed} 個報告章節產生失敗。", + at_a_glance: "概覽", + whats_working: "做得好的:", + whats_hindering: "遇到的阻礙:", + quick_wins: "快速改善:", + looking_ahead: "展望未來:", + nav_work: "工作領域", + nav_usage: "使用方式", + nav_wins: "亮眼成果", + nav_friction: "問題所在", + nav_suggestions: "建議", + nav_horizon: "未來展望", + stat_sessions: "會話", + stat_messages: "訊息", + stat_hours: "小時", + stat_days: "天", + stat_msgs_per_day: "訊息/天", + stat_median_response: "回應時間中位數", + stat_avg_response: "平均回應時間", + section_work: "工作領域", + section_usage: "你如何使用 OpenBitFun", + section_wins: "亮眼成果", + section_friction: "問題所在", + section_suggestions: "建議", + section_horizon: "未來展望", + chart_goals: "你的需求", + chart_tools: "常用工具", + chart_languages: "程式語言", + chart_session_types: "會話類型", + chart_tool_errors: "工具錯誤統計", + chart_agent_types: "智慧體類型", + chart_response_time: "使用者回應時間分布", + chart_time_of_day: "依時段分布", + chart_what_helped: "最有幫助的部分", + chart_outcomes: "結果分布", + chart_friction_types: "主要阻礙類型", + chart_satisfaction: "滿意度(推估)", + time_morning: "上午 (6-12)", + time_afternoon: "下午 (12-18)", + time_evening: "晚上 (18-24)", + time_night: "凌晨 (0-6)", + sessions_suffix: "個會話", + no_data: "暫無資料", + no_project_areas: "未辨識出專案領域。", + no_interaction_style: "暫無互動風格資料。", + no_big_wins: "尚未辨識出亮眼成果。", + no_friction: "未發現明顯的阻礙。", + no_horizon: "尚未辨識出未來的工作流程。", + md_additions: "OPENBITFUN.md 補充", + copy: "複製", + copy_all_checked: "複製選取項目", + features_to_try: "推薦功能", + usage_patterns: "使用模式", + try_this_prompt: "試試這個提示:", + copied: "已複製!", + median_label: "中位數", + average_label: "平均值", + stat_lines: "行", + stat_files: "檔案", + } + } } -pub fn generate_html(report: &InsightsReport, locale: &str) -> String { +pub fn generate_html(report: &InsightsReport, locale: LocaleId) -> String { let l = HtmlLabels::for_locale(locale); let subtitle = l @@ -212,13 +286,31 @@ pub fn generate_html(report: &InsightsReport, locale: &str) -> String { .replace("{analyzed}", &report.analyzed_sessions.to_string()) .replace( "{start}", - &report.date_range.start[..10.min(report.date_range.start.len())], + report + .date_range + .start + .split('T') + .next() + .unwrap_or_default(), ) .replace( "{end}", - &report.date_range.end[..10.min(report.date_range.end.len())], + report.date_range.end.split('T').next().unwrap_or_default(), ); + let partial_notice = + if report.analyzed_sessions < report.total_sessions || report.failed_sections != 0 { + format!( + "

{}

", + html_escape( + &l.partial_report + .replace("{failed}", &report.failed_sections.to_string()) + ) + ) + } else { + String::new() + }; + let at_a_glance = render_at_a_glance(&report.at_a_glance, &l); let nav_toc = render_nav_toc(&l); let stats_row = render_stats_row(report, &l); @@ -256,7 +348,7 @@ pub fn generate_html(report: &InsightsReport, locale: &str) -> String { format!( r#" - + {page_title} @@ -269,6 +361,7 @@ pub fn generate_html(report: &InsightsReport, locale: &str) -> String {

{page_title}

{subtitle}

+ {partial_notice} {at_a_glance} {nav_toc} @@ -309,6 +402,7 @@ pub fn generate_html(report: &InsightsReport, locale: &str) -> String { "#, + lang = locale.as_str(), CSS = CSS_STYLES, JS = js_with_labels, page_title = html_escape(l.title), @@ -525,7 +619,7 @@ fn render_usage_charts(stats: &InsightsStats, l: &HtmlLabels) -> String { html.push_str(&response_time_chart); } - let time_of_day_chart = render_time_of_day_chart(&stats.hour_counts, l); + let time_of_day_chart = render_time_of_day_chart(stats, l); let mut tool_error_items: Vec<(String, u32)> = stats .tool_errors @@ -687,41 +781,45 @@ fn render_response_time_chart( ) } -fn render_time_of_day_chart( - hour_counts: &std::collections::HashMap, - l: &HtmlLabels, -) -> String { - if hour_counts.is_empty() { - return format!( - r#"
{}
{}
"#, - html_escape(l.chart_time_of_day), - html_escape(l.no_data), - ); - } +const TIME_PERIODS: [std::ops::Range; 4] = [6..12, 12..18, 18..24, 0..6]; - let hour_json: Vec = (0..24) - .map(|h| format!("\"{}\":{}", h, hour_counts.get(&h).copied().unwrap_or(0))) - .collect(); +fn render_time_of_day_chart(stats: &InsightsStats, l: &HtmlLabels) -> String { + let labels = [ + l.time_morning, + l.time_afternoon, + l.time_evening, + l.time_night, + ]; + let items = labels + .iter() + .zip(TIME_PERIODS) + .map(|(label, hours)| { + let count = hours + .map(|hour| stats.hour_counts.get(&hour).copied().unwrap_or(0)) + .sum(); + (label.to_string(), count) + }) + .collect::>(); + + // Legacy reports only have local hour counts, so there is no reliable way + // to convert them to a different time zone. + if stats.activity_by_utc_minute.is_empty() { + return render_bar_chart(l.chart_time_of_day, &items, "#8b5cf6", 4); + } + let minutes = serde_json::to_string(&stats.activity_by_utc_minute).unwrap_or_default(); + let labels = serde_json::to_string(&labels).unwrap_or_default(); format!( - r#"
+ r#"
{title} - +
-
"#, title = html_escape(l.chart_time_of_day), - hour_data = hour_json.join(","), - lm = l.time_morning, - la = l.time_afternoon, - le = l.time_evening, - ln = l.time_night, + minutes = html_escape(&minutes), + labels = html_escape(&labels), ) } @@ -887,6 +985,7 @@ fn render_friction_categories(categories: &[FrictionCategory], l: &HtmlLabels) - } fn render_suggestions(suggestions: &InsightsSuggestions, l: &HtmlLabels) -> String { + let copy = html_escape(l.copy); let mut sections = Vec::new(); if !suggestions.openbitfun_md_additions.is_empty() { @@ -899,11 +998,10 @@ fn render_suggestions(suggestions: &InsightsSuggestions, l: &HtmlLabels) -> Stri r#"
{}
- +
{}
"#, html_escape(&md.content), - js_escape(&md.content), html_escape(&md.rationale), i = i, ) @@ -914,7 +1012,7 @@ fn render_suggestions(suggestions: &InsightsSuggestions, l: &HtmlLabels) -> Stri r#"

{md_title}

- +
{items}
"#, @@ -935,10 +1033,9 @@ fn render_suggestions(suggestions: &InsightsSuggestions, l: &HtmlLabels) -> Stri format!( r#"
{} - +
"#, html_escape(&f.example_usage), - js_escape(&f.example_usage), ) }; @@ -986,11 +1083,10 @@ fn render_suggestions(suggestions: &InsightsSuggestions, l: &HtmlLabels) -> Stri r#"
{}
{} - +
"#, html_escape(l.try_this_prompt), html_escape(&p.suggested_prompt), - js_escape(&p.suggested_prompt), ) }; @@ -1021,6 +1117,7 @@ fn render_suggestions(suggestions: &InsightsSuggestions, l: &HtmlLabels) -> Stri } fn render_horizon(intro: &str, workflows: &[HorizonWorkflow], l: &HtmlLabels) -> String { + let copy = html_escape(l.copy); if workflows.is_empty() { return format!(r#"
{}
"#, html_escape(l.no_horizon)); } @@ -1047,22 +1144,16 @@ fn render_horizon(intro: &str, workflows: &[HorizonWorkflow], l: &HtmlLabels) -> String::new() } else { let escaped = html_escape(&h.copyable_prompt); - let js_escaped = h - .copyable_prompt - .replace('\\', "\\\\") - .replace('\'', "\\'") - .replace('\n', "\\n"); format!( r#"
{try_prompt}
{code} - +
"#, try_prompt = html_escape(l.try_this_prompt), code = escaped, - js_code = js_escaped, ) }; @@ -1175,13 +1266,6 @@ fn find_closing_single_star(chars: &[char], start: usize) -> Option { None } -fn js_escape(s: &str) -> String { - s.replace('\\', "\\\\") - .replace('\'', "\\'") - .replace('\n', "\\n") - .replace('\r', "") -} - const CSS_STYLES: &str = r#" * { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; background: #f8fafc; color: #334155; line-height: 1.65; padding: 48px 24px; } @@ -1276,6 +1360,17 @@ const CSS_STYLES: &str = r#" "#; const JS_SCRIPT: &str = r#" + document.querySelectorAll('.copy-btn').forEach(function(btn) { + btn.addEventListener('click', function() { + var item = btn.closest('.feature-code, .claude-md-item'); + var code = item && item.querySelector('.cmd-code, code'); + if (code) copyText(btn, code.textContent); + }); + }); + document.querySelectorAll('.copy-all-btn').forEach(function(btn) { + btn.addEventListener('click', function() { copyAllChecked(btn); }); + }); + function copyText(btn, text) { navigator.clipboard.writeText(text).then(function() { var orig = btn.textContent; @@ -1314,7 +1409,10 @@ const JS_SCRIPT: &str = r#" (function initTimezoneSelector() { var sel = document.getElementById('tz-selector'); - if (!sel || !window.__hourCountsUTC) return; + var chart = document.getElementById('time-of-day-chart'); + if (!sel || !chart) return; + var minutes = JSON.parse(chart.dataset.minutes); + var labels = JSON.parse(chart.dataset.labels); var common = [ 'UTC', 'America/New_York','America/Chicago','America/Denver','America/Los_Angeles', @@ -1331,43 +1429,93 @@ const JS_SCRIPT: &str = r#" if (tz === localTz) opt.selected = true; sel.appendChild(opt); }); - updateTimeChart(); + function update() { updateTimeChart(sel.value, minutes, labels); } + sel.addEventListener('change', update); + update(); })(); - function updateTimeChart() { - var sel = document.getElementById('tz-selector'); + function updateTimeChart(tz, minutes, labels) { var container = document.getElementById('time-bars'); - if (!sel || !container || !window.__hourCountsUTC) return; - var tz = sel.value; - var shifted = {}; - for (var h = 0; h < 24; h++) { - var utcCount = window.__hourCountsUTC[h] || 0; - if (utcCount === 0) continue; - var d = new Date(Date.UTC(2024,0,1,h,0,0)); - var localH = parseInt(d.toLocaleString('en-US',{hour:'numeric',hour12:false,timeZone:tz})); - shifted[localH] = (shifted[localH]||0) + utcCount; - } - var labels = window.__timeLabels; - var periods = [ - {label:labels.morning, hours:[6,7,8,9,10,11]}, - {label:labels.afternoon, hours:[12,13,14,15,16,17]}, - {label:labels.evening, hours:[18,19,20,21,22,23]}, - {label:labels.night, hours:[0,1,2,3,4,5]} - ]; - var maxVal = 0; - var data = periods.map(function(p) { - var count = 0; - p.hours.forEach(function(h){count += shifted[h]||0;}); - if (count > maxVal) maxVal = count; - return {label:p.label, count:count}; + var formatHour = new Intl.DateTimeFormat('en-GB', { + hour: 'numeric', hourCycle: 'h23', timeZone: tz + }); + var counts = [0, 0, 0, 0]; + Object.entries(minutes).forEach(function(entry) { + var hour = Number(formatHour.format(new Date(Number(entry[0]) * 60000))); + var period = (Math.floor(hour / 6) + 3) % 4; + counts[period] += entry[1]; }); - var html = ''; - data.forEach(function(d) { - var pct = maxVal > 0 ? (d.count/maxVal*100) : 0; - html += '
'+d.label+'' - +'
' - +''+d.count+'
'; + var periods = labels.map(function(label, i) { return {label:label, count:counts[i]}; }); + var maxVal = 0; + periods.forEach(function(p) { maxVal = Math.max(maxVal, p.count); }); + container.replaceChildren(); + periods.forEach(function(d) { + var row = document.createElement('div'); + row.className = 'bar-row'; + var label = document.createElement('span'); + label.className = 'bar-label'; + label.textContent = d.label; + var track = document.createElement('div'); + track.className = 'bar-track'; + var fill = document.createElement('div'); + fill.className = 'bar-fill'; + fill.style.width = (maxVal > 0 ? d.count / maxVal * 100 : 0) + '%'; + fill.style.background = '#8b5cf6'; + track.appendChild(fill); + var value = document.createElement('span'); + value.className = 'bar-value'; + value.textContent = d.count; + row.append(label, track, value); + container.appendChild(row); }); - container.innerHTML = html; } "#; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn copy_buttons_treat_model_output_as_text_in_every_section() { + let labels = HtmlLabels::for_locale(LocaleId::EnUS); + let text = "\"quotes\" & 'apostrophes'\nsecond line".to_owned(); + let suggestions = render_suggestions( + &InsightsSuggestions { + openbitfun_md_additions: vec![MdAddition { + section: "Section".to_owned(), + content: text.clone(), + rationale: String::new(), + }], + features_to_try: vec![FeatureRecommendation { + feature: "Feature".to_owned(), + description: String::new(), + example_usage: text.clone(), + benefit: String::new(), + }], + usage_patterns: vec![UsagePattern { + pattern: "Pattern".to_owned(), + description: String::new(), + detail: String::new(), + suggested_prompt: text.clone(), + }], + }, + &labels, + ); + let horizon = render_horizon( + "", + &[HorizonWorkflow { + title: "Workflow".to_owned(), + whats_possible: String::new(), + how_to_try: String::new(), + copyable_prompt: text.clone(), + }], + &labels, + ); + + let html = suggestions + &horizon; + assert_eq!(html.matches(&html_escape(&text)).count(), 4); + assert_eq!(html.matches("class=\"copy-btn\"").count(), 4); + assert!(!html.contains(&text)); + assert!(!html.contains("onclick=")); + } +} diff --git a/src/crates/assembly/core/src/agentic/insights/service.rs b/src/crates/assembly/core/src/agentic/insights/service.rs index aeb91c2eca..3fd806030a 100644 --- a/src/crates/assembly/core/src/agentic/insights/service.rs +++ b/src/crates/assembly/core/src/agentic/insights/service.rs @@ -1,4 +1,4 @@ -use crate::agentic::insights::cancellation; +use crate::agentic::insights::cancellation::{self, Registration}; use crate::agentic::insights::collector::InsightsCollector; use crate::agentic::insights::facet_cache; use crate::agentic::insights::html::generate_html; @@ -15,6 +15,7 @@ use crate::service::config::AppConfig; use crate::service::i18n::LocaleId; use crate::util::errors::{OpenBitFunError, OpenBitFunResult}; use crate::util::types::{GeminiResponse, GeminiUsage, Message, ToolDefinition}; +use futures::{stream, StreamExt}; use log::{debug, info, warn}; use openbitfun_agent_content::insights::{ AREAS as AREAS_PROMPT_TEMPLATE, AT_A_GLANCE as AT_A_GLANCE_PROMPT_TEMPLATE, @@ -23,24 +24,39 @@ use openbitfun_agent_content::insights::{ INTERACTION_STYLE as INTERACTION_STYLE_PROMPT_TEMPLATE, SUGGESTIONS as SUGGESTIONS_PROMPT_TEMPLATE, WINS as WINS_PROMPT_TEMPLATE, }; +use openbitfun_services_core::json_store::JsonFileStore; use serde_json::Value; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use tokio::sync::Semaphore; -use tokio_util::sync::CancellationToken; const MAX_CONCURRENT_FACET_EXTRACTIONS: usize = 5; +const ANALYSIS_SECTION_COUNT: u32 = 8; -#[derive(Clone)] struct TrackedAIClient { client: Arc, + model_id: String, usage: GenerationUsageTracker, } impl TrackedAIClient { - fn new(client: Arc, usage: GenerationUsageTracker) -> Self { - Self { client, usage } + fn new(client: Arc, model_id: String, usage: GenerationUsageTracker) -> Self { + Self { + client, + model_id, + usage, + } + } + + fn model_identity(&self) -> [&str; 4] { + let config = &self.client.config; + [ + &self.model_id, + &config.format, + &config.request_url, + &config.model, + ] } async fn send_message( @@ -130,74 +146,90 @@ impl InsightsService { } } - async fn get_user_language() -> String { - match get_global_config_service().await { - Ok(config_service) => match config_service.get_config::(Some("app")).await { - Ok(app_config) => app_config.language, - Err(_) => "en-US".to_string(), - }, - Err(_) => "en-US".to_string(), - } + async fn get_user_language() -> LocaleId { + let Ok(config_service) = get_global_config_service().await else { + return LocaleId::EnUS; + }; + config_service + .get_config::(Some("app")) + .await + .ok() + .and_then(|config| LocaleId::from_str(&config.language)) + .unwrap_or(LocaleId::EnUS) } - fn build_language_instruction(lang: &str) -> String { + fn build_language_instruction(locale: LocaleId) -> String { let json_rule = concat!( "\n\nCRITICAL JSON RULE: Inside JSON string values you MUST escape every literal double-quote as \\\".", " Do NOT place unescaped \" characters inside string values.", " For example, write \"he said \\\"hello\\\"\" instead of \"he said \"hello\"\".", ); - - if lang.starts_with("en") { - json_rule.to_string() - } else { - let lang_name = match lang { - "ja" | "ja-JP" => "Japanese (日本語)", - "ko" | "ko-KR" => "Korean (한국어)", - "fr" | "fr-FR" => "French (Français)", - "de" | "de-DE" => "German (Deutsch)", - "es" | "es-ES" => "Spanish (Español)", - "pt" | "pt-BR" => "Portuguese (Português)", - "ru" | "ru-RU" => "Russian (Русский)", - _ => LocaleId::from_str(lang) - .map(|locale| locale.model_language_name()) - .unwrap_or(lang), - }; - format!( - "\n\nIMPORTANT: All descriptive text, summaries, suggestions, and narrative content in your response MUST be written in {}. Keep JSON keys and enum values in English.{}", - lang_name, json_rule - ) - } + format!( + "\n\nIMPORTANT: All descriptive text, summaries, suggestions, and narrative content in your response MUST be written in {}. Keep JSON keys and enum values in English.{}", + locale.model_language_name(), json_rule + ) } - /// Main entry: run the full insights pipeline pub async fn generate( days: u32, model_selector: Option, + generation_id: Option, ) -> OpenBitFunResult { Self::validate_days(days)?; - let registration = cancellation::register().await; - let result = - Self::generate_inner(days, model_selector.as_deref(), ®istration.token).await; - cancellation::unregister(registration.id).await; + let generation = cancellation::register(generation_id).await; + let pipeline = cancellation::PIPELINE.lock().await; + let result = cancellation::run_until_cancelled( + &generation.token, + Box::pin(Self::build_report( + days, + model_selector.as_deref(), + &generation, + )), + ) + .await; + + let result = match result { + Ok(report) => { + if cancellation::claim_completion(generation.id).await { + let result = Self::save_report(report).await; + if result.is_ok() { + Self::emit_progress(&generation, "Complete!", "complete", 0, 0).await; + info!("Insights report generated"); + } + result + } else { + Err(OpenBitFunError::service("Insights generation cancelled")) + } + } + Err(error) => Err(error), + }; + cancellation::unregister(generation.id).await; + drop(pipeline); result } - /// Cancel the current insights generation. - pub async fn cancel() -> Result<(), String> { - cancellation::cancel().await + pub async fn cancel(generation_id: Option<&str>) -> Result<(), String> { + cancellation::cancel(generation_id).await } - async fn generate_inner( + async fn build_report( days: u32, model_selector: Option<&str>, - token: &CancellationToken, + generation: &Registration, ) -> OpenBitFunResult { let user_lang = Self::get_user_language().await; - let lang_instruction = Self::build_language_instruction(&user_lang); + let lang_instruction = Self::build_language_instruction(user_lang); debug!("Insights generation using language: {}", user_lang); // Stage 1: Data Collection - Self::emit_progress("Collecting session data...", "data_collection", 0, 0).await; + Self::emit_progress( + generation, + "Collecting session data...", + "data_collection", + 0, + 0, + ) + .await; let (base_stats, transcripts) = InsightsCollector::collect(days).await?; if transcripts.is_empty() { @@ -212,52 +244,57 @@ impl InsightsService { base_stats.total_messages ); - Self::check_cancelled(token)?; - // Stage 2: Parallel Facet Extraction let ai_factory = get_global_ai_client_factory().await.map_err(|e| { OpenBitFunError::service(format!("Failed to get AI client factory: {}", e)) })?; let selected_model = normalize_insights_model_selector(model_selector); - let ai_client = ai_factory - .get_client_resolved(selected_model) + let model_id = ai_factory + .resolve_model_id(selected_model) .await .map_err(|e| { - OpenBitFunError::service(format!( - "Failed to resolve selected insights model '{}': {}", - selected_model, e - )) + OpenBitFunError::service(format!("Failed to resolve selected insights model: {e}")) })?; + let ai_client = ai_factory.get_client_by_id(&model_id).await.map_err(|e| { + OpenBitFunError::service(format!("Failed to load selected insights model: {e}")) + })?; let generation_models = vec![ai_client.config.model.clone()]; let usage_tracker = GenerationUsageTracker::default(); - let ai_client = TrackedAIClient::new(ai_client, usage_tracker.clone()); + let ai_client = TrackedAIClient::new(ai_client, model_id, usage_tracker.clone()); let facets = - Self::extract_facets_adaptive(&ai_client, &transcripts, &lang_instruction, token) + Self::extract_facets_adaptive(&ai_client, &transcripts, &lang_instruction, generation) .await?; info!("Extracted facets for {} sessions", facets.len()); - Self::check_cancelled(token)?; - // Stage 3: Aggregation (Rust-side, no AI) - Self::emit_progress("Aggregating analysis...", "aggregation", 0, 0).await; + Self::emit_progress(generation, "Aggregating analysis...", "aggregation", 0, 0).await; let aggregate = InsightsCollector::aggregate(&base_stats, &facets); - Self::check_cancelled(token)?; - // Stage 4a: Parallel analysis — 7 independent tasks - Self::emit_progress("Analyzing patterns...", "analysis", 0, 0).await; + Self::emit_progress(generation, "Analyzing patterns...", "analysis", 0, 0).await; let (suggestions, areas, wins_friction, interaction, horizon, fun_ending) = - Self::generate_analysis_parallel(&ai_client, &aggregate, &lang_instruction).await; - - Self::check_cancelled(token)?; + Self::generate_analysis_parallel(&ai_client, &aggregate, &lang_instruction, generation) + .await; + let mut failed_sections = 0; + let suggestions = + section_or_default(suggestions, &mut failed_sections, default_suggestions); + let areas = section_or_default(areas, &mut failed_sections, Vec::new); + let wins_friction = WinsFrictionResult::from_sections(wins_friction, &mut failed_sections); + let interaction = section_or_default( + interaction, + &mut failed_sections, + InteractionStyleResult::default, + ); + let horizon = section_or_default(horizon, &mut failed_sections, HorizonResult::default); + let fun_ending = section_or_default(fun_ending, &mut failed_sections, || None); // Stage 4b: Synthesis — at_a_glance depends on 4a results - Self::emit_progress("Writing summary...", "synthesis", 0, 0).await; + Self::emit_progress(generation, "Writing summary...", "synthesis", 0, 0).await; let at_a_glance = Self::generate_synthesis( &ai_client, @@ -269,11 +306,11 @@ impl InsightsService { &lang_instruction, ) .await; - - Self::check_cancelled(token)?; + let at_a_glance = section_or_default(at_a_glance, &mut failed_sections, AtAGlance::default); + ensure_report_has_analysis(facets.len(), failed_sections)?; // Stage 5: Assembly - Self::emit_progress("Assembling report...", "assembly", 0, 0).await; + Self::emit_progress(generation, "Assembling report...", "assembly", 0, 0).await; let report = Self::assemble_report( base_stats, aggregate, @@ -286,157 +323,98 @@ impl InsightsService { fun_ending, usage_tracker.snapshot(), generation_models, + failed_sections, + user_lang, ); - let report = Self::save_report(report, &user_lang).await?; - - Self::emit_progress("Complete!", "complete", 0, 0).await; - info!("Insights report generated successfully"); - Ok(report) } - fn check_cancelled(token: &CancellationToken) -> OpenBitFunResult<()> { - if token.is_cancelled() { - Err(OpenBitFunError::service("Insights generation cancelled")) - } else { - Ok(()) - } - } - // ============ Stage 2: Facet Extraction ============ async fn extract_facets_adaptive( ai_client: &TrackedAIClient, transcripts: &[SessionTranscript], lang_instruction: &str, - token: &CancellationToken, + generation: &Registration, ) -> OpenBitFunResult> { let total = transcripts.len(); - let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_FACET_EXTRACTIONS)); - let counter = Arc::new(AtomicUsize::new(0)); - let rate_limited = Arc::new(AtomicBool::new(false)); - let cancelled = Arc::new(AtomicBool::new(false)); - - let handles: Vec<_> = transcripts - .iter() - .enumerate() - .map(|(idx, t)| { - let client = ai_client.clone(); - let sem = semaphore.clone(); - let transcript = t.clone(); - let cnt = counter.clone(); - let rl = rate_limited.clone(); - let cl = cancelled.clone(); - let lang = lang_instruction.to_string(); - let child_token = token.clone(); - - tokio::spawn(async move { - let _permit = sem - .acquire() - .await - .map_err(|e| OpenBitFunError::service(format!("Semaphore error: {}", e)))?; - - if cl.load(Ordering::Relaxed) || child_token.is_cancelled() { - return Err(OpenBitFunError::service("Insights generation cancelled")); - } - - if rl.load(Ordering::Relaxed) { - return Err(OpenBitFunError::service("skipped_rate_limited")); - } - - let n = cnt.fetch_add(1, Ordering::Relaxed) + 1; - Self::emit_progress( - &format!("Analyzing session {}/{}...", n, total), - "facet_extraction", - n, - total, - ) - .await; - - let result = Self::extract_single_facet(&client, &transcript, &lang).await; - - if let Err(ref e) = result { - if is_rate_limit_error(e) { - rl.store(true, Ordering::Relaxed); - } - } - - result.map(|facet| (idx, facet)) - }) + let counter = AtomicUsize::new(0); + let rate_limited = AtomicBool::new(false); + let counter = &counter; + let rate_limited = &rate_limited; + let mut pending = stream::iter(0..total) + .map(move |index| async move { + if rate_limited.load(Ordering::Relaxed) { + return (index, None); + } + let current = counter.fetch_add(1, Ordering::Relaxed) + 1; + Self::emit_progress( + generation, + &format!("Analyzing session {current}/{total}..."), + "facet_extraction", + current, + total, + ) + .await; + let result = + Self::extract_single_facet(ai_client, &transcripts[index], lang_instruction) + .await; + if result.as_ref().is_err_and(is_rate_limit_error) { + rate_limited.store(true, Ordering::Relaxed); + } + (index, Some(result)) }) - .collect(); + .buffer_unordered(MAX_CONCURRENT_FACET_EXTRACTIONS); let mut facets = Vec::new(); - let mut failed_indices: Vec = Vec::new(); - let mut hit_rate_limit = false; - - for (idx, handle) in handles.into_iter().enumerate() { - if token.is_cancelled() { - return Err(OpenBitFunError::service("Insights generation cancelled")); - } - match handle.await { - Ok(Ok((_orig_idx, facet))) => facets.push(facet), - Ok(Err(e)) => { - let err_str = e.to_string(); - if err_str.contains("cancelled") { - return Err(e); - } - if err_str.contains("skipped_rate_limited") || is_rate_limit_error(&e) { - hit_rate_limit = true; - failed_indices.push(idx); - } else { - warn!("Facet extraction failed for session {}: {}", idx, e); - } + let mut retry_indices = Vec::new(); + while let Some((index, result)) = pending.next().await { + match result { + Some(Ok(facet)) => facets.push((index, facet)), + Some(Err(error)) if !is_rate_limit_error(&error) => { + warn!("Facet extraction failed for session {index}: {error}"); } - Err(e) => warn!("Facet task panicked: {}", e), + _ => retry_indices.push(index), } } - - if hit_rate_limit && !failed_indices.is_empty() { - let retry_count = failed_indices.len(); - warn!( - "Rate limit detected, retrying {} sessions sequentially", - retry_count - ); + if !retry_indices.is_empty() { + retry_indices.sort_unstable(); + let retry_count = retry_indices.len(); Self::emit_progress( - &format!( - "Rate limited. Retrying {} sessions sequentially...", - retry_count - ), + generation, + &format!("Rate limited. Retrying {retry_count} sessions sequentially..."), "facet_retry", 0, retry_count, ) .await; - tokio::time::sleep(Duration::from_secs(3)).await; - for (i, idx) in failed_indices.iter().enumerate() { - Self::check_cancelled(token)?; - + for (attempt, index) in retry_indices.into_iter().enumerate() { Self::emit_progress( - &format!("Retrying session {}/{}...", i + 1, retry_count), + generation, + &format!("Retrying session {}/{retry_count}...", attempt + 1), "facet_retry", - i + 1, + attempt + 1, retry_count, ) .await; - - match Self::extract_single_facet(ai_client, &transcripts[*idx], lang_instruction) + match Self::extract_single_facet(ai_client, &transcripts[index], lang_instruction) .await { - Ok(facet) => facets.push(facet), - Err(e) => warn!("Sequential retry also failed for session {}: {}", idx, e), + Ok(facet) => facets.push((index, facet)), + Err(error) => warn!("Sequential retry failed for session {index}: {error}"), } - - if i + 1 < retry_count { + if attempt + 1 < retry_count { tokio::time::sleep(Duration::from_millis(500)).await; } } } - Ok(facets) + ensure_report_has_analysis(facets.len(), 0)?; + facets.sort_unstable_by_key(|(index, _)| *index); + Ok(facets.into_iter().map(|(_, facet)| facet).collect()) } async fn extract_single_facet( @@ -444,10 +422,6 @@ impl InsightsService { transcript: &SessionTranscript, lang_instruction: &str, ) -> OpenBitFunResult { - if let Ok(Some(cached)) = facet_cache::try_load_cached_facet(transcript).await { - return Ok(cached); - } - let session_info = format!( "Session: {}\nAgent: {}\nName: {}\nDate: {}\nDuration: {} min\n\n{}", transcript.session_id, @@ -463,7 +437,13 @@ impl InsightsService { FACET_PROMPT_TEMPLATE.replace("{session_transcript}", &session_info), lang_instruction ); - let messages = vec![Message::user(prompt)]; + let model_identity = ai_client.model_identity(); + if let Ok(Some(cached)) = + facet_cache::try_load_cached_facet(transcript, &model_identity, &prompt).await + { + return Ok(cached); + } + let messages = vec![Message::user(prompt.clone())]; let response = ai_client .send_message(messages, None) @@ -475,6 +455,10 @@ impl InsightsService { OpenBitFunError::Deserialization(format!("Failed to parse facet JSON: {}", e)) })?; + let brief_summary = value["brief_summary"] + .as_str() + .filter(|summary| !summary.trim().is_empty()) + .ok_or_else(|| OpenBitFunError::service("Session analysis has no summary"))?; let facet = SessionFacet { session_id: transcript.session_id.clone(), underlying_goal: value["underlying_goal"].as_str().unwrap_or("").to_string(), @@ -495,7 +479,7 @@ impl InsightsService { friction_counts: parse_string_u32_map(&value["friction_counts"]), friction_detail: value["friction_detail"].as_str().unwrap_or("").to_string(), primary_success: value["primary_success"].as_str().unwrap_or("").to_string(), - brief_summary: value["brief_summary"].as_str().unwrap_or("").to_string(), + brief_summary: brief_summary.to_owned(), languages_used: value["languages_used"] .as_array() .map(|arr| { @@ -514,7 +498,7 @@ impl InsightsService { .unwrap_or_default(), }; - let _ = facet_cache::save_cached_facet(transcript, &facet).await; + let _ = facet_cache::save_cached_facet(transcript, &facet, &model_identity, &prompt).await; Ok(facet) } @@ -525,243 +509,95 @@ impl InsightsService { ai_client: &TrackedAIClient, aggregate: &InsightsAggregate, lang_instruction: &str, + generation: &Registration, ) -> ( - InsightsSuggestions, - Vec, - WinsFrictionResult, - InteractionStyleResult, - HorizonResult, - Option, + OpenBitFunResult, + OpenBitFunResult>, + ( + OpenBitFunResult, + OpenBitFunResult, + ), + OpenBitFunResult, + OpenBitFunResult, + OpenBitFunResult>, ) { let aggregate_json = aggregate_stats_json_for_prompt(aggregate); - let summaries_text = summaries_block(aggregate); - let friction_text = friction_block(aggregate); - - let semaphore = Arc::new(Semaphore::new(3)); - - // Task 1: Suggestions - let client_1 = ai_client.clone(); - let agg_1 = aggregate.clone(); - let lang_1 = lang_instruction.to_string(); - let sem_1 = semaphore.clone(); - let suggestions_handle = tokio::spawn(async move { - let _permit = sem_1.acquire().await.unwrap(); - Self::generate_suggestions(&client_1, &agg_1, &lang_1).await - }); - - // Task 2: Areas - let client_2 = ai_client.clone(); - let agg_2 = aggregate.clone(); - let lang_2 = lang_instruction.to_string(); - let sem_2 = semaphore.clone(); - let areas_handle = tokio::spawn(async move { - let _permit = sem_2.acquire().await.unwrap(); - Self::identify_areas(&client_2, &agg_2, &lang_2).await - }); - - // Task 3a: Wins - let client_3a = ai_client.clone(); - let agg_json_3a = aggregate_json.clone(); - let summaries_3a = summaries_text.clone(); - let lang_3a = lang_instruction.to_string(); - let sem_3a = semaphore.clone(); - let wins_handle = tokio::spawn(async move { - let _permit = sem_3a.acquire().await.unwrap(); - Self::analyze_wins(&client_3a, &agg_json_3a, &summaries_3a, &lang_3a).await - }); - - // Task 3b: Friction - let client_3b = ai_client.clone(); - let agg_json_3b = aggregate_json.clone(); - let summaries_3b = summaries_text.clone(); - let friction_3b = friction_text.clone(); - let lang_3b = lang_instruction.to_string(); - let sem_3b = semaphore.clone(); - let friction_handle = tokio::spawn(async move { - let _permit = sem_3b.acquire().await.unwrap(); - Self::analyze_friction( - &client_3b, - &agg_json_3b, - &summaries_3b, - &friction_3b, - &lang_3b, - ) - .await - }); - - // Task 4: Interaction Style - let client_4 = ai_client.clone(); - let agg_json_4 = aggregate_json.clone(); - let summaries_4 = summaries_text.clone(); - let lang_4 = lang_instruction.to_string(); - let sem_4 = semaphore.clone(); - let interaction_handle = tokio::spawn(async move { - let _permit = sem_4.acquire().await.unwrap(); - Self::analyze_interaction_style(&client_4, &agg_json_4, &summaries_4, &lang_4).await - }); - - // Task 5: Horizon - let client_5 = ai_client.clone(); - let agg_json_5 = aggregate_json.clone(); - let summaries_5 = summaries_text.clone(); - let friction_5 = friction_text.clone(); - let lang_5 = lang_instruction.to_string(); - let sem_5 = semaphore.clone(); - let horizon_handle = tokio::spawn(async move { - let _permit = sem_5.acquire().await.unwrap(); - Self::generate_horizon(&client_5, &agg_json_5, &summaries_5, &friction_5, &lang_5).await - }); - - // Task 6: Fun Ending - let client_6 = ai_client.clone(); - let agg_json_6 = aggregate_json.clone(); - let summaries_6 = summaries_text.clone(); - let lang_6 = lang_instruction.to_string(); - let sem_6 = semaphore.clone(); - let fun_ending_handle = tokio::spawn(async move { - let _permit = sem_6.acquire().await.unwrap(); - Self::generate_fun_ending(&client_6, &agg_json_6, &summaries_6, &lang_6).await - }); - - // Collect results with retry on transient failures - let suggestions = Self::resolve_with_retry( - suggestions_handle, - "Suggestions", - || async { Self::generate_suggestions(ai_client, aggregate, lang_instruction).await }, - default_suggestions, - ) - .await; - - let areas = Self::resolve_with_retry( - areas_handle, - "Areas", - || async { Self::identify_areas(ai_client, aggregate, lang_instruction).await }, - Vec::new, - ) - .await; - - let wins_result = Self::resolve_with_retry( - wins_handle, - "Wins", - || async { - Self::analyze_wins( - ai_client, - &aggregate_stats_json_for_prompt(aggregate), - &summaries_block(aggregate), - lang_instruction, - ) - .await - }, - WinsResult::default, - ) - .await; - - let friction_result = Self::resolve_with_retry( - friction_handle, - "Friction", - || async { + let summaries = summaries_block(aggregate); + let friction_details = friction_block(aggregate); + let semaphore = Semaphore::new(3); + + let (suggestions, areas, wins, friction, interaction, horizon, ending) = tokio::join!( + Self::resolve_with_retry(generation, &semaphore, "Suggestions", || { + Self::generate_suggestions(ai_client, aggregate, lang_instruction) + }), + Self::resolve_with_retry(generation, &semaphore, "Areas", || { + Self::identify_areas(ai_client, aggregate, lang_instruction) + }), + Self::resolve_with_retry(generation, &semaphore, "Wins", || { + Self::analyze_wins(ai_client, &aggregate_json, &summaries, lang_instruction) + }), + Self::resolve_with_retry(generation, &semaphore, "Friction", || { Self::analyze_friction( ai_client, - &aggregate_stats_json_for_prompt(aggregate), - &summaries_block(aggregate), - &friction_block(aggregate), + &aggregate_json, + &summaries, + &friction_details, lang_instruction, ) - .await - }, - FrictionResult::default, - ) - .await; - - let wins_friction = WinsFrictionResult { - wins_intro: wins_result.intro, - big_wins: wins_result.big_wins, - friction_intro: friction_result.intro, - friction_categories: friction_result.friction_categories, - }; - - let interaction = Self::resolve_with_retry( - interaction_handle, - "Interaction Style", - || async { + }), + Self::resolve_with_retry(generation, &semaphore, "Interaction Style", || { Self::analyze_interaction_style( ai_client, - &aggregate_stats_json_for_prompt(aggregate), - &summaries_block(aggregate), + &aggregate_json, + &summaries, lang_instruction, ) - .await - }, - InteractionStyleResult::default, - ) - .await; - - let horizon = Self::resolve_with_retry( - horizon_handle, - "Horizon", - || async { + }), + Self::resolve_with_retry(generation, &semaphore, "Horizon", || { Self::generate_horizon( ai_client, - &aggregate_stats_json_for_prompt(aggregate), - &summaries_block(aggregate), - &friction_block(aggregate), - lang_instruction, - ) - .await - }, - HorizonResult::default, - ) - .await; - - let fun_ending = Self::resolve_with_retry( - fun_ending_handle, - "Fun Ending", - || async { - Self::generate_fun_ending( - ai_client, - &aggregate_stats_json_for_prompt(aggregate), - &summaries_block(aggregate), + &aggregate_json, + &summaries, + &friction_details, lang_instruction, ) - .await - }, - || None, - ) - .await; - + }), + Self::resolve_with_retry(generation, &semaphore, "Fun Ending", || { + Self::generate_fun_ending(ai_client, &aggregate_json, &summaries, lang_instruction) + }), + ); ( suggestions, areas, - wins_friction, + (wins, friction), interaction, horizon, - fun_ending, + ending, ) } - /// Generic helper to resolve a spawned task with retry on transient failures. - /// - /// Retries on rate-limit errors, empty AI responses, and JSON extraction failures. - async fn resolve_with_retry( - handle: tokio::task::JoinHandle>, + async fn resolve_with_retry( + generation: &Registration, + semaphore: &Semaphore, label: &str, - retry_fn: RetryFn, - default_fn: DefaultFn, - ) -> T + call: impl Fn() -> F, + ) -> OpenBitFunResult where - RetryFut: std::future::Future>, - RetryFn: FnOnce() -> RetryFut, - DefaultFn: FnOnce() -> T, + F: std::future::Future>, { - let result = handle - .await - .map_err(|e| OpenBitFunError::service(format!("{} task panicked: {}", label, e))); - - match result { - Ok(Ok(val)) => val, - Ok(Err(e)) if is_retryable_error(&e) => { - warn!("{} failed (retryable): {}, retrying after delay", label, e); + let attempt = || async { + let _permit = semaphore + .acquire() + .await + .map_err(|error| OpenBitFunError::service(error.to_string()))?; + Box::pin(call()).await + }; + let result = attempt().await; + if let Err(error) = &result { + if is_retryable_error(error) { + warn!("{label} failed (retryable): {error}"); Self::emit_progress( + generation, &format!("Retrying {}...", label.to_lowercase()), "analysis_retry", 0, @@ -769,20 +605,10 @@ impl InsightsService { ) .await; tokio::time::sleep(Duration::from_secs(3)).await; - retry_fn().await.unwrap_or_else(|e| { - warn!("{} retry failed: {}, using defaults", label, e); - default_fn() - }) - } - Ok(Err(e)) => { - warn!("{} failed: {}, using defaults", label, e); - default_fn() - } - Err(e) => { - warn!("{} task error: {}, using defaults", label, e); - default_fn() + return attempt().await; } } + result } // ============ Stage 4b: Synthesis ============ @@ -795,7 +621,7 @@ impl InsightsService { wins_friction: &WinsFrictionResult, interaction: &InteractionStyleResult, lang_instruction: &str, - ) -> AtAGlance { + ) -> OpenBitFunResult { let aggregate_json = aggregate_stats_json_for_prompt(aggregate); let areas_text = areas @@ -810,7 +636,7 @@ impl InsightsService { let interaction_text = serde_json::to_string_pretty(interaction).unwrap_or_else(|_| "{}".to_string()); - match Self::generate_at_a_glance( + Self::generate_at_a_glance( ai_client, &aggregate_json, &areas_text, @@ -820,13 +646,6 @@ impl InsightsService { lang_instruction, ) .await - { - Ok(val) => val, - Err(e) => { - warn!("At a Glance generation failed: {}, using defaults", e); - AtAGlance::default() - } - } } // ============ Individual Analysis Methods ============ @@ -872,6 +691,14 @@ impl InsightsService { safe_truncate(&json_str, 500) )) })?; + require_response_arrays( + &value, + &[ + "openbitfun_md_additions", + "features_to_try", + "usage_patterns", + ], + )?; debug!( "Suggestions parsed: md_additions={}, features={}, patterns={}", @@ -996,6 +823,7 @@ impl InsightsService { let value: Value = serde_json::from_str(&json_str).map_err(|e| { OpenBitFunError::Deserialization(format!("Failed to parse areas JSON: {}", e)) })?; + require_response_arrays(&value, &["areas"])?; Ok(value["areas"] .as_array() @@ -1044,6 +872,7 @@ impl InsightsService { let value: Value = serde_json::from_str(&json_str).map_err(|e| { OpenBitFunError::Deserialization(format!("Failed to parse wins JSON: {}", e)) })?; + require_response_arrays(&value, &["impressive_workflows"])?; Ok(WinsResult { intro: value["intro"].as_str().unwrap_or("").to_string(), @@ -1097,6 +926,7 @@ impl InsightsService { let value: Value = serde_json::from_str(&json_str).map_err(|e| { OpenBitFunError::Deserialization(format!("Failed to parse friction JSON: {}", e)) })?; + require_response_arrays(&value, &["friction_categories"])?; Ok(FrictionResult { intro: value["intro"].as_str().unwrap_or("").to_string(), @@ -1162,6 +992,14 @@ impl InsightsService { e )) })?; + if value["narrative"] + .as_str() + .is_none_or(|text| text.trim().is_empty()) + { + return Err(OpenBitFunError::service( + "Interaction style has no narrative", + )); + } Ok(InteractionStyleResult { narrative: value["narrative"].as_str().unwrap_or("").to_string(), @@ -1213,6 +1051,12 @@ impl InsightsService { let value: Value = serde_json::from_str(&json_str).map_err(|e| { OpenBitFunError::Deserialization(format!("Failed to parse at-a-glance JSON: {}", e)) })?; + if json_value_to_string(&value["whats_working"]) + .trim() + .is_empty() + { + return Err(OpenBitFunError::service("Report summary has no analysis")); + } let looking_ahead = { let v = json_value_to_string(&value["looking_ahead"]); @@ -1264,6 +1108,7 @@ impl InsightsService { let value: Value = serde_json::from_str(&json_str).map_err(|e| { OpenBitFunError::Deserialization(format!("Failed to parse horizon JSON: {}", e)) })?; + require_response_arrays(&value, &["opportunities"])?; Ok(HorizonResult { intro: value["intro"].as_str().unwrap_or("").to_string(), @@ -1319,6 +1164,13 @@ impl InsightsService { let value: Value = serde_json::from_str(&json_str).map_err(|e| { OpenBitFunError::Deserialization(format!("Failed to parse fun ending JSON: {}", e)) })?; + if value["headline"] + .as_str() + .or(value["title"].as_str()) + .is_none_or(|text| text.trim().is_empty()) + { + return Err(OpenBitFunError::service("Report ending has no headline")); + } Ok(Some(FunEnding { headline: value["headline"] @@ -1338,7 +1190,7 @@ impl InsightsService { #[allow(clippy::too_many_arguments)] fn assemble_report( - _base_stats: BaseStats, + base_stats: BaseStats, aggregate: InsightsAggregate, suggestions: InsightsSuggestions, areas: Vec, @@ -1349,6 +1201,8 @@ impl InsightsService { fun_ending: Option, generation_usage: InsightsGenerationUsage, generation_models: Vec, + failed_sections: u32, + locale: LocaleId, ) -> InsightsReport { let days_covered = if !aggregate.date_range.start.is_empty() && !aggregate.date_range.end.is_empty() { @@ -1380,9 +1234,11 @@ impl InsightsService { .duration_since(UNIX_EPOCH) .unwrap_or_default() .as_secs(), + locale: Some(locale.as_str().to_owned()), date_range: aggregate.date_range.clone(), total_sessions: aggregate.sessions, analyzed_sessions: aggregate.analyzed, + failed_sections, total_messages: aggregate.messages, days_covered, session_usage: aggregate.session_usage.clone(), @@ -1398,6 +1254,7 @@ impl InsightsService { session_types: aggregate.session_types.clone(), languages: aggregate.languages.clone(), hour_counts: aggregate.hour_counts.clone(), + activity_by_utc_minute: base_stats.activity_by_utc_minute, agent_types: aggregate.agent_types.clone(), response_time_buckets: aggregate.response_time_buckets.clone(), median_response_time_secs: aggregate.median_response_time_secs, @@ -1429,10 +1286,7 @@ impl InsightsService { // ============ Save / Load / Utility ============ - async fn save_report( - mut report: InsightsReport, - locale: &str, - ) -> OpenBitFunResult { + async fn save_report(mut report: InsightsReport) -> OpenBitFunResult { let path_manager = get_path_manager_arc(); let usage_dir = path_manager.user_data_dir().join("usage-data"); tokio::fs::create_dir_all(&usage_dir) @@ -1441,21 +1295,17 @@ impl InsightsService { let timestamp = report.generated_at; - let html_content = generate_html(&report, locale); let html_path = usage_dir.join(format!("insights-{}.html", timestamp)); - tokio::fs::write(&html_path, &html_content) - .await - .map_err(|e| OpenBitFunError::io(format!("Failed to write HTML report: {}", e)))?; + Self::write_report_html(&report, &html_path, report_locale(&report, LocaleId::EnUS)) + .await?; report.html_report_path = Some(html_path.to_string_lossy().to_string()); let json_path = usage_dir.join(format!("insights-{}.json", timestamp)); - let json_str = serde_json::to_string_pretty(&report).map_err(|e| { - OpenBitFunError::serialization(format!("Failed to serialize report: {}", e)) - })?; - tokio::fs::write(&json_path, &json_str) + JsonFileStore + .write_atomic_strict(&json_path, &report) .await - .map_err(|e| OpenBitFunError::io(format!("Failed to write report JSON: {}", e)))?; + .map_err(|e| OpenBitFunError::io(format!("Failed to write report JSON: {e}")))?; info!( "Report saved: json={}, html={}", @@ -1468,6 +1318,33 @@ impl InsightsService { Ok(report) } + async fn write_report_html( + report: &InsightsReport, + path: &std::path::Path, + locale: LocaleId, + ) -> OpenBitFunResult<()> { + JsonFileStore + .write_text_atomic_strict(path, &generate_html(report, locale)) + .await + .map_err(|e| OpenBitFunError::io(format!("Failed to write HTML report: {e}"))) + } + + async fn refresh_report_html( + report: &mut InsightsReport, + json_path: &std::path::Path, + current_locale: LocaleId, + ) { + let path = json_path.with_extension("html"); + let locale = report_locale(report, current_locale); + report.html_report_path = match Self::write_report_html(report, &path, locale).await { + Ok(()) => Some(path.to_string_lossy().into_owned()), + Err(error) => { + warn!("Could not regenerate safe HTML for saved insights report: {error}"); + None + } + }; + } + async fn cleanup_old_reports(usage_dir: &std::path::Path, keep: usize) { let mut entries = match tokio::fs::read_dir(usage_dir).await { Ok(dir) => dir, @@ -1527,9 +1404,15 @@ impl InsightsService { let json_str = tokio::fs::read_to_string(&canonical_path) .await .map_err(|e| OpenBitFunError::io(format!("Failed to read report file: {}", e)))?; - let report: InsightsReport = serde_json::from_str(&json_str).map_err(|e| { + let mut report: InsightsReport = serde_json::from_str(&json_str).map_err(|e| { OpenBitFunError::Deserialization(format!("Failed to parse report: {}", e)) })?; + Self::refresh_report_html( + &mut report, + &canonical_path, + Self::get_user_language().await, + ) + .await; Ok(report) } @@ -1580,6 +1463,7 @@ impl InsightsService { generated_at: report.generated_at, total_sessions: report.total_sessions, analyzed_sessions: report.analyzed_sessions, + failed_sections: report.failed_sections, date_range: report.date_range, path: json_path.to_string_lossy().to_string(), total_messages: report.total_messages, @@ -1605,8 +1489,18 @@ impl InsightsService { Ok(reports) } - async fn emit_progress(message: &str, stage: &str, current: usize, total: usize) { + async fn emit_progress( + generation: &Registration, + message: &str, + stage: &str, + current: usize, + total: usize, + ) { + if generation.token.is_cancelled() { + return; + } let payload = serde_json::json!({ + "generationId": generation.client_id, "message": message, "stage": stage, "current": current, @@ -1635,6 +1529,25 @@ struct WinsFrictionResult { friction_categories: Vec, } +impl WinsFrictionResult { + fn from_sections( + (wins, friction): ( + OpenBitFunResult, + OpenBitFunResult, + ), + failed_sections: &mut u32, + ) -> Self { + let wins = section_or_default(wins, failed_sections, WinsResult::default); + let friction = section_or_default(friction, failed_sections, FrictionResult::default); + Self { + wins_intro: wins.intro, + big_wins: wins.big_wins, + friction_intro: friction.intro, + friction_categories: friction.friction_categories, + } + } +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] struct WinsResult { intro: String, @@ -1727,6 +1640,89 @@ fn is_retryable_error(e: &OpenBitFunError) -> bool { || msg.contains("connection reset") } +fn report_locale(report: &InsightsReport, current_locale: LocaleId) -> LocaleId { + if let Some(locale) = report.locale.as_deref().and_then(LocaleId::from_str) { + return locale; + } + + // Legacy reports did not persist a locale. Use narrative prose only, since + // chart categories and technical names can be English in Chinese reports. + let prose = [ + &report.at_a_glance.whats_working, + &report.at_a_glance.whats_hindering, + &report.at_a_glance.quick_wins, + &report.at_a_glance.looking_ahead, + &report.interaction_style.narrative, + &report.wins_intro, + &report.friction_intro, + &report.horizon_intro, + ]; + let (han, latin) = + prose + .iter() + .flat_map(|text| text.chars()) + .fold((0usize, 0usize), |(han, latin), ch| { + ( + han + usize::from( + matches!(ch, '\u{3400}'..='\u{4dbf}' | '\u{4e00}'..='\u{9fff}'), + ), + latin + usize::from(ch.is_ascii_alphabetic()), + ) + }); + + if han >= 8 && han * 3 >= latin { + if current_locale == LocaleId::ZhTW { + LocaleId::ZhTW + } else { + LocaleId::ZhCN + } + } else if latin >= 24 && latin > han * 8 { + LocaleId::EnUS + } else { + current_locale + } +} + +fn ensure_report_has_analysis( + analyzed_sessions: usize, + failed_sections: u32, +) -> OpenBitFunResult<()> { + if analyzed_sessions == 0 { + return Err(OpenBitFunError::service( + "The selected model could not analyze any sessions", + )); + } + if failed_sections == ANALYSIS_SECTION_COUNT { + return Err(OpenBitFunError::service( + "The selected model could not generate any report sections", + )); + } + Ok(()) +} + +fn section_or_default( + result: OpenBitFunResult, + failed_sections: &mut u32, + default: impl FnOnce() -> T, +) -> T { + result.unwrap_or_else(|error| { + warn!("Insights report section failed: {error}"); + *failed_sections += 1; + default() + }) +} + +fn require_response_arrays(value: &Value, names: &[&str]) -> OpenBitFunResult<()> { + for name in names { + if !value[*name].is_array() { + return Err(OpenBitFunError::service(format!( + "Model response is missing an array for {name}" + ))); + } + } + Ok(()) +} + fn default_suggestions() -> InsightsSuggestions { InsightsSuggestions { openbitfun_md_additions: Vec::new(), @@ -1791,6 +1787,141 @@ fn json_value_to_string(value: &Value) -> String { mod tests { use super::*; + #[test] + fn generation_can_run_on_a_host_worker() { + fn assert_send(_: T) {} + assert_send(InsightsService::generate(30, None, None)); + } + + #[test] + fn all_failed_analysis_cannot_be_saved_as_a_success() { + assert!(ensure_report_has_analysis(0, 0).is_err()); + let mut failed_sections = 0; + for _ in 0..ANALYSIS_SECTION_COUNT { + section_or_default( + Err(OpenBitFunError::service("Fake provider failure")), + &mut failed_sections, + || (), + ); + } + assert!(ensure_report_has_analysis(2, failed_sections).is_err()); + assert!(ensure_report_has_analysis(2, failed_sections - 1).is_ok()); + assert!(require_response_arrays(&serde_json::json!({}), &["areas"]).is_err()); + assert!(require_response_arrays(&serde_json::json!({"areas": []}), &["areas"]).is_ok()); + } + + fn report_fixture() -> InsightsReport { + let stats = BaseStats { + total_sessions: 2, + ..BaseStats::default() + }; + let aggregate = InsightsCollector::aggregate(&stats, &[]); + InsightsService::assemble_report( + stats, + aggregate, + default_suggestions(), + vec![], + WinsFrictionResult::from_sections( + (Ok(WinsResult::default()), Ok(FrictionResult::default())), + &mut 0, + ), + InteractionStyleResult::default(), + AtAGlance::default(), + HorizonResult::default(), + None, + InsightsGenerationUsage::default(), + vec![], + 1, + LocaleId::EnUS, + ) + } + + #[tokio::test] + async fn legacy_report_round_trips_and_gets_a_safe_export_on_open() { + let mut legacy = serde_json::to_value(report_fixture()).unwrap(); + legacy.as_object_mut().unwrap().remove("failed_sections"); + legacy.as_object_mut().unwrap().remove("locale"); + legacy["at_a_glance"]["whats_working"] = + serde_json::json!("The focused regression tests verify the fix."); + legacy["stats"]["hour_counts"] = serde_json::json!({"18": 2}); + assert!(legacy["stats"].get("activity_by_utc_minute").is_none()); + let mut report: InsightsReport = serde_json::from_value(legacy).unwrap(); + assert_eq!(report.failed_sections, 0); + assert_eq!(report.locale, None); + assert_eq!(report.stats.hour_counts[&18], 2); + let round_trip: InsightsReport = + serde_json::from_str(&serde_json::to_string(&report).unwrap()).unwrap(); + assert_eq!(round_trip.stats.hour_counts, report.stats.hour_counts); + + let dir = tempfile::tempdir().unwrap(); + let json_path = dir.path().join("insights-123.json"); + let html_path = json_path.with_extension("html"); + tokio::fs::write(&html_path, "old export").await.unwrap(); + report.html_report_path = Some("untrusted-legacy-path.html".to_owned()); + InsightsService::refresh_report_html(&mut report, &json_path, LocaleId::ZhCN).await; + assert_eq!(report.html_report_path.as_deref(), html_path.to_str()); + let html = tokio::fs::read_to_string(html_path).await.unwrap(); + assert!(html.contains(r#""#)); + assert!(html.contains("Evening (18-24)")); + assert!(!html.contains("id=\"tz-selector\"")); + assert!(!html.contains("old export")); + } + + #[tokio::test] + async fn saved_report_language_survives_an_application_language_change() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("insights-123.json"); + let mut report = report_fixture(); + report.locale = Some("zh-TW".to_owned()); + report.at_a_glance.quick_wins = "建議先加入有針對性的回歸測試。".to_owned(); + let persisted = serde_json::to_vec(&report).unwrap(); + let mut reopened: InsightsReport = serde_json::from_slice(&persisted).unwrap(); + + InsightsService::refresh_report_html(&mut reopened, &path, LocaleId::EnUS).await; + let html = tokio::fs::read_to_string(path.with_extension("html")) + .await + .unwrap(); + assert!(html.contains(r#""#)); + assert!(html.contains("概覽")); + assert!(html.contains(&report.at_a_glance.quick_wins)); + assert_eq!(reopened.locale.as_deref(), Some("zh-TW")); + } + + #[test] + fn legacy_chinese_narrative_survives_an_english_application_locale() { + let mut report = report_fixture(); + report.locale = None; + report.at_a_glance.whats_working = + "为导入功能添加回归测试,确保 CSV 中的空行和引号都能正常处理。".to_owned(); + assert_eq!(report_locale(&report, LocaleId::EnUS), LocaleId::ZhCN); + } + + #[test] + fn prompt_explicitly_requests_the_report_language_for_each_locale() { + for locale in LocaleId::all() { + let prompt = InsightsService::build_language_instruction(locale); + assert!(prompt.contains(&format!("written in {}", locale.model_language_name()))); + } + } + + #[test] + fn partial_report_exposes_failed_sections_and_utc_buckets() { + let mut report = report_fixture(); + report.analyzed_sessions = 1; + report.stats.activity_by_utc_minute.insert(29_750_999, 2); + let html = generate_html(&report, LocaleId::EnUS); + assert!(html.contains("Partial report. 1 report sections failed.")); + assert!(html.contains("data-minutes=\"{"29750999":2}\"")); + let persisted: InsightsReport = + serde_json::from_value(serde_json::to_value(&report).unwrap()).unwrap(); + assert_eq!(persisted.failed_sections, 1); + assert_eq!(persisted.analyzed_sessions, 1); + assert_eq!( + persisted.stats.activity_by_utc_minute, + report.stats.activity_by_utc_minute + ); + } + #[test] fn retired_auto_insights_input_is_canonicalized_to_primary() { assert_eq!(normalize_insights_model_selector(Some(" auto ")), "primary"); diff --git a/src/crates/assembly/core/src/agentic/insights/session_paths.rs b/src/crates/assembly/core/src/agentic/insights/session_paths.rs index 043bfdbea3..a74667f96e 100644 --- a/src/crates/assembly/core/src/agentic/insights/session_paths.rs +++ b/src/crates/assembly/core/src/agentic/insights/session_paths.rs @@ -3,7 +3,7 @@ use crate::agentic::session::session_store_port::CoreSessionStorePort; use crate::service::workspace::get_global_workspace_service; use openbitfun_runtime_ports::SessionStorePort; -use std::collections::HashSet; +use std::collections::{BTreeMap, BTreeSet}; use std::path::PathBuf; #[derive(Debug, Clone)] @@ -13,26 +13,74 @@ pub struct EffectiveSessionStorageTarget { pub session_storage_path: PathBuf, } -/// Enumerate registered workspace IDs, then ask the persistence owner for roots. +/// Resolve project owners rather than scanning each execution worktree. /// A failed resolution is never replaced by the logical execution directory. pub async fn collect_effective_session_storage_targets( ) -> crate::OpenBitFunResult> { let service = get_global_workspace_service() .ok_or_else(|| crate::OpenBitFunError::service("Workspace service is unavailable"))?; - let mut targets = Vec::new(); - let mut seen = HashSet::new(); - for workspace in service.list_workspace_infos().await { - let resolution = CoreSessionStorePort::default() - .resolve_workspace_storage(&workspace.id) + let workspaces = service.list_workspace_infos().await; + let project_ids = workspaces + .iter() + .map(|workspace| workspace.project_workspace_id()) + .collect::, _>>() + .map_err(crate::OpenBitFunError::service)?; + let mut targets = BTreeMap::new(); + let store = CoreSessionStorePort::default(); + for project_id in project_ids { + let resolution = store + .resolve_workspace_storage(project_id) .await .map_err(|error| crate::OpenBitFunError::service(error.to_string()))?; - if resolution.effective_storage_path.exists() && seen.insert(workspace.id.clone()) { - targets.push(EffectiveSessionStorageTarget { - workspace_id: workspace.id, - workspace_path: workspace.root_path, - session_storage_path: resolution.effective_storage_path, - }); + if resolution.effective_storage_path.is_dir() { + insert_storage_target( + &mut targets, + EffectiveSessionStorageTarget { + workspace_id: project_id.to_owned(), + workspace_path: resolution.requested_workspace_path, + session_storage_path: resolution.effective_storage_path, + }, + ); } } - Ok(targets) + Ok(targets.into_values().collect()) +} + +fn insert_storage_target( + targets: &mut BTreeMap, + target: EffectiveSessionStorageTarget, +) { + targets + .entry(target.session_storage_path.clone()) + .or_insert(target); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn shared_storage_is_scanned_once_and_remote_mirrors_remain_distinct() { + let mut targets = BTreeMap::new(); + for (id, workspace, storage) in [ + ("project", "/repo", "/runtime/project/sessions"), + ("worktree", "/worktrees/branch", "/runtime/project/sessions"), + ("ssh-a", "/repo", "/runtime/ssh-a/sessions"), + ("ssh-b", "/repo", "/runtime/ssh-b/sessions"), + ] { + insert_storage_target( + &mut targets, + EffectiveSessionStorageTarget { + workspace_id: id.into(), + workspace_path: workspace.into(), + session_storage_path: storage.into(), + }, + ); + } + assert_eq!(targets.len(), 3); + assert_eq!( + targets[&PathBuf::from("/runtime/project/sessions")].workspace_id, + "project" + ); + } } diff --git a/src/crates/assembly/core/src/agentic/insights/types.rs b/src/crates/assembly/core/src/agentic/insights/types.rs index 6cc92c6b61..6cb84c95cc 100644 --- a/src/crates/assembly/core/src/agentic/insights/types.rs +++ b/src/crates/assembly/core/src/agentic/insights/types.rs @@ -1,5 +1,5 @@ use serde::{Deserialize, Serialize}; -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; // ============ Stage 1: Data Collection ============ @@ -9,7 +9,8 @@ pub struct SessionTranscript { pub session_id: String, pub agent_type: String, pub session_name: String, - pub workspace_path: Option, + #[serde(default, alias = "workspace_path")] + pub session_storage_scope: Option, /// For facet cache fingerprinting (`SessionSummary.last_activity_at`). #[serde(default)] pub last_activity_unix_secs: u64, @@ -37,6 +38,8 @@ pub struct BaseStats { pub tool_usage: HashMap, pub tool_errors: HashMap, pub hour_counts: HashMap, + #[serde(default)] + pub activity_by_utc_minute: BTreeMap, pub agent_types: HashMap, /// Raw response time intervals in seconds (intermediate, not serialized to report) #[serde(skip)] @@ -230,6 +233,9 @@ pub struct InsightsStats { pub session_types: HashMap, pub languages: HashMap, pub hour_counts: HashMap, + /// UTC minute buckets for timezone conversion in exported reports. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub activity_by_utc_minute: BTreeMap, pub agent_types: HashMap, #[serde(default)] pub response_time_buckets: HashMap, @@ -255,9 +261,14 @@ pub struct InsightsStats { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct InsightsReport { pub generated_at: u64, + /// The language requested from the model when this report was generated. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub locale: Option, pub date_range: DateRange, pub total_sessions: u32, pub analyzed_sessions: u32, + #[serde(default)] + pub failed_sections: u32, pub total_messages: u32, pub days_covered: u32, @@ -322,6 +333,8 @@ pub struct InsightsReportMeta { pub generated_at: u64, pub total_sessions: u32, pub analyzed_sessions: u32, + #[serde(default)] + pub failed_sections: u32, pub date_range: DateRange, pub path: String, #[serde(default)] diff --git a/src/web-ui/src/app/scenes/my-agent/InsightsHtml.test.ts b/src/web-ui/src/app/scenes/my-agent/InsightsHtml.test.ts new file mode 100644 index 0000000000..1d63dce6b7 --- /dev/null +++ b/src/web-ui/src/app/scenes/my-agent/InsightsHtml.test.ts @@ -0,0 +1,70 @@ +// @vitest-environment jsdom + +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +const renderer = readFileSync( + resolve(process.cwd(), '../crates/assembly/core/src/agentic/insights/html.rs'), + 'utf8', +); +const script = renderer.split('const JS_SCRIPT: &str = r#"')[1].split('"#;')[0]; + +afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + document.body.replaceChildren(); +}); + +describe('insights HTML report script', () => { + it('copies the displayed text with its original quotes and punctuation', async () => { + vi.useFakeTimers(); + document.body.innerHTML = ` +
+ "quoted" & <examples> 'apostrophes' + +
+ `; + const writeText = vi.fn().mockResolvedValue(undefined); + const clipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard'); + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }); + try { + window.eval(script); + document.querySelector('button')!.click(); + expect(writeText).toHaveBeenCalledExactlyOnceWith('"quoted" & \'apostrophes\''); + await vi.runAllTimersAsync(); + } finally { + if (clipboard) Object.defineProperty(navigator, 'clipboard', clipboard); + else Reflect.deleteProperty(navigator, 'clipboard'); + } + }); + + it('uses original UTC minutes once and follows the selected timezone', () => { + document.body.innerHTML = ` +
+ +
+
+ `; + const chart = document.getElementById('time-of-day-chart')!; + chart.dataset.minutes = JSON.stringify({ + [Date.UTC(2026, 10, 19, 10, 0) / 60_000]: 2, + [Date.UTC(2026, 10, 19, 12, 30) / 60_000]: 3, + [Date.UTC(2026, 6, 19, 21, 30) / 60_000]: 5, + }); + chart.dataset.labels = JSON.stringify(['Morning', 'Afternoon', 'Evening', 'Night']); + window.eval(script); + + const selector = document.querySelector('#tz-selector')!; + const countsIn = (zone: string) => { + selector.value = zone; + selector.dispatchEvent(new Event('change')); + return [...document.querySelectorAll('.bar-value')].map(element => Number(element.textContent)); + }; + + expect(countsIn('UTC')).toEqual([2, 3, 5, 0]); + expect(countsIn('Asia/Shanghai')).toEqual([0, 0, 5, 5]); + expect(countsIn('Asia/Kolkata')).toEqual([0, 2, 3, 5]); + expect(countsIn('America/New_York')).toEqual([3, 5, 0, 2]); + }); +}); diff --git a/src/web-ui/src/app/scenes/my-agent/InsightsScene.tsx b/src/web-ui/src/app/scenes/my-agent/InsightsScene.tsx index 8273f2a5d8..27f06a5fd3 100644 --- a/src/web-ui/src/app/scenes/my-agent/InsightsScene.tsx +++ b/src/web-ui/src/app/scenes/my-agent/InsightsScene.tsx @@ -385,6 +385,9 @@ const ReportMetaCard: React.FC<{
+ {(meta.analyzed_sessions < meta.total_sessions || (meta.failed_sections ?? 0) > 0) && ( + {t('insights.partialReport')} + )} {meta.total_hours.toFixed(1)} {t('insights.hours')} @@ -527,7 +530,7 @@ const ReportNav: React.FC<{ report: InsightsReport; scrollContainerRef: React.Re }; const ReportView: React.FC<{ report: InsightsReport; onBack: () => void }> = ({ report, onBack }) => { - const { t } = useI18n('common'); + const { t, formatNumber } = useI18n('common'); const bodyRef = useRef(null); const handleOpenHtml = useCallback(async () => { @@ -583,6 +586,15 @@ const ReportView: React.FC<{ report: InsightsReport; onBack: () => void }> = ({

{t('insights.reportTitle', { dateStart, dateEnd })}

+ {(report.analyzed_sessions < report.total_sessions || (report.failed_sections ?? 0) > 0) && ( +

+ {t('insights.partialReportCoverage', { + analyzed: formatNumber(report.analyzed_sessions), + total: formatNumber(report.total_sessions), + failed: formatNumber(report.failed_sections ?? 0), + })} +

+ )}
diff --git a/src/web-ui/src/app/scenes/my-agent/insightsStore.test.ts b/src/web-ui/src/app/scenes/my-agent/insightsStore.test.ts index ab9838f140..51a6c874ae 100644 --- a/src/web-ui/src/app/scenes/my-agent/insightsStore.test.ts +++ b/src/web-ui/src/app/scenes/my-agent/insightsStore.test.ts @@ -145,6 +145,72 @@ describe('insightsStore generation lifecycle', () => { expect(useInsightsStore.getState().view).toBe('report'); }); + it('discards old-generation events delivered to the current listener', async () => { + const pendingReport = deferred(); + let progressHandler: ((event: InsightsProgressEvent) => void) | undefined; + apiMocks.generateInsights.mockReturnValueOnce(pendingReport.promise); + apiMocks.listenProgress.mockImplementationOnce(async (handler) => { + progressHandler = handler; + return vi.fn(); + }); + + const run = useInsightsStore.getState().generateReport(); + const generationId = useInsightsStore.getState().activeGenerationRunId; + await vi.waitFor(() => expect(apiMocks.generateInsights).toHaveBeenCalledTimes(1)); + const event = { stage: 'analysis', message: 'Analysis', current: 0, total: 0 }; + progressHandler?.({ ...event, generationId: 'older-generation' }); + expect(useInsightsStore.getState().progress.stage).toBe('starting'); + progressHandler?.({ ...event, generationId }); + expect(useInsightsStore.getState().progress.stage).toBe('analysis'); + + await useInsightsStore.getState().cancelGeneration(); + expect(apiMocks.cancelGeneration).toHaveBeenCalledWith(generationId); + pendingReport.reject(new Error('cancelled')); + await run; + }); + + it('cancels locally before the progress listener finishes registering', async () => { + const listener = deferred<() => void>(); + const unlisten = vi.fn(); + apiMocks.listenProgress.mockReturnValueOnce(listener.promise); + const run = useInsightsStore.getState().generateReport(); + + await useInsightsStore.getState().cancelGeneration(); + listener.resolve(unlisten); + await run; + + expect(apiMocks.generateInsights).not.toHaveBeenCalled(); + expect(apiMocks.cancelGeneration).not.toHaveBeenCalled(); + expect(unlisten).toHaveBeenCalledOnce(); + expect(useInsightsStore.getState().generating).toBe(false); + }); + + it('keeps a failed cancellation visible while the report is still running', async () => { + const pendingReport = deferred(); + apiMocks.generateInsights.mockReturnValueOnce(pendingReport.promise); + apiMocks.cancelGeneration.mockRejectedValueOnce(new Error('Service unavailable')); + const run = useInsightsStore.getState().generateReport(); + await vi.waitFor(() => expect(apiMocks.generateInsights).toHaveBeenCalledTimes(1)); + + await useInsightsStore.getState().cancelGeneration(); + expect(useInsightsStore.getState().generating).toBe(true); + expect(useInsightsStore.getState().error).toContain('Service unavailable'); + pendingReport.resolve(report(1)); + await run; + expect(useInsightsStore.getState().view).toBe('report'); + }); + + it('keeps a provider failure on the error screen instead of displaying a report', async () => { + apiMocks.generateInsights.mockRejectedValueOnce(new Error('The selected model could not analyze any sessions')); + await useInsightsStore.getState().generateReport(); + + const state = useInsightsStore.getState(); + expect(state.generating).toBe(false); + expect(state.currentReport).toBeNull(); + expect(state.view).toBe('list'); + expect(state.error).toContain('could not analyze any sessions'); + }); + it('marks backend analysis retries as retrying progress', async () => { const pendingReport = deferred(); let progressHandler: ((event: InsightsProgressEvent) => void) | undefined; @@ -176,7 +242,7 @@ describe('insightsStore generation lifecycle', () => { const run = useInsightsStore.getState().generateReport(); await vi.waitFor(() => { - expect(apiMocks.generateInsights).toHaveBeenCalledWith(30, 'model-insights'); + expect(apiMocks.generateInsights).toHaveBeenCalledWith(30, 'model-insights', expect.any(String)); }); await useInsightsStore.getState().cancelGeneration(); diff --git a/src/web-ui/src/app/scenes/my-agent/insightsStore.ts b/src/web-ui/src/app/scenes/my-agent/insightsStore.ts index d5068b6d84..8651520d54 100644 --- a/src/web-ui/src/app/scenes/my-agent/insightsStore.ts +++ b/src/web-ui/src/app/scenes/my-agent/insightsStore.ts @@ -5,7 +5,8 @@ import { createLogger } from '@/shared/utils/logger'; const log = createLogger('InsightsStore'); const RETRY_STAGES = new Set(['facet_retry', 'analysis_retry']); -let nextGenerationRunId = 0; +let submittedRunId: string | null = null; +let cancellation: { runId: string; accepted: Promise } | null = null; export type InsightsView = 'list' | 'report'; @@ -27,7 +28,7 @@ interface InsightsState { selectedModel: string; error: string; loadingMetas: boolean; - activeGenerationRunId: number | null; + activeGenerationRunId: string | null; setSelectedDays: (days: number) => void; setSelectedModel: (modelId: string) => void; @@ -86,7 +87,7 @@ export const useInsightsStore = create((set, get) => ({ generateReport: async () => { const { selectedDays, selectedModel, generating } = get(); if (generating) return; - const runId = ++nextGenerationRunId; + const runId = globalThis.crypto?.randomUUID?.() ?? `insights-${Date.now()}-${Math.random().toString(36).slice(2)}`; set({ generating: true, @@ -98,7 +99,7 @@ export const useInsightsStore = create((set, get) => ({ let unlisten: (() => void) | undefined; try { unlisten = await insightsApi.listenProgress((event: InsightsProgressEvent) => { - if (get().activeGenerationRunId !== runId) return; + if (get().activeGenerationRunId !== runId || (event.generationId && event.generationId !== runId)) return; const { message, stage, current, total } = event; set({ progress: { @@ -111,7 +112,9 @@ export const useInsightsStore = create((set, get) => ({ }); }); - const report = await insightsApi.generateInsights(selectedDays, selectedModel); + if (get().activeGenerationRunId !== runId) return; + submittedRunId = runId; + const report = await insightsApi.generateInsights(selectedDays, selectedModel, runId); if (get().activeGenerationRunId !== runId) return; log.info('Insights report generated', { sessions: report.total_sessions, @@ -120,12 +123,14 @@ export const useInsightsStore = create((set, get) => ({ set({ currentReport: report, view: 'report', + error: '', generating: false, activeGenerationRunId: null, progress: { ...defaultProgress }, }); get().fetchReportMetas(); } catch (err) { + if (cancellation?.runId === runId && await cancellation.accepted) return; if (get().activeGenerationRunId !== runId) return; log.error('Failed to generate insights', err); set({ @@ -136,23 +141,34 @@ export const useInsightsStore = create((set, get) => ({ progress: { ...defaultProgress }, }); } finally { + if (submittedRunId === runId) submittedRunId = null; unlisten?.(); } }, cancelGeneration: async () => { const runId = get().activeGenerationRunId; - if (!get().generating || runId == null) return; - try { - await insightsApi.cancelGeneration(); - } catch (err) { - log.error('Failed to cancel insights generation', err); + if (!get().generating || runId == null || cancellation?.runId === runId) return; + if (submittedRunId === runId) { + const accepted = insightsApi.cancelGeneration(runId).then( + () => true, + (err) => { + log.error('Failed to cancel insights generation', err); + if (get().activeGenerationRunId === runId) set({ error: String(err) }); + return false; + }, + ); + cancellation = { runId, accepted }; + const cancelled = await accepted; + if (cancellation?.runId === runId) cancellation = null; + if (!cancelled) return; } if (get().activeGenerationRunId !== runId) return; set({ generating: false, activeGenerationRunId: null, progress: { ...defaultProgress }, + error: '', }); }, diff --git a/src/web-ui/src/infrastructure/api/insightsApi.ts b/src/web-ui/src/infrastructure/api/insightsApi.ts index 89148de31b..5b0feb1cf2 100644 --- a/src/web-ui/src/infrastructure/api/insightsApi.ts +++ b/src/web-ui/src/infrastructure/api/insightsApi.ts @@ -89,6 +89,7 @@ export interface InsightsStats { session_types: Record; languages: Record; hour_counts: Record; + activity_by_utc_minute?: Record; agent_types: Record; response_time_buckets: Record; median_response_time_secs: number | null; @@ -103,9 +104,11 @@ export interface InsightsStats { export interface InsightsReport { generated_at: number; + locale?: string; date_range: DateRange; total_sessions: number; analyzed_sessions: number; + failed_sections?: number; total_messages: number; days_covered: number; session_usage: InsightsSessionUsage; @@ -153,6 +156,7 @@ export interface InsightsReportMeta { generated_at: number; total_sessions: number; analyzed_sessions: number; + failed_sections?: number; date_range: DateRange; path: string; total_messages: number; @@ -166,6 +170,7 @@ export interface InsightsReportMeta { } export interface InsightsProgressEvent { + generationId?: string | null; message: string; stage: string; current: number; @@ -175,10 +180,13 @@ export interface InsightsProgressEvent { // ============ API client ============ export const insightsApi = { - async generateInsights(days?: number, modelId?: string): Promise { - return api.invoke('generate_insights', { - request: { days: days ?? 30, modelId: modelId || 'primary' }, - }); + async generateInsights(days?: number, modelId?: string, generationId?: string): Promise { + // Generation spans multiple model calls and can be cancelled separately. + return api.invoke( + 'generate_insights', + { request: { days: days ?? 30, modelId: modelId || 'primary', ...(generationId && { generationId }) } }, + { timeout: 0 }, + ); }, async getLatestInsights(): Promise { @@ -197,8 +205,8 @@ export const insightsApi = { }); }, - async cancelGeneration(): Promise { - return api.invoke('cancel_insights_generation'); + async cancelGeneration(generationId: string): Promise { + return api.invoke('cancel_insights_generation', { request: { generationId } }); }, async listenProgress( diff --git a/src/web-ui/src/infrastructure/api/service-api/ApiClient.test.ts b/src/web-ui/src/infrastructure/api/service-api/ApiClient.test.ts index a7e637610f..b9f3c1370f 100644 --- a/src/web-ui/src/infrastructure/api/service-api/ApiClient.test.ts +++ b/src/web-ui/src/infrastructure/api/service-api/ApiClient.test.ts @@ -1,4 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { insightsApi } from '../insightsApi'; import { ApiClient, createRetryMiddleware } from './ApiClient'; import { workspaceAPI } from './WorkspaceAPI'; import { @@ -284,6 +285,30 @@ describe('ApiClient startup trace classification', () => { } }); + it('returns an insights report that takes longer than the default deadline', async () => { + vi.useFakeTimers(); + try { + const report = { total_sessions: 12, analyzed_sessions: 12 }; + adapterMocks.request.mockImplementationOnce(() => new Promise(resolve => { + setTimeout(() => resolve(report), 60_000); + })); + + const result = insightsApi.generateInsights(30, 'primary'); + await Promise.all([ + expect(result).resolves.toEqual(report), + vi.advanceTimersByTimeAsync(60_000), + ]); + + expect(adapterMocks.request).toHaveBeenCalledExactlyOnceWith( + 'generate_insights', + { request: { days: 30, modelId: 'primary' } }, + expect.any(Object), + ); + } finally { + vi.useRealTimers(); + } + }); + it.each(['workspace', 'legacy'] as const)('waits for a long %s directory deletion to finish', async (entry) => { vi.useFakeTimers(); try { diff --git a/src/web-ui/src/locales/en-US/common.json b/src/web-ui/src/locales/en-US/common.json index 21bf1fe29a..94471af1b5 100644 --- a/src/web-ui/src/locales/en-US/common.json +++ b/src/web-ui/src/locales/en-US/common.json @@ -1920,6 +1920,8 @@ "messages": "Messages", "analyzed": "analyzed", "analyzedSessions": "Sessions analyzed", + "partialReport": "Partial report", + "partialReportCoverage": "Partial report. {{analyzed}} of {{total}} sessions analyzed. {{failed}} report sections failed.", "hours": "Hours", "days": "Days", "msgsPerDay": "Msgs/Day", diff --git a/src/web-ui/src/locales/zh-CN/common.json b/src/web-ui/src/locales/zh-CN/common.json index 0b88c8187e..95db37d7a3 100644 --- a/src/web-ui/src/locales/zh-CN/common.json +++ b/src/web-ui/src/locales/zh-CN/common.json @@ -1920,6 +1920,8 @@ "messages": "消息", "analyzed": "已分析", "analyzedSessions": "已分析会话", + "partialReport": "部分生成", + "partialReportCoverage": "报告部分生成。已分析 {{analyzed}} / {{total}} 个会话,{{failed}} 个报告章节生成失败。", "hours": "小时", "days": "天", "msgsPerDay": "消息/天", diff --git a/src/web-ui/src/locales/zh-TW/common.json b/src/web-ui/src/locales/zh-TW/common.json index 6a8dfa18cf..6b17599d39 100644 --- a/src/web-ui/src/locales/zh-TW/common.json +++ b/src/web-ui/src/locales/zh-TW/common.json @@ -1920,6 +1920,8 @@ "messages": "消息", "analyzed": "已分析", "analyzedSessions": "已分析會話", + "partialReport": "部分產生", + "partialReportCoverage": "報告部分產生。已分析 {{analyzed}} / {{total}} 個會話,{{failed}} 個報告章節產生失敗。", "hours": "小時", "days": "天", "msgsPerDay": "消息/天",