Skip to content

armgit / ente

Public Imported from GitHub
0

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

Remove Ensu logout and auto-reset, purge legacy login/sync data

Manav Rathie23f5cfabd13
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.kt
index d7d7c0e927..a7dfd05842 100644
--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.kt
+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.kt
@@ -15,8 +15,10 @@ import io.ente.ensu.config.loadConfigDefaults
import io.ente.ensu.llm.LlmProvider
import io.ente.ensu.logging.FileLogRepository
import io.ente.ensu.storage.CredentialStore
+import io.ente.ensu.storage.LegacyDataCleanup
import io.ente.ensu.logging.LogLevel
import io.ente.ensu.AppStore
+import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.first
@@ -55,6 +57,10 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
val launchMessage = "App launched app=$appVersion device=${Build.MANUFACTURER} ${Build.MODEL} os=${Build.VERSION.RELEASE} (sdk=${Build.VERSION.SDK_INT})"
logRepository.log(LogLevel.Info, launchMessage, tag = "App")
+ viewModelScope.launch(Dispatchers.IO) {
+ runCatching { LegacyDataCleanup.run(getApplication(), credentialStore) }
+ }
+
viewModelScope.launch {
val initialSettings = runCatching {
advancedSettingsDataStore.settingsFlow.first()
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRepository.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRepository.kt
index 34fe7ab1fa..28ec5ced3f 100644
--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRepository.kt
+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRepository.kt
@@ -18,14 +18,14 @@ import java.io.File
class ChatRepository(
context: Context,
- private val credentialStore: CredentialStore
+ credentialStore: CredentialStore
) {
private val filePaths = FilePathManager(context)
private val attachmentsDir = filePaths.attachmentsDir
private val dbFile = filePaths.mainDbFile
private val attachmentsDbFile = filePaths.attachmentsDbFile
- private var dbKey = credentialStore.getOrCreateChatDbKey()
+ private val dbKey = credentialStore.getOrCreateChatDbKey()
private var db: EnsuDb = openDb(dbFile, dbKey)
fun listSessions(): List<ChatSession> = withDbRecovery {
@@ -138,20 +138,6 @@ class ChatRepository(
db.updateSessionTitle(sessionId, title)
}
- fun deleteAllData() {
- // Full reset removes current storage plus legacy sync leftovers.
- dbFile.delete()
- attachmentsDbFile.delete()
- filePaths.legacyOnlineDbFile.delete()
- filePaths.legacySyncDir.deleteRecursively()
- filePaths.attachmentsDir.deleteRecursively()
-
- filePaths.attachmentsDir.mkdirs()
-
- dbKey = credentialStore.getOrCreateChatDbKey()
- db = openDb(dbFile, dbKey)
- }
-
private fun openDb(dbFile: File, key: ByteArray): EnsuDb {
return EnsuDb.open(
dbFile.absolutePath,
@@ -171,10 +157,6 @@ class ChatRepository(
reopenDb()
return block()
}
- if (shouldResetDb(error)) {
- resetDb()
- return block()
- }
throw error
}
}
@@ -187,19 +169,7 @@ class ChatRepository(
db = openDb(dbFile, dbKey)
}
- private fun shouldResetDb(error: DbException): Boolean {
- return error is DbException.Crypto ||
- error is DbException.InvalidBlobLength ||
- error is DbException.InvalidEncryptedField
- }
-
private fun isReadonlyDbError(error: DbException): Boolean {
return error is DbException.ReadonlyDatabase
}
-
- private fun resetDb() {
- dbFile.delete()
- attachmentsDbFile.delete()
- db = openDb(dbFile, dbKey)
- }
}
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.kt
index db0ac306a8..e2b4586cea 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
@@ -13,6 +13,7 @@ import io.ente.ensu.llm.LlmProvider
import io.ente.ensu.chat.Attachment
import io.ente.ensu.chat.ChatMessage
import io.ente.ensu.chat.ChatSession
+import io.ente.ensu.bindings.DbException
import io.ente.ensu.bindings.LlmException
import io.ente.ensu.bindings.ConfigDefaults
import io.ente.ensu.logging.LogLevel
@@ -396,7 +397,19 @@ internal class ChatStoreActions(
fun loadSessionsFromDb() {
val scope = scope ?: return
scope.launch(Dispatchers.IO) {
- val sessions = chatRepository.listSessions().map { session ->
+ val loaded = try {
+ chatRepository.listSessions()
+ } catch (error: DbException) {
+ logRepository.log(
+ LogLevel.Error,
+ "Failed to load sessions",
+ details = error.message,
+ tag = "Chat",
+ throwable = error
+ )
+ return@launch
+ }
+ val sessions = loaded.map { session ->
val summary = sessionSummaries[sessionKey(session.id)]
if (!summary.isNullOrBlank()) {
session.copy(title = summary)
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/CredentialStore.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/CredentialStore.kt
index 643fbc9f93..f84c67aea6 100644
--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/CredentialStore.kt
+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/CredentialStore.kt
@@ -37,6 +37,19 @@ class CredentialStore(context: Context) {
return generated
}
+ fun removeLegacyCredentials() {
+ // Ensures the chat DB key no longer needs the master key fallback.
+ getOrCreateChatDbKey()
+ prefs.edit()
+ .remove("email")
+ .remove("user_id")
+ .remove("last_user_id")
+ .remove("secret_key")
+ .remove("token")
+ .remove(KEY_MASTER_KEY)
+ .apply()
+ }
+
private fun encode(bytes: ByteArray): String {
return Base64.encodeToString(bytes, Base64.NO_WRAP or Base64.URL_SAFE)
}
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/FilePathManager.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/FilePathManager.kt
index d310f6cf40..1e4ee1d08c 100644
--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/FilePathManager.kt
+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/FilePathManager.kt
@@ -8,8 +8,6 @@ class FilePathManager(context: Context) {
val attachmentsDir: File = ensureDir(File(appDataDir, "attachments"))
val mainDbFile: File = File(appDataDir, "llmchat.db")
val attachmentsDbFile: File = File(appDataDir, "llmchat_sync.db")
- val legacyOnlineDbFile: File = File(appDataDir, "llmchat_online.db")
- val legacySyncDir: File = File(appDataDir, "llmchat")
private fun ensureDir(dir: File): File {
if (!dir.exists()) {
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/LegacyDataCleanup.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/LegacyDataCleanup.kt
new file mode 100644
index 0000000000..bee391d98e
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/LegacyDataCleanup.kt
@@ -0,0 +1,21 @@
+package io.ente.ensu.storage
+
+import android.content.Context
+import java.io.File
+
+/**
+ * One-shot removal of data written by the retired login and sync builds, so
+ * that credentials and chat copies the user can no longer see or delete do not
+ * linger on disk.
+ *
+ * Added Jul 2026, v0.1.19. Remove once old installs age out (tag: Migration).
+ */
+object LegacyDataCleanup {
+ fun run(context: Context, credentialStore: CredentialStore) {
+ credentialStore.removeLegacyCredentials()
+
+ File(context.filesDir, "llmchat_online.db").delete()
+ File(context.filesDir, "llmchat").deleteRecursively()
+ File(context.filesDir, "datastore/ensu_developer_settings.preferences_pb").delete()
+ }
+}
diff --git a/mobile/native/apple/apps/ensu/Ensu/Chat/ChatDataCleaner.swift b/mobile/native/apple/apps/ensu/Ensu/Chat/ChatDataCleaner.swift
deleted file mode 100644
index 42b3eebc4d..0000000000
--- a/mobile/native/apple/apps/ensu/Ensu/Chat/ChatDataCleaner.swift
+++ /dev/null
@@ -1,24 +0,0 @@
-import Foundation
-
-enum ChatDataCleaner {
- static func deleteAllData() {
- let baseDir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
- ?? FileManager.default.temporaryDirectory
- let dbDir = baseDir.appendingPathComponent("llmchat", isDirectory: true)
-
- let mainDbUrl = dbDir.appendingPathComponent("llmchat.db")
- let attachmentsDbUrl = dbDir.appendingPathComponent("llmchat_sync.db")
- let onlineDbUrl = dbDir.appendingPathComponent("llmchat_online.db")
- let attachmentsDirUrl = dbDir.appendingPathComponent("chat_attachments", isDirectory: true)
- let encryptedAttachmentsDirUrl = dbDir.appendingPathComponent("chat_attachments_encrypted", isDirectory: true)
- let metaDirUrl = dbDir.appendingPathComponent("sync_meta", isDirectory: true)
-
- // Full reset removes current storage plus legacy sync leftovers.
- try? FileManager.default.removeItem(at: mainDbUrl)
- try? FileManager.default.removeItem(at: attachmentsDbUrl)
- try? FileManager.default.removeItem(at: onlineDbUrl)
- try? FileManager.default.removeItem(at: attachmentsDirUrl)
- try? FileManager.default.removeItem(at: encryptedAttachmentsDirUrl)
- try? FileManager.default.removeItem(at: metaDirUrl)
- }
-}
diff --git a/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift b/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift
index 84a1aac6c5..5a93d8508f 100644
--- a/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift
+++ b/mobile/native/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift
@@ -356,19 +356,6 @@ final class ChatViewModel: ObservableObject {
}
}
- func deleteAllData() async {
- await Task.detached { ChatDataCleaner.deleteAllData() }.value
- sessions = []
- messages = []
- currentSessionId = nil
- messageStore.removeAll()
- branchSelections.removeAll()
- childrenByParentCache.removeAll()
- attachmentDownloads = []
- currentSessionMissingAttachments = []
- refreshAttachmentDownloadState()
- }
-
func beginEditing(message: RenderedChatMessage) {
guard !isChatUnsupported else {
showUnsupportedDeviceDialog = true
diff --git a/mobile/native/apple/apps/ensu/Ensu/EnsuApp.swift b/mobile/native/apple/apps/ensu/Ensu/EnsuApp.swift
index 690a6f4505..d11d61c2e7 100644
--- a/mobile/native/apple/apps/ensu/Ensu/EnsuApp.swift
+++ b/mobile/native/apple/apps/ensu/Ensu/EnsuApp.swift
@@ -6,6 +6,7 @@ struct EnsuApp: App {
init() {
EnsuLogging.shared.start()
+ LegacyDataCleanup.run()
}
var body: some Scene {
diff --git a/mobile/native/apple/apps/ensu/Ensu/Services/CredentialStore.swift b/mobile/native/apple/apps/ensu/Ensu/Services/CredentialStore.swift
index 798c38481c..90064015ea 100644
--- a/mobile/native/apple/apps/ensu/Ensu/Services/CredentialStore.swift
+++ b/mobile/native/apple/apps/ensu/Ensu/Services/CredentialStore.swift
@@ -13,6 +13,16 @@ final class CredentialStore {
static let chatDbKey = "ensu.chatDbKey"
}
+ func removeLegacyCredentials() {
+ let chatDbKey = getOrCreateChatDbKey()
+ guard let persisted = try? KeychainStore.get(service: keychainService, account: KeychainAccount.chatDbKey), persisted == chatDbKey else {
+ return
+ }
+ for account in ["ensu.token", "ensu.secretKey", KeychainAccount.masterKey] {
+ try? KeychainStore.delete(service: keychainService, account: account)
+ }
+ }
+
func getOrCreateChatDbKey() -> Data {
if let existing = try? KeychainStore.get(service: keychainService, account: KeychainAccount.chatDbKey), existing.count == 32 {
return existing
diff --git a/mobile/native/apple/apps/ensu/Ensu/Services/LegacyDataCleanup.swift b/mobile/native/apple/apps/ensu/Ensu/Services/LegacyDataCleanup.swift
new file mode 100644
index 0000000000..83aca0e42b
--- /dev/null
+++ b/mobile/native/apple/apps/ensu/Ensu/Services/LegacyDataCleanup.swift
@@ -0,0 +1,27 @@
+import Foundation
+
+/// One-shot removal of data written by the retired login and sync builds, so
+/// that credentials and chat copies the user can no longer see or delete do
+/// not linger.
+///
+/// Added Jul 2026, v0.1.19. Remove once old installs age out (tag: Migration).
+enum LegacyDataCleanup {
+ static func run() {
+ CredentialStore.shared.removeLegacyCredentials()
+
+ let defaults = UserDefaults.standard
+ for key in ["ensu.email", "ensu.userId", "ensu.lastUserId", "ensu.customEndpoint"] {
+ defaults.removeObject(forKey: key)
+ }
+
+ Task.detached(priority: .utility) {
+ guard let baseDir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else {
+ return
+ }
+ let dbDir = baseDir.appendingPathComponent("llmchat", isDirectory: true)
+ for item in ["llmchat_online.db", "chat_attachments_encrypted", "sync_meta"] {
+ try? FileManager.default.removeItem(at: dbDir.appendingPathComponent(item))
+ }
+ }
+ }
+}
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 7036a9c58b..acd3a57d2b 100644
--- a/rust/apps/ensu/src-tauri/src/commands/chat_db.rs
+++ b/rust/apps/ensu/src-tauri/src/commands/chat_db.rs
@@ -570,45 +570,6 @@ pub async fn chat_db_insert_message_with_uuid(
.await
}
-#[tauri::command]
-pub async fn chat_db_reset(state: State<'_, ChatDbState>, app: AppHandle) -> Result<(), ApiError> {
- let inner = state.inner.clone();
- async_runtime::spawn_blocking(move || {
- {
- let mut guard = inner
- .lock()
- .map_err(|_| ApiError::new("lock", "Failed to lock chat DB state"))?;
- *guard = None;
- }
-
- let path = chat_db_path(&app)?;
- let wal_path = PathBuf::from(format!("{}-wal", path.display()));
- let shm_path = PathBuf::from(format!("{}-shm", path.display()));
- let attachments_db_path = attachments_db_path(&app)?;
- let attachments_db_wal_path =
- PathBuf::from(format!("{}-wal", attachments_db_path.display()));
- let attachments_db_shm_path =
- PathBuf::from(format!("{}-shm", attachments_db_path.display()));
-
- for candidate in [
- path,
- wal_path,
- shm_path,
- attachments_db_path,
- attachments_db_wal_path,
- attachments_db_shm_path,
- ] {
- if candidate.exists() {
- fs::remove_file(&candidate).map_err(|err| ApiError::new("io", err.to_string()))?;
- }
- }
-
- Ok(())
- })
- .await
- .map_err(|_| chat_db_thread_error())?
-}
-
#[tauri::command]
pub async fn chat_db_migrate_legacy(
app: AppHandle,
diff --git a/rust/apps/ensu/src-tauri/src/main.rs b/rust/apps/ensu/src-tauri/src/main.rs
index 8e19543ae5..cada2c3f50 100644
--- a/rust/apps/ensu/src-tauri/src/main.rs
+++ b/rust/apps/ensu/src-tauri/src/main.rs
@@ -53,7 +53,6 @@ fn main() {
commands::chat_db::chat_db_upsert_session,
commands::chat_db::chat_db_insert_message_with_uuid,
commands::chat_db::chat_db_compress_attachment_image_file,
- commands::chat_db::chat_db_reset,
commands::chat_db::chat_db_migrate_legacy,
commands::llm::llm_init_backend,
commands::llm::llm_load_model,
diff --git a/web/apps/ensu/package.json b/web/apps/ensu/package.json
index 59c4aaff4f..284e8b53ed 100644
--- a/web/apps/ensu/package.json
+++ b/web/apps/ensu/package.json
@@ -14,7 +14,6 @@
"@tauri-apps/plugin-updater": "2.10.1",
"@wllama/wllama": "2.4.0",
"ente-base": "*",
- "ente-new": "*",
"ente-wasm": "*",
"idb": "8.0.3",
"katex": "0.17.0",
diff --git a/web/apps/ensu/src/pages/_app.tsx b/web/apps/ensu/src/pages/_app.tsx
index 2bb0aa7f11..9fd2c26ad8 100644
--- a/web/apps/ensu/src/pages/_app.tsx
+++ b/web/apps/ensu/src/pages/_app.tsx
@@ -1,6 +1,5 @@
import { WhatsNewDialog } from "@/components/WhatsNewDialog";
import { setupAutoAppUpdates } from "@/services/app-update";
-import { resetEnsuAppState } from "@/services/reset";
import { isTauriRuntime } from "@/services/tauri-runtime";
import {
getPendingDesktopWhatsNew,
@@ -10,6 +9,7 @@ import {
import { CssBaseline } from "@mui/material";
import { ThemeProvider } from "@mui/material/styles";
import { staticAppTitle } from "ente-base/app";
+import { assertionFailed } from "ente-base/assert";
import { CustomHead } from "ente-base/components/Head";
import {
LoadingIndicator,
@@ -92,10 +92,6 @@ const App: React.FC<AppProps> = ({ Component, pageProps }) => {
};
}, []);
- const resetAppState = useCallback(() => {
- void resetEnsuAppState();
- }, []);
-
const handleWhatsNewClose = useCallback(() => {
markDesktopWhatsNewSeen();
setIsWhatsNewOpen(false);
@@ -103,8 +99,8 @@ const App: React.FC<AppProps> = ({ Component, pageProps }) => {
}, []);
const baseContext = useMemo(
- () => deriveBaseContext({ logout: resetAppState, showMiniDialog }),
- [resetAppState, showMiniDialog],
+ () => deriveBaseContext({ logout: assertionFailed, showMiniDialog }),
+ [showMiniDialog],
);
const title = staticAppTitle;
diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsx
index dca27524fd..b025839097 100644
--- a/web/apps/ensu/src/pages/chat.tsx
+++ b/web/apps/ensu/src/pages/chat.tsx
@@ -408,7 +408,7 @@ const detectTauriRuntime = () => detectTauriAppRuntime();
const Page: React.FC = () => {
const router = useRouter();
- const { showMiniDialog } = useBaseContext();
+ const { showMiniDialog, onGenericError } = useBaseContext();
const theme = useTheme();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
const assetBasePath = router.basePath ?? "";
@@ -2322,9 +2322,14 @@ const Page: React.FC = () => {
const handleConfirmDeleteSession = useCallback(async () => {
if (!deleteSessionId) return;
- await handleDeleteSession(deleteSessionId);
- setDeleteSessionId(null);
- }, [deleteSessionId, handleDeleteSession]);
+ try {
+ await handleDeleteSession(deleteSessionId);
+ } catch (error) {
+ onGenericError(error);
+ } finally {
+ setDeleteSessionId(null);
+ }
+ }, [deleteSessionId, handleDeleteSession, onGenericError]);
const handleCancelDeleteSession = useCallback(() => {
setDeleteSessionId(null);
@@ -3681,7 +3686,12 @@ const Page: React.FC = () => {
let activeSessionId = currentSessionId;
if (!activeSessionId) {
- activeSessionId = await createSession(chatKey);
+ try {
+ activeSessionId = await createSession(chatKey);
+ } catch (error) {
+ onGenericError(error);
+ return;
+ }
setCurrentSessionId(activeSessionId);
currentSessionIdRef.current = activeSessionId;
setIsDraftSession(false);
@@ -3861,6 +3871,7 @@ const Page: React.FC = () => {
pendingDocuments,
pendingImages,
showMiniDialog,
+ onGenericError,
slicePathUntil,
startGeneration,
writeInferenceImages,
diff --git a/web/apps/ensu/src/services/chat/store.ts b/web/apps/ensu/src/services/chat/store.ts
index a3d2e2b323..22cc72738c 100644
--- a/web/apps/ensu/src/services/chat/store.ts
+++ b/web/apps/ensu/src/services/chat/store.ts
@@ -1,4 +1,8 @@
import { base64ToBytes } from "@/services/base64";
+import {
+ secureStorageDelete,
+ secureStorageGet,
+} from "@/services/secure-storage";
import { isTauriRuntime } from "@/services/tauri-runtime";
import { getKV, removeKV, setKV } from "ente-base/kv";
import log from "ente-base/log";
@@ -207,45 +211,6 @@ const getErrorCode = (error: unknown) => {
return typeof code === "string" ? code : undefined;
};
-const shouldResetDbError = (error: unknown) => {
- const code = getErrorCode(error);
- return (
- code === "db_crypto" ||
- code === "db_invalid_blob_length" ||
- code === "db_invalid_encrypted_field"
- );
-};
-
-let lastDbResetAt = 0;
-
-const withNativeDbRecovery = async <T>(
- label: string,
- operation: () => Promise<T>,
-): Promise<T> => {
- try {
- return await operation();
- } catch (error) {
- if (!shouldResetDbError(error)) {
- throw error;
- }
- const now = Date.now();
- if (now - lastDbResetAt < 1000) {
- throw error;
- }
- lastDbResetAt = now;
- log.warn(
- `Chat DB error while ${label}, resetting local store: ${formatLogError(error)}`,
- );
- try {
- await resetChatStore();
- } catch (resetError) {
- log.error("Failed to reset chat store after DB error", resetError);
- throw error;
- }
- return await operation();
- }
-};
-
const loadChatStoreState = (): ChatStoreState => {
if (typeof localStorage === "undefined") {
return { sessions: [], messages: [], attachmentBytes: [] };
@@ -846,6 +811,64 @@ const migrateLegacyNativeChatStoreToV2 = async (
return false;
};
+/**
+ * One-shot removal of data written by the retired login and sync builds, so
+ * that credentials and chat copies the user can no longer see or delete do not
+ * linger.
+ *
+ * Added Jul 2026, v0.1.19. Remove once old installs age out (tag: Migration).
+ */
+const cleanupLegacyData = async () => {
+ if (isTauriRuntime()) {
+ // The legacy keyring entries are potential decryption keys for a
+ // not-yet-migrated legacy DB, and potential sources of the v2 chat
+ // key. Only delete them once the legacy DB migration has completed
+ // and the v2 key is durably in the OS keyring.
+ if (!isNativeMigrationDone()) return;
+ if (!(await secureStorageGet("localChatKey.v2"))) return;
+
+ const entries = ["masterKey", "localChatKey", "remoteChatKey"];
+ const userID = legacyUserID();
+ if (userID) {
+ entries.push(
+ `remoteChatKey.v2.${userID}`,
+ `remoteChatKey.${userID}`,
+ );
+ }
+ for (const entry of entries) await secureStorageDelete(entry);
+
+ const [{ exists, remove }, { appDataDir, join }] = await Promise.all([
+ import("@tauri-apps/plugin-fs"),
+ import("@tauri-apps/api/path"),
+ ]);
+ const syncMetaDir = await join(await appDataDir(), "sync_meta");
+ if (await exists(syncMetaDir)) {
+ await remove(syncMetaDir, { recursive: true });
+ }
+ }
+
+ [
+ "user",
+ "srpAttributes",
+ "keyAttributes",
+ "originalKeyAttributes",
+ "isFirstLogin",
+ ].forEach((key) => localStorage.removeItem(key));
+
+ await removeKV("token");
+};
+
+const legacyUserID = () => {
+ try {
+ const raw = localStorage.getItem("user");
+ if (!raw) return undefined;
+ const id = (JSON.parse(raw) as { id?: unknown }).id;
+ return typeof id === "number" ? id : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
export const initializeChatStorePersistence = async (chatKey: string) => {
if (_chatPersistenceInitKey === chatKey && _chatPersistenceInitPromise) {
return _chatPersistenceInitPromise;
@@ -864,15 +887,15 @@ export const initializeChatStorePersistence = async (chatKey: string) => {
markNativeMigrationDone();
}
}
- return;
- }
-
- if (hasLegacyChatStore()) {
+ } else if (hasLegacyChatStore()) {
await migrateLegacyLocalChatStoreToIndexedDb();
- return;
+ } else {
+ await migrateLegacyIndexedDbChatStore();
}
- await migrateLegacyIndexedDbChatStore();
+ void cleanupLegacyData().catch((error: unknown) =>
+ log.error("Failed to clean up legacy data", error),
+ );
})().catch((error: unknown) => {
if (_chatPersistenceInitPromise === initPromise) {
_chatPersistenceInitPromise = undefined;
@@ -904,64 +927,58 @@ const invokeChat = async <T>(
};
const listSessionsNative = async (chatKey: string): Promise<ChatSession[]> => {
- return withNativeDbRecovery("listing sessions", async () => {
- const sessions = await invokeChat<NativeSession[]>(
- "chat_db_list_sessions_with_preview",
- { keyB64: chatKey },
- );
-
- const activeSessions = sessions.filter((session) => !session.deletedAt);
+ const sessions = await invokeChat<NativeSession[]>(
+ "chat_db_list_sessions_with_preview",
+ { keyB64: chatKey },
+ );
- return activeSessions.map((session) => ({
- sessionUuid: session.sessionUuid,
- rootSessionUuid: session.sessionUuid,
- branchFromMessageUuid: undefined,
- title: safeTitle(session.title),
- createdAt: session.createdAt,
- updatedAt: session.updatedAt,
- lastMessagePreview: session.lastMessagePreview ?? undefined,
- }));
- });
+ const activeSessions = sessions.filter((session) => !session.deletedAt);
+
+ return activeSessions.map((session) => ({
+ sessionUuid: session.sessionUuid,
+ rootSessionUuid: session.sessionUuid,
+ branchFromMessageUuid: undefined,
+ title: safeTitle(session.title),
+ createdAt: session.createdAt,
+ updatedAt: session.updatedAt,
+ lastMessagePreview: session.lastMessagePreview ?? undefined,
+ }));
};
const listMessagesNative = async (
sessionUuid: string,
chatKey: string,
): Promise<ChatMessage[]> => {
- return withNativeDbRecovery("listing messages", async () => {
- const messages = await invokeChat<NativeMessage[]>(
- "chat_db_get_messages",
- { keyB64: chatKey, sessionUuid },
- );
-
- return messages
- .filter((message) => !message.deletedAt)
- .map((message) => ({
- messageUuid: message.messageUuid,
- sessionUuid: message.sessionUuid,
- parentMessageUuid: message.parentMessageUuid ?? undefined,
- sender: message.sender,
- text: message.text,
- createdAt: message.createdAt,
- attachments: message.attachments?.map((attachment) => ({
- id: attachment.id,
- kind: attachment.kind,
- name: attachment.name,
- size: attachment.size,
- uploadedAt: attachment.uploadedAt ?? undefined,
- })),
- }));
+ const messages = await invokeChat<NativeMessage[]>("chat_db_get_messages", {
+ keyB64: chatKey,
+ sessionUuid,
});
+
+ return messages
+ .filter((message) => !message.deletedAt)
+ .map((message) => ({
+ messageUuid: message.messageUuid,
+ sessionUuid: message.sessionUuid,
+ parentMessageUuid: message.parentMessageUuid ?? undefined,
+ sender: message.sender,
+ text: message.text,
+ createdAt: message.createdAt,
+ attachments: message.attachments?.map((attachment) => ({
+ id: attachment.id,
+ kind: attachment.kind,
+ name: attachment.name,
+ size: attachment.size,
+ uploadedAt: attachment.uploadedAt ?? undefined,
+ })),
+ }));
};
const createSessionNative = async (chatKey: string) => {
- return withNativeDbRecovery("creating session", async () => {
- const session = await invokeChat<NativeSession>(
- "chat_db_create_session",
- { keyB64: chatKey, title: "New chat" },
- );
- return session.sessionUuid;
+ const session = await invokeChat<NativeSession>("chat_db_create_session", {
+ keyB64: chatKey,
+ title: "New chat",
});
+ return session.sessionUuid;
};
const updateSessionTitleNative = async (
@@ -969,12 +986,10 @@ const updateSessionTitleNative = async (
sessionUuid: string,
title: string,
) => {
- await withNativeDbRecovery("updating session title", async () => {
- await invokeChat("chat_db_update_session_title", {
- keyB64: chatKey,
- sessionUuid,
- title,
- });
+ await invokeChat("chat_db_update_session_title", {
+ keyB64: chatKey,
+ sessionUuid,
+ title,
});
};
@@ -986,64 +1001,56 @@ const addMessageNative = async (
parentMessageUuid?: string,
attachments: ChatAttachment[] = [],
): Promise<ChatMessage> => {
- return withNativeDbRecovery("adding message", async () => {
- const message = await invokeChat<NativeMessage>(
- "chat_db_insert_message",
- {
- keyB64: chatKey,
- input: {
- sessionUuid,
- sender,
- text,
- parentMessageUuid,
- attachments: attachments.map((attachment) => ({
- id: attachment.id,
- kind: attachment.kind,
- name: attachment.name,
- size: attachment.size,
- uploadedAt: attachment.uploadedAt ?? null,
- })),
- },
- },
- );
-
- if (sender === "self") {
- try {
- const session = await invokeChat<NativeSession | null>(
- "chat_db_get_session",
- { keyB64: chatKey, sessionUuid },
- );
- if (
- session &&
- safeTitle(session.title).toLowerCase() === "new chat"
- ) {
- const title = sessionTitleFromText(text, "New chat");
- await updateSessionTitleNative(chatKey, sessionUuid, title);
- }
- } catch (error) {
- if (shouldResetDbError(error)) {
- throw error;
- }
- log.error("Failed to update native session title", error);
- }
- }
-
- return {
- messageUuid: message.messageUuid,
- sessionUuid: message.sessionUuid,
- parentMessageUuid: message.parentMessageUuid ?? undefined,
- sender: message.sender,
- text: message.text,
- createdAt: message.createdAt,
- attachments: message.attachments?.map((attachment) => ({
+ const message = await invokeChat<NativeMessage>("chat_db_insert_message", {
+ keyB64: chatKey,
+ input: {
+ sessionUuid,
+ sender,
+ text,
+ parentMessageUuid,
+ attachments: attachments.map((attachment) => ({
id: attachment.id,
kind: attachment.kind,
name: attachment.name,
size: attachment.size,
- uploadedAt: attachment.uploadedAt ?? undefined,
+ uploadedAt: attachment.uploadedAt ?? null,
})),
- };
+ },
});
+
+ if (sender === "self") {
+ try {
+ const session = await invokeChat<NativeSession | null>(
+ "chat_db_get_session",
+ { keyB64: chatKey, sessionUuid },
+ );
+ if (
+ session &&
+ safeTitle(session.title).toLowerCase() === "new chat"
+ ) {
+ const title = sessionTitleFromText(text, "New chat");
+ await updateSessionTitleNative(chatKey, sessionUuid, title);
+ }
+ } catch (error) {
+ log.error("Failed to update native session title", error);
+ }
+ }
+
+ return {
+ messageUuid: message.messageUuid,
+ sessionUuid: message.sessionUuid,
+ parentMessageUuid: message.parentMessageUuid ?? undefined,
+ sender: message.sender,
+ text: message.text,
+ createdAt: message.createdAt,
+ attachments: message.attachments?.map((attachment) => ({
+ id: attachment.id,
+ kind: attachment.kind,
+ name: attachment.name,
+ size: attachment.size,
+ uploadedAt: attachment.uploadedAt ?? undefined,
+ })),
+ };
};
const updateMessageNative = async (
@@ -1051,21 +1058,17 @@ const updateMessageNative = async (
text: string,
chatKey: string,
) => {
- await withNativeDbRecovery("updating message", async () => {
- await invokeChat("chat_db_update_message_text", {
- keyB64: chatKey,
- messageUuid,
- text,
- });
+ await invokeChat("chat_db_update_message_text", {
+ keyB64: chatKey,
+ messageUuid,
+ text,
});
};
const deleteSessionNative = async (sessionUuid: string, chatKey: string) => {
- await withNativeDbRecovery("deleting session", async () => {
- await invokeChat("chat_db_delete_session", {
- keyB64: chatKey,
- sessionUuid,
- });
+ await invokeChat("chat_db_delete_session", {
+ keyB64: chatKey,
+ sessionUuid,
});
};
@@ -1341,26 +1344,6 @@ export const getBranchSelections = async (rootSessionUuid: string) => {
);
};
-export const resetChatStore = async () => {
- if (typeof window === "undefined") return;
-
- localStorage.removeItem(STORAGE_KEY);
-
- if (isTauriRuntime()) {
- await invokeChat("chat_db_reset");
- return;
- }
- try {
- if (_chatDb) {
- (await _chatDb).close();
- }
- } catch (error) {
- log.error("Failed to close chat IndexedDB before reset", error);
- }
- _chatDb = undefined;
- await deleteDB("ensu-chat");
-};
-
export const setBranchSelection = async (
rootSessionUuid: string,
selectionKey: string,
diff --git a/web/apps/ensu/src/services/reset.ts b/web/apps/ensu/src/services/reset.ts
deleted file mode 100644
index 4a51b7a139..0000000000
--- a/web/apps/ensu/src/services/reset.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import log from "ente-base/log";
-
-export const resetEnsuAppState = async () => {
- const ignoreError = (label: string, e: unknown) =>
- log.error(`Ignoring error during reset (${label})`, e);
-
- try {
- const { resetChatStore } = await import("@/services/chat/store");
- await resetChatStore();
- } catch (e) {
- ignoreError("chat store", e);
- }
-
- window.location.replace("/");
-};
diff --git a/web/package-lock.json b/web/package-lock.json
index 515f2dadd7..48a154b3fe 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -175,7 +175,6 @@
"@tauri-apps/plugin-updater": "2.10.1",
"@wllama/wllama": "2.4.0",
"ente-base": "*",
- "ente-new": "*",
"ente-wasm": "*",
"idb": "8.0.3",
"katex": "0.17.0",