Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix: embeddings/inline inject ux (#7963)
Akarshan Biswasece946665e99
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsxindex fb757ee3c..f28d2dd1a 100644--- a/web-app/src/containers/ChatInput.tsx+++ b/web-app/src/containers/ChatInput.tsx@@ -4,7 +4,6 @@ import { usePrompt } from '@/hooks/usePrompt'import { useThreads } from '@/hooks/useThreads'import { useCallback, useEffect, useMemo, useRef, useState, memo } from 'react'import { Button } from '@/components/ui/button'-import { Progress } from '@/components/ui/progress'import {Tooltip,TooltipContent,@@ -64,11 +63,8 @@ import { useMessages } from '@/hooks/useMessages'import { useShallow } from 'zustand/react/shallow'import { McpExtensionToolLoader } from './McpExtensionToolLoader'import {- ContentType,ExtensionTypeEnum,MCPExtension,- MessageStatus,- ThreadMessage,fs,VectorDBExtension,} from '@janhq/core'@@ -76,9 +72,7 @@ import { ExtensionManager } from '@/lib/extension'import { useAttachments } from '@/hooks/useAttachments'import { toast } from 'sonner'import { isPlatformTauri } from '@/lib/platform/utils'-import { processAttachmentsForSend } from '@/lib/attachmentProcessing'import { useAttachmentIngestionPrompt } from '@/hooks/useAttachmentIngestionPrompt'-import { useToolApproval } from '@/hooks/useToolApproval'import {NEW_THREAD_ATTACHMENT_KEY,useChatAttachments,@@ -122,10 +116,8 @@ const ChatInput = memo(function ChatInput({const [rows, setRows] = useState(1)const serviceHub = useServiceHub()const abortControllers = useAppState((state) => state.abortControllers)- const updateLoadingModel = useAppState((state) => state.updateLoadingModel)const tools = useAppState((state) => state.tools)const cancelToolCall = useAppState((state) => state.cancelToolCall)- const setActiveModels = useAppState((state) => state.setActiveModels)const prompt = usePrompt((state) => state.prompt)const setPrompt = usePrompt((state) => state.setPrompt)const addToHistory = usePrompt((state) => state.addToHistory)@@ -266,7 +258,6 @@ const ChatInput = memo(function 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)// Derived: any document currently processing (ingestion in progress)const attachmentsKey = currentThreadId ?? NEW_THREAD_ATTACHMENT_KEY@@ -276,7 +267,6 @@ const ChatInput = memo(function ChatInput({[attachmentsKey]))- const attachmentsKeyRef = useRef(attachmentsKey)const setAttachmentsForThread = useChatAttachments((state) => state.setAttachments)@@ -288,16 +278,12 @@ const ChatInput = memo(function ChatInput({)const getProviderByName = useModelProvider((state) => state.getProviderByName)- useEffect(() => {- attachmentsKeyRef.current = attachmentsKey- }, [attachmentsKey])-const ingestingDocs = attachments.some((a) => a.type === 'document' && a.processing)const ingestingAny = attachments.some((a) => a.processing)- const [fileIngestProgress, setFileIngestProgress] = useState<{+ const [, setFileIngestProgress] = useState<{completed: numbertotal: number} | null>(null)@@ -327,51 +313,6 @@ const ChatInput = memo(function ChatInput({}}, [currentThreadId, transferAttachments])- const updateAttachmentProcessing = useCallback(- (- fileName: string,- status: 'processing' | 'done' | 'error' | 'clear_all',- updatedAttachment?: Partial<Attachment>- ) => {- const targetKey = attachmentsKeyRef.current- const storeState = useChatAttachments.getState()-- // Find all keys that have this attachment (including NEW_THREAD_ATTACHMENT_KEY)- const allMatchingKeys = Object.entries(storeState.attachmentsByThread)- .filter(([, list]) => list?.some((att) => att.name === fileName))- .map(([key]) => key)-- // Always include targetKey and all matching keys- const keysToUpdate = new Set([targetKey, ...allMatchingKeys])-- const applyUpdate = (key: string) => {- if (status === 'clear_all') {- clearAttachmentsForThread(key)- return- }-- setAttachmentsForThread(key, (prev) =>- prev.map((att) =>- att.name === fileName- ? {- ...att,- ...updatedAttachment,- processing: status === 'processing',- processed:- status === 'done'- ? true- : (updatedAttachment?.processed ?? att.processed),- }- : att- )- )- }-- keysToUpdate.forEach((key) => applyUpdate(key as string))- },- [clearAttachmentsForThread, setAttachmentsForThread]- )-// Check for mmproj existence or vision capability when model changesuseEffect(() => {const checkMmprojSupport = async () => {@@ -544,7 +485,11 @@ const ChatInput = memo(function ChatInput({}setPrompt('')- clearAttachmentsForThread(attachmentsKey)+ // Don't clear attachments here — document attachments stored under+ // NEW_THREAD_ATTACHMENT_KEY need to survive until the thread detail+ // page transfers and processes them. The thread detail page's+ // processAndSendMessage already calls clearAttachmentsForThread after+ // processing is complete.}}@@ -617,76 +562,19 @@ const ChatInput = memo(function ChatInput({const processNewDocumentAttachments = useCallback(async (docs: Attachment[]) => {- if (!docs.length || !currentThreadId) return-- const modelReady = await (async () => {- if (!selectedModel?.id) return false- if (activeModels.includes(selectedModel.id)) return true- const provider = getProviderByName(selectedProvider)- if (!provider) return false- try {- updateLoadingModel(true)- await serviceHub.models().startModel(provider, selectedModel.id)- const active = await serviceHub.models().getActiveModels()- setActiveModels(active || [])- return active?.includes(selectedModel.id) ?? false- } catch (err) {- console.warn(- 'Failed to start model before attachment validation',- err- )- return false- } finally {- updateLoadingModel(false)- }- })()-- const modelContextLength = (() => {- const ctx = selectedModel?.settings?.ctx_len?.controller_props?.value- if (typeof ctx === 'number') return ctx- if (typeof ctx === 'string') {- const parsed = parseInt(ctx, 10)- return Number.isFinite(parsed) ? parsed : undefined- }- return undefined- })()-- const rawContextThreshold =- typeof modelContextLength === 'number' && modelContextLength > 0- ? Math.floor(- modelContextLength *- (typeof autoInlineContextRatio === 'number'- ? autoInlineContextRatio- : 0.75)- )- : undefined+ if (!docs.length) return- const contextThreshold =- typeof rawContextThreshold === 'number' &&- Number.isFinite(rawContextThreshold) &&- rawContextThreshold > 0- ? rawContextThreshold- : undefined-- const hasContextEstimate =- modelReady &&- typeof contextThreshold === 'number' &&- Number.isFinite(contextThreshold) &&- contextThreshold > 0+ // Only collect the user's inline-vs-embeddings preference via the+ // dialog. Actual ingestion is always deferred to send time+ // (processAttachmentsForSend inside processAndSendMessage).const docsNeedingPrompt = docs.filter((doc) => {if (doc.processed || doc.injectionMode) return falseconst preference = doc.parseMode ?? parsePreference- return (- preference === 'prompt' ||- (preference === 'auto' && !hasContextEstimate)- )+ return preference === 'prompt' || preference === 'auto'})- // Map to store individual choices for each document- const docChoices = new Map<string, 'inline' | 'embeddings'>()-if (docsNeedingPrompt.length > 0) {- // Ask for each file individually+ const choices = new Map<string, 'inline' | 'embeddings'>()for (let i = 0; i < docsNeedingPrompt.length; i++) {const doc = docsNeedingPrompt[i]const choice = await useAttachmentIngestionPrompt@@ -699,121 +587,40 @@ const ChatInput = memo(function ChatInput({)if (!choice) {- // User cancelled - remove all pending docs+ // User cancelled — remove all pending docssetAttachmentsForThread(attachmentsKey, (prev) =>prev.filter((att) =>!docsNeedingPrompt.some(- (doc) => doc.path && att.path && doc.path === att.path+ (d) => d.path && att.path && d.path === att.path)))return}- // Store the choice for this specific documentif (doc.path) {- docChoices.set(doc.path, choice)+ choices.set(doc.path, choice)}}- }-- const estimateTokens = async (- text: string- ): Promise<number | undefined> => {- try {- if (!selectedModel?.id || !modelReady) return undefined- const tokenCount = await serviceHub- .models()- .getTokensCount(selectedModel.id, [- {- id: 'inline-attachment',- object: 'thread.message',- thread_id: currentThreadId,- role: 'user',- content: [- {- type: ContentType.Text,- text: { value: text, annotations: [] },- },- ],- status: MessageStatus.Ready,- created_at: Date.now(),- completed_at: Date.now(),- } as ThreadMessage,- ])- if (- typeof tokenCount !== 'number' ||- !Number.isFinite(tokenCount) ||- tokenCount <= 0- ) {- return undefined- }- return tokenCount- } catch (e) {- console.debug('Failed to estimate tokens for attachment content', e)- return undefined- }- }-- try {- const { processedAttachments, hasEmbeddedDocuments } =- await processAttachmentsForSend({- attachments: docs,- threadId: currentThreadId,- serviceHub,- selectedProvider,- contextThreshold,- estimateTokens,- parsePreference,- perFileChoices: docChoices.size > 0 ? docChoices : undefined,- updateAttachmentProcessing,- onIngestProgress: setFileIngestProgress,- })- if (processedAttachments.length > 0) {+ // Persist each document's chosen mode so processAttachmentsForSend+ // can pick it up at send time.+ if (choices.size > 0) {setAttachmentsForThread(attachmentsKey, (prev) =>prev.map((att) => {- const match = processedAttachments.find(- (p) => p.path && att.path && p.path === att.path- )- return match ? { ...att, ...match } : att+ const mode = att.path ? choices.get(att.path) : undefined+ return mode ? { ...att, parseMode: mode } : att}))}-- if (hasEmbeddedDocuments) {- const toolApproval = useToolApproval.getState()- const ragTools = useAppState.getState().ragToolNames- for (const toolName of ragTools) {- toolApproval.approveToolForThread(currentThreadId, toolName)- }- useThreads.getState().updateThread(currentThreadId, {- metadata: { hasDocuments: true },- })- }- } catch (e) {- console.error('Failed to process attachments:', e)- } finally {- setFileIngestProgress(null)}},[ATTACHMENT_AUTO_INLINE_FALLBACK_BYTES,attachmentsKey,- autoInlineContextRatio,- activeModels,- currentThreadId,- getProviderByName,parsePreference,- selectedModel?.id,- selectedModel?.settings?.ctx_len?.controller_props?.value,- selectedProvider,- serviceHub,- setActiveModels,setAttachmentsForThread,- updateAttachmentProcessing,- updateLoadingModel,])@@ -1733,24 +1540,6 @@ const ChatInput = memo(function ChatInput({)})}</div>- {fileIngestProgress && fileIngestProgress.total > 0 && (- <div className="space-y-1.5 pr-1">- <div className="flex justify-between gap-2 text-xs text-muted-foreground">- <span>{t('common:uploadingAttachments')}</span>- <span className="tabular-nums shrink-0">- {fileIngestProgress.completed} /{' '}- {fileIngestProgress.total}- </span>- </div>- <Progress- value={- (fileIngestProgress.completed /- fileIngestProgress.total) *- 100- }- />- </div>- )}</div>)}{queuedMessages.length > 0 && (diff --git a/web-app/src/hooks/__tests__/useAttachmentIngestionPrompt.test.ts b/web-app/src/hooks/__tests__/useAttachmentIngestionPrompt.test.tsnew file mode 100644index 000000000..6c6bf6e36--- /dev/null+++ b/web-app/src/hooks/__tests__/useAttachmentIngestionPrompt.test.ts@@ -0,0 +1,101 @@+import { describe, it, expect, beforeEach } from 'vitest'+import { act } from '@testing-library/react'+import { useAttachmentIngestionPrompt } from '../useAttachmentIngestionPrompt'++describe('useAttachmentIngestionPrompt', () => {+ beforeEach(() => {+ useAttachmentIngestionPrompt.setState({+ isModalOpen: false,+ currentAttachment: null,+ currentIndex: 0,+ totalCount: 0,+ sizeThreshold: 0,+ resolver: null,+ })+ })++ it('starts with modal closed', () => {+ const state = useAttachmentIngestionPrompt.getState()+ expect(state.isModalOpen).toBe(false)+ expect(state.currentAttachment).toBeNull()+ })++ it('showPrompt opens modal and sets attachment info', async () => {+ const attachment = { name: 'test.pdf', size: 1024 }++ // Don't await — it blocks until choose/cancel is called+ const promise = useAttachmentIngestionPrompt+ .getState()+ .showPrompt(attachment, 512_000, 0, 3)++ const state = useAttachmentIngestionPrompt.getState()+ expect(state.isModalOpen).toBe(true)+ expect(state.currentAttachment).toEqual(attachment)+ expect(state.currentIndex).toBe(0)+ expect(state.totalCount).toBe(3)+ expect(state.sizeThreshold).toBe(512_000)++ // Resolve it so the test doesn't hang+ act(() => {+ useAttachmentIngestionPrompt.getState().choose('inline')+ })++ const result = await promise+ expect(result).toBe('inline')+ })++ it('choose resolves the promise with the selected mode', async () => {+ const promise = useAttachmentIngestionPrompt+ .getState()+ .showPrompt({ name: 'doc.pdf', size: 100 }, 1000, 0, 1)++ act(() => {+ useAttachmentIngestionPrompt.getState().choose('embeddings')+ })++ expect(await promise).toBe('embeddings')+ expect(useAttachmentIngestionPrompt.getState().isModalOpen).toBe(false)+ })++ it('cancel resolves with undefined', async () => {+ const promise = useAttachmentIngestionPrompt+ .getState()+ .showPrompt({ name: 'doc.pdf', size: 100 }, 1000, 0, 1)++ act(() => {+ useAttachmentIngestionPrompt.getState().cancel()+ })++ expect(await promise).toBeUndefined()+ expect(useAttachmentIngestionPrompt.getState().isModalOpen).toBe(false)+ })++ it('handles sequential prompts for multiple documents', async () => {+ const docs = [+ { name: 'a.pdf', size: 100 },+ { name: 'b.pdf', size: 200 },+ ]+ const choices: Array<'inline' | 'embeddings' | undefined> = []++ for (let i = 0; i < docs.length; i++) {+ const promise = useAttachmentIngestionPrompt+ .getState()+ .showPrompt(docs[i], 1000, i, docs.length)++ expect(useAttachmentIngestionPrompt.getState().currentIndex).toBe(i)+ expect(useAttachmentIngestionPrompt.getState().totalCount).toBe(+ docs.length+ )++ act(() => {+ useAttachmentIngestionPrompt+ .getState()+ .choose(i === 0 ? 'inline' : 'embeddings')+ })++ choices.push(await promise)+ }++ expect(choices).toEqual(['inline', 'embeddings'])+ })+})diff --git a/web-app/src/hooks/__tests__/useChatAttachments.test.ts b/web-app/src/hooks/__tests__/useChatAttachments.test.tsnew file mode 100644index 000000000..ac5938138--- /dev/null+++ b/web-app/src/hooks/__tests__/useChatAttachments.test.ts@@ -0,0 +1,212 @@+import { describe, it, expect, beforeEach } from 'vitest'+import { act } from '@testing-library/react'+import {+ useChatAttachments,+ NEW_THREAD_ATTACHMENT_KEY,+} from '../useChatAttachments'+import type { Attachment } from '@/types/attachment'++const docAttachment = (+ overrides: Partial<Attachment> = {}+): Attachment => ({+ name: 'test.pdf',+ type: 'document',+ path: '/tmp/test.pdf',+ fileType: 'pdf',+ ...overrides,+})++const imageAttachment = (+ overrides: Partial<Attachment> = {}+): Attachment => ({+ name: 'photo.jpg',+ type: 'image',+ mimeType: 'image/jpeg',+ ...overrides,+})++describe('useChatAttachments', () => {+ beforeEach(() => {+ // Reset the store between tests+ useChatAttachments.setState({ attachmentsByThread: {} })+ })++ describe('getAttachments', () => {+ it('returns empty array for unknown thread', () => {+ const result = useChatAttachments.getState().getAttachments('unknown')+ expect(result).toEqual([])+ })++ it('defaults to NEW_THREAD_ATTACHMENT_KEY when no threadId given', () => {+ const doc = docAttachment()+ act(() => {+ useChatAttachments+ .getState()+ .setAttachments(NEW_THREAD_ATTACHMENT_KEY, [doc])+ })+ expect(useChatAttachments.getState().getAttachments()).toEqual([doc])+ })+ })++ describe('setAttachments', () => {+ it('sets attachments for a thread with an array', () => {+ const doc = docAttachment()+ act(() => {+ useChatAttachments.getState().setAttachments('thread-1', [doc])+ })+ expect(useChatAttachments.getState().getAttachments('thread-1')).toEqual([+ doc,+ ])+ })++ it('supports functional updater', () => {+ const doc1 = docAttachment({ name: 'a.pdf' })+ const doc2 = docAttachment({ name: 'b.pdf' })+ act(() => {+ useChatAttachments.getState().setAttachments('thread-1', [doc1])+ })+ act(() => {+ useChatAttachments+ .getState()+ .setAttachments('thread-1', (prev) => [...prev, doc2])+ })+ expect(+ useChatAttachments.getState().getAttachments('thread-1')+ ).toHaveLength(2)+ })++ it('can update parseMode on existing attachments', () => {+ const doc = docAttachment({ parseMode: 'auto' })+ act(() => {+ useChatAttachments+ .getState()+ .setAttachments(NEW_THREAD_ATTACHMENT_KEY, [doc])+ })+ act(() => {+ useChatAttachments+ .getState()+ .setAttachments(NEW_THREAD_ATTACHMENT_KEY, (prev) =>+ prev.map((a) => ({ ...a, parseMode: 'embeddings' as const }))+ )+ })+ const result = useChatAttachments+ .getState()+ .getAttachments(NEW_THREAD_ATTACHMENT_KEY)+ expect(result[0].parseMode).toBe('embeddings')+ })+ })++ describe('clearAttachments', () => {+ it('removes all attachments for a thread', () => {+ act(() => {+ useChatAttachments+ .getState()+ .setAttachments('thread-1', [docAttachment()])+ })+ act(() => {+ useChatAttachments.getState().clearAttachments('thread-1')+ })+ expect(useChatAttachments.getState().getAttachments('thread-1')).toEqual(+ []+ )+ })++ it('does not affect other threads', () => {+ const doc1 = docAttachment({ name: 'a.pdf' })+ const doc2 = docAttachment({ name: 'b.pdf' })+ act(() => {+ useChatAttachments.getState().setAttachments('thread-1', [doc1])+ useChatAttachments.getState().setAttachments('thread-2', [doc2])+ })+ act(() => {+ useChatAttachments.getState().clearAttachments('thread-1')+ })+ expect(useChatAttachments.getState().getAttachments('thread-1')).toEqual(+ []+ )+ expect(+ useChatAttachments.getState().getAttachments('thread-2')+ ).toEqual([doc2])+ })+ })++ describe('transferAttachments', () => {+ it('moves attachments from source to destination key', () => {+ const doc = docAttachment()+ act(() => {+ useChatAttachments+ .getState()+ .setAttachments(NEW_THREAD_ATTACHMENT_KEY, [doc])+ })+ act(() => {+ useChatAttachments+ .getState()+ .transferAttachments(NEW_THREAD_ATTACHMENT_KEY, 'thread-1')+ })++ // Source is empty+ expect(+ useChatAttachments+ .getState()+ .getAttachments(NEW_THREAD_ATTACHMENT_KEY)+ ).toEqual([])+ // Destination has the attachments+ expect(useChatAttachments.getState().getAttachments('thread-1')).toEqual([+ doc,+ ])+ })++ it('does not overwrite existing destination attachments', () => {+ const doc1 = docAttachment({ name: 'existing.pdf' })+ const doc2 = docAttachment({ name: 'transferred.pdf' })+ act(() => {+ useChatAttachments.getState().setAttachments('thread-1', [doc1])+ useChatAttachments+ .getState()+ .setAttachments(NEW_THREAD_ATTACHMENT_KEY, [doc2])+ })+ act(() => {+ useChatAttachments+ .getState()+ .transferAttachments(NEW_THREAD_ATTACHMENT_KEY, 'thread-1')+ })+ // Existing destination is preserved+ expect(useChatAttachments.getState().getAttachments('thread-1')).toEqual([+ doc1,+ ])+ })++ it('is a no-op when source is empty', () => {+ const doc = docAttachment()+ act(() => {+ useChatAttachments.getState().setAttachments('thread-1', [doc])+ })+ act(() => {+ useChatAttachments+ .getState()+ .transferAttachments(NEW_THREAD_ATTACHMENT_KEY, 'thread-1')+ })+ // Destination unchanged+ expect(useChatAttachments.getState().getAttachments('thread-1')).toEqual([+ doc,+ ])+ })++ it('preserves parseMode choices through transfer', () => {+ const doc = docAttachment({ parseMode: 'embeddings' })+ act(() => {+ useChatAttachments+ .getState()+ .setAttachments(NEW_THREAD_ATTACHMENT_KEY, [doc])+ })+ act(() => {+ useChatAttachments+ .getState()+ .transferAttachments(NEW_THREAD_ATTACHMENT_KEY, 'thread-1')+ })+ const transferred =+ useChatAttachments.getState().getAttachments('thread-1')+ expect(transferred[0].parseMode).toBe('embeddings')+ })+ })+})diff --git a/web-app/src/lib/__tests__/attachmentProcessing.test.ts b/web-app/src/lib/__tests__/attachmentProcessing.test.tsnew file mode 100644index 000000000..24e8dc029--- /dev/null+++ b/web-app/src/lib/__tests__/attachmentProcessing.test.ts@@ -0,0 +1,255 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'+import {+ processAttachmentsForSend,+ type AttachmentProcessingResult,+} from '../attachmentProcessing'+import type { Attachment } from '@/types/attachment'++// Minimal mock for ServiceHub methods used by processAttachmentsForSend+const createMockServiceHub = (overrides: Record<string, unknown> = {}) => ({+ uploads: () => ({+ ingestImage: vi+ .fn()+ .mockResolvedValue({ id: 'img-1', size: 100 }),+ ingestFileAttachment: vi+ .fn()+ .mockResolvedValue({ id: 'doc-1', size: 500, chunkCount: 3 }),+ ingestFileAttachmentForProject: vi+ .fn()+ .mockResolvedValue({ id: 'proj-doc-1', size: 500, chunkCount: 5 }),+ ...overrides,+ }),+ rag: () => ({+ parseDocument: vi.fn().mockResolvedValue('parsed document text'),+ }),+})++const docAttachment = (overrides: Partial<Attachment> = {}): Attachment => ({+ name: 'report.pdf',+ type: 'document',+ path: '/tmp/report.pdf',+ fileType: 'pdf',+ ...overrides,+})++const imageAttachment = (overrides: Partial<Attachment> = {}): Attachment => ({+ name: 'photo.jpg',+ type: 'image',+ base64: 'abc123',+ mimeType: 'image/jpeg',+ ...overrides,+})++describe('processAttachmentsForSend', () => {+ const threadId = 'thread-1'++ describe('images', () => {+ it('ingests unprocessed images and returns them with id', async () => {+ const hub = createMockServiceHub()+ const img = imageAttachment()++ const result = await processAttachmentsForSend({+ attachments: [img],+ threadId,+ serviceHub: hub as any,+ parsePreference: 'auto',+ })++ expect(result.processedAttachments).toHaveLength(1)+ expect(result.processedAttachments[0].id).toBe('img-1')+ expect(result.processedAttachments[0].processed).toBe(true)+ })++ it('skips already-processed images', async () => {+ const hub = createMockServiceHub()+ const img = imageAttachment({ processed: true, id: 'existing-id' })++ const result = await processAttachmentsForSend({+ attachments: [img],+ threadId,+ serviceHub: hub as any,+ parsePreference: 'auto',+ })++ expect(result.processedAttachments[0].id).toBe('existing-id')+ expect(hub.uploads().ingestImage).not.toHaveBeenCalled()+ })+ })++ describe('documents — parseMode routing', () => {+ it('uses inline mode when parseMode is "inline"', async () => {+ const hub = createMockServiceHub()+ const doc = docAttachment({ parseMode: 'inline' })++ const result = await processAttachmentsForSend({+ attachments: [doc],+ threadId,+ serviceHub: hub as any,+ parsePreference: 'auto',+ })++ expect(result.processedAttachments[0].injectionMode).toBe('inline')+ expect(result.processedAttachments[0].inlineContent).toBe(+ 'parsed document text'+ )+ expect(result.hasEmbeddedDocuments).toBe(false)+ })++ it('uses embeddings mode when parseMode is "embeddings"', async () => {+ const hub = createMockServiceHub()+ const doc = docAttachment({ parseMode: 'embeddings' })++ const result = await processAttachmentsForSend({+ attachments: [doc],+ threadId,+ serviceHub: hub as any,+ parsePreference: 'auto',+ })++ expect(result.processedAttachments[0].injectionMode).toBe('embeddings')+ expect(result.processedAttachments[0].id).toBe('doc-1')+ expect(result.hasEmbeddedDocuments).toBe(true)+ })++ it('falls back to embeddings when inline parsing fails', async () => {+ const failingParse = vi.fn().mockRejectedValue(new Error('parse failed'))+ const hub = {+ ...createMockServiceHub(),+ rag: () => ({ parseDocument: failingParse }),+ }+ const doc = docAttachment({ parseMode: 'inline' })++ const result = await processAttachmentsForSend({+ attachments: [doc],+ threadId,+ serviceHub: hub as any,+ parsePreference: 'auto',+ })++ // Falls back to embeddings since parsedContent is absent+ expect(result.processedAttachments[0].injectionMode).toBe('embeddings')+ expect(result.hasEmbeddedDocuments).toBe(true)+ })++ it('skips already-processed documents', async () => {+ const hub = createMockServiceHub()+ const doc = docAttachment({+ processed: true,+ id: 'existing-doc',+ injectionMode: 'embeddings',+ })++ const result = await processAttachmentsForSend({+ attachments: [doc],+ threadId,+ serviceHub: hub as any,+ parsePreference: 'auto',+ })++ expect(result.processedAttachments[0].id).toBe('existing-doc')+ expect(hub.uploads().ingestFileAttachment).not.toHaveBeenCalled()+ })++ it('forces embeddings for project files', async () => {+ const hub = createMockServiceHub()+ const doc = docAttachment({ parseMode: 'inline' })++ const result = await processAttachmentsForSend({+ attachments: [doc],+ threadId,+ projectId: 'proj-1',+ serviceHub: hub as any,+ parsePreference: 'auto',+ })++ expect(result.processedAttachments[0].injectionMode).toBe('embeddings')+ expect(result.processedAttachments[0].id).toBe('proj-doc-1')+ })+ })++ describe('auto mode with perFileChoices', () => {+ it('respects per-file user choice for auto-mode documents', async () => {+ const hub = createMockServiceHub()+ const doc = docAttachment({ parseMode: 'auto' })+ const choices = new Map<string, 'inline' | 'embeddings'>([+ ['/tmp/report.pdf', 'inline'],+ ])++ const result = await processAttachmentsForSend({+ attachments: [doc],+ threadId,+ serviceHub: hub as any,+ parsePreference: 'auto',+ perFileChoices: choices,+ })++ expect(result.processedAttachments[0].injectionMode).toBe('inline')+ })+ })++ describe('callbacks', () => {+ it('calls updateAttachmentProcessing for each document', async () => {+ const hub = createMockServiceHub()+ const doc = docAttachment({ parseMode: 'embeddings' })+ const updateFn = vi.fn()++ await processAttachmentsForSend({+ attachments: [doc],+ threadId,+ serviceHub: hub as any,+ parsePreference: 'auto',+ updateAttachmentProcessing: updateFn,+ })++ // Called with 'processing' then 'done'+ expect(updateFn).toHaveBeenCalledWith('report.pdf', 'processing')+ expect(updateFn).toHaveBeenCalledWith(+ 'report.pdf',+ 'done',+ expect.objectContaining({ processed: true, injectionMode: 'embeddings' })+ )+ })++ it('fires onIngestProgress for multi-file uploads', async () => {+ const hub = createMockServiceHub()+ const docs = [+ docAttachment({ name: 'a.pdf', path: '/a.pdf', parseMode: 'embeddings' }),+ docAttachment({ name: 'b.pdf', path: '/b.pdf', parseMode: 'embeddings' }),+ ]+ const progressFn = vi.fn()++ await processAttachmentsForSend({+ attachments: docs,+ threadId,+ serviceHub: hub as any,+ parsePreference: 'auto',+ onIngestProgress: progressFn,+ })++ // Initial: {completed: 0, total: 2}, then increments+ expect(progressFn).toHaveBeenCalledWith({ completed: 0, total: 2 })+ expect(progressFn).toHaveBeenCalledWith({ completed: 1, total: 2 })+ expect(progressFn).toHaveBeenCalledWith({ completed: 2, total: 2 })+ })+ })++ describe('mixed attachments', () => {+ it('processes images and documents together', async () => {+ const hub = createMockServiceHub()+ const img = imageAttachment()+ const doc = docAttachment({ parseMode: 'embeddings' })++ const result = await processAttachmentsForSend({+ attachments: [img, doc],+ threadId,+ serviceHub: hub as any,+ parsePreference: 'auto',+ })++ expect(result.processedAttachments).toHaveLength(2)+ expect(result.processedAttachments[0].type).toBe('image')+ expect(result.processedAttachments[1].type).toBe('document')+ expect(result.hasEmbeddedDocuments).toBe(true)+ })+ })+})diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsxindex f1dbc772c..1dee9bd1e 100644--- a/web-app/src/routes/threads/$threadId.tsx+++ b/web-app/src/routes/threads/$threadId.tsx@@ -162,6 +162,7 @@ function ThreadDetail() {autoIncreaseAttempts > 0 &&autoIncreaseAttempts < MAX_AUTO_INCREASE_ATTEMPTSconst [contextLimitError, setContextLimitError] = useState<Error | null>(null)+ const [processingEmbeddings, setProcessingEmbeddings] = useState(false)// Refs so onFinish (captured in closure) always calls the latest callbacksconst handleContextSizeIncreaseRef = useRef<(() => void) | null>(null)@@ -591,10 +592,41 @@ function ThreadDetail() {...allAttachments.filter((a) => a.type === 'document'),]+ const messageId = generateId()+ const hasDocuments = combinedAttachments.some(+ (a) => a.type === 'document' && !a.processed+ )+ const hasEmbeddingDocuments = combinedAttachments.some(+ (a) =>+ a.type === 'document' &&+ !a.processed &&+ a.parseMode !== 'inline'+ )++ // When there are unprocessed documents (e.g. first-message flow),+ // show the user message in the conversation immediately so the UI+ // doesn't hang while embeddings are generated.+ if (hasDocuments) {+ const previewMessage = newUserThreadContent(+ threadId,+ text,+ combinedAttachments,+ messageId+ )+ const previewUI =+ convertThreadMessagesToUIMessages([previewMessage])+ setChatMessages((prev) => [...prev, ...previewUI])+ }++ // Clear attachment chips from the input — they are now either+ // about to be sent or visible in the preview message above.+ clearAttachmentsForThread(attachmentsKey)+// Process attachments (ingest images, parse/index documents)let processedAttachments = combinedAttachmentsconst projectId = thread?.metadata?.project?.idif (combinedAttachments.length > 0) {+ if (hasEmbeddingDocuments) setProcessingEmbeddings(true)try {const parsePreference = useAttachments.getState().parseModeconst result = await processAttachmentsForSend({@@ -620,13 +652,25 @@ function ThreadDetail() {}} catch (error) {console.error('Failed to process attachments:', error)- // Don't send message if attachment processing failed+ // Remove the preview message on failure+ if (hasDocuments) {+ setChatMessages((prev) =>+ prev.filter((m) => m.id !== messageId)+ )+ }return+ } finally {+ setProcessingEmbeddings(false)}}- const messageId = generateId()- // Create and persist the user message to the backend with all processed attachments+ // Remove the preview before sendMessage adds the real user message+ // with the same id — this prevents duplicates.+ if (hasDocuments) {+ setChatMessages((prev) => prev.filter((m) => m.id !== messageId))+ }++ // Persist the final message to backendconst userMessage = newUserThreadContent(threadId,text,@@ -661,9 +705,6 @@ function ThreadDetail() {id: messageId,metadata: { ...userMessage.metadata, createdAt: new Date() },})-- // Clear attachments after sending- clearAttachmentsForThread(attachmentsKey)},[sendMessage,@@ -672,6 +713,7 @@ function ThreadDetail() {addMessage,getAttachments,attachmentsKey,+ setChatMessages,clearAttachmentsForThread,serviceHub,selectedProvider,@@ -1061,6 +1103,11 @@ function ThreadDetail() {isAnimating={false}/>)}+ {processingEmbeddings && (+ <div className="flex flex-row items-center gap-2">+ <Shimmer duration={1}>Processing embeddings...</Shimmer>+ </div>+ )}{(status === CHAT_STATUS.SUBMITTED ||isAutoIncreasingContext) && (<div className="flex flex-row items-center gap-2">