Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Replace client error heuristics

Manav Rathicb47a6a70477
diff --git a/rust/apps/ensu/src-tauri/src/commands/chat_db.rs b/rust/apps/ensu/src-tauri/src/commands/chat_db.rs
index 230ec13a25..fbdc505d67 100644
--- a/rust/apps/ensu/src-tauri/src/commands/chat_db.rs
+++ b/rust/apps/ensu/src-tauri/src/commands/chat_db.rs
@@ -489,8 +489,13 @@ pub async fn chat_db_compress_attachment_image_file(
let data = fs::read(canonical_path).map_err(|error| {
ApiError::new("io", format!("failed to read image file '{path}': {error}"))
})?;
- ente_ensu::image::compress_attachment_image(&data)
- .map_err(|error| ApiError::new("image", error.to_string()))
+ ente_ensu::image::compress_attachment_image(&data).map_err(|error| {
+ let name = match &error {
+ ente_ensu::image::ImageError::TooLarge(_) => "image_too_large",
+ _ => "image",
+ };
+ ApiError::new(name, ente_core::error::chain(&error))
+ })
})
.await
.map_err(|_| image_thread_error())?
diff --git a/rust/bindings/wasm/core/src/contacts.rs b/rust/bindings/wasm/core/src/contacts.rs
index 5e15083fa1..03eeadbaf9 100644
--- a/rust/bindings/wasm/core/src/contacts.rs
+++ b/rust/bindings/wasm/core/src/contacts.rs
@@ -27,7 +27,13 @@ pub enum Error {
impl Error {
fn name(&self) -> Option<&'static str> {
- None
+ match self {
+ Self::Legacy(ente_legacy::Error::ContactNotOnEnte) => Some("contact_not_on_ente"),
+ Self::Legacy(ente_legacy::Error::ActiveRecoverySession) => {
+ Some("active_recovery_session")
+ }
+ _ => None,
+ }
}
fn message(&self) -> String {
diff --git a/rust/crates/ensu/src/image.rs b/rust/crates/ensu/src/image.rs
index fc9f534516..2e225885e2 100644
--- a/rust/crates/ensu/src/image.rs
+++ b/rust/crates/ensu/src/image.rs
@@ -1,4 +1,5 @@
-use ente_image::{ImageError, image_compression::compress_image_bytes_to_jpeg};
+pub use ente_image::ImageError;
+use ente_image::image_compression::compress_image_bytes_to_jpeg;
pub const ATTACHMENT_IMAGE_MAX_LONG_EDGE: u32 = 512;
pub const ATTACHMENT_IMAGE_JPEG_QUALITY: u8 = 85;
diff --git a/rust/crates/image/src/error.rs b/rust/crates/image/src/error.rs
index 2137e9c11d..0a0ad4a2dd 100644
--- a/rust/crates/image/src/error.rs
+++ b/rust/crates/image/src/error.rs
@@ -6,12 +6,26 @@ pub type ImageResult<T> = Result<T, ImageError>;
pub enum ImageError {
#[error("decode error: {0}")]
Decode(String),
+ #[error("image too large")]
+ TooLarge(#[source] image::ImageError),
#[error("postprocess error: {0}")]
Postprocess(String),
}
impl From<image::ImageError> for ImageError {
fn from(value: image::ImageError) -> Self {
- ImageError::Decode(value.to_string())
+ if matches!(
+ &value,
+ image::ImageError::Limits(error)
+ if matches!(
+ error.kind(),
+ image::error::LimitErrorKind::DimensionError
+ | image::error::LimitErrorKind::InsufficientMemory
+ )
+ ) {
+ Self::TooLarge(value)
+ } else {
+ Self::Decode(value.to_string())
+ }
}
}
diff --git a/rust/crates/legacy/src/client.rs b/rust/crates/legacy/src/client.rs
index fd1f294a9a..79685c90b1 100644
--- a/rust/crates/legacy/src/client.rs
+++ b/rust/crates/legacy/src/client.rs
@@ -82,7 +82,7 @@ impl LegacyClient {
let public_key = self
.public_key(email)
.await?
- .ok_or_else(|| Error::InvalidInput("legacy contact is not on Ente".into()))?;
+ .ok_or(Error::ContactNotOnEnte)?;
let recovery_key = self.current_recovery_key(current_user_key_attrs)?;
let recipient_public_key = b64::decode(&public_key)?;
let encrypted_key = sealed::seal(
diff --git a/rust/crates/legacy/src/error.rs b/rust/crates/legacy/src/error.rs
index f0ee1650d0..a57ef727ff 100644
--- a/rust/crates/legacy/src/error.rs
+++ b/rust/crates/legacy/src/error.rs
@@ -18,6 +18,9 @@ pub enum Error {
#[error("invalid input: {0}")]
InvalidInput(String),
+ #[error("legacy contact is not on Ente")]
+ ContactNotOnEnte,
+
#[error("a recovery is already in progress")]
ActiveRecoverySession,
diff --git a/rust/crates/ml/src/error.rs b/rust/crates/ml/src/error.rs
index e0fc09775c..c01e2d21f0 100644
--- a/rust/crates/ml/src/error.rs
+++ b/rust/crates/ml/src/error.rs
@@ -39,6 +39,7 @@ impl From<ente_image::ImageError> for MlError {
fn from(value: ente_image::ImageError) -> Self {
match value {
ente_image::ImageError::Decode(message) => MlError::Decode(message),
+ ente_image::ImageError::TooLarge(error) => MlError::Decode(error.to_string()),
ente_image::ImageError::Postprocess(message) => MlError::Image(message),
}
}
diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsx
index 3f4bfcc5e2..1d0fad0aab 100644
--- a/web/apps/ensu/src/pages/chat.tsx
+++ b/web/apps/ensu/src/pages/chat.tsx
@@ -131,14 +131,13 @@ const imageProcessingFailureDialog = (
error: unknown,
selectedImageCount: number,
) => {
- const { name, message } = tauriCommandError(error);
- const lowerMessage = message?.toLowerCase() ?? "";
+ const { name } = tauriCommandError(error);
const subject =
selectedImageCount == 1
? "The selected image"
: "One of the selected images";
- if (name == "image" && lowerMessage.includes("memory limit")) {
+ if (name == "image_too_large") {
return {
title: "Image too large",
message: `${subject} is too large for Ensu to process. Try resizing it or exporting a smaller copy, then attach it again.`,
@@ -1886,34 +1885,10 @@ const Page: React.FC = () => {
);
const formatErrorMessage = useCallback((error: unknown) => {
- const normalizeErrorMessage = (message: string) => {
- if (
- message.toLowerCase().includes("length out of range of buffer")
- ) {
- return "Prompt exceeds the model context window. Reduce history, lower max tokens, or increase context length.";
- }
- return message;
- };
-
- if (error instanceof Error) return normalizeErrorMessage(error.message);
- if (typeof error === "string") return normalizeErrorMessage(error);
- if (error && typeof error === "object") {
- const maybeMessage = (error as { message?: unknown }).message;
- if (typeof maybeMessage === "string" && maybeMessage.trim()) {
- return normalizeErrorMessage(maybeMessage);
- }
- if ("__wbg_ptr" in error) {
- return "Model failed to start. Please refresh and try again.";
- }
- }
- try {
- const serialized = JSON.stringify(error);
- return serialized
- ? normalizeErrorMessage(serialized)
- : "Unknown model error";
- } catch {
- return "Unknown model error";
+ if (error instanceof Error && error.name == "prompt_too_long") {
+ return "Prompt exceeds the model context window. Reduce history, lower max tokens, or increase context length.";
}
+ return error instanceof Error ? error.message : "Unknown model error";
}, []);
const trimToWords = useCallback((text: string, maxWords: number) => {
diff --git a/web/apps/ensu/src/services/llm/inference.ts b/web/apps/ensu/src/services/llm/inference.ts
index 43771c1218..b49cab7a3d 100644
--- a/web/apps/ensu/src/services/llm/inference.ts
+++ b/web/apps/ensu/src/services/llm/inference.ts
@@ -7,6 +7,7 @@ import {
ModelValidationStatus,
Wllama,
WllamaAbortError,
+ WllamaError,
} from "@wllama/wllama/esm/index.js";
import wllamaPackage from "@wllama/wllama/package.json";
import log from "ente-base/log";
@@ -123,7 +124,11 @@ class WasmInference implements InferenceBackend {
params: ContextParams = {},
) {
const modelUrl = ensureUrl(model.modelPath);
- await this.ensureModelLoaded(modelUrl, params);
+ try {
+ await this.ensureModelLoaded(modelUrl, params);
+ } catch (error) {
+ throw normalizeWllamaError(error, "Model failed to start");
+ }
}
async applyChatTemplate(
@@ -157,13 +162,17 @@ class WasmInference implements InferenceBackend {
request: GenerateChatRequest,
onEvent?: (event: GenerateEvent) => void,
): Promise<GenerateSummary> {
- const addAssistant = request.addAssistant ?? true;
- const prompt = await this.wllama.formatChat(
- request.messages,
- addAssistant,
- request.templateOverride ?? undefined,
- );
- return this.generateCompletion(prompt, request, onEvent);
+ try {
+ const addAssistant = request.addAssistant ?? true;
+ const prompt = await this.wllama.formatChat(
+ request.messages,
+ addAssistant,
+ request.templateOverride ?? undefined,
+ );
+ return await this.generateCompletion(prompt, request, onEvent);
+ } catch (error) {
+ throw normalizeWllamaError(error, "Generation failed");
+ }
}
cancel(jobId: number): Promise<void> {
@@ -438,11 +447,6 @@ class WasmInference implements InferenceBackend {
});
}
}
- } catch (error) {
- if (error instanceof WllamaAbortError) {
- throw new Error("Generation cancelled", { cause: error });
- }
- throw error instanceof Error ? error : new Error(String(error));
} finally {
this.abortControllers.delete(jobId);
}
@@ -709,6 +713,20 @@ const safeJson = (value: unknown) => {
}
};
+const normalizeWllamaError = (error: unknown, fallback: string) => {
+ if (error instanceof WllamaAbortError) {
+ return new Error("Generation cancelled", { cause: error });
+ }
+
+ if (error instanceof WllamaError && error.type == "kv_cache_full") {
+ const normalized = new Error(error.message, { cause: error });
+ normalized.name = "prompt_too_long";
+ return normalized;
+ }
+ if (error instanceof Error) return error;
+ return new Error(typeof error === "string" ? error : fallback);
+};
+
const buildGenerateChatRequest = (request: GenerateChatRequest) => ({
messages: request.messages,
template_override: request.templateOverride ?? null,
diff --git a/web/packages/contacts/legacy/components/LegacyAddContactContent.tsx b/web/packages/contacts/legacy/components/LegacyAddContactContent.tsx
index b4fe428fa6..87da598ee3 100644
--- a/web/packages/contacts/legacy/components/LegacyAddContactContent.tsx
+++ b/web/packages/contacts/legacy/components/LegacyAddContactContent.tsx
@@ -30,9 +30,6 @@ interface LegacyAddContactContentProps {
variant?: "page" | "sheet";
}
-const getErrorMessage = (error: unknown) =>
- error instanceof Error ? error.message : "Something went wrong";
-
const nonEnteDialogAttributes = (email: string) => ({
title: "Cannot add trusted contact",
message: `${email} is not linked to an Ente account yet, so it cannot be used as a trusted contact.`,
@@ -176,8 +173,10 @@ export const LegacyAddContactContent: React.FC<
selectedRecoveryDays,
);
} catch (error) {
- const message = getErrorMessage(error);
- if (message.includes("not on Ente")) {
+ if (
+ error instanceof Error &&
+ error.name == "contact_not_on_ente"
+ ) {
setTimeout(() => {
showMiniDialog(
nonEnteDialogAttributes(
@@ -187,9 +186,7 @@ export const LegacyAddContactContent: React.FC<
}, 0);
return;
}
- throw error instanceof Error
- ? error
- : new Error(message);
+ throw error;
}
await onAdded();
},
diff --git a/web/packages/contacts/legacy/components/LegacyDrawerContent.tsx b/web/packages/contacts/legacy/components/LegacyDrawerContent.tsx
index f0cad3b605..13b3d5e55f 100644
--- a/web/packages/contacts/legacy/components/LegacyDrawerContent.tsx
+++ b/web/packages/contacts/legacy/components/LegacyDrawerContent.tsx
@@ -137,9 +137,6 @@ const warningBannerSx = {
backgroundColor: "rgba(255, 82, 82, 0.14)",
};
-const getErrorMessage = (error: unknown) =>
- error instanceof Error ? error.message : "Something went wrong";
-
interface LegacyDrawerContentProps {
open: boolean;
suggestedUsers?: LegacySuggestedUser[];
@@ -333,8 +330,10 @@ export const LegacyDrawerContent: React.FC<LegacyDrawerContentProps> = ({
setActiveSheet(undefined);
await refreshAfterMutation();
} catch (error) {
- const message = getErrorMessage(error);
- if (message.includes("active recovery session")) {
+ if (
+ error instanceof Error &&
+ error.name == "active_recovery_session"
+ ) {
showMiniDialog({
title: "Recovery in progress",
message: