Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix: persist file ingestion progress + cleaner citations and spell check (#8162)

Akarshan Biswas15b4de1763e2
diff --git a/web-app/src/components/CitationLink.tsx b/web-app/src/components/CitationLink.tsx
index c2ec814d0..116891ddf 100644
--- a/web-app/src/components/CitationLink.tsx
+++ b/web-app/src/components/CitationLink.tsx
@@ -53,7 +53,7 @@ export const CitationLink = memo(
<button
type="button"
className={cn(
- 'no-underline text-primary hover:text-primary/80 mx-0.5 align-super text-[0.7em] cursor-pointer',
+ 'no-underline text-primary hover:text-primary/80 mx-0.5 align-super text-[0.85em] font-medium cursor-pointer',
className
)}
>
diff --git a/web-app/src/containers/ProjectFiles.tsx b/web-app/src/containers/ProjectFiles.tsx
index f3534358f..6afb1b95e 100644
--- a/web-app/src/containers/ProjectFiles.tsx
+++ b/web-app/src/containers/ProjectFiles.tsx
@@ -16,6 +16,7 @@ import { useAttachments } from '@/hooks/useAttachments'
import { ExtensionTypeEnum, FileStat, VectorDBExtension } from '@janhq/core'
import { ExtensionManager } from '@/lib/extension'
import { IconLoader2, IconPaperclip } from '@tabler/icons-react'
+import { useProjectUploads } from '@/stores/project-uploads-store'
type ProjectFilesProps = {
projectId: string
@@ -298,13 +299,15 @@ export default function ProjectFiles({ projectId, lng }: ProjectFilesProps) {
const [files, setFiles] = useState<ProjectFile[]>([])
const [loading, setLoading] = useState(true)
- const [uploading, setUploading] = useState(false)
- const [uploadProgress, setUploadProgress] = useState<{
- current: number
- total: number
- } | null>(null)
const [isDragging, setIsDragging] = useState(false)
+ const uploadProgress = useProjectUploads((s) => s.progress[projectId])
+ const completedTick = useProjectUploads(
+ (s) => s.completedTick[projectId] ?? 0,
+ )
+ const ingestFiles = useProjectUploads((s) => s.ingest)
+ const uploading = !!uploadProgress
+
const loadProjectFiles = useCallback(async () => {
setLoading(true)
try {
@@ -326,7 +329,7 @@ export default function ProjectFiles({ projectId, lng }: ProjectFilesProps) {
useEffect(() => {
loadProjectFiles()
- }, [loadProjectFiles])
+ }, [loadProjectFiles, completedTick])
const processFilePaths = useCallback(
async (paths: string[]) => {
@@ -410,40 +413,31 @@ export default function ProjectFiles({ projectId, lng }: ProjectFilesProps) {
if (newAttachments.length === 0) return
- const total = newAttachments.length
- setUploading(true)
- setUploadProgress({ current: 0, total })
- let currentFileName: string | undefined
- try {
- for (let i = 0; i < newAttachments.length; i++) {
- const att = newAttachments[i]
- currentFileName = att.name
- const result = await serviceHub
- .uploads()
- .ingestFileAttachmentForProject(projectId, att)
- if (!result.id) {
- throw new Error('Failed to ingest file')
- }
- setUploadProgress({ current: i + 1, total })
- }
- toast.success(
- t('common:toast.fileUploaded.title') ?? 'File uploaded successfully'
- )
- await loadProjectFiles()
- } catch (error) {
- console.error('Failed to upload file:', error)
- toast.error(
- t('common:toast.uploadFailed.title') ?? 'Failed to upload file',
- {
- description: humanizeUploadError(t, error, currentFileName),
- }
- )
- } finally {
- setUploadProgress(null)
- setUploading(false)
- }
+ await ingestFiles(
+ projectId,
+ newAttachments,
+ (pid, att) =>
+ serviceHub.uploads().ingestFileAttachmentForProject(pid, att),
+ {
+ onSuccess: () => {
+ toast.success(
+ t('common:toast.fileUploaded.title') ??
+ 'File processed successfully',
+ )
+ },
+ onError: (error, fileName) => {
+ console.error('Failed to process file:', error)
+ toast.error(
+ t('common:toast.uploadFailed.title') ?? 'Failed to process file',
+ {
+ description: humanizeUploadError(t, error, fileName),
+ },
+ )
+ },
+ },
+ )
},
- [files, loadProjectFiles, maxFileSizeMB, projectId, serviceHub, t]
+ [files, ingestFiles, maxFileSizeMB, projectId, serviceHub, t]
)
const handleUpload = async () => {
@@ -476,7 +470,7 @@ export default function ProjectFiles({ projectId, lng }: ProjectFilesProps) {
} catch (error) {
console.error('Failed to open file dialog:', error)
toast.error(
- t('common:toast.uploadFailed.title') ?? 'Failed to upload file',
+ t('common:toast.uploadFailed.title') ?? 'Failed to process file',
{
description: humanizeUploadError(t, error),
}
@@ -581,7 +575,7 @@ export default function ProjectFiles({ projectId, lng }: ProjectFilesProps) {
) : (
<UploadIcon className="size-4" />
)}
- <span>Upload</span>
+ <span>{t('common:projects.processButton')}</span>
</Button>
</div>
diff --git a/web-app/src/containers/__tests__/ProjectFiles.test.tsx b/web-app/src/containers/__tests__/ProjectFiles.test.tsx
index 6ad6814e7..8955b370f 100644
--- a/web-app/src/containers/__tests__/ProjectFiles.test.tsx
+++ b/web-app/src/containers/__tests__/ProjectFiles.test.tsx
@@ -146,8 +146,8 @@ describe('ProjectFiles', () => {
it('shows an info toast when upload is clicked while attachments are disabled', async () => {
attachmentsStateRef.attachmentsState = { enabled: false, maxFileSizeMB: 10 }
render(<ProjectFiles projectId="p1" lng="en" />)
- await waitFor(() => expect(screen.getByText('Upload')).toBeInTheDocument())
- fireEvent.click(screen.getByText('Upload'))
+ await waitFor(() => expect(screen.getByText('common:projects.processButton')).toBeInTheDocument())
+ fireEvent.click(screen.getByText('common:projects.processButton'))
await waitFor(() => expect(toastMock.info).toHaveBeenCalled())
expect(dialogOpenMock).not.toHaveBeenCalled()
})
@@ -155,16 +155,16 @@ describe('ProjectFiles', () => {
it('opens the file dialog when upload is clicked', async () => {
dialogOpenMock.mockResolvedValue(null)
render(<ProjectFiles projectId="p1" lng="en" />)
- await waitFor(() => expect(screen.getByText('Upload')).toBeInTheDocument())
- fireEvent.click(screen.getByText('Upload'))
+ await waitFor(() => expect(screen.getByText('common:projects.processButton')).toBeInTheDocument())
+ fireEvent.click(screen.getByText('common:projects.processButton'))
await waitFor(() => expect(dialogOpenMock).toHaveBeenCalled())
})
it('toasts error when opening the dialog throws', async () => {
dialogOpenMock.mockRejectedValue(new Error('dialog broken'))
render(<ProjectFiles projectId="p1" lng="en" />)
- await waitFor(() => expect(screen.getByText('Upload')).toBeInTheDocument())
- fireEvent.click(screen.getByText('Upload'))
+ await waitFor(() => expect(screen.getByText('common:projects.processButton')).toBeInTheDocument())
+ fireEvent.click(screen.getByText('common:projects.processButton'))
await waitFor(() => expect(toastMock.error).toHaveBeenCalled())
})
diff --git a/web-app/src/containers/dialogs/AddEditAssistant.tsx b/web-app/src/containers/dialogs/AddEditAssistant.tsx
index a2c2fb00d..283490955 100644
--- a/web-app/src/containers/dialogs/AddEditAssistant.tsx
+++ b/web-app/src/containers/dialogs/AddEditAssistant.tsx
@@ -26,6 +26,7 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { useTheme } from '@/hooks/useTheme'
+import { useGeneralSetting } from '@/hooks/useGeneralSetting'
import { AvatarEmoji } from '@/containers/AvatarEmoji'
import { useTranslation } from '@/i18n/react-i18next-compat'
import { cn } from '@/lib/utils'
@@ -55,6 +56,7 @@ export default function AddEditAssistant({
initialData?.instructions || ''
)
const { isDark } = useTheme()
+ const spellCheckChatInput = useGeneralSetting((s) => s.spellCheckChatInput)
const [paramsKeys, setParamsKeys] = useState<string[]>([''])
const [paramsValues, setParamsValues] = useState<unknown[]>([''])
const [paramsTypes, setParamsTypes] = useState<string[]>(['string'])
@@ -323,6 +325,10 @@ export default function AddEditAssistant({
onChange={(e) => setDescription(e.target.value)}
placeholder={t('assistants:enterDescription')}
className="resize-none"
+ spellCheck={spellCheckChatInput}
+ data-gramm={spellCheckChatInput}
+ data-gramm_editor={spellCheckChatInput}
+ data-gramm_grammarly={spellCheckChatInput}
/>
</div>
@@ -336,6 +342,10 @@ export default function AddEditAssistant({
placeholder={t('assistants:enterInstructions')}
className="resize-none"
rows={4}
+ spellCheck={spellCheckChatInput}
+ data-gramm={spellCheckChatInput}
+ data-gramm_editor={spellCheckChatInput}
+ data-gramm_grammarly={spellCheckChatInput}
/>
<div className="text-xs text-muted-foreground">
{t('assistants:instructionsDateHint')}
diff --git a/web-app/src/lib/__tests__/grounding.test.ts b/web-app/src/lib/__tests__/grounding.test.ts
new file mode 100644
index 000000000..f61d5ba2a
--- /dev/null
+++ b/web-app/src/lib/__tests__/grounding.test.ts
@@ -0,0 +1,73 @@
+import { describe, it, expect } from 'vitest'
+import { splitSentences } from '@/lib/grounding'
+
+describe('splitSentences', () => {
+ it('returns no sentences for empty input', () => {
+ expect(splitSentences('')).toEqual([])
+ })
+
+ it('drops fragments shorter than 12 plain chars', () => {
+ expect(splitSentences('Hi. Bye.')).toEqual([])
+ })
+
+ it('splits two plain sentences on terminator + space', () => {
+ const result = splitSentences('Plain sentence one. Plain sentence two!')
+ expect(result.map((s) => s.formatted)).toEqual([
+ 'Plain sentence one.',
+ 'Plain sentence two!',
+ ])
+ })
+
+ it('keeps abbreviations like "e.g." inside a single sentence', () => {
+ const result = splitSentences(
+ 'We find that Hawk is able to extrapolate (e.g., up to 1M tokens). Another sentence here.',
+ )
+ expect(result.map((s) => s.formatted)).toEqual([
+ 'We find that Hawk is able to extrapolate (e.g., up to 1M tokens).',
+ 'Another sentence here.',
+ ])
+ })
+
+ it('keeps "i.e." inside the sentence', () => {
+ const result = splitSentences(
+ 'The model variant, i.e., the small one, performs well here.',
+ )
+ expect(result.map((s) => s.formatted)).toEqual([
+ 'The model variant, i.e., the small one, performs well here.',
+ ])
+ })
+
+ it('splits on question and exclamation marks followed by space', () => {
+ const result = splitSentences('Is this working? Yes it is working now!')
+ expect(result.map((s) => s.formatted)).toEqual([
+ 'Is this working?',
+ 'Yes it is working now!',
+ ])
+ })
+
+ it('captures trailing sentence with no terminator', () => {
+ const result = splitSentences(
+ 'First complete sentence here. Trailing sentence with no period',
+ )
+ expect(result.map((s) => s.formatted)).toEqual([
+ 'First complete sentence here.',
+ 'Trailing sentence with no period',
+ ])
+ })
+
+ it('strips markdown when producing the plain form', () => {
+ const [s] = splitSentences(
+ 'This **bold sentence** and `code` matter here.',
+ )
+ expect(s.formatted).toBe('This **bold sentence** and `code` matter here.')
+ expect(s.plain).toBe('This bold sentence and code matter here.')
+ })
+
+ it('handles terminator at end of input (no trailing space)', () => {
+ const result = splitSentences(
+ 'One full sentence here. Two full sentence here.',
+ )
+ expect(result).toHaveLength(2)
+ expect(result[1].formatted).toBe('Two full sentence here.')
+ })
+})
diff --git a/web-app/src/lib/grounding.ts b/web-app/src/lib/grounding.ts
index 3a85d19bb..1377d031e 100644
--- a/web-app/src/lib/grounding.ts
+++ b/web-app/src/lib/grounding.ts
@@ -1,6 +1,11 @@
import type { RagCitation } from '@/components/Citations'
-const SENTENCE_BOUNDARY = /([^.!?\n]+[.!?]+(?:["')\]]+)?|\S[^\n]*$)/g
+// Sentence boundary: a run of non-terminator chars (or terminators not
+// followed by whitespace/end — e.g. the periods inside "e.g."), ending in a
+// terminator that IS followed by whitespace/end. Fallback alternative
+// catches trailing sentences with no closing terminator.
+const SENTENCE_BOUNDARY =
+ /((?:[^.!?\n]|[.!?](?!\s|$))+[.!?]+(?:["')\]]+)?(?=\s|$)|\S[^\n]*$)/g
const stripMarkdown = (s: string): string =>
s
diff --git a/web-app/src/locales/ca/common.json b/web-app/src/locales/ca/common.json
index 907e29ca8..efaca2323 100644
--- a/web-app/src/locales/ca/common.json
+++ b/web-app/src/locales/ca/common.json
@@ -294,7 +294,8 @@
"searchProjects": "Cerca projectes...",
"noProjectsFound": "No s’han trobat projectes",
"tryDifferentSearch": "Prova amb un terme de cerca diferent",
- "uploadingFiles": "S’estan pujant els fitxers…"
+ "uploadingFiles": "S’estan processant els fitxers…",
+ "processButton": "Afegeix"
},
"attachmentsIngestion": {
"title": "Tria com ingerir els adjunts",
diff --git a/web-app/src/locales/cs/common.json b/web-app/src/locales/cs/common.json
index ec1e685e1..d716c92f9 100644
--- a/web-app/src/locales/cs/common.json
+++ b/web-app/src/locales/cs/common.json
@@ -303,7 +303,8 @@
"searchProjects": "Hledat projekty...",
"noProjectsFound": "Nebyly nalezeny žádné projekty",
"tryDifferentSearch": "Zkuste jiný vyhledávací výraz",
- "uploadingFiles": "Nahrávání souborů…"
+ "uploadingFiles": "Zpracování souborů…",
+ "processButton": "Přidat"
},
"errorDialog": {
"titleFallback": "Něco se pokazilo",
diff --git a/web-app/src/locales/de-DE/common.json b/web-app/src/locales/de-DE/common.json
index 2121f0083..240f1347a 100644
--- a/web-app/src/locales/de-DE/common.json
+++ b/web-app/src/locales/de-DE/common.json
@@ -303,7 +303,8 @@
"searchProjects": "Projekte durchsuchen...",
"noProjectsFound": "Keine Projekte gefunden",
"tryDifferentSearch": "Versuchen Sie einen anderen Suchbegriff",
- "uploadingFiles": "Dateien werden hochgeladen…"
+ "uploadingFiles": "Dateien werden verarbeitet…",
+ "processButton": "Hinzufügen"
},
"errorDialog": {
"titleFallback": "Etwas ist schiefgelaufen",
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index ebf8ce288..5f6ce5ce5 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -311,7 +311,8 @@
"noAssistantAssigned": "No assistant assigned to this project",
"files": "Files",
"filesDescription": "Add PDFs, documents, or other text to reference in this project.",
- "uploadingFiles": "Uploading files…",
+ "uploadingFiles": "Processing files…",
+ "processButton": "Add",
"deleteProjectDialog": {
"title": "Delete Project",
"permanentDelete": "This will permanently delete all threads.",
@@ -459,12 +460,12 @@
"description": "Thread removed from \"{{projectName}}\" successfully"
},
"fileUploaded": {
- "title": "File Uploaded",
- "description": "File has been uploaded and indexed successfully"
+ "title": "File Processed",
+ "description": "File has been processed and indexed successfully"
},
"uploadFailed": {
- "title": "Upload Failed",
- "description": "Failed to upload file",
+ "title": "Processing Failed",
+ "description": "Failed to process file",
"subjectThisFile": "This file",
"pdfMalformedXref": "{{subject}} has a malformed PDF cross-reference table and could not be parsed. Try opening it in a PDF viewer and re-saving it (File → Print → Save as PDF), then upload again.",
"pdfScanned": "{{subject}} appears to be a scanned or image-based PDF. OCR isn't supported yet — please upload a text-based PDF.",
@@ -474,7 +475,7 @@
"unsupportedType": "File type \"{{type}}\" is not supported.",
"ioError": "Could not read {{subject}}: {{message}}",
"parseGeneric": "{{subject}} could not be parsed: {{message}}",
- "fallback": "Failed to upload {{subject}}."
+ "fallback": "Failed to process {{subject}}."
},
"fileDeleted": {
"title": "File Deleted",
diff --git a/web-app/src/locales/es/common.json b/web-app/src/locales/es/common.json
index ceb6f40e7..b6662e9d7 100644
--- a/web-app/src/locales/es/common.json
+++ b/web-app/src/locales/es/common.json
@@ -286,7 +286,8 @@
"noAssistantAssigned": "No hay asistente asignado a este proyecto",
"files": "Archivos",
"filesDescription": "Agrega PDFs, documentos u otros textos para usar como referencia en este proyecto.",
- "uploadingFiles": "Subiendo archivos…",
+ "uploadingFiles": "Procesando archivos…",
+ "processButton": "Añadir",
"deleteProjectDialog": {
"title": "Eliminar proyecto",
"permanentDelete": "Esto eliminará permanentemente todos los hilos.",
@@ -438,12 +439,12 @@
"description": "Hilo removido de \"{{projectName}}\" correctamente"
},
"fileUploaded": {
- "title": "Archivo subido",
- "description": "El archivo se ha subido e indexado correctamente"
+ "title": "Archivo procesado",
+ "description": "El archivo se ha procesado e indexado correctamente"
},
"uploadFailed": {
- "title": "Error al subir",
- "description": "Error al subir el archivo"
+ "title": "Error de procesamiento",
+ "description": "Error al procesar el archivo"
},
"fileDeleted": {
"title": "Archivo eliminado",
diff --git a/web-app/src/locales/fr/common.json b/web-app/src/locales/fr/common.json
index b45dc72dc..4d6338ec3 100644
--- a/web-app/src/locales/fr/common.json
+++ b/web-app/src/locales/fr/common.json
@@ -302,7 +302,8 @@
"searchProjects": "Rechercher des projets...",
"noProjectsFound": "Aucun projet trouvé",
"tryDifferentSearch": "Essayez un autre terme de recherche",
- "uploadingFiles": "Téléversement des fichiers…"
+ "uploadingFiles": "Traitement des fichiers…",
+ "processButton": "Ajouter"
},
"errorDialog": {
"titleFallback": "Une erreur s'est produite",
diff --git a/web-app/src/locales/hi/common.json b/web-app/src/locales/hi/common.json
index 6a14f785f..910372c30 100644
--- a/web-app/src/locales/hi/common.json
+++ b/web-app/src/locales/hi/common.json
@@ -286,7 +286,8 @@
"noAssistantAssigned": "इस प्रोजेक्ट को कोई सहायक असाइन नहीं किया गया है",
"files": "फाइलें",
"filesDescription": "इस प्रोजेक्ट में संदर्भ के रूप में उपयोग के लिए PDF, दस्तावेज़ या अन्य टेक्स्ट जोड़ें।",
- "uploadingFiles": "फाइलें अपलोड हो रही हैं…",
+ "uploadingFiles": "फाइलें प्रोसेस हो रही हैं…",
+ "processButton": "जोड़ें",
"deleteProjectDialog": {
"title": "प्रोजेक्ट हटाएं",
"permanentDelete": "यह सभी थ्रेड्स को स्थायी रूप से हटा देगा।",
@@ -438,12 +439,12 @@
"description": "थ्रेड को \"{{projectName}}\" से सफलतापूर्वक हटाया गया"
},
"fileUploaded": {
- "title": "फ़ाइल अपलोड की गई",
- "description": "फ़ाइल सफलतापूर्वक अपलोड और इंडेक्स की गई"
+ "title": "फ़ाइल प्रोसेस की गई",
+ "description": "फ़ाइल सफलतापूर्वक प्रोसेस और इंडेक्स की गई"
},
"uploadFailed": {
- "title": "अपलोड में त्रुटि",
- "description": "फ़ाइल अपलोड करने में त्रुटि हुई"
+ "title": "प्रोसेसिंग में त्रुटि",
+ "description": "फ़ाइल प्रोसेस करने में त्रुटि हुई"
},
"fileDeleted": {
"title": "फ़ाइल हटाई गई",
diff --git a/web-app/src/locales/id/common.json b/web-app/src/locales/id/common.json
index 73eeddd53..bec7de46f 100644
--- a/web-app/src/locales/id/common.json
+++ b/web-app/src/locales/id/common.json
@@ -397,7 +397,8 @@
"searchProjects": "Cari proyek...",
"noProjectsFound": "Tidak ada proyek ditemukan",
"tryDifferentSearch": "Coba kata kunci pencarian lain",
- "uploadingFiles": "Mengunggah file…"
+ "uploadingFiles": "Memproses file…",
+ "processButton": "Tambah"
},
"llamacppBusyOnExit": {
"title": "llama.cpp is still busy",
diff --git a/web-app/src/locales/ja/common.json b/web-app/src/locales/ja/common.json
index e5ec37e75..5a1c1ca2a 100644
--- a/web-app/src/locales/ja/common.json
+++ b/web-app/src/locales/ja/common.json
@@ -294,7 +294,8 @@
"collapseThreads": "スレッドを折りたたむ",
"expandThreads": "スレッドを展開する",
"update": "更新",
- "uploadingFiles": "ファイルをアップロードしています…"
+ "uploadingFiles": "ファイルを処理しています…",
+ "processButton": "追加"
},
"errorDialog": {
"titleFallback": "問題が発生しました",
diff --git a/web-app/src/locales/ko/common.json b/web-app/src/locales/ko/common.json
index ca06c168a..4eec7b7f8 100644
--- a/web-app/src/locales/ko/common.json
+++ b/web-app/src/locales/ko/common.json
@@ -284,7 +284,8 @@
"noAssistantAssigned": "이 프로젝트에 할당된 어시스턴트가 없습니다",
"files": "파일",
"filesDescription": "이 프로젝트에서 참조할 PDF, 문서 또는 기타 텍스트를 추가하세요.",
- "uploadingFiles": "파일 업로드 중…",
+ "uploadingFiles": "파일 처리 중…",
+ "processButton": "추가",
"deleteProjectDialog": {
"title": "프로젝트 삭제",
"permanentDelete": "모든 스레드가 영구적으로 삭제됩니다.",
@@ -436,12 +437,12 @@
"description": "스레드가 \"{{projectName}}\"에서 성공적으로 제거되었습니다"
},
"fileUploaded": {
- "title": "파일 업로드됨",
- "description": "파일이 성공적으로 업로드 및 인덱싱되었습니다"
+ "title": "파일 처리됨",
+ "description": "파일이 성공적으로 처리 및 인덱싱되었습니다"
},
"uploadFailed": {
- "title": "업로드 실패",
- "description": "파일을 업로드하지 못했습니다"
+ "title": "처리 실패",
+ "description": "파일을 처리하지 못했습니다"
},
"fileDeleted": {
"title": "파일 삭제됨",
diff --git a/web-app/src/locales/pl/common.json b/web-app/src/locales/pl/common.json
index e15e37d93..71cfc63cf 100644
--- a/web-app/src/locales/pl/common.json
+++ b/web-app/src/locales/pl/common.json
@@ -297,7 +297,8 @@
"searchProjects": "Szukaj projektów...",
"noProjectsFound": "Nie znaleziono projektów",
"tryDifferentSearch": "Spróbuj innego wyszukiwania",
- "uploadingFiles": "Przesyłanie plików…"
+ "uploadingFiles": "Przetwarzanie plików…",
+ "processButton": "Dodaj"
},
"errorDialog": {
"titleFallback": "Coś poszło nie tak",
diff --git a/web-app/src/locales/pt-BR/common.json b/web-app/src/locales/pt-BR/common.json
index f4b8f45d7..bb793cf7c 100644
--- a/web-app/src/locales/pt-BR/common.json
+++ b/web-app/src/locales/pt-BR/common.json
@@ -300,7 +300,8 @@
"searchProjects": "Buscar projetos...",
"noProjectsFound": "Nenhum projeto encontrado",
"tryDifferentSearch": "Tente um termo de busca diferente",
- "uploadingFiles": "Enviando arquivos…"
+ "uploadingFiles": "Processando arquivos…",
+ "processButton": "Adicionar"
},
"errorDialog": {
"titleFallback": "Algo deu errado",
diff --git a/web-app/src/locales/ru/common.json b/web-app/src/locales/ru/common.json
index 5e2a5b9df..2d0671349 100644
--- a/web-app/src/locales/ru/common.json
+++ b/web-app/src/locales/ru/common.json
@@ -303,7 +303,8 @@
"searchProjects": "Поиск проектов...",
"noProjectsFound": "Проекты не найдены",
"tryDifferentSearch": "Попробуйте другой поисковый запрос",
- "uploadingFiles": "Загрузка файлов…"
+ "uploadingFiles": "Обработка файлов…",
+ "processButton": "Добавить"
},
"attachmentsIngestion": {
"title": "Выберите способ обработки вложений",
diff --git a/web-app/src/locales/vn/common.json b/web-app/src/locales/vn/common.json
index 52108697d..ddbdbadf1 100644
--- a/web-app/src/locales/vn/common.json
+++ b/web-app/src/locales/vn/common.json
@@ -256,7 +256,8 @@
"searchProjects": "Tìm kiếm dự án...",
"noProjectsFound": "Không tìm thấy dự án nào",
"tryDifferentSearch": "Thử từ khóa tìm kiếm khác",
- "uploadingFiles": "Đang tải lên tệp…",
+ "uploadingFiles": "Đang xử lý tệp…",
+ "processButton": "Thêm",
"deleteProjectDialog": {
"title": "Xóa dự án",
"permanentDelete": "Điều này sẽ xóa vĩnh viễn tất cả các chủ đề.",
diff --git a/web-app/src/locales/zh-CN/common.json b/web-app/src/locales/zh-CN/common.json
index 5bf4f68f3..c95e5f735 100644
--- a/web-app/src/locales/zh-CN/common.json
+++ b/web-app/src/locales/zh-CN/common.json
@@ -255,7 +255,8 @@
"searchProjects": "搜索项目...",
"noProjectsFound": "未找到项目",
"tryDifferentSearch": "尝试不同的搜索词",
- "uploadingFiles": "正在上传文件…",
+ "uploadingFiles": "正在处理文件…",
+ "processButton": "添加",
"createNewProject": "创建新项目",
"deleteProjectDialog": {
"title": "删除项目",
diff --git a/web-app/src/locales/zh-TW/common.json b/web-app/src/locales/zh-TW/common.json
index c8ddcae64..7533528be 100644
--- a/web-app/src/locales/zh-TW/common.json
+++ b/web-app/src/locales/zh-TW/common.json
@@ -255,7 +255,8 @@
"searchProjects": "搜尋專案...",
"noProjectsFound": "找不到專案",
"tryDifferentSearch": "嘗試不同的搜尋詞",
- "uploadingFiles": "正在上傳檔案…",
+ "uploadingFiles": "正在處理檔案…",
+ "processButton": "新增",
"createNewProject": "建立新專案",
"deleteProjectDialog": {
"title": "刪除專案",
diff --git a/web-app/src/stores/project-uploads-store.ts b/web-app/src/stores/project-uploads-store.ts
new file mode 100644
index 000000000..0fba6002b
--- /dev/null
+++ b/web-app/src/stores/project-uploads-store.ts
@@ -0,0 +1,104 @@
+import { create } from 'zustand'
+import type { Attachment } from '@/types/attachment'
+
+export type ProjectUploadProgress = {
+ current: number
+ total: number
+ currentFileName?: string
+}
+
+type IngestFn = (
+ projectId: string,
+ attachment: Attachment,
+) => Promise<{ id?: string }>
+
+type IngestHandlers = {
+ onSuccess: () => void
+ onError: (error: unknown, fileName?: string) => void
+}
+
+interface ProjectUploadsState {
+ progress: Record<string, ProjectUploadProgress>
+ // Monotonic counter per project that increments after every successful
+ // ingestion. Consumers watch this to refresh their file list whenever a
+ // file finishes in the background — including while they were unmounted.
+ completedTick: Record<string, number>
+ isIngesting: (projectId: string) => boolean
+ ingest: (
+ projectId: string,
+ attachments: Attachment[],
+ ingestFn: IngestFn,
+ handlers: IngestHandlers,
+ ) => Promise<void>
+}
+
+export const useProjectUploads = create<ProjectUploadsState>((set, get) => ({
+ progress: {},
+ completedTick: {},
+ isIngesting: (projectId) => !!get().progress[projectId],
+ ingest: async (projectId, attachments, ingestFn, handlers) => {
+ const total = attachments.length
+ if (total === 0) return
+ if (get().progress[projectId]) return
+
+ set((s) => ({
+ progress: {
+ ...s.progress,
+ [projectId]: {
+ current: 0,
+ total,
+ currentFileName: attachments[0]?.name,
+ },
+ },
+ }))
+
+ let currentFileName: string | undefined
+ try {
+ for (let i = 0; i < attachments.length; i++) {
+ const att = attachments[i]
+ currentFileName = att.name
+
+ set((s) => {
+ const existing = s.progress[projectId]
+ if (!existing) return s
+ return {
+ progress: {
+ ...s.progress,
+ [projectId]: {
+ ...existing,
+ current: i,
+ currentFileName: att.name,
+ },
+ },
+ }
+ })
+
+ const result = await ingestFn(projectId, att)
+ if (!result.id) throw new Error('Failed to ingest file')
+
+ set((s) => {
+ const existing = s.progress[projectId]
+ const nextTick = (s.completedTick[projectId] ?? 0) + 1
+ return {
+ progress: existing
+ ? {
+ ...s.progress,
+ [projectId]: { ...existing, current: i + 1 },
+ }
+ : s.progress,
+ completedTick: { ...s.completedTick, [projectId]: nextTick },
+ }
+ })
+ }
+ handlers.onSuccess()
+ } catch (error) {
+ handlers.onError(error, currentFileName)
+ } finally {
+ set((s) => {
+ const next = { ...s.progress }
+ delete next[projectId]
+ return { progress: next }
+ })
+ }
+ },
+}))