Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
Improve file attachments re submit (#7102)
Dinh Long Nguyenc4a7c059096f
diff --git a/extensions/llamacpp-extension/src/util.ts b/extensions/llamacpp-extension/src/util.tsindex 203788f9b..006a77812 100644--- a/extensions/llamacpp-extension/src/util.ts+++ b/extensions/llamacpp-extension/src/util.ts@@ -118,15 +118,29 @@ export type EmbedBatchResult = {usage?: EmbedUsage}-export function estimateTokensFromText(text: string, charsPerToken = 2): number {+// Embedding batching constants+const DEFAULT_CHARS_PER_TOKEN = 3+const UBATCH_SAFETY_MARGIN = 0.5++export function estimateTokensFromText(text: string, charsPerToken = DEFAULT_CHARS_PER_TOKEN): number {return Math.max(1, Math.ceil(text.length / Math.max(charsPerToken, 1)))}export function buildEmbedBatches(inputs: string[],ubatchSize: number,- charsPerToken = 2+ charsPerToken = DEFAULT_CHARS_PER_TOKEN): EmbedBatch[] {+ // Ensure ubatch_size is large enough for at least 1 token with safety margin+ const minUbatchSize = Math.ceil(1 / UBATCH_SAFETY_MARGIN)+ if (ubatchSize < minUbatchSize) {+ throw new Error(+ `ubatch_size (${ubatchSize}) is too small. Minimum required: ${minUbatchSize}`+ )+ }++ const safeLimit = Math.floor(ubatchSize * UBATCH_SAFETY_MARGIN)+const batches: EmbedBatch[] = []let current: string[] = []let currentTokens = 0@@ -143,13 +157,17 @@ export function buildEmbedBatches(for (const text of inputs) {const estTokens = estimateTokensFromText(text, charsPerToken)- if (!current.length && estTokens > ubatchSize) {++ // If single text exceeds safe limit, still allow it as single batch+ // (ensure at least one text per batch)+ if (estTokens > safeLimit) {+ if (current.length) push()batches.push({ batch: [text], offset })offset += 1continue}- if (currentTokens + estTokens > ubatchSize && current.length) {+ if (currentTokens + estTokens > safeLimit && current.length) {push()}@@ -158,6 +176,12 @@ export function buildEmbedBatches(}push()++ // Validate that no batch is empty+ if (batches.some(b => b.batch.length === 0)) {+ throw new Error('Internal error: empty batch detected')+ }+return batches}diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsxindex 9a72ac7e2..d6aabaf02 100644--- a/web-app/src/containers/ChatInput.tsx+++ b/web-app/src/containers/ChatInput.tsx@@ -148,6 +148,7 @@ const ChatInput = ({const attachmentsEnabled = useAttachments((s) => s.enabled)const parsePreference = useAttachments((s) => s.parseMode)+ const maxFileSizeMB = useAttachments((s) => s.maxFileSizeMB)const autoInlineContextRatio = useAttachments((s) => s.autoInlineContextRatio)// Determine whether to show the Attach documents button (simple gating)const showAttachmentButton =@@ -190,7 +191,8 @@ const ChatInput = ({const updateAttachmentProcessing = useCallback((fileName: string,- status: 'processing' | 'done' | 'error' | 'clear_docs' | 'clear_all'+ status: 'processing' | 'done' | 'error' | 'clear_all',+ updatedAttachment?: Partial<Attachment>) => {const targetKey = attachmentsKeyRef.currentconst storeState = useChatAttachments.getState()@@ -204,13 +206,6 @@ const ChatInput = ({const keysToUpdate = new Set([targetKey, ...allMatchingKeys])const applyUpdate = (key: string) => {- if (status === 'clear_docs') {- setAttachmentsForThread(key, (prev) =>- prev.filter((a) => a.type !== 'document')- )- return- }-if (status === 'clear_all') {clearAttachmentsForThread(key)return@@ -221,8 +216,11 @@ const ChatInput = ({att.name === fileName? {...att,+ ...updatedAttachment,processing: status === 'processing',- processed: status === 'done' ? true : att.processed,+ processed: status === 'done'+ ? true+ : updatedAttachment?.processed ?? att.processed,}: att)@@ -588,6 +586,23 @@ const ChatInput = ({)}+ const maxFileSizeBytes =+ typeof maxFileSizeMB === 'number' && maxFileSizeMB > 0+ ? maxFileSizeMB * 1024 * 1024+ : undefined++ if (maxFileSizeBytes !== undefined) {+ const hasOversized = preparedAttachments.some(+ (att) => typeof att.size === 'number' && att.size > maxFileSizeBytes+ )+ if (hasOversized) {+ toast.error('File too large', {+ description: `One or more files exceed the ${maxFileSizeMB}MB limit`,+ })+ return+ }+ }+let duplicates: string[] = []let newDocAttachments: Attachment[] = []diff --git a/web-app/src/hooks/useChat.ts b/web-app/src/hooks/useChat.tsindex 2490a7855..9b92005eb 100644--- a/web-app/src/hooks/useChat.ts+++ b/web-app/src/hooks/useChat.ts@@ -502,7 +502,8 @@ export const useChat = () => {projectId?: string,updateAttachmentProcessing?: (fileName: string,- status: 'processing' | 'done' | 'error' | 'clear_docs' | 'clear_all'+ status: 'processing' | 'done' | 'error' | 'clear_all',+ updatedAttachment?: Partial<Attachment>) => void,continueFromMessageId?: string) => {@@ -658,9 +659,7 @@ export const useChat = () => {// All attachments (images + docs) ingested successfully.// Build the user content once; use it for both the outbound request// and persisting to the store so both are identical.- if (updateAttachmentProcessing) {- updateAttachmentProcessing('__CLEAR_ALL__', 'clear_all')- }+ updateAttachmentProcessing?.('__CLEAR_ALL__', 'clear_all')const userContent = newUserThreadContent(activeThread.id,message,diff --git a/web-app/src/lib/attachmentProcessing.ts b/web-app/src/lib/attachmentProcessing.tsindex 430ddadc0..ffd08194a 100644--- a/web-app/src/lib/attachmentProcessing.ts+++ b/web-app/src/lib/attachmentProcessing.ts@@ -8,7 +8,6 @@ type AttachmentProcessingStatus =| 'processing'| 'done'| 'error'- | 'clear_docs'| 'clear_all'type AttachmentProcessingOptions = {@@ -21,7 +20,11 @@ type AttachmentProcessingOptions = {parsePreference: 'auto' | 'inline' | 'embeddings' | 'prompt'autoFallbackMode?: 'inline' | 'embeddings'perFileChoices?: Map<string, 'inline' | 'embeddings'>- updateAttachmentProcessing?: (name: string, status: AttachmentProcessingStatus) => void+ updateAttachmentProcessing?: (+ name: string,+ status: AttachmentProcessingStatus,+ updatedAttachment?: Partial<Attachment>+ ) => void}export type AttachmentProcessingResult = {@@ -96,6 +99,9 @@ export const processAttachmentsForSend = async (contextThreshold > 0? contextThreshold: undefined+ const notifyUpdate = (+ ...args: Parameters<NonNullable<AttachmentProcessingOptions['updateAttachmentProcessing']>>+ ) => updateAttachmentProcessing?.(...args)// Images: ingest before sendingconst images = attachments.filter((a) => a.type === 'image')@@ -107,9 +113,7 @@ export const processAttachmentsForSend = async (continue}- if (updateAttachmentProcessing) {- updateAttachmentProcessing(img.name, 'processing')- }+ notifyUpdate(img.name, 'processing')const res = await serviceHub.uploads().ingestImage(threadId, img)processedAttachments.push({@@ -118,14 +122,14 @@ export const processAttachmentsForSend = async (processed: true,processing: false,})- if (updateAttachmentProcessing) {- updateAttachmentProcessing(img.name, 'done')- }+ notifyUpdate(img.name, 'done', {+ id: res.id,+ processed: true,+ processing: false,+ })} catch (err) {console.error(`Failed to ingest image ${img.name}:`, err)- if (updateAttachmentProcessing) {- updateAttachmentProcessing(img.name, 'error')- }+ notifyUpdate(img.name, 'error')const desc = formatAttachmentError(err)toast.error('Failed to ingest image attachment', { description: desc })throw err instanceof Error ? err : new Error(desc)@@ -143,9 +147,7 @@ export const processAttachmentsForSend = async (continue}- if (updateAttachmentProcessing) {- updateAttachmentProcessing(doc.name, 'processing')- }+ notifyUpdate(doc.name, 'processing')const targetPreference = doc.parseMode ?? parsePreferencelet targetMode: 'inline' | 'embeddings' =@@ -213,16 +215,17 @@ export const processAttachmentsForSend = async (injectionMode: 'inline',})- if (updateAttachmentProcessing) {- updateAttachmentProcessing(doc.name, 'done')- }+ notifyUpdate(doc.name, 'done', {+ processing: false,+ processed: true,+ inlineContent: parsedContent,+ injectionMode: 'inline',+ })continue}// Default: ingest as embeddings- if (updateAttachmentProcessing) {- updateAttachmentProcessing(doc.name, 'processing')- }+ notifyUpdate(doc.name, 'processing')const res = await serviceHub.uploads()@@ -239,14 +242,17 @@ export const processAttachmentsForSend = async (})hasEmbeddedDocuments = true- if (updateAttachmentProcessing) {- updateAttachmentProcessing(doc.name, 'done')- }+ notifyUpdate(doc.name, 'done', {+ id: res.id,+ size: res.size ?? doc.size,+ chunkCount: res.chunkCount ?? doc.chunkCount,+ processing: false,+ processed: true,+ injectionMode: 'embeddings',+ })} catch (err) {console.error(`Failed to ingest ${doc.name}:`, err)- if (updateAttachmentProcessing) {- updateAttachmentProcessing(doc.name, 'error')- }+ notifyUpdate(doc.name, 'error')const desc = formatAttachmentError(err)toast.error('Failed to index attachments', { description: desc })throw err instanceof Error ? err : new Error(desc)