π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Remove Ensu lint bypasses
Manav Rathie8a3be2abb4b
diff --git a/web/apps/ensu/eslint.config.mjs b/web/apps/ensu/eslint.config.mjsindex 4ba2fc45c1..641d994d1e 100644--- a/web/apps/ensu/eslint.config.mjs+++ b/web/apps/ensu/eslint.config.mjs@@ -1,35 +1 @@-import baseConfig from "../../packages/build-config/eslintrc-next-app.mjs";--export default [- ...baseConfig,- {- files: ["**/*.{ts,tsx}"],- rules: {- "@typescript-eslint/array-type": "off",- "@typescript-eslint/consistent-indexed-object-style": "off",- "@typescript-eslint/consistent-type-definitions": "off",- "@typescript-eslint/no-base-to-string": "off",- "@typescript-eslint/no-confusing-void-expression": "off",- "@typescript-eslint/no-deprecated": "off",- "@typescript-eslint/no-dynamic-delete": "off",- "@typescript-eslint/no-empty-function": "off",- "@typescript-eslint/no-explicit-any": "off",- "@typescript-eslint/no-meaningless-void-operator": "off",- "@typescript-eslint/no-misused-promises": "off",- "@typescript-eslint/no-misused-spread": "off",- "@typescript-eslint/no-non-null-asserted-optional-chain": "off",- "@typescript-eslint/no-unnecessary-condition": "off",- "@typescript-eslint/no-unsafe-assignment": "off",- "@typescript-eslint/no-unused-vars": "off",- "@typescript-eslint/non-nullable-type-assertion-style": "off",- "@typescript-eslint/prefer-optional-chain": "off",- "@typescript-eslint/prefer-promise-reject-errors": "off",- "@typescript-eslint/prefer-regexp-exec": "off",- "@typescript-eslint/require-await": "off",- "@typescript-eslint/return-await": "off",- "no-control-regex": "off",- "no-unsafe-finally": "off",- "prefer-const": "off",- },- },-];+export { default } from "ente-build-config/eslintrc-next-app.mjs";diff --git a/web/apps/ensu/next.config.mjs b/web/apps/ensu/next.config.mjsindex 11465a0d54..df866c2bf1 100644--- a/web/apps/ensu/next.config.mjs+++ b/web/apps/ensu/next.config.mjs@@ -1,6 +1,6 @@import nextConfig from "ente-base/next.config.base.js";-/** @type {{ process?: { env?: Record<string, string> } }} */+/** @type {{ process?: { env?: Record<string, string | undefined> } }} */const globalWithProcess = globalThis;const env = globalWithProcess.process?.env;const isTauriBuild = env?.ENTE_TAURI === "1";@@ -11,10 +11,9 @@ const normalizedBasePath = rawBasePath: `/${rawBasePath}`: undefined;-export default {+/** @satisfies {import("next").NextConfig} */+const config = {...nextConfig,- eslint: { ignoreDuringBuilds: true },- typescript: { ignoreBuildErrors: true },...(isTauriBuild ? { output: "export" } : {}),...(normalizedBasePath? {@@ -24,3 +23,5 @@ export default {}: {}),};++export default config;diff --git a/web/apps/ensu/src/components/MarkdownRenderer.tsx b/web/apps/ensu/src/components/MarkdownRenderer.tsxindex b20a6ffae3..379fde2660 100644--- a/web/apps/ensu/src/components/MarkdownRenderer.tsx+++ b/web/apps/ensu/src/components/MarkdownRenderer.tsx@@ -35,36 +35,10 @@ const extractCodeText = (node: React.ReactNode): string => {const CodeBlock = ({ children, node: _node, ...rest }: PreProps) => {const codeText = extractCodeText(children).replace(/\n$/, "");- const handleCopy = useCallback(() => {- if (- typeof navigator === "undefined" ||- typeof document === "undefined"- ) {- return;- }-- const clipboard = navigator.clipboard;- if (clipboard && typeof clipboard.writeText === "function") {- void clipboard.writeText(codeText);- return;- }-- const textarea = document.createElement("textarea");- textarea.value = codeText;- textarea.setAttribute("readonly", "true");- textarea.style.position = "fixed";- textarea.style.opacity = "0";- textarea.style.pointerEvents = "none";- document.body.appendChild(textarea);- textarea.select();- try {- document.execCommand("copy");- } catch {- // The legacy copy path has no failure recourse.- } finally {- document.body.removeChild(textarea);- }- }, [codeText]);+ const handleCopy = useCallback(+ () => void navigator.clipboard.writeText(codeText),+ [codeText],+ );return (<Box className="markdown-code-block" sx={{ position: "relative" }}>diff --git a/web/apps/ensu/src/components/chat/ChatComposer.tsx b/web/apps/ensu/src/components/chat/ChatComposer.tsxindex 64518f87c8..5629e76ebb 100644--- a/web/apps/ensu/src/components/chat/ChatComposer.tsx+++ b/web/apps/ensu/src/components/chat/ChatComposer.tsx@@ -22,16 +22,24 @@ import {import type { SxProps, Theme } from "@mui/material/styles";import React, { memo } from "react";-type IconProps = { size: number; strokeWidth: number };+interface IconProps {+ size: number;+ strokeWidth: number;+}-type DocumentAttachment = {+interface DocumentAttachment {id: string;name: string;size: number;text: string;-};+}-type ImageAttachment = { id: string; name: string; size: number; file: File };+interface ImageAttachment {+ id: string;+ name: string;+ size: number;+ file: File;+}type SuggestedModelStatus =| "checking"diff --git a/web/apps/ensu/src/components/chat/ChatDialogs.tsx b/web/apps/ensu/src/components/chat/ChatDialogs.tsxindex d8a472021a..8145105571 100644--- a/web/apps/ensu/src/components/chat/ChatDialogs.tsx+++ b/web/apps/ensu/src/components/chat/ChatDialogs.tsx@@ -195,6 +195,7 @@ export const ChatDialogs = memo(React.useState(false);const [draftSystemPrompt, setDraftSystemPrompt] = React.useState("");+ const wasSystemPromptSettingsOpen = React.useRef(false);const modelOptions = React.useMemo(() => [@@ -224,12 +225,13 @@ export const ChatDialogs = memo(showModelSettings,]);- // The draft resyncs only when the dialog opens, hence the deps- // suppression below.React.useEffect(() => {- if (!showSystemPromptSettings) return;- setDraftSystemPrompt(systemPrompt);- }, [showSystemPromptSettings]); // eslint-disable-line react-hooks/exhaustive-deps+ const didOpen =+ showSystemPromptSettings &&+ !wasSystemPromptSettingsOpen.current;+ wasSystemPromptSettingsOpen.current = showSystemPromptSettings;+ if (didOpen) setDraftSystemPrompt(systemPrompt);+ }, [showSystemPromptSettings, systemPrompt]);const validateModelSettings = React.useCallback(() => {const contextErrorValue =diff --git a/web/apps/ensu/src/components/chat/ChatMessageList.tsx b/web/apps/ensu/src/components/chat/ChatMessageList.tsxindex 2399ab3942..2927db10d9 100644--- a/web/apps/ensu/src/components/chat/ChatMessageList.tsx+++ b/web/apps/ensu/src/components/chat/ChatMessageList.tsx@@ -16,18 +16,25 @@ import {import { HugeiconsIcon } from "@hugeicons/react";import { Box, IconButton, Stack, Typography } from "@mui/material";import type { SxProps, Theme } from "@mui/material/styles";+import type { SystemStyleObject } from "@mui/system";import React, { memo, useCallback, useEffect, useMemo, useState } from "react";-type DocumentAttachment = {+interface DocumentAttachment {id: string;name: string;text: string;size: number;-};+}-type IconProps = { size: number; strokeWidth: number };+interface IconProps {+ size: number;+ strokeWidth: number;+}-export type ParsedDocuments = { text: string; documents: DocumentAttachment[] };+export interface ParsedDocuments {+ text: string;+ documents: DocumentAttachment[];+}export interface ChatMessageListProps {messages: ChatMessage[];@@ -39,7 +46,7 @@ export interface ChatMessageListProps {isStreamingOutro: boolean;stickToBottom: boolean;onStickToBottomChange: (value: boolean) => void;- scrollContainerRef: React.MutableRefObject<HTMLDivElement | null>;+ scrollContainerRef: React.RefObject<HTMLDivElement | null>;onScroll: () => void;onUserScrollIntent: () => void;onOpenAttachment: (@@ -60,7 +67,7 @@ export interface ChatMessageListProps {userMessageTextSx: SxProps<Theme>;assistantTextSx: SxProps<Theme>;assistantMarkdownSx: SxProps<Theme>;- streamingMessageSx: SxProps<Theme>;+ streamingMessageSx: SystemStyleObject<Theme>;actionButtonSx: SxProps<Theme>;smallIconProps: IconProps;actionIconProps: IconProps;@@ -189,7 +196,7 @@ interface MessageRowProps {userBubbleBackground: string;userMessageTextSx: SxProps<Theme>;assistantMarkdownSx: SxProps<Theme>;- streamingMessageSx: SxProps<Theme>;+ streamingMessageSx: SystemStyleObject<Theme>;actionButtonSx: SxProps<Theme>;smallIconProps: IconProps;actionIconProps: IconProps;@@ -378,9 +385,7 @@ const MessageRow = memo(isGenerating={isGenerating && isStreaming}- isOutroPhase={- isStreaming && isStreamingOutro- }+ isOutroPhase={isStreamingOutro}fallbackText={`${loadingPhrase ?? "Generating your reply"}${dots}`}/></Stack>@@ -491,7 +496,6 @@ const MessageRow = memo(aria-label="Previous branch"sx={actionButtonSx}onClick={() =>- switcher &&onPrevBranch(switcher)}>@@ -510,16 +514,13 @@ const MessageRow = memo(textAlign: "center",}}>- {switcher- ? switcher.currentIndex + 1- : 1}- /{switcher ? switcher.total : 1}+ {switcher.currentIndex + 1}/+ {switcher.total}</Typography><IconButtonaria-label="Next branch"sx={actionButtonSx}onClick={() =>- switcher &&onNextBranch(switcher)}>@@ -564,7 +565,6 @@ const MessageRow = memo(aria-label="Previous branch"sx={actionButtonSx}onClick={() =>- switcher &&onPrevBranch(switcher)}>@@ -583,16 +583,13 @@ const MessageRow = memo(textAlign: "center",}}>- {switcher- ? switcher.currentIndex + 1- : 1}- /{switcher ? switcher.total : 1}+ {switcher.currentIndex + 1}/+ {switcher.total}</Typography><IconButtonaria-label="Next branch"sx={actionButtonSx}onClick={() =>- switcher &&onNextBranch(switcher)}>diff --git a/web/apps/ensu/src/components/chat/ChatSidebar.tsx b/web/apps/ensu/src/components/chat/ChatSidebar.tsxindex 55cc9bf918..388fd3dfbc 100644--- a/web/apps/ensu/src/components/chat/ChatSidebar.tsx+++ b/web/apps/ensu/src/components/chat/ChatSidebar.tsx@@ -23,7 +23,10 @@ import {import type { SxProps, Theme } from "@mui/material/styles";import React, { memo } from "react";-type IconProps = { size: number; strokeWidth: number };+interface IconProps {+ size: number;+ strokeWidth: number;+}export interface ChatSidebarProps {drawerCollapsed: boolean;@@ -40,7 +43,7 @@ export interface ChatSidebarProps {handleNewChat: () => void;handleOpenDrawer: () => void;handleCollapseDrawer: () => void;- groupedSessions: Array<[string, ChatSession[]]>;+ groupedSessions: [string, ChatSession[]][];currentSessionId?: string;handleSelectSession: (sessionId: string) => void;requestRenameSession: (session: ChatSession) => void;@@ -284,7 +287,7 @@ export const ChatSidebar = memo(</Typography>{group.map((session) => {const sessionTitle =- session.title?.trim() || "New chat";+ session.title.trim() || "New chat";return (<ListItemButtonkey={session.sessionUuid}diff --git a/web/apps/ensu/src/components/chat/GeneratingRiveIndicator.tsx b/web/apps/ensu/src/components/chat/GeneratingRiveIndicator.tsxindex 2e8d197392..7b825511c2 100644--- a/web/apps/ensu/src/components/chat/GeneratingRiveIndicator.tsx+++ b/web/apps/ensu/src/components/chat/GeneratingRiveIndicator.tsx@@ -1,12 +1,12 @@import { Box, Typography } from "@mui/material";import { memo, useEffect, useState } from "react";-type GeneratingRiveIndicatorProps = {+interface GeneratingRiveIndicatorProps {size?: number;fallbackText?: string;isGenerating?: boolean;isOutroPhase?: boolean;-};+}const DOT_STEP_MS = 420;diff --git a/web/apps/ensu/src/components/chat/HoverRiveLogo.tsx b/web/apps/ensu/src/components/chat/HoverRiveLogo.tsxindex 0919eaa24d..e90aa8691b 100644--- a/web/apps/ensu/src/components/chat/HoverRiveLogo.tsx+++ b/web/apps/ensu/src/components/chat/HoverRiveLogo.tsx@@ -2,11 +2,15 @@ import { Box } from "@mui/material";import { useRouter } from "next/router";import { memo, useEffect, useRef, useState } from "react";-type HoverRiveLogoProps = { staticSrc: string; alt: string; sizePx?: number };+interface HoverRiveLogoProps {+ staticSrc: string;+ alt: string;+ sizePx?: number;+}type RivePlaybackTarget = string | string[];-type RiveInstance = {+interface RiveInstance {cleanup?: () => void;resizeDrawingSurfaceToCanvas?: () => void;play?: (animation?: RivePlaybackTarget) => void;@@ -15,7 +19,7 @@ type RiveInstance = {reset?: () => void;animationNames?: string[];stateMachineNames?: string[];-};+}const RIVE_SRC = "/animations/ensu.riv";@@ -30,7 +34,7 @@ const HoverRiveLogo = memo(const [isReady, setIsReady] = useState(false);const [failedToLoad, setFailedToLoad] = useState(false);const { basePath } = useRouter();- const riveSrc = `${basePath ?? ""}${RIVE_SRC}`;+ const riveSrc = `${basePath}${RIVE_SRC}`;useEffect(() => {if (typeof window === "undefined") return;diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsxindex 49ae1d3375..efeb327c88 100644--- a/web/apps/ensu/src/pages/chat.tsx+++ b/web/apps/ensu/src/pages/chat.tsx@@ -249,14 +249,19 @@ const SESSION_TITLE_PROMPT =const REPEAT_PENALTY = 1.18;const STREAMING_OUTRO_DURATION_MS = 520;-type DocumentAttachment = {+interface DocumentAttachment {id: string;name: string;text: string;size: number;-};+}-type ImageAttachment = { id: string; name: string; size: number; file: File };+interface ImageAttachment {+ id: string;+ name: string;+ size: number;+ file: File;+}const createDocumentBlockRegex = () =>/----- BEGIN DOCUMENT: ([^\n]+) -----\n([\s\S]*?)\n----- END DOCUMENT: \1 -----/g;@@ -293,7 +298,7 @@ const parseDocumentBlocks = (text: string) => {const stripHiddenPartsText = (text: string) =>text- .replace(/\u0000/g, "")+ .replaceAll("\0", "").replace(/<think>[\s\S]*?<\/think>/g, "").replace(/<todo_list>[\s\S]*?<\/todo_list>/g, "").trim();@@ -412,7 +417,7 @@ const Page: React.FC = () => {const { showMiniDialog, onGenericError } = useBaseContext();const theme = useTheme();const isSmall = useMediaQuery(theme.breakpoints.down("md"));- const assetBasePath = router.basePath ?? "";+ const assetBasePath = router.basePath;const logoSrc = `${assetBasePath}/images/ensu-logo.svg`;const [isDarkMode, setIsDarkMode] = useState(theme.palette.mode === "dark");@@ -445,9 +450,7 @@ const Page: React.FC = () => {const logoFilter = isDarkMode ? "none" : "invert(1)";const userBubbleBackground = isDarkMode ? "fill.faintHover" : "fill.faint";const messageFontFamily = theme.typography.fontFamily ?? "inherit";- const codeFontFamily =- theme.typography.code?.fontFamily ??- 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace';+ const codeFontFamily = theme.typography.code.fontFamily;const codeBlockBackground = isDarkMode? "rgba(255, 255, 255, 0.06)": "rgba(0, 0, 0, 0.04)";@@ -658,8 +661,6 @@ const Page: React.FC = () => {const providerRef = useRef<LlmProvider | null>(null);const currentJobIdRef = useRef<number | null>(null);- const pendingCancelRef = useRef(false);- const stopRequestedRef = useRef(false);const generationTokenRef = useRef(0);const lastGenerationRef = useRef<{parentMessageUuid: string;@@ -673,9 +674,10 @@ const Page: React.FC = () => {const attachmentPreviewUrlsRef = useRef<Record<string, string>>({});const pendingPreviewUrlsRef = useRef<Record<string, string>>({});const imagePreviewUrlRef = useRef<string | null>(null);- const attachmentPreviewInFlightRef = useRef<Record<string, Promise<void>>>(- {},+ const attachmentPreviewInFlightRef = useRef(+ new Map<string, Promise<void>>(),);+const chatViewportRef = useRef<HTMLDivElement | null>(null);const scrollContainerRef = useRef<HTMLDivElement | null>(null);const lastScrollTopRef = useRef(0);@@ -703,7 +705,7 @@ const Page: React.FC = () => {const scheduleIdleTask = useCallback((callback: () => void, timeout = 1200) => {- if (typeof window === "undefined") return () => {};+ if (typeof window === "undefined") return () => undefined;if (typeof window.requestIdleCallback === "function") {const handle = window.requestIdleCallback(() => callback(), {timeout,@@ -1335,7 +1337,7 @@ const Page: React.FC = () => {);const deleteSessionLabel = useMemo(() => {- const title = deleteSessionTarget?.title?.trim();+ const title = deleteSessionTarget?.title.trim();if (title && title !== "New chat") {return `"${title}"`;}@@ -1374,7 +1376,6 @@ const Page: React.FC = () => {setPendingImages([]);setStickToBottom(true);currentJobIdRef.current = null;- pendingCancelRef.current = false;}, [currentSessionId]);useEffect(() => {@@ -1415,7 +1416,7 @@ const Page: React.FC = () => {async (attachment: ChatAttachment, sessionUuid: string) => {if (!chatKey || !firstPaintDone) return;if (attachmentPreviewUrlsRef.current[attachment.id]) return;- if (attachmentPreviewInFlightRef.current[attachment.id]) return;+ if (attachmentPreviewInFlightRef.current.has(attachment.id)) return;const task = (async () => {try {@@ -1442,29 +1443,24 @@ const Page: React.FC = () => {}})();- attachmentPreviewInFlightRef.current[attachment.id] = task;+ attachmentPreviewInFlightRef.current.set(attachment.id, task);try {await task;} finally {- delete attachmentPreviewInFlightRef.current[attachment.id];+ attachmentPreviewInFlightRef.current.delete(attachment.id);}},[chatKey, firstPaintDone, inferImageMime],);useEffect(() => {- const next = { ...pendingPreviewUrlsRef.current };const activeIds = new Set(pendingImages.map((image) => image.id));+ const next: Record<string, string> = {};- Object.keys(next).forEach((id) => {- if (!activeIds.has(id)) {- const url = next[id];- if (url) {- URL.revokeObjectURL(url);- }- delete next[id];- }- });+ for (const [id, url] of Object.entries(pendingPreviewUrlsRef.current)) {+ if (activeIds.has(id)) next[id] = url;+ else URL.revokeObjectURL(url);+ }pendingImages.forEach((image) => {if (!next[image.id]) {@@ -1511,7 +1507,7 @@ const Page: React.FC = () => {const query = sessionSearch.trim().toLowerCase();if (!query) return sessions;return sessions.filter((session) => {- const title = session.title?.toLowerCase() ?? "";+ const title = session.title.toLowerCase();const preview = session.lastMessagePreview?.toLowerCase() ?? "";return title.includes(query) || preview.includes(query);});@@ -1537,7 +1533,7 @@ const Page: React.FC = () => {);const displayMessages = useMemo(() => {- const base = messageState.path ?? [];+ const base = messageState.path;const augmented: ChatMessage[] = [];for (let i = 0; i < base.length; i++) {const msg = base[i];@@ -1595,16 +1591,11 @@ const Page: React.FC = () => {});setAttachmentPreviews((prev) => {- const next = { ...prev };- Object.keys(next).forEach((id) => {- if (!activeIds.has(id)) {- const url = next[id];- if (url) {- URL.revokeObjectURL(url);- }- delete next[id];- }- });+ const next: Record<string, string> = {};+ for (const [id, url] of Object.entries(prev)) {+ if (activeIds.has(id)) next[id] = url;+ else URL.revokeObjectURL(url);+ }attachmentPreviewUrlsRef.current = next;return next;});@@ -1620,7 +1611,7 @@ const Page: React.FC = () => {const showDrawerToggle = isSmall || drawerCollapsed;const drawerWidth = isSmall ? 300 : drawerCollapsed ? 0 : 320;- const desktopBreakpoint = theme.breakpoints.values.lg ?? 1200;+ const desktopBreakpoint = theme.breakpoints.values.lg;const isDesktopOverlay = !isSmall && chatViewportWidth >= desktopBreakpoint;const showImageAttachment = isTauriRuntime;const showDownloadProgress =@@ -1646,18 +1637,20 @@ const Page: React.FC = () => {}, [allowMmproj, resolvedDefaultModel, selectedModelId]);const downloadStatusLabel = useMemo(() => {- if (!showDownloadProgress) return null;- const status = downloadStatus?.status ?? "";+ if (!downloadStatus?.status || downloadStatus.status === "Ready") {+ return null;+ }+ const status = downloadStatus.status;if (status.toLowerCase().includes("loading")) {return status;}- if (downloadStatus?.totalBytes && downloadStatus.percent >= 0) {+ if (downloadStatus.totalBytes && downloadStatus.percent >= 0) {const downloaded = downloadStatus.bytesDownloaded ?? 0;return `Downloading... ${formatBytes(downloaded)} / ${formatBytes(downloadStatus.totalBytes)}`;}if (status) return status;return "Downloading...";- }, [downloadStatus, showDownloadProgress]);+ }, [downloadStatus]);const focusInput = useCallback(() => {if (showModelGate) return;@@ -1729,21 +1722,20 @@ const Page: React.FC = () => {if ("__wbg_ptr" in error) {return "Model failed to start. Please refresh and try again.";}- const text = String(error);- if (text && text !== "[object Object]") {- return normalizeErrorMessage(text);- }}try {- return normalizeErrorMessage(JSON.stringify(error));+ const serialized = JSON.stringify(error);+ return serialized+ ? normalizeErrorMessage(serialized)+ : "Unknown model error";} catch {- return normalizeErrorMessage(String(error));+ return "Unknown model error";}}, []);const trimToWords = useCallback((text: string, maxWords: number) => {const normalized = text- .replace(/\u0000/g, "")+ .replaceAll("\0", "").replace(/[\r\n\t]+/g, " ").replace(/\s+/g, " ").trim();@@ -1858,12 +1850,12 @@ const Page: React.FC = () => {const persistSessionTitle = useCallback((sessionUuid: string, title: string, key: string) => {const previous = sessionTitleUpdatesRef.current.get(sessionUuid);- const task = (previous?.catch(() => {}) ?? Promise.resolve()).then(- async () => {- await updateSessionTitle(sessionUuid, title, key);- updateSessionTitleInState(sessionUuid, title);- },- );+ const task = (+ previous?.catch(() => undefined) ?? Promise.resolve()+ ).then(async () => {+ await updateSessionTitle(sessionUuid, title, key);+ updateSessionTitleInState(sessionUuid, title);+ });sessionTitleUpdatesRef.current.set(sessionUuid, task);void task.finally(() => {@@ -1873,7 +1865,7 @@ const Page: React.FC = () => {sessionTitleUpdatesRef.current.delete(sessionUuid);}})- .catch(() => {});+ .catch(() => undefined);return task;},[updateSessionTitleInState],@@ -2168,19 +2160,18 @@ const Page: React.FC = () => {}, []);const buildHistory = useCallback(- async (+ (path: ChatMessage[],promptText: string,contextSize: number,maxTokensCount?: number,stopAtMessageUuid?: string | null,- ): Promise<LlmMessage[]> => {+ ): LlmMessage[] => {const candidates = slicePathUntil(path, stopAtMessageUuid);const lastCandidate = candidates[candidates.length - 1];const trimmedCandidates =stopAtMessageUuid &&- lastCandidate &&- lastCandidate.messageUuid === stopAtMessageUuid+ lastCandidate?.messageUuid === stopAtMessageUuid? candidates.slice(0, -1): candidates;@@ -2308,8 +2299,6 @@ const Page: React.FC = () => {if (currentSessionIdRef.current === sessionId) {generationTokenRef.current += 1;- pendingCancelRef.current = false;- stopRequestedRef.current = false;const jobId = currentJobIdRef.current;currentJobIdRef.current = null;@@ -2340,7 +2329,7 @@ const Page: React.FC = () => {const requestRenameSession = useCallback((session: ChatSession) => {if (pendingSessionRenamesRef.current.has(session.sessionUuid)) return;setRenameSessionId(session.sessionUuid);- setRenameSessionTitle(session.title?.trim() || "New chat");+ setRenameSessionTitle(session.title.trim() || "New chat");}, []);const handleCancelRenameSession = useCallback(() => {@@ -2434,7 +2423,7 @@ const Page: React.FC = () => {message.sessionUuid,);const name =- attachment.name?.trim() || `image-${attachment.id}`;+ attachment.name.trim() || `image-${attachment.id}`;const file = new File([toSafeBlobPart(bytes)], name, {type: inferImageMime(name),});@@ -2509,7 +2498,7 @@ const Page: React.FC = () => {);const baseName =- attachment.name?.trim() || `attachment-${attachment.id}`;+ attachment.name.trim() || `attachment-${attachment.id}`;const treatAsImage = attachment.kind === "image";const filename = treatAsImage? baseName@@ -2553,16 +2542,13 @@ const Page: React.FC = () => {return;}- if (!treatAsImage) {- const text = new TextDecoder().decode(bytes);- const blob = new Blob([text], {- type: "text/plain;charset=utf-8",- });- const url = URL.createObjectURL(blob);- window.open(url, "_blank", "noopener");- window.setTimeout(() => URL.revokeObjectURL(url), 1000);- return;- }+ const text = new TextDecoder().decode(bytes);+ const blob = new Blob([text], {+ type: "text/plain;charset=utf-8",+ });+ const url = URL.createObjectURL(blob);+ window.open(url, "_blank", "noopener");+ window.setTimeout(() => URL.revokeObjectURL(url), 1000);} catch (error) {log.error("Failed to open attachment", error);showMiniDialog({@@ -2606,12 +2592,10 @@ const Page: React.FC = () => {const handleStopGeneration = useCallback(() => {const jobId = currentJobIdRef.current;- pendingCancelRef.current = true;- stopRequestedRef.current = true;generationTokenRef.current += 1;flushStreamingText();- const finalText = streamingBufferRef.current.replace(/\u0000/g, "");+ const finalText = streamingBufferRef.current.replaceAll("\0", "");const trimmedText = finalText.trim();const parentMessageUuid = streamingParentId;const activeSessionId = currentSessionIdRef.current ?? currentSessionId;@@ -2725,11 +2709,6 @@ const Page: React.FC = () => {sessionUuid ?? currentSessionIdRef.current ?? currentSessionId;if (!chatKey || !activeSessionId) return;- if (pendingCancelRef.current) {- pendingCancelRef.current = false;- }- stopRequestedRef.current = false;-const generationToken = generationTokenRef.current + 1;generationTokenRef.current = generationToken;@@ -2780,16 +2759,16 @@ const Page: React.FC = () => {if (resetContext) {await provider.resetContext(contextSize);+ if (!isActiveGeneration()) return;}- const history =- (await buildHistory(- historyPath,- promptText,- contextSize,- maxTokens,- stopAtMessageUuid,- )) ?? [];+ const history = buildHistory(+ historyPath,+ promptText,+ contextSize,+ maxTokens,+ stopAtMessageUuid,+ );const messages: LlmMessage[] = [{@@ -2811,45 +2790,24 @@ const Page: React.FC = () => {);}- if (pendingCancelRef.current || stopRequestedRef.current) {- pendingCancelRef.current = false;- stopRequestedRef.current = false;- provider.cancelGeneration(-1);- if (previousSelection) {- void updateBranchSelectionState(- parentMessageUuid,- previousSelection,- );- }- setIsGenerating(false);- setIsStreamingOutro(false);- setIsDownloading(false);- setStreamingParentId(null);- streamingBufferRef.current = "";- streamingChunksRef.current = [];- streamingCreatedAtRef.current = null;- setStreamingText("");- currentJobIdRef.current = null;- return;- }-- const hasImages =- (imagePaths?.length ?? 0) > 0 &&- provider.getBackendKind() === "tauri";- const mmprojPath = hasImages+ const nativeImagePaths =+ imagePaths?.length && provider.getBackendKind() === "tauri"+ ? imagePaths+ : undefined;+ const mmprojPath = nativeImagePaths? provider.getCurrentMmprojPath(): undefined;- if (hasImages && !mmprojPath) {+ if (nativeImagePaths && !mmprojPath) {throw new Error("MMProj model not available");}- await provider- .generateChatStream(+ try {+ await provider.generateChatStream({messages,- imagePaths: hasImages ? imagePaths : undefined,+ imagePaths: nativeImagePaths,mmprojPath,- mediaMarker: hasImages+ mediaMarker: nativeImagePaths? (mediaMarker ?? MEDIA_MARKER): undefined,maxTokens,@@ -2864,25 +2822,18 @@ const Page: React.FC = () => {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") {+ } else {currentJobIdRef.current = event.summary.job_id;}},- )- .catch((error: unknown) => {- errorMessage =- error instanceof Error- ? error.message- : String(error);- });+ );+ } catch (error) {+ errorMessage =+ error instanceof Error ? error.message : String(error);+ }if (!isActiveGeneration()) {return;@@ -2907,7 +2858,7 @@ const Page: React.FC = () => {return;}- const assistantText = finalText.replace(/\u0000/g, "");+ const assistantText = finalText.replaceAll("\0", "");setIsStreamingOutro(true);await new Promise<void>((resolve) => {@@ -2951,19 +2902,17 @@ const Page: React.FC = () => {);}} finally {- if (!isActiveGeneration()) {- return;+ if (isActiveGeneration()) {+ setIsGenerating(false);+ setIsStreamingOutro(false);+ setIsDownloading(false);+ streamingBufferRef.current = "";+ streamingChunksRef.current = [];+ setStreamingText("");+ setStreamingParentId(null);+ streamingCreatedAtRef.current = null;+ currentJobIdRef.current = null;}- setIsGenerating(false);- setIsStreamingOutro(false);- setIsDownloading(false);- streamingBufferRef.current = "";- streamingChunksRef.current = [];- setStreamingText("");- setStreamingParentId(null);- streamingCreatedAtRef.current = null;- currentJobIdRef.current = null;- pendingCancelRef.current = false;}},[@@ -3029,7 +2978,7 @@ const Page: React.FC = () => {historyPath,stopAtMessageUuid: parentUuid,resetContext: true,- sessionUuid: currentSessionId ?? undefined,+ sessionUuid: currentSessionId,});},[@@ -3047,7 +2996,7 @@ const Page: React.FC = () => {const handlePrevBranch = useCallback((switcher: BranchSwitcher) => {- if (!switcher || switcher.total <= 1) return;+ if (switcher.total <= 1) return;const nextIndex =(switcher.currentIndex - 1 + switcher.total) % switcher.total;const target = switcher.targets[nextIndex];@@ -3059,7 +3008,7 @@ const Page: React.FC = () => {const handleNextBranch = useCallback((switcher: BranchSwitcher) => {- if (!switcher || switcher.total <= 1) return;+ if (switcher.total <= 1) return;const nextIndex = (switcher.currentIndex + 1) % switcher.total;const target = switcher.targets[nextIndex];if (!target) return;@@ -3643,30 +3592,21 @@ const Page: React.FC = () => {showMiniDialog,]);- const openAttachmentMenu = useCallback(- (_event: React.MouseEvent<HTMLElement>) => {- closeAttachmentMenu();- if (showImageAttachment) {- if (isImageAttachmentLimitReached) return;- if (isTauriRuntime) {- void openTauriImageSelector();- } else {- openImageSelector();- }- return;- }- openDocumentSelector();- },- [- closeAttachmentMenu,- isTauriRuntime,- isImageAttachmentLimitReached,- openDocumentSelector,- openImageSelector,- openTauriImageSelector,- showImageAttachment,- ],- );+ const openAttachmentMenu = useCallback(() => {+ closeAttachmentMenu();+ if (showImageAttachment) {+ if (isImageAttachmentLimitReached) return;+ void openTauriImageSelector();+ return;+ }+ openDocumentSelector();+ }, [+ closeAttachmentMenu,+ isImageAttachmentLimitReached,+ openDocumentSelector,+ openTauriImageSelector,+ showImageAttachment,+ ]);const handleAttachmentChoice = useCallback((choice: "image" | "document") => {@@ -3743,7 +3683,7 @@ const Page: React.FC = () => {}const messageText = buildPromptWithDocuments(- trimmed.replace(/\u0000/g, ""),+ trimmed.replaceAll("\0", ""),pendingDocuments,);const persistedAttachmentIds = new Set(diff --git a/web/apps/ensu/src/services/app-update.ts b/web/apps/ensu/src/services/app-update.tsindex 30f017f1c8..d63e7c9e9b 100644--- a/web/apps/ensu/src/services/app-update.ts+++ b/web/apps/ensu/src/services/app-update.ts@@ -89,7 +89,7 @@ const showUpdatePrompt = (showMiniDialog: ShowMiniDialog, version: string) => {const checkAndPromptForAppUpdates = async (showMiniDialog: ShowMiniDialog) => {const result = await checkForAppUpdates();- if (result?.kind !== "available") return result;+ if (result.kind !== "available") return result;if (promptedVersion === result.version) return result;promptedVersion = result.version;showUpdatePrompt(showMiniDialog, result.version);@@ -100,7 +100,7 @@ export const handleManualAppUpdateCheck = async (showMiniDialog: ShowMiniDialog,) => {const result = await checkForAppUpdates();- if (!result || result.kind === "not-supported") return;+ if (result.kind === "not-supported") return;if (result.kind === "up-to-date") {showMiniDialog({@@ -125,7 +125,7 @@ export const handleManualAppUpdateCheck = async (export const setupAutoAppUpdates = (showMiniDialog: ShowMiniDialog) => {if (!isTauriRuntime() || !buildEnvIsProductionBuild || intervalId) {- return () => {};+ return () => undefined;}void checkAndPromptForAppUpdates(showMiniDialog);diff --git a/web/apps/ensu/src/services/chat/attachments.ts b/web/apps/ensu/src/services/chat/attachments.tsindex b1e38a5d7f..a1c5495a30 100644--- a/web/apps/ensu/src/services/chat/attachments.ts+++ b/web/apps/ensu/src/services/chat/attachments.ts@@ -5,7 +5,7 @@ const ATTACHMENT_KEY_INFO = "llmchat_attachment_v1";const BLOB_HEADER_BYTES = 24;const ensureCryptoSubtle = () => {- if (typeof crypto === "undefined" || !crypto.subtle) {+ if (typeof crypto === "undefined") {throw new Error("WebCrypto not available for attachment encryption");}return crypto.subtle;diff --git a/web/apps/ensu/src/services/chat/branching.ts b/web/apps/ensu/src/services/chat/branching.tsindex c829fbcd74..89b26c0916 100644--- a/web/apps/ensu/src/services/chat/branching.ts+++ b/web/apps/ensu/src/services/chat/branching.ts@@ -3,9 +3,7 @@ import type { ChatMessage } from "./store";export const ROOT_SELECTION_KEY = "__root__";export const STREAMING_SELECTION_KEY = "__streaming__";-export interface BranchSelections {- [selectionKey: string]: string;-}+export type BranchSelections = Record<string, string>;export interface BranchSwitcher {selectionKey: string;@@ -84,7 +82,7 @@ export const buildSelectedPath = (const rawKids = children.get(current.messageUuid) ?? [];const kids = dedupeSiblingDuplicates(rawKids);- if (streaming && streaming.parentMessageUuid === current.messageUuid) {+ if (streaming?.parentMessageUuid === current.messageUuid) {const targets = [...kids.map((msg) => msg.messageUuid),STREAMING_SELECTION_KEY,diff --git a/web/apps/ensu/src/services/chat/compatibility.ts b/web/apps/ensu/src/services/chat/compatibility.tsindex 0900fb92c0..7a83bda750 100644--- a/web/apps/ensu/src/services/chat/compatibility.ts+++ b/web/apps/ensu/src/services/chat/compatibility.ts@@ -43,12 +43,15 @@ type OldMessage = Omit<StoredMessage, "attachments"> & {deletedAt?: number | null;isDeleted?: boolean;};-type AttachmentBytes = { id: string; data: Uint8Array<ArrayBuffer> };-type BrowserStore = {+interface AttachmentBytes {+ id: string;+ data: Uint8Array<ArrayBuffer>;+}+interface BrowserStore {sessions: OldSession[];messages: OldMessage[];attachmentBytes: AttachmentBytes[];-};+}interface OldIndexedDb extends DBSchema {sessions: { key: string; value: OldSession };@@ -287,13 +290,8 @@ const removeCurrentBrowserTombstones = async () => {};const readOldIndexedDb = async () => {- let created = false;- const source = await openDB<OldIndexedDb>(OLD_INDEXED_DB, undefined, {- upgrade: () => {- created = true;- },- });- if (created || !source.objectStoreNames.contains("sessions")) {+ const source = await openDB<OldIndexedDb>(OLD_INDEXED_DB);+ if (!source.objectStoreNames.contains("sessions")) {source.close();await deleteDB(OLD_INDEXED_DB);return undefined;diff --git a/web/apps/ensu/src/services/chat/store.ts b/web/apps/ensu/src/services/chat/store.tsindex a8637de41b..b5ac5566fd 100644--- a/web/apps/ensu/src/services/chat/store.ts+++ b/web/apps/ensu/src/services/chat/store.ts@@ -539,7 +539,7 @@ export const listSessions = async (chatKey: string): Promise<ChatSession[]> => {list.sort((a, b) => b.createdAt - a.createdAt);}- return Promise.all(+ return await Promise.all(activeSessions.map(async (session) => {const title = await decryptSessionTitle(session, chatKey);const latest = bySession.get(session.sessionUuid)?.[0];@@ -585,7 +585,7 @@ export const listMessages = async (.filter((message) => message.sessionUuid === sessionUuid).sort((a, b) => a.createdAt - b.createdAt);- return Promise.all(+ return await Promise.all(sessionMessages.map(async (message) => ({messageUuid: message.messageUuid,sessionUuid: message.sessionUuid,diff --git a/web/apps/ensu/src/services/llm/inference.ts b/web/apps/ensu/src/services/llm/inference.tsindex 878a3e2f6a..96b9ef256d 100644--- a/web/apps/ensu/src/services/llm/inference.ts+++ b/web/apps/ensu/src/services/llm/inference.ts@@ -58,8 +58,8 @@ export interface ContextParams {export interface InferenceBackend {readonly kind: BackendType;- initBackend(): Promise<void>;- loadModel(params: LoadModelParams): Promise<void>;+ initBackend?(): Promise<void>;+ loadModel(params: LoadModelParams): void | Promise<void>;createContext(model: { modelPath: string },params?: ContextParams,@@ -113,9 +113,7 @@ class WasmInference implements InferenceBackend {this.wllama = new Wllama(wasmPaths, wllamaConfig);}- async initBackend() {}-- async loadModel(params: LoadModelParams) {+ loadModel(params: LoadModelParams) {const modelUrl = ensureUrl(params.modelPath);this.loadedModelUrl = modelUrl;}@@ -151,9 +149,7 @@ class WasmInference implements InferenceBackend {});return urls.every((url) => {const existing = models.find((model) => model.url === url);- return (- existing && existing.validate() === ModelValidationStatus.VALID- );+ return existing?.validate() === ModelValidationStatus.VALID;});}@@ -170,8 +166,6 @@ class WasmInference implements InferenceBackend {return this.generateCompletion(prompt, request, onEvent);}- async prewarmMultimodalContext() {}-cancel(jobId: number) {if (jobId <= 0) {for (const controller of this.abortControllers.values()) {@@ -241,7 +235,7 @@ class WasmInference implements InferenceBackend {private async ensureModelCached(modelUrl: string) {if (typeof navigator === "undefined" ||- !navigator.storage ||+ !("storage" in navigator) ||!("getDirectory" in navigator.storage)) {return;@@ -278,10 +272,7 @@ class WasmInference implements InferenceBackend {includeInvalid: true,});const existing = models.find((model) => model.url === url);- if (- existing &&- existing.validate() === ModelValidationStatus.VALID- ) {+ if (existing?.validate() === ModelValidationStatus.VALID) {totals[index] = existing.size;loaded[index] = existing.size;emitProgress("Ready");@@ -294,7 +285,7 @@ class WasmInference implements InferenceBackend {create: true,});const file = await handle.getFile();- let downloaded = file.size ?? 0;+ let downloaded = file.size;const metadata =await this.modelManager.cacheManager.getMetadata(url);@@ -308,7 +299,7 @@ class WasmInference implements InferenceBackend {const headers: HeadersInit | undefined = downloaded? { Range: `bytes=${downloaded}-` }: undefined;- let res = await fetch(url, { headers });+ const res = await fetch(url, { headers });if (!res.ok || !res.body) {throw new Error(`Failed to download model (${res.status})`);}@@ -346,7 +337,6 @@ class WasmInference implements InferenceBackend {while (true) {const { done, value } = await reader.read();if (done) break;- if (!value) continue;await writable.write(value);downloaded += value.length;loaded[index] = downloaded;@@ -432,7 +422,7 @@ class WasmInference implements InferenceBackend {let lastText = "";for await (const chunk of stream) {- const currentText = chunk.currentText ?? "";+ const currentText = chunk.currentText;const delta = currentText.slice(lastText.length);lastText = currentText;generatedTokens += 1;@@ -470,7 +460,7 @@ class WasmInference implements InferenceBackend {}private async resolveStopTokens(stopSequences: string[]) {- if (!stopSequences || stopSequences.length === 0) {+ if (stopSequences.length === 0) {return { stopTokens: [] as number[] };}@@ -498,7 +488,7 @@ class WasmInference implements InferenceBackend {const parseContentRangeTotal = (header: string | null) => {if (!header) return undefined;- const match = header.match(/\/(\d+)/);+ const match = /\/(\d+)/.exec(header);if (!match) return undefined;const total = Number(match[1]);return Number.isFinite(total) ? total : undefined;@@ -665,7 +655,7 @@ class TauriInference implements InferenceBackend {log.error("LLM tauri generate failed", err);throw err;} finally {- void unlisten();+ unlisten();}}@@ -750,31 +740,25 @@ const buildGenerateChatRequest = (request: GenerateChatRequest) => ({const buildSamplingConfig = (request: GenerateChatRequest) => {const sampling: Record<string, unknown> = {};- if (request.temperature !== undefined && request.temperature !== null) {+ if (request.temperature !== undefined) {sampling.temp = request.temperature;}- if (request.topP !== undefined && request.topP !== null) {+ if (request.topP !== undefined) {sampling.top_p = request.topP;}- if (request.topK !== undefined && request.topK !== null) {+ if (request.topK !== undefined) {sampling.top_k = request.topK;}- if (request.repeatPenalty !== undefined && request.repeatPenalty !== null) {+ if (request.repeatPenalty !== undefined) {sampling.penalty_repeat = request.repeatPenalty;}- if (- request.frequencyPenalty !== undefined &&- request.frequencyPenalty !== null- ) {+ if (request.frequencyPenalty !== undefined) {sampling.penalty_freq = request.frequencyPenalty;}- if (- request.presencePenalty !== undefined &&- request.presencePenalty !== null- ) {+ if (request.presencePenalty !== undefined) {sampling.penalty_present = request.presencePenalty;}- if (request.grammar !== undefined && request.grammar !== null) {+ if (request.grammar !== undefined) {sampling.grammar = request.grammar;}diff --git a/web/apps/ensu/src/services/llm/provider.ts b/web/apps/ensu/src/services/llm/provider.tsindex 6307614cfc..324efbf4e6 100644--- a/web/apps/ensu/src/services/llm/provider.ts+++ b/web/apps/ensu/src/services/llm/provider.ts@@ -158,7 +158,7 @@ export class LlmProvider {public async initialize() {if (this.initialized) return;- await this.backend.initBackend();+ await this.backend.initBackend?.();await this.resolveDefaultModelForDevice();this.initialized = true;}@@ -363,7 +363,7 @@ export class LlmProvider {try {await ensurePromise;} finally {- if (this.ensureInFlight?.promise === ensurePromise) {+ if (this.ensureInFlight.promise === ensurePromise) {this.ensureInFlight = undefined;}}@@ -444,7 +444,7 @@ export class LlmProvider {return;}const total = event.total ?? 0;- const loaded = event.loaded ?? 0;+ const loaded = event.loaded;const percent = total? Math.min(99, Math.round((loaded / total) * 100)): 0;diff --git a/web/apps/ensu/tsconfig.json b/web/apps/ensu/tsconfig.jsonindex ad758c19a5..2ff1f734c6 100644--- a/web/apps/ensu/tsconfig.json+++ b/web/apps/ensu/tsconfig.json@@ -3,6 +3,7 @@"compilerOptions": {"paths": { "@/*": ["./src/*"] },"allowJs": true,+ "checkJs": true,"incremental": true,"exactOptionalPropertyTypes": false},