π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Type the errors end to end, from core through the FFI
Manav Rathi0439517bc422
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.ktindex 094dfdcf35..828eb56384 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.kt@@ -12,6 +12,7 @@ import io.ente.ensu.llm.LlmProviderimport io.ente.ensu.chat.Attachmentimport io.ente.ensu.chat.ChatMessageimport io.ente.ensu.chat.ChatSession+import io.ente.ensu.bindings.LlmExceptionimport io.ente.ensu.bindings.ConfigDefaultsimport io.ente.ensu.logging.LogLevelimport io.ente.ensu.chat.MessageAuthor@@ -582,7 +583,7 @@ internal class ChatStoreActions(shouldUpdateUi = isActive())} catch (err: Throwable) {- val interrupted = stopRequested || err.message?.contains("cancel", ignoreCase = true) == true+ val interrupted = stopRequested || err is LlmException.CancelledfinishGeneration(sessionId,userMessage,diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/VoiceInput.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/VoiceInput.ktindex b6768d39f9..6d392e0c92 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/VoiceInput.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/VoiceInput.kt@@ -139,14 +139,14 @@ internal class VoiceTranscriptionController(state = VoiceInputState.Error("Voice transcription is not available on this device.")} catch (error: TranscriptionException) {Log.w(TAG, "Voice model preparation failed: ${error.message}", error)- state = VoiceInputState.Error(transcriptionErrorMessage(error.message))+ state = VoiceInputState.Error(transcriptionErrorMessage(error))} catch (error: Throwable) {Log.w(TAG,"Voice model preparation failed: ${error.javaClass.simpleName}: ${error.message}",error)- state = VoiceInputState.Error(transcriptionErrorMessage(error.message))+ state = VoiceInputState.Error("Could not transcribe voice input.")}}}@@ -287,14 +287,14 @@ internal class VoiceTranscriptionController(state = VoiceInputState.Error("Voice transcription is not available on this device.")} catch (error: TranscriptionException) {Log.w(TAG, "Voice transcription failed: ${error.message}", error)- state = VoiceInputState.Error(transcriptionErrorMessage(error.message))+ state = VoiceInputState.Error(transcriptionErrorMessage(error))} catch (error: Throwable) {Log.w(TAG,"Voice transcription failed: ${error.javaClass.simpleName}: ${error.message}",error)- state = VoiceInputState.Error(transcriptionErrorMessage(error.message))+ state = VoiceInputState.Error("Could not transcribe voice input.")}}@@ -446,21 +446,13 @@ internal class VoiceTranscriptionController(private fun downloadErrorMessage(): String ="Voice model download failed. Check your connection and try again."- private fun transcriptionErrorMessage(message: String?): String {- val lowerMessage = message.orEmpty().lowercase()- return when {- lowerMessage.contains("download") ||- lowerMessage.contains("http") ||- lowerMessage.contains("request") ||- lowerMessage.contains("connection") ||- lowerMessage.contains("network") ||- lowerMessage.contains("dns") ||- lowerMessage.contains("certificate") ||- lowerMessage.contains("tls") -> downloadErrorMessage()- lowerMessage.contains("model") -> "Voice model could not be loaded."- lowerMessage.contains("vad") -> "Could not detect speech in this recording."- else -> "Could not transcribe voice input."- }+ private fun transcriptionErrorMessage(error: TranscriptionException): String = when (error) {+ is TranscriptionException.Download -> downloadErrorMessage()+ is TranscriptionException.NotDownloaded,+ is TranscriptionException.VadNotDownloaded,+ is TranscriptionException.Transcribe -> "Voice model could not be loaded."+ is TranscriptionException.InvalidAudio -> "Could not detect speech in this recording."+ is TranscriptionException.Io -> "Could not transcribe voice input."}private fun showTransientError(message: String) {diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.ktindex 619a81a9d8..167be8f556 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt@@ -510,7 +510,9 @@ class LlmProvider(}private fun Throwable.isDownloadCancellation(): Boolean {- return message?.contains("cancelled", ignoreCase = true) == true+ // The message check covers the system DownloadManager fallback path.+ return this is LlmException.Cancelled ||+ message?.contains("cancelled", ignoreCase = true) == true}private fun cancelNativeDownloads(target: LlmModelTarget) {@@ -780,8 +782,6 @@ class LlmProvider(request: LlmChatRequest,onToken: (String) -> Unit): NativeSummary {- var error: Throwable? = null-val callback = object : LlmGenerationEventCallback {override fun onEvent(event: LlmGenerationEvent) {when (event) {@@ -794,17 +794,14 @@ class LlmProvider(is LlmGenerationEvent.Done -> {currentJobId = null}- is LlmGenerationEvent.Error -> {- currentJobId = null- error = LlmException.Message(event.message)- }}}}- val summary = context.generateChatStream(request, callback)-- error?.let { throw it }- return summary+ try {+ return context.generateChatStream(request, callback)+ } finally {+ currentJobId = null+ }}}diff --git a/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift b/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swiftindex 3a5f12ba05..0d4ada624c 100644--- a/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift+++ b/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift@@ -1958,6 +1958,8 @@ final class ChatViewModel: ObservableObject {private func isCancellation(_ error: Error) -> Bool {if error is CancellationError { return true }+ if case LlmError.Cancelled = error { return true }+ // The description check covers the URLSession download fallback path.return error.localizedDescription.localizedCaseInsensitiveContains("cancel")}@@ -1974,6 +1976,18 @@ final class ChatViewModel: ObservableObject {if isCancellation(error) { return false }if isOutOfStorageError(error) { return false }+ if case let LlmError.Download(inner) = error {+ switch inner {+ case .validation:+ return false+ case let .http(status):+ if status == 401 || status == 403 || status == 404 { return false }+ default:+ break+ }+ }++ // The message checks cover the URLSession download fallback path.let message = error.localizedDescription.lowercased()if message.contains("not gguf") { return false }if message.contains("http 401") || message.contains("http 403") || message.contains("http 404") {diff --git a/mobile/native/apple/apps/ensu/Ensu/Services/LlmProvider.swift b/mobile/native/apple/apps/ensu/Ensu/Services/LlmProvider.swiftindex 95192cc15a..69305e0fc4 100644--- a/mobile/native/apple/apps/ensu/Ensu/Services/LlmProvider.swift+++ b/mobile/native/apple/apps/ensu/Ensu/Services/LlmProvider.swift@@ -238,9 +238,6 @@ final class LlmProvider {grammar: nil)- var error: Error?- let lock = NSLock()-let sink = CallbackSink { event inswitch event {case let .text(jobId, text, _):@@ -248,11 +245,6 @@ final class LlmProvider {onToken(text)case .done:self.currentJobId = nil- case let .error(_, message):- self.currentJobId = nil- lock.lock()- error = NSError(domain: "LlmProvider", code: -2, userInfo: [NSLocalizedDescriptionKey: message])- lock.unlock()}}@@ -261,15 +253,9 @@ final class LlmProvider {do {self.unloadTranscriptionModelIfLoaded()let summary = try context.generateChatStream(request: request, callback: sink)- lock.lock()- let localError = error- lock.unlock()- if let localError {- continuation.resume(throwing: localError)- } else {- continuation.resume(returning: summary)- }+ continuation.resume(returning: summary)} catch {+ self.currentJobId = nilcontinuation.resume(throwing: error)}}@@ -607,7 +593,9 @@ final class LlmProvider {}private func isDownloadCancellation(_ error: Error) -> Bool {- error is CancellationError ||+ if case LlmError.Cancelled = error { return true }+ // The description check covers the URLSession fallback path.+ return error is CancellationError ||isRustDownloadCancelled() ||error.localizedDescription.range(of: "cancelled", options: .caseInsensitive) != nil}diff --git a/mobile/native/apple/apps/ensu/EnsuTests/LlmIntegrationTests.swift b/mobile/native/apple/apps/ensu/EnsuTests/LlmIntegrationTests.swiftindex dd45b1354c..853ee748e5 100644--- a/mobile/native/apple/apps/ensu/EnsuTests/LlmIntegrationTests.swift+++ b/mobile/native/apple/apps/ensu/EnsuTests/LlmIntegrationTests.swift@@ -15,13 +15,6 @@ private final class GenerateEventCollector: LlmGenerationEventCallback {}}- var lastError: String? {- events.compactMap { event in- if case let .error(_, message) = event { return message }- return nil- }.last- }-var textOutput: String {events.compactMap { event inif case let .text(_, text, _) = event { return text }@@ -80,7 +73,6 @@ final class LlmIntegrationTests: XCTestCase {XCTAssertGreaterThan(summary.jobId, 0)XCTAssertTrue(collector.hasDone)- XCTAssertNil(collector.lastError)XCTAssertFalse(collector.textOutput.isEmpty)}@@ -131,7 +123,6 @@ final class LlmIntegrationTests: XCTestCase {XCTAssertGreaterThan(summary.jobId, 0)XCTAssertTrue(collector.hasDone)- XCTAssertNil(collector.lastError)XCTAssertFalse(collector.textOutput.isEmpty)}diff --git a/rust/apps/ensu/src-tauri/src/commands/llm.rs b/rust/apps/ensu/src-tauri/src/commands/llm.rsindex badef2a457..b273a0db5c 100644--- a/rust/apps/ensu/src-tauri/src/commands/llm.rs+++ b/rust/apps/ensu/src-tauri/src/commands/llm.rs@@ -30,8 +30,6 @@ impl Default for ModelDownloadState {}}-const PANIC_JOB_ID: i64 = 0;-#[derive(Debug, Deserialize)]#[serde(rename_all = "camelCase")]pub struct DownloadRequest {@@ -56,6 +54,32 @@ fn llm_error(message: impl Into<String>) -> ApiError {ApiError::new("llm", message)}+fn llm_api_error(err: llm::Error) -> ApiError {+ let code = match &err {+ llm::Error::Cancelled => "cancelled",+ llm::Error::Panicked => "panicked",+ llm::Error::InvalidInput(_) => "invalid_input",+ llm::Error::NotFound { .. } => "not_found",+ llm::Error::Unsupported(_) => "unsupported",+ llm::Error::PromptTooLong { .. } => "prompt_too_long",+ llm::Error::Llama { .. } => "llm",+ llm::Error::Download(err) => download_code(err),+ };+ ApiError::new(code, err.to_string())+}++fn download_code(err: &download::Error) -> &'static str {+ match err {+ download::Error::Cancelled => "cancelled",+ download::Error::Target { source, .. } => download_code(source),+ download::Error::Fallback { single, .. } => download_code(single),+ download::Error::Http(_) => "http",+ download::Error::Validation(_) => "validation",+ download::Error::Network(_) => "network",+ _ => "download",+ }+}+fn llm_thread_error() -> ApiError {ApiError::new("llm", "LLM task failed")}@@ -103,10 +127,6 @@ enum Event {Done {summary: llm::GenerationSummary,},- Error {- job_id: llm::JobId,- message: String,- },}impl From<llm::GenerationEvent> for Event {@@ -122,7 +142,6 @@ impl From<llm::GenerationEvent> for Event {token_id,},llm::GenerationEvent::Done { summary } => Self::Done { summary },- llm::GenerationEvent::Error { job_id, message } => Self::Error { job_id, message },}}}@@ -206,12 +225,6 @@ impl llm::EventSink for EventSink {self.flush_text();let _ = self.window.emit("llm-event", Event::Done { summary });}- llm::GenerationEvent::Error { job_id, message } => {- self.flush_text();- let _ = self- .window- .emit("llm-event", Event::Error { job_id, message });- }}}}@@ -244,7 +257,7 @@ pub async fn llm_download_model_files(},move || cancel_requested.load(Ordering::SeqCst),)- .map_err(|err| llm_error(err.to_string()))+ .map_err(llm_api_error)}).await.map_err(|_| fs_thread_error())?@@ -354,7 +367,7 @@ fn format_rate(bytes_per_second: f64) -> String {pub async fn llm_init_backend() -> Result<(), ApiError> {logging::log("LLM", "init backend requested");async_runtime::spawn_blocking(|| match catch_unwind(AssertUnwindSafe(llm::init_backend)) {- Ok(result) => result.map_err(llm_error),+ Ok(result) => result.map_err(llm_api_error),Err(payload) => {let message = panic_message(payload);log_command_panic("llm_init_backend", &message);@@ -384,7 +397,7 @@ pub async fn llm_load_model();let model = async_runtime::spawn_blocking(move || {match catch_unwind(AssertUnwindSafe(|| llm::Model::load(params))) {- Ok(result) => result.map_err(llm_error),+ Ok(result) => result.map_err(llm_api_error),Err(payload) => {let message = panic_message(payload);log_command_panic("llm_load_model", &message);@@ -432,7 +445,7 @@ pub async fn llm_create_context(let context = async_runtime::spawn_blocking(move || {match catch_unwind(AssertUnwindSafe(|| llm::Context::new(&model, params))) {- Ok(result) => result.map_err(llm_error),+ Ok(result) => result.map_err(llm_api_error),Err(payload) => {let message = panic_message(payload);log_command_panic("llm_create_context", &message);@@ -495,7 +508,7 @@ pub async fn llm_prewarm_multimodal_context(match catch_unwind(AssertUnwindSafe(|| {context.prewarm_multimodal(mmproj_path, media_marker)})) {- Ok(result) => result.map_err(llm_error),+ Ok(result) => result.map_err(llm_api_error),Err(payload) => {let message = panic_message(payload);log_command_panic("llm_prewarm_multimodal_context", &message);@@ -516,11 +529,11 @@ pub async fn llm_prewarm_multimodal_context(}#[tauri::command]-pub fn llm_generate_chat_stream(- state: TauriState<State>,+pub async fn llm_generate_chat_stream(+ state: TauriState<'_, State>,window: WebviewWindow,request: llm::ChatRequest,-) -> Result<(), ApiError> {+) -> Result<llm::GenerationSummary, ApiError> {let context = state.context.lock()@@ -531,29 +544,24 @@ pub fn llm_generate_chat_stream(async_runtime::spawn_blocking(move || {match catch_unwind(AssertUnwindSafe(|| {let mut sink = EventSink::new(window.clone());- let _ = context.generate_chat_stream(request, &mut sink);+ context.generate_chat_stream(request, &mut sink)})) {- Ok(()) => {}+ Ok(Ok(summary)) => Ok(summary),+ Ok(Err(err)) => Err(llm_api_error(err)),Err(payload) => {let message = panic_message(payload);log_command_panic("llm_generate_chat_stream", &message);- let _ = window.emit(- "llm-event",- Event::Error {- job_id: PANIC_JOB_ID,- message: format!("Generation panicked: {message}"),- },- );+ Err(llm_error(format!("Generation panicked: {message}")))}}- });-- Ok(())+ })+ .await+ .map_err(|_| llm_thread_error())?}#[tauri::command]-pub fn llm_cancel(job_id: i64) -> Result<(), ApiError> {- llm::cancel(job_id).map_err(llm_error)+pub fn llm_cancel(job_id: i64) {+ llm::cancel(job_id);}pub(crate) fn clear_for_exit(app: &AppHandle) {diff --git a/rust/bindings/uniffi/ensu/src/download.rs b/rust/bindings/uniffi/ensu/src/download.rsnew file mode 100644index 0000000000..35a17f099f--- /dev/null+++ b/rust/bindings/uniffi/ensu/src/download.rs@@ -0,0 +1,37 @@+use ente_ensu::download;++#[derive(Debug, Clone, uniffi::Enum)]+pub enum DownloadError {+ Cancelled,+ Validation { message: String },+ Http { status: u16 },+ Network { message: String },+ SizeMismatch { expected: u64, actual: u64 },+ Protocol { message: String },+ InvalidTarget { message: String },+ Io { message: String },+}++impl From<download::Error> for DownloadError {+ fn from(value: download::Error) -> Self {+ match value {+ download::Error::Cancelled => Self::Cancelled,+ download::Error::Target { source, .. } => Self::from(*source),+ download::Error::Fallback { single, .. } => Self::from(*single),+ download::Error::Validation(message) => Self::Validation { message },+ download::Error::Http(status) => Self::Http { status },+ download::Error::Network(message) => Self::Network { message },+ download::Error::SizeMismatch { expected, actual } => {+ Self::SizeMismatch { expected, actual }+ }+ download::Error::Protocol(message) => Self::Protocol { message },+ download::Error::InvalidTarget(message) => Self::InvalidTarget { message },+ download::Error::Io(err) => Self::Io {+ message: err.to_string(),+ },+ download::Error::Json(err) => Self::Io {+ message: err.to_string(),+ },+ }+ }+}diff --git a/rust/bindings/uniffi/ensu/src/lib.rs b/rust/bindings/uniffi/ensu/src/lib.rsindex 458baabb52..6696eba6f8 100644--- a/rust/bindings/uniffi/ensu/src/lib.rs+++ b/rust/bindings/uniffi/ensu/src/lib.rs@@ -2,6 +2,7 @@ uniffi::setup_scaffolding!("ensu");pub mod config;pub mod db;+pub mod download;pub mod image;pub mod llm;pub mod transcription;diff --git a/rust/bindings/uniffi/ensu/src/llm.rs b/rust/bindings/uniffi/ensu/src/llm.rsindex 03140440d1..26ee7ce321 100644--- a/rust/bindings/uniffi/ensu/src/llm.rs+++ b/rust/bindings/uniffi/ensu/src/llm.rs@@ -1,17 +1,59 @@use ente_ensu::download;use ente_ensu::llm;++use crate::download::DownloadError;use std::sync::Arc;use thiserror::Error;#[derive(Debug, Error, uniffi::Error)]pub enum LlmError {- #[error("{0}")]- Message(String),+ #[error("Generation cancelled")]+ Cancelled,+ #[error("Generation panicked")]+ Panicked,+ #[error("{detail}")]+ InvalidInput { detail: String },+ #[error("{what} not found at {path}")]+ NotFound { what: String, path: String },+ #[error("{detail}")]+ Unsupported { detail: String },+ #[error("Prompt length {tokens} exceeds context size {context_size}")]+ PromptTooLong { tokens: u64, context_size: u32 },+ #[error("{op}: {detail}")]+ Llama { op: String, detail: String },+ #[error("download failed")]+ Download { error: DownloadError },}-impl From<String> for LlmError {- fn from(value: String) -> Self {- Self::Message(value)+impl From<llm::Error> for LlmError {+ fn from(value: llm::Error) -> Self {+ match value {+ llm::Error::Cancelled => Self::Cancelled,+ llm::Error::Panicked => Self::Panicked,+ llm::Error::InvalidInput(message) => Self::InvalidInput { detail: message },+ llm::Error::NotFound { what, path } => Self::NotFound {+ what: what.to_string(),+ path,+ },+ llm::Error::Unsupported(message) => Self::Unsupported {+ detail: message.to_string(),+ },+ llm::Error::PromptTooLong {+ tokens,+ context_size,+ } => Self::PromptTooLong {+ tokens: tokens as u64,+ context_size,+ },+ llm::Error::Llama { op, message } => Self::Llama {+ op: op.to_string(),+ detail: message,+ },+ llm::Error::Download(err) => match DownloadError::from(err) {+ DownloadError::Cancelled => Self::Cancelled,+ error => Self::Download { error },+ },+ }}}@@ -99,10 +141,6 @@ pub enum LlmGenerationEvent {Done {summary: LlmGenerationSummary,},- Error {- job_id: i64,- message: String,- },}#[derive(uniffi::Object)]@@ -275,7 +313,6 @@ impl From<llm::GenerationEvent> for LlmGenerationEvent {llm::GenerationEvent::Done { summary } => Self::Done {summary: summary.into(),},- llm::GenerationEvent::Error { job_id, message } => Self::Error { job_id, message },}}}@@ -317,10 +354,10 @@ pub fn llm_download_model_files(move |progress| progress_callback.on_progress(progress.into()),move || cancel_callback.is_cancelled(),)- .map_err(|err| LlmError::Message(err.to_string()))+ .map_err(LlmError::from)}#[uniffi::export]pub fn llm_cancel(job_id: i64) {- let _ = llm::cancel(job_id);+ llm::cancel(job_id);}diff --git a/rust/bindings/uniffi/ensu/src/transcription.rs b/rust/bindings/uniffi/ensu/src/transcription.rsindex 3fd70c8959..96539c1d62 100644--- a/rust/bindings/uniffi/ensu/src/transcription.rs+++ b/rust/bindings/uniffi/ensu/src/transcription.rs@@ -4,15 +4,42 @@ use thiserror::Error;use ente_ensu::transcription;+use crate::download::DownloadError;+#[derive(Debug, Error, uniffi::Error)]pub enum TranscriptionError {- #[error("{0}")]- Message(String),+ #[error("Transcription model is not downloaded")]+ NotDownloaded,+ #[error("Voice activity model is not downloaded")]+ VadNotDownloaded,+ #[error("{detail}")]+ InvalidAudio { detail: String },+ #[error("download failed")]+ Download { error: DownloadError },+ #[error("{detail}")]+ Transcribe { detail: String },+ #[error("{detail}")]+ Io { detail: String },}impl From<transcription::TranscriptionError> for TranscriptionError {fn from(value: transcription::TranscriptionError) -> Self {- Self::Message(value.to_string())+ match value {+ transcription::TranscriptionError::NotDownloaded => Self::NotDownloaded,+ transcription::TranscriptionError::VadNotDownloaded => Self::VadNotDownloaded,+ transcription::TranscriptionError::InvalidAudio(message) => {+ Self::InvalidAudio { detail: message }+ }+ transcription::TranscriptionError::Download(err) => {+ Self::Download { error: err.into() }+ }+ transcription::TranscriptionError::Transcribe(message) => {+ Self::Transcribe { detail: message }+ }+ transcription::TranscriptionError::Io(err) => Self::Io {+ detail: err.to_string(),+ },+ }}}diff --git a/rust/crates/ensu/src/llm/context.rs b/rust/crates/ensu/src/llm/context.rsindex 5b732fd284..5d1ceb4a6d 100644--- a/rust/crates/ensu/src/llm/context.rs+++ b/rust/crates/ensu/src/llm/context.rs@@ -11,7 +11,7 @@ use std::path::Path;use std::sync::Arc;use super::model::ModelRef;-use super::{backend, format_error};+use super::{Error, backend, format_error};#[derive(Debug, Clone, Serialize, Deserialize)]pub struct ContextParams {@@ -56,8 +56,8 @@ unsafe impl Sync for Context {}impl Context {fn try_new(owner: ModelRef,- builder: impl for<'a> FnOnce(&'a ModelRef) -> Result<LlamaContext<'a>, String>,- ) -> Result<Self, String> {+ builder: impl for<'a> FnOnce(&'a ModelRef) -> Result<LlamaContext<'a>, Error>,+ ) -> Result<Self, Error> {ContextCell::try_new(owner, builder).map(|cell| Context {cell: Mutex::new(cell),mtmd_context: Mutex::new(None),@@ -77,9 +77,12 @@ impl Context {model: &LlamaModel,mmproj_path: &str,marker: &str,- ) -> Result<Arc<MtmdContext>, String> {+ ) -> Result<Arc<MtmdContext>, Error> {if !Path::new(mmproj_path).exists() {- return Err(format!("mmproj file not found at {mmproj_path}"));+ return Err(Error::NotFound {+ what: "mmproj file",+ path: mmproj_path.to_string(),+ });}let (key, params) = mtmd_cache_key_and_params(mmproj_path, marker)?;@@ -92,12 +95,16 @@ impl Context {}let mtmd_ctx = Arc::new(- MtmdContext::init_from_file(mmproj_path, model, ¶ms)- .map_err(|err| format_error("Failed to initialize mmproj", err))?,+ MtmdContext::init_from_file(mmproj_path, model, ¶ms).map_err(|err| {+ Error::Llama {+ op: "Failed to initialize mmproj",+ message: err.to_string(),+ }+ })?,);if !mtmd_ctx.support_vision() {- return Err("Model does not support vision input".to_string());+ return Err(Error::Unsupported("Model does not support vision input"));}*guard = Some(CachedMtmdContext {@@ -111,9 +118,9 @@ impl Context {fn mtmd_cache_key_and_params(mmproj_path: &str,marker: &str,-) -> Result<(MtmdCacheKey, MtmdContextParams), String> {+) -> Result<(MtmdCacheKey, MtmdContextParams), Error> {let media_marker = CString::new(marker.to_string())- .map_err(|err| format_error("Invalid media marker", err))?;+ .map_err(|err| Error::InvalidInput(format_error("Invalid media marker", err)))?;let params = MtmdContextParams {use_gpu: false,print_timings: false,@@ -123,7 +130,7 @@ fn mtmd_cache_key_and_params(let marker = params.media_marker.to_str()- .map_err(|err| format_error("Invalid media marker", err))?+ .map_err(|err| Error::InvalidInput(format_error("Invalid media marker", err)))?.to_string();let key = MtmdCacheKey {mmproj_path: mmproj_path.to_string(),@@ -136,20 +143,20 @@ fn mtmd_cache_key_and_params(}impl Context {- pub fn new(model: &ModelRef, params: ContextParams) -> Result<ContextRef, String> {+ pub fn new(model: &ModelRef, params: ContextParams) -> Result<ContextRef, Error> {let mut context_params = LlamaContextParams::default();if let Some(context_size) = params.context_size {- let context_size =- u32::try_from(context_size).map_err(|_| "context_size must be > 0".to_string())?;+ let context_size = u32::try_from(context_size)+ .map_err(|_| Error::InvalidInput("context_size must be > 0".to_string()))?;let context_size = NonZeroU32::new(context_size)- .ok_or_else(|| "context_size must be > 0".to_string())?;+ .ok_or_else(|| Error::InvalidInput("context_size must be > 0".to_string()))?;context_params = context_params.with_n_ctx(Some(context_size));}if let Some(n_threads) = params.n_threads {if n_threads <= 0 {- return Err("n_threads must be > 0".to_string());+ return Err(Error::InvalidInput("n_threads must be > 0".to_string()));}context_params = context_params.with_n_threads(n_threads)@@ -157,7 +164,8 @@ impl Context {}if let Some(n_batch) = params.n_batch {- let n_batch = u32::try_from(n_batch).map_err(|_| "n_batch must be > 0".to_string())?;+ let n_batch = u32::try_from(n_batch)+ .map_err(|_| Error::InvalidInput("n_batch must be > 0".to_string()))?;context_params = context_params.with_n_batch(n_batch);}@@ -166,7 +174,10 @@ impl Context {model.model().new_context(backend, context_params)- .map_err(|err| format_error("Failed to create context", err))+ .map_err(|err| Error::Llama {+ op: "Failed to create context",+ message: err.to_string(),+ })})?;Ok(Arc::new(context))@@ -176,7 +187,7 @@ impl Context {&self,mmproj_path: String,media_marker: Option<String>,- ) -> Result<(), String> {+ ) -> Result<(), Error> {let marker = media_marker.unwrap_or_else(|| mtmd_default_marker().to_string());self.with_context_mut(|ctx| {self.cached_mtmd_context(ctx.model, &mmproj_path, &marker)diff --git a/rust/crates/ensu/src/llm/download.rs b/rust/crates/ensu/src/llm/download.rsindex 507b9d0239..2503131b61 100644--- a/rust/crates/ensu/src/llm/download.rs+++ b/rust/crates/ensu/src/llm/download.rs@@ -10,8 +10,9 @@ pub fn download_model_files(targets: Vec<Target>,on_progress: impl FnMut(Progress),is_cancelled: impl Fn() -> bool,-) -> Result<(), download::Error> {- download::fetch(targets, validate_gguf, on_progress, is_cancelled)+) -> Result<(), super::Error> {+ download::fetch(targets, validate_gguf, on_progress, is_cancelled)?;+ Ok(())}fn validate_gguf(_target: &Target, path: &Path) -> Result<(), String> {diff --git a/rust/crates/ensu/src/llm/event.rs b/rust/crates/ensu/src/llm/event.rsindex 1a7dfd7ba6..b228c28c26 100644--- a/rust/crates/ensu/src/llm/event.rs+++ b/rust/crates/ensu/src/llm/event.rs@@ -33,8 +33,4 @@ pub enum GenerationEvent {Done {summary: GenerationSummary,},- Error {- job_id: JobId,- message: String,- },}diff --git a/rust/crates/ensu/src/llm/generate.rs b/rust/crates/ensu/src/llm/generate.rsindex 995f7f1364..4ed7e8ee64 100644--- a/rust/crates/ensu/src/llm/generate.rs+++ b/rust/crates/ensu/src/llm/generate.rs@@ -17,12 +17,11 @@ use std::time::Instant;use super::context::Context;use super::event::{EventSink, GenerationEvent, GenerationSummary, JobId};-use super::format_error;+use super::{Error, format_error};static JOB_COUNTER: AtomicI64 = AtomicI64::new(1);static CANCEL_FLAGS: OnceLock<Mutex<HashMap<JobId, Arc<AtomicBool>>>> = OnceLock::new();-const CANCEL_MESSAGE: &str = "Generation cancelled";const DEFAULT_GENERATION_MAX_TOKENS: i32 = 8_192;fn cancel_flags() -> &'static Mutex<HashMap<JobId, Arc<AtomicBool>>> {@@ -42,9 +41,9 @@ fn cancel_all() {}}-fn check_cancelled(cancel_flag: &AtomicBool) -> Result<(), String> {+fn check_cancelled(cancel_flag: &AtomicBool) -> Result<(), Error> {if cancel_flag.load(Ordering::Relaxed) {- Err(CANCEL_MESSAGE.to_string())+ Err(Error::Cancelled)} else {Ok(())}@@ -118,7 +117,7 @@ fn build_chat_prompt(messages: Vec<ChatMessage>,template_override: Option<String>,add_assistant: bool,-) -> Result<String, String> {+) -> Result<String, Error> {let template_text = match template_override {Some(template) => template,None => model@@ -128,11 +127,11 @@ fn build_chat_prompt(.unwrap_or_else(|| "chatml".to_string()),};let template = LlamaChatTemplate::new(&template_text)- .map_err(|err| format_error("Invalid chat template", err))?;+ .map_err(|err| Error::InvalidInput(format_error("Invalid chat template", err)))?;if template_text.contains("enable_thinking") {let messages_json = serde_json::to_string(&messages)- .map_err(|err| format_error("Invalid chat messages", err))?;+ .map_err(|err| Error::InvalidInput(format_error("Invalid chat messages", err)))?;let params = OpenAIChatTemplateParams {messages_json: &messages_json,tools_json: None,@@ -151,7 +150,10 @@ fn build_chat_prompt(};let result = model.apply_chat_template_oaicompat(&template, ¶ms)- .map_err(|err| format_error("Failed to apply chat template", err))?;+ .map_err(|err| Error::Llama {+ op: "Failed to apply chat template",+ message: err.to_string(),+ })?;return Ok(result.prompt);}@@ -159,13 +161,16 @@ fn build_chat_prompt(.into_iter().map(|message| {LlamaChatMessage::new(message.role, message.content)- .map_err(|err| format_error("Invalid chat message", err))+ .map_err(|err| Error::InvalidInput(format_error("Invalid chat message", err)))})- .collect::<Result<Vec<_>, String>>()?;+ .collect::<Result<Vec<_>, Error>>()?;model.apply_chat_template(&template, &chat_messages, add_assistant)- .map_err(|err| format_error("Failed to apply chat template", err))+ .map_err(|err| Error::Llama {+ op: "Failed to apply chat template",+ message: err.to_string(),+ })}fn should_add_bos(model: &LlamaModel, prompt: &str) -> AddBos {@@ -323,14 +328,14 @@ fn run_generation_loop(generated_tokens_count: &mut i32,mut pos: i32,mut logits_index: i32,-) -> Result<(), String> {+) -> Result<(), Error> {let mut decoder = StreamDecoder::new(stop_sequences);let mut stop_triggered = false;let n_ctx = ctx.n_ctx();for _ in 0..max_tokens {if cancel_flag.load(Ordering::Relaxed) {- return Err("Generation cancelled".to_string());+ return Err(Error::Cancelled);}if pos >= n_ctx as i32 {break;@@ -344,8 +349,10 @@ fn run_generation_loop(break;}- let bytes = token_piece_bytes(ctx.model, token)- .map_err(|err| format_error("Detokenize failed", err))?;+ let bytes = token_piece_bytes(ctx.model, token).map_err(|err| Error::Llama {+ op: "Detokenize failed",+ message: err.to_string(),+ })?;let step = decoder.push_bytes(&bytes);if let Some(text) = step.text {@@ -364,9 +371,14 @@ fn run_generation_loop(let mut step_batch = LlamaBatch::new(1, 1);step_batch.add(token, pos, &[0], true)- .map_err(|err| format_error("Failed to add token", err))?;- ctx.decode(&mut step_batch)- .map_err(|err| format_error("Decode failed", err))?;+ .map_err(|err| Error::Llama {+ op: "Failed to add token",+ message: err.to_string(),+ })?;+ ctx.decode(&mut step_batch).map_err(|err| Error::Llama {+ op: "Decode failed",+ message: err.to_string(),+ })?;logits_index = 0;pos += 1;@@ -386,7 +398,7 @@ fn run_generation_loop(Ok(())}-fn build_sampler(model: &LlamaModel, request: &SamplingParams) -> Result<LlamaSampler, String> {+fn build_sampler(model: &LlamaModel, request: &SamplingParams) -> Result<LlamaSampler, Error> {let mut samplers = Vec::new();let mut repeat_penalty = request.repeat_penalty.unwrap_or(1.0);@@ -417,7 +429,7 @@ fn build_sampler(model: &LlamaModel, request: &SamplingParams) -> Result<LlamaSaif let Some(grammar) = request.grammar.as_deref() {samplers.push(LlamaSampler::grammar(model, grammar, "root")- .map_err(|err| format_error("Invalid grammar", err))?,+ .map_err(|err| Error::InvalidInput(format_error("Invalid grammar", err)))?,);}@@ -452,7 +464,7 @@ impl Context {&self,request: ChatRequest,sink: &mut dyn EventSink,- ) -> Result<GenerationSummary, String> {+ ) -> Result<GenerationSummary, Error> {generate_chat_stream(self, request, sink)}}@@ -461,7 +473,7 @@ fn generate_chat_stream(context: &Context,request: ChatRequest,sink: &mut dyn EventSink,-) -> Result<GenerationSummary, String> {+) -> Result<GenerationSummary, Error> {let ChatRequest {messages,template_override,@@ -497,10 +509,9 @@ fn generate_chat_stream(let mut prompt_tokens_count: i32 = 0;let mut generated_tokens_count: i32 = 0;- let mut error_message: Option<String> = None;let result = match catch_unwind(AssertUnwindSafe(|| {- context.with_context_mut(|ctx| -> Result<(), String> {+ context.with_context_mut(|ctx| -> Result<(), Error> {let add_assistant = add_assistant.unwrap_or(true);let mut messages = messages;let image_paths = image_paths.unwrap_or_default();@@ -518,7 +529,9 @@ fn generate_chat_stream(.iter().rposition(|message| message.role == "user").or_else(|| messages.len().checked_sub(1))- .ok_or_else(|| "No chat messages provided".to_string())?;+ .ok_or_else(|| {+ Error::InvalidInput("No chat messages provided".to_string())+ })?;if !messages[target_index].content.ends_with('\n') {messages[target_index].content.push('\n');}@@ -529,10 +542,10 @@ fn generate_chat_stream(.sum();}if marker_count != image_paths.len() {- return Err(format!(+ return Err(Error::InvalidInput(format!("Found {marker_count} media markers but {} images were provided",image_paths.len()- ));+ )));}}@@ -551,30 +564,34 @@ fn generate_chat_stream(if image_paths.is_empty() {let add_bos = should_add_bos(ctx.model, &prompt);- let prompt_tokens = ctx- .model- .str_to_token(&prompt, add_bos)- .map_err(|err| format_error("Tokenize failed", err))?;+ let prompt_tokens =+ ctx.model+ .str_to_token(&prompt, add_bos)+ .map_err(|err| Error::Llama {+ op: "Tokenize failed",+ message: err.to_string(),+ })?;if prompt_tokens.is_empty() {- return Err("Prompt produced no tokens".to_string());+ return Err(Error::InvalidInput("Prompt produced no tokens".to_string()));}- prompt_tokens_count = i32::try_from(prompt_tokens.len())- .map_err(|_| "Prompt is too long".to_string())?;-let n_ctx = ctx.n_ctx();if prompt_tokens.len() as u32 > n_ctx {- return Err(format!(- "Prompt length {} exceeds context size {}",- prompt_tokens.len(),- n_ctx- ));+ return Err(Error::PromptTooLong {+ tokens: prompt_tokens.len(),+ context_size: n_ctx,+ });}+ prompt_tokens_count =+ i32::try_from(prompt_tokens.len()).map_err(|_| Error::PromptTooLong {+ tokens: prompt_tokens.len(),+ context_size: n_ctx,+ })?;let n_batch = ctx.n_batch() as usize;if n_batch == 0 {- return Err("Context batch size is 0".to_string());+ return Err(Error::InvalidInput("Context batch size is 0".to_string()));}ctx.clear_kv_cache();@@ -591,10 +608,15 @@ fn generate_chat_stream(let logits = token_offset + idx + 1 == prompt_tokens.len();batch.add(*token, pos, &[0], logits)- .map_err(|err| format_error("Failed to add prompt token", err))?;+ .map_err(|err| Error::Llama {+ op: "Failed to add prompt token",+ message: err.to_string(),+ })?;}- ctx.decode(&mut batch)- .map_err(|err| format_error("Prompt decode failed", err))?;+ ctx.decode(&mut batch).map_err(|err| Error::Llama {+ op: "Prompt decode failed",+ message: err.to_string(),+ })?;if end == prompt_tokens.len() {logits_index = (chunk.len() - 1) as i32;}@@ -622,7 +644,9 @@ fn generate_chat_stream(}let mmproj_path = mmproj_path.ok_or_else(|| {- "mmproj_path is required when image_paths are provided".to_string()+ Error::InvalidInput(+ "mmproj_path is required when image_paths are provided".to_string(),+ )})?;let mtmd_ctx = context.cached_mtmd_context(ctx.model, &mmproj_path, &marker)?;@@ -630,12 +654,18 @@ fn generate_chat_stream(for image_path in &image_paths {check_cancelled(&cancel_flag)?;if !Path::new(image_path).exists() {- return Err(format!("Image file not found at {image_path}"));+ return Err(Error::NotFound {+ what: "Image file",+ path: image_path.clone(),+ });}- let bitmap = MtmdBitmap::from_file(&mtmd_ctx, image_path)- .map_err(|err| format_error("Failed to load image", err))?;+ let bitmap =+ MtmdBitmap::from_file(&mtmd_ctx, image_path).map_err(|err| Error::Llama {+ op: "Failed to load image",+ message: err.to_string(),+ })?;if bitmap.is_audio() {- return Err("Audio inputs are not supported".to_string());+ return Err(Error::Unsupported("Audio inputs are not supported"));}bitmaps.push(bitmap);}@@ -648,29 +678,35 @@ fn generate_chat_stream(parse_special: true,};- let chunks = mtmd_ctx- .tokenize(input_text, &bitmap_refs)- .map_err(|err| format_error("Failed to tokenize multimodal input", err))?;+ let chunks =+ mtmd_ctx+ .tokenize(input_text, &bitmap_refs)+ .map_err(|err| Error::Llama {+ op: "Failed to tokenize multimodal input",+ message: err.to_string(),+ })?;if chunks.is_empty() {- return Err("Prompt produced no tokens".to_string());+ return Err(Error::InvalidInput("Prompt produced no tokens".to_string()));}- prompt_tokens_count = i32::try_from(chunks.total_tokens())- .map_err(|_| "Prompt is too long".to_string())?;-let n_ctx = ctx.n_ctx();let total_positions = chunks.total_positions();if total_positions as u32 > n_ctx {- return Err(format!(- "Prompt length {} exceeds context size {}",- total_positions, n_ctx- ));+ return Err(Error::PromptTooLong {+ tokens: total_positions as usize,+ context_size: n_ctx,+ });}+ prompt_tokens_count =+ i32::try_from(chunks.total_tokens()).map_err(|_| Error::PromptTooLong {+ tokens: chunks.total_tokens(),+ context_size: n_ctx,+ })?;let n_batch = ctx.n_batch() as i32;if n_batch <= 0 {- return Err("Context batch size is 0".to_string());+ return Err(Error::InvalidInput("Context batch size is 0".to_string()));}ctx.clear_kv_cache();@@ -678,7 +714,10 @@ fn generate_chat_stream(let n_past = chunks.eval_chunks(&mtmd_ctx, ctx, 0, 0, n_batch, true)- .map_err(|err| format_error("Failed to evaluate multimodal prompt", err))?;+ .map_err(|err| Error::Llama {+ op: "Failed to evaluate multimodal prompt",+ message: err.to_string(),+ })?;check_cancelled(&cancel_flag)?;let mut sampler = build_sampler(ctx.model, &sampler_request)?;@@ -709,12 +748,9 @@ fn generate_chat_stream(})})) {Ok(inner) => inner,- Err(_) => Err("Generation panicked".to_string()),+ Err(_) => Err(Error::Panicked),};-- if let Err(err) = result {- error_message = Some(err);- }+ result?;let summary = GenerationSummary {job_id,@@ -723,10 +759,6 @@ fn generate_chat_stream(total_time_ms: Some(start.elapsed().as_millis() as i64),};- if let Some(message) = error_message {- sink.add(GenerationEvent::Error { job_id, message });- }-sink.add(GenerationEvent::Done {summary: summary.clone(),});@@ -734,15 +766,14 @@ fn generate_chat_stream(Ok(summary)}-pub fn cancel(job_id: JobId) -> Result<(), String> {+pub fn cancel(job_id: JobId) {if job_id <= 0 {cancel_all();- return Ok(());+ return;}if let Some(flag) = cancel_flags().lock().get(&job_id) {flag.store(true, Ordering::Relaxed);}- Ok(())}#[cfg(test)]diff --git a/rust/crates/ensu/src/llm/mod.rs b/rust/crates/ensu/src/llm/mod.rsindex 03e64a1bf8..1108480a8c 100644--- a/rust/crates/ensu/src/llm/mod.rs+++ b/rust/crates/ensu/src/llm/mod.rs@@ -13,12 +13,35 @@ pub use model::*;use llama_cpp_2::llama_backend::LlamaBackend;use std::sync::OnceLock;+#[derive(Debug, thiserror::Error)]+pub enum Error {+ #[error("Generation cancelled")]+ Cancelled,+ #[error("Generation panicked")]+ Panicked,+ #[error("{0}")]+ InvalidInput(String),+ #[error("{what} not found at {path}")]+ NotFound { what: &'static str, path: String },+ #[error("{0}")]+ Unsupported(&'static str),+ #[error("Prompt length {tokens} exceeds context size {context_size}")]+ PromptTooLong { tokens: usize, context_size: u32 },+ #[error("{op}: {message}")]+ Llama { op: &'static str, message: String },+ #[error(transparent)]+ Download(#[from] crate::download::Error),+}+static BACKEND: OnceLock<Result<LlamaBackend, String>> = OnceLock::new();-fn backend() -> Result<&'static LlamaBackend, String> {+fn backend() -> Result<&'static LlamaBackend, Error> {match BACKEND.get_or_init(|| LlamaBackend::init().map_err(|err| err.to_string())) {Ok(backend) => Ok(backend),- Err(err) => Err(format!("Failed to initialize backend: {err}")),+ Err(err) => Err(Error::Llama {+ op: "Failed to initialize backend",+ message: err.clone(),+ }),}}diff --git a/rust/crates/ensu/src/llm/model.rs b/rust/crates/ensu/src/llm/model.rsindex 5b30975e3a..8ab2f23a62 100644--- a/rust/crates/ensu/src/llm/model.rs+++ b/rust/crates/ensu/src/llm/model.rs@@ -3,7 +3,7 @@ use serde::{Deserialize, Serialize};use std::path::Path;use std::sync::Arc;-use super::{backend, format_error};+use super::{Error, backend};#[derive(Debug, Clone, Serialize, Deserialize)]pub struct ModelLoadParams {@@ -20,13 +20,13 @@ pub struct Model {pub type ModelRef = Arc<Model>;impl Model {- pub fn load(params: ModelLoadParams) -> Result<ModelRef, String> {+ pub fn load(params: ModelLoadParams) -> Result<ModelRef, Error> {let backend = backend()?;let mut model_params = llama_cpp_2::model::params::LlamaModelParams::default();if let Some(n_gpu_layers) = params.n_gpu_layers {- let layers =- u32::try_from(n_gpu_layers).map_err(|_| "n_gpu_layers must be >= 0".to_string())?;+ let layers = u32::try_from(n_gpu_layers)+ .map_err(|_| Error::InvalidInput("n_gpu_layers must be >= 0".to_string()))?;model_params = model_params.with_n_gpu_layers(layers);}@@ -36,7 +36,10 @@ impl Model {let model =LlamaModel::load_from_file(backend, Path::new(¶ms.model_path), &model_params)- .map_err(|err| format_error("Failed to load model", err))?;+ .map_err(|err| Error::Llama {+ op: "Failed to load model",+ message: err.to_string(),+ })?;Ok(Arc::new(Model { model }))}@@ -46,6 +49,6 @@ impl Model {}}-pub fn init_backend() -> Result<(), String> {+pub fn init_backend() -> Result<(), Error> {backend().map(|_| ())}diff --git a/rust/crates/ensu/src/transcription/audio.rs b/rust/crates/ensu/src/transcription/audio.rsindex 031d76cf7f..7e7db88dd1 100644--- a/rust/crates/ensu/src/transcription/audio.rs+++ b/rust/crates/ensu/src/transcription/audio.rs@@ -4,7 +4,7 @@ use std::time::Duration;use rubato::{FftFixedIn, Resampler};use transcribe_rs::vad::{SileroVad, SmoothedVad, Vad};-use crate::transcription::{Result, error};+use crate::transcription::{Result, TranscriptionError};const TARGET_SAMPLE_RATE: usize = 16_000;const RESAMPLER_CHUNK_SIZE: usize = 1024;@@ -19,10 +19,14 @@ pub fn extract_speech_from_pcm16(pcm_le: &[u8],) -> Result<Vec<f32>> {if input_sample_rate == 0 {- return Err(error("input sample rate must be greater than zero"));+ return Err(TranscriptionError::InvalidAudio(+ "input sample rate must be greater than zero".to_string(),+ ));}if !pcm_le.len().is_multiple_of(2) {- return Err(error("PCM16 input must contain an even number of bytes"));+ return Err(TranscriptionError::InvalidAudio(+ "PCM16 input must contain an even number of bytes".to_string(),+ ));}let samples = pcm_le@@ -44,7 +48,7 @@ fn extract_speech(let vad_model_path = vad_model_path.as_ref();if !vad_model_path.is_file() {- return Err(error("Voice activity model is not downloaded"));+ return Err(TranscriptionError::VadNotDownloaded);}let silero = SileroVad::new(vad_model_path, VAD_THRESHOLD)?;let mut vad = SmoothedVad::new(@@ -101,7 +105,9 @@ impl FrameResampler {fn new(in_hz: usize, out_hz: usize, frame_dur: Duration) -> Result<Self> {let frame_samples = ((out_hz as f64 * frame_dur.as_secs_f64()).round()) as usize;if frame_samples == 0 {- return Err(error("frame duration too short"));+ return Err(TranscriptionError::InvalidAudio(+ "frame duration too short".to_string(),+ ));}let resampler = if in_hz == out_hz {diff --git a/rust/crates/ensu/src/transcription/mod.rs b/rust/crates/ensu/src/transcription/mod.rsindex b421bea94b..3ec3461afa 100644--- a/rust/crates/ensu/src/transcription/mod.rs+++ b/rust/crates/ensu/src/transcription/mod.rs@@ -8,30 +8,30 @@ pub use transcriber::Transcriber;#[derive(Debug, thiserror::Error)]pub enum TranscriptionError {+ #[error("Transcription model is not downloaded")]+ NotDownloaded,+ #[error("Voice activity model is not downloaded")]+ VadNotDownloaded,#[error("{0}")]- Message(String),-}--impl From<std::io::Error> for TranscriptionError {- fn from(value: std::io::Error) -> Self {- Self::Message(value.to_string())- }+ InvalidAudio(String),+ #[error(transparent)]+ Download(#[from] crate::download::Error),+ #[error("{0}")]+ Transcribe(String),+ #[error(transparent)]+ Io(#[from] std::io::Error),}impl From<transcribe_rs::TranscribeError> for TranscriptionError {fn from(value: transcribe_rs::TranscribeError) -> Self {- Self::Message(value.to_string())+ Self::Transcribe(value.to_string())}}impl From<rubato::ResamplerConstructionError> for TranscriptionError {fn from(value: rubato::ResamplerConstructionError) -> Self {- Self::Message(value.to_string())+ Self::InvalidAudio(value.to_string())}}pub type Result<T> = std::result::Result<T, TranscriptionError>;--pub(crate) fn error(message: impl Into<String>) -> TranscriptionError {- TranscriptionError::Message(message.into())-}diff --git a/rust/crates/ensu/src/transcription/model.rs b/rust/crates/ensu/src/transcription/model.rsindex 2a35fc7e97..afab940549 100644--- a/rust/crates/ensu/src/transcription/model.rs+++ b/rust/crates/ensu/src/transcription/model.rs@@ -9,7 +9,7 @@ use flate2::read::GzDecoder;use tar::Archive;use crate::download;-use crate::transcription::{Result, error};+use crate::transcription::{Result, TranscriptionError};const MODEL_URL: &str = "https://models.ente.io/parakeet-v3-int8.tar.gz";const MODEL_DIR_NAME: &str = "parakeet-tdt-0.6b-v3-int8";@@ -103,11 +103,10 @@ pub(crate) fn download_model(},|| false,) {- let message = err.to_string();on_event(ModelEvent::DownloadError {- message: message.clone(),+ message: err.to_string(),});- return Err(error(message));+ return Err(TranscriptionError::Download(err));}if need_model {@@ -118,11 +117,10 @@ pub(crate) fn download_model(let _ = fs::remove_file(download::metadata_path_for(&archive_path));if let Err(err) = extract_result {let _ = fs::remove_dir_all(&extracting_path);- let message = err.to_string();on_event(ModelEvent::DownloadError {- message: message.clone(),+ message: err.to_string(),});- return Err(error(message));+ return Err(err);}on_event(ModelEvent::ExtractionCompleted);}diff --git a/rust/crates/ensu/src/transcription/transcriber.rs b/rust/crates/ensu/src/transcription/transcriber.rsindex 5bc14e9798..1f75ba7180 100644--- a/rust/crates/ensu/src/transcription/transcriber.rs+++ b/rust/crates/ensu/src/transcription/transcriber.rs@@ -7,7 +7,7 @@ use transcribe_rs::onnx::parakeet::{ParakeetModel, ParakeetParams, TimestampGranuse crate::transcription::audio::extract_speech_from_pcm16;use crate::transcription::model::{self, ModelEvent};use crate::transcription::text::filter_transcription_output;-use crate::transcription::{Result, error};+use crate::transcription::{Result, TranscriptionError};pub struct Transcriber {models_dir: PathBuf,@@ -48,7 +48,7 @@ impl Transcriber {let model_dir = self.downloaded_model_dir()?;let vad_model_path = model::vad_model_path(&self.models_dir);if !vad_model_path.is_file() {- return Err(error("Voice activity model is not downloaded"));+ return Err(TranscriptionError::VadNotDownloaded);}let speech = extract_speech_from_pcm16(&vad_model_path, input_sample_rate, &pcm_le)?;@@ -72,7 +72,7 @@ impl Transcriber {fn downloaded_model_dir(&self) -> Result<PathBuf> {let model_dir = model::model_path(&self.models_dir);if !model_dir.is_dir() {- return Err(error("Transcription model is not downloaded"));+ return Err(TranscriptionError::NotDownloaded);}Ok(model_dir)}diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsxindex 0c97178a79..a113d1c3b8 100644--- a/web/apps/ensu/src/pages/chat.tsx+++ b/web/apps/ensu/src/pages/chat.tsx@@ -1849,7 +1849,6 @@ const Page: React.FC = () => {await provider.ensureModelReady(settings);let summary = "";- let errorMessage: string | null = null;await provider.generateChatStream({@@ -1865,18 +1864,10 @@ const Page: React.FC = () => {(event) => {if (event.type === "text") {summary += event.text;- return;- }- if (event.type === "error") {- errorMessage = event.message;}},);- if (errorMessage) {- throw new Error(errorMessage);- }-return summary;},[ensureProvider, getModelSettings],@@ -2781,41 +2772,46 @@ const Page: React.FC = () => {throw new Error("MMProj model not available");}- await provider.generateChatStream(- {- messages,- imagePaths: hasImages ? imagePaths : undefined,- mmprojPath,- mediaMarker: hasImages- ? (mediaMarker ?? MEDIA_MARKER)- : undefined,- maxTokens,- temperature: 0.7,- topP: 0.9,- repeatPenalty: REPEAT_PENALTY,- },- (event: GenerateEvent) => {- if (!isActiveGeneration()) {- return;- }- if (event.type === "text") {- if (!currentJobIdRef.current) {- currentJobIdRef.current = event.job_id;- if (pendingCancelRef.current) {- pendingCancelRef.current = false;- provider.cancelGeneration(event.job_id);- return;+ await provider+ .generateChatStream(+ {+ messages,+ imagePaths: hasImages ? imagePaths : undefined,+ mmprojPath,+ mediaMarker: hasImages+ ? (mediaMarker ?? MEDIA_MARKER)+ : undefined,+ maxTokens,+ temperature: 0.7,+ topP: 0.9,+ repeatPenalty: REPEAT_PENALTY,+ },+ (event: GenerateEvent) => {+ if (!isActiveGeneration()) {+ return;+ }+ if (event.type === "text") {+ if (!currentJobIdRef.current) {+ currentJobIdRef.current = event.job_id;+ if (pendingCancelRef.current) {+ pendingCancelRef.current = false;+ provider.cancelGeneration(event.job_id);+ return;+ }}+ streamingChunksRef.current.push(event.text);+ scheduleStreamingFlush();+ } else if (event.type === "done") {+ currentJobIdRef.current = event.summary.job_id;}- streamingChunksRef.current.push(event.text);- scheduleStreamingFlush();- } else if (event.type === "error") {- errorMessage = event.message;- } else if (event.type === "done") {- currentJobIdRef.current = event.summary.job_id;- }- },- );+ },+ )+ .catch((error: unknown) => {+ errorMessage =+ error instanceof Error+ ? error.message+ : String(error);+ });if (!isActiveGeneration()) {return;diff --git a/web/apps/ensu/src/services/llm/inference.ts b/web/apps/ensu/src/services/llm/inference.tsindex e372029a5c..55302a9f79 100644--- a/web/apps/ensu/src/services/llm/inference.ts+++ b/web/apps/ensu/src/services/llm/inference.ts@@ -405,7 +405,6 @@ class WasmInference implements InferenceBackend {this.abortControllers.set(jobId, controller);let generatedTokens = 0;- let errorMessage: string | null = null;let promptTokens: number | null = null;try {@@ -452,20 +451,14 @@ class WasmInference implements InferenceBackend {}}} catch (error) {- if (!(error instanceof WllamaAbortError)) {- errorMessage =- error instanceof Error ? error.message : String(error);- } else {- errorMessage = "Generation aborted";+ if (error instanceof WllamaAbortError) {+ throw new Error("Generation cancelled");}+ throw error instanceof Error ? error : new Error(String(error));} finally {this.abortControllers.delete(jobId);}- if (errorMessage && onEvent) {- onEvent({ type: "error", job_id: jobId, message: errorMessage });- }-const summary = {job_id: jobId,prompt_tokens: promptTokens,@@ -635,19 +628,7 @@ class TauriInference implements InferenceBackend {request: GenerateChatRequest,onEvent?: (event: GenerateEvent) => void,): Promise<GenerateSummary> {- const panicJobId = 0;let resolvedJobId: number | null = null;- let errorMessage: string | null = null;-- let resolveSummary!: (summary: GenerateSummary) => void;- let rejectSummary!: (error: Error) => void;-- const summaryPromise = new Promise<GenerateSummary>(- (resolve, reject) => {- resolveSummary = resolve;- rejectSummary = reject;- },- );const unlisten = await listen<GenerateEvent>("llm-event", (event) => {const payload = event.payload;@@ -663,25 +644,6 @@ class TauriInference implements InferenceBackend {if (onEvent) {onEvent(payload);}-- if (payload.type === "error") {- if (payload.job_id === panicJobId) {- rejectSummary(new Error(payload.message));- void unlisten();- return;- }- errorMessage = payload.message;- }-- if (payload.type === "done") {- if (errorMessage) {- // still resolve summary; error is emitted separately- resolveSummary(payload.summary);- } else {- resolveSummary(payload.summary);- }- void unlisten();- }});try {@@ -689,20 +651,16 @@ class TauriInference implements InferenceBackend {messageCount: request.messages.length,maxTokens: request.maxTokens ?? null,});- await invoke("llm_generate_chat_stream", {+ return await invoke<GenerateSummary>("llm_generate_chat_stream", {request: buildGenerateChatRequest(request),});} catch (error) {- void unlisten();- const err = normalizeInvokeError(- error,- "Failed to start generation",- );+ const err = normalizeInvokeError(error, "Generation failed");log.error("LLM tauri generate failed", err);- rejectSummary(err);+ throw err;+ } finally {+ void unlisten();}-- return summaryPromise;}cancel(jobId: number) {diff --git a/web/apps/ensu/src/services/llm/types.ts b/web/apps/ensu/src/services/llm/types.tsindex edf43981d7..4e7249ebf3 100644--- a/web/apps/ensu/src/services/llm/types.ts+++ b/web/apps/ensu/src/services/llm/types.ts@@ -41,8 +41,7 @@ export interface GenerateSummary {export type GenerateEvent =| { type: "text"; job_id: number; text: string; token_id?: number | null }- | { type: "done"; summary: GenerateSummary }- | { type: "error"; job_id: number; message: string };+ | { type: "done"; summary: GenerateSummary };export interface GenerateChatRequest {messages: LlmMessage[];